├── .gitignore ├── README.md ├── codeeval ├── .project ├── easy │ ├── 001fizzbuzz │ │ ├── README.md │ │ ├── input │ │ ├── solution.cpp │ │ ├── solution.py │ │ └── solution.rb │ ├── 004sumofprimes │ │ ├── README.md │ │ ├── solution.c │ │ ├── solution.py │ │ ├── solution.r │ │ └── solution.rb │ ├── 008reversewords │ │ ├── README.md │ │ ├── input │ │ ├── solution.c │ │ ├── solution.cpp │ │ ├── solution.js │ │ ├── solution.py │ │ └── solution.rb │ ├── 018multiplesofanumber │ │ ├── README.md │ │ ├── input │ │ ├── solution.c │ │ ├── solution.cpp │ │ └── solution.rb │ ├── 019bitpositions │ │ ├── README.md │ │ ├── input │ │ ├── output │ │ ├── solution.bash │ │ ├── solution.go │ │ ├── solution.js │ │ ├── solution.lua │ │ ├── solution.php │ │ ├── solution.py │ │ └── solution.rb │ ├── 020lowercase │ │ ├── README.md │ │ ├── input │ │ ├── solution.js │ │ ├── solution.py │ │ ├── solution.rb │ │ └── solution.sh │ ├── 021sumofdigits │ │ ├── README.md │ │ ├── input │ │ ├── solution.php │ │ └── solution.rb │ ├── 022fibonacciseries │ │ ├── README.md │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 024sumofintegersfromfile │ │ ├── input │ │ ├── solution.py │ │ └── solution.rb │ ├── 025oddnumbers │ │ ├── solution.c │ │ ├── solution.js │ │ ├── solution.lua │ │ ├── solution.php │ │ └── solution.py │ ├── 027decimaltobinary │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 029uniqueelements │ │ ├── input │ │ ├── input2 │ │ ├── solution.c │ │ ├── solution.cpp │ │ ├── solution.js │ │ ├── solution.py │ │ └── solution.rb │ ├── 030setintersection │ │ ├── input │ │ ├── input2 │ │ ├── output │ │ ├── solution.c │ │ └── solution.cpp │ ├── 031rightmostchar │ │ ├── input │ │ ├── solution.c │ │ ├── solution.cpp │ │ ├── solution.lua │ │ ├── solution.php │ │ ├── solution.py │ │ └── solution.rb │ ├── 039happynumbers │ │ ├── input │ │ ├── solution.cpp │ │ ├── solution.py │ │ └── solution.rb │ ├── 040selfdescribingnumbers │ │ ├── input │ │ ├── output │ │ └── solution.cpp │ ├── 062nmodm │ │ ├── input │ │ ├── solution.c │ │ ├── solution.cpp │ │ ├── solution.js │ │ ├── solution.lua │ │ ├── solution.php │ │ ├── solution.py │ │ └── solution.rb │ ├── 067hextodecimal │ │ ├── input │ │ ├── output │ │ ├── solution.cpp │ │ ├── solution.lua │ │ ├── solution.py │ │ └── solution.rb │ ├── 082armstrongnumbers │ │ ├── data │ │ └── solution.cpp │ ├── 083beautifulstrings │ │ ├── input │ │ ├── output │ │ ├── solution.c │ │ └── solution.cpp │ ├── 087queryboard │ │ ├── input │ │ └── solution.cpp │ ├── 091simplesorting │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 092penultimateword │ │ ├── data │ │ ├── solution.cpp │ │ └── solution.rb │ ├── 093capitalizewords │ │ ├── input │ │ ├── output │ │ └── solution.cpp │ ├── 096swapcase │ │ ├── README.md │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 097findawriter │ │ ├── input │ │ └── solution.cpp │ ├── 099calculatedistance │ │ ├── input │ │ ├── solution.cpp │ │ └── solution.lua │ ├── 100evennumbers │ │ ├── input │ │ ├── output │ │ ├── solution.hs │ │ └── solution.lua │ ├── 103lowestuniquenumber │ │ ├── input │ │ └── solution.cpp │ ├── 104wordtodigit │ │ ├── input │ │ ├── solution.cpp │ │ └── solution.rb │ ├── 106romannumerals │ │ ├── input │ │ └── solution.cpp │ ├── 111longestword │ │ ├── input │ │ ├── input2 │ │ └── solution.cpp │ ├── 112swapelements │ │ ├── input │ │ └── solution.cpp │ ├── 113multiplylists │ │ ├── input │ │ └── solution.cpp │ ├── 116morsecode │ │ ├── input │ │ └── solution.rb │ ├── 128compressedsequence │ │ ├── input │ │ └── solution.cpp │ ├── 139workingexperience │ │ ├── input │ │ └── solution.cpp │ ├── 147lettercasepercentageratio │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 156rollercoaster │ │ ├── input │ │ └── solution.cpp │ ├── 167readmore │ │ ├── input │ │ ├── solution.py │ │ └── solution.rb │ ├── 173withoutrepetitions │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 174slangflavor │ │ ├── input │ │ ├── output │ │ ├── solution.c │ │ ├── solution.cpp │ │ ├── solution.lua │ │ ├── solution.py │ │ └── solution.rb │ ├── 192comparepoints │ │ ├── input │ │ └── solution.cpp │ ├── 196swapnumbers │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 199stringmask │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ ├── 202stepwiseword │ │ ├── input │ │ └── solution.cpp │ ├── 203stringandarrows │ │ ├── input │ │ ├── solution.c │ │ ├── solution.cpp │ │ └── solution.lua │ ├── 205cleanupthewords │ │ ├── input │ │ └── solution.c │ ├── 208highestscore │ │ ├── data │ │ ├── solution.c │ │ └── solution.cpp │ ├── 225testing │ │ ├── input │ │ ├── solution.c │ │ └── solution.cpp │ └── 227realfake │ │ ├── input │ │ └── solution.cpp ├── hard │ ├── 014stringpermutations │ │ ├── README.md │ │ ├── input │ │ ├── output │ │ ├── solution.lua │ │ ├── solution.py │ │ └── solution.rb │ ├── 028stringsearch │ │ ├── README.md │ │ ├── input │ │ ├── solution.cpp │ │ ├── solution.lua │ │ └── solution.rb │ └── 110texttonumber │ │ ├── README.md │ │ ├── input │ │ └── solution.rb └── medium │ ├── 002longestlines │ ├── README.md │ ├── input │ ├── solution.c │ ├── solution.cpp │ ├── solution.js │ └── solution.py │ ├── 005detectingcycles │ ├── input │ └── solution.c │ ├── 009stackimplementation │ ├── input │ ├── solution.c │ └── solution.cpp │ ├── 010mthtolastelement │ ├── input │ ├── solution.c │ └── solution.cpp │ ├── 012firstnonrepeatedchar │ ├── input │ └── solution.cpp │ ├── 013removechars │ ├── README.md │ ├── input │ ├── solution.cpp │ ├── solution.js │ ├── solution.py │ └── solution.rb │ ├── 027decimaltobinary │ ├── input │ └── solution.cpp │ ├── 032trailingstring │ ├── input │ ├── input2 │ ├── solution.c │ └── solution.cpp │ ├── 035emailvalidation │ ├── input │ ├── input2 │ └── solution.py │ ├── 046primenumbers │ ├── README.md │ ├── input │ ├── solution.cpp │ ├── solution.js │ ├── solution.py │ └── solution.rb │ ├── 054cashregister │ ├── data │ └── solution.cpp │ ├── 074minimumcoins │ ├── input │ ├── solution.cpp │ ├── solution.py │ └── solution.rb │ ├── 097findawriter │ ├── README.md │ └── solution.cpp │ └── 193magicnumbers │ ├── input │ └── solution.cpp ├── exercism ├── README.md ├── c │ ├── all-your-base │ │ ├── README.md │ │ ├── src │ │ │ ├── all_your_base.c │ │ │ └── all_your_base.h │ │ └── test │ │ │ └── test_all_your_base.c │ ├── anagram │ │ ├── README.md │ │ ├── src │ │ │ ├── anagram.c │ │ │ └── anagram.h │ │ └── test │ │ │ └── test_anagram.c │ ├── atbash-cipher │ │ ├── README.md │ │ ├── src │ │ │ ├── atbash_cipher.c │ │ │ └── atbash_cipher.h │ │ └── test │ │ │ └── test_atbash_cipher.c │ ├── bob │ │ ├── README.md │ │ ├── src │ │ │ ├── bob.c │ │ │ └── bob.h │ │ └── test │ │ │ └── test_bob.c │ ├── hello-world │ │ ├── README.md │ │ ├── src │ │ │ ├── hello_world.c │ │ │ └── hello_world.h │ │ └── test │ │ │ └── test_hello_world.c │ ├── isogram │ │ ├── README.md │ │ ├── src │ │ │ ├── isogram.c │ │ │ └── isogram.h │ │ └── test │ │ │ └── test_isogram.c │ ├── leap │ │ ├── README.md │ │ ├── src │ │ │ ├── leap.c │ │ │ └── leap.h │ │ └── test │ │ │ └── test_leap.c │ ├── run-length-encoding │ │ ├── README.md │ │ ├── src │ │ │ ├── run_length_encoding.c │ │ │ └── run_length_encoding.h │ │ └── test │ │ │ └── test_run_length_encoding.c │ └── sum-of-multiples │ │ ├── README.md │ │ ├── src │ │ ├── sum_of_multiples.c │ │ └── sum_of_multiples.h │ │ └── test │ │ └── test_sum_of_multiples.c ├── elisp │ ├── anagram │ │ ├── README.md │ │ ├── anagram-test.el │ │ └── anagram.el │ ├── bob │ │ ├── README.md │ │ ├── bob-test.el │ │ └── bob.el │ ├── difference-of-squares │ │ ├── README.md │ │ ├── difference-of-squares-test.el │ │ └── difference-of-squares.el │ ├── gigasecond │ │ ├── README.md │ │ ├── gigasecond-test.el │ │ └── gigasecond.el │ ├── hamming │ │ ├── README.md │ │ ├── hamming-test.el │ │ └── hamming.el │ ├── hello-world │ │ ├── README.md │ │ ├── hello-world-test.el │ │ └── hello-world.el │ ├── leap │ │ ├── README.md │ │ ├── leap-test.el │ │ └── leap.el │ ├── pangram │ │ ├── README.md │ │ ├── pangram-test.el │ │ └── pangram.el │ ├── raindrops │ │ ├── README.md │ │ ├── raindrops-test.el │ │ └── raindrops.el │ ├── robot-name │ │ ├── README.md │ │ ├── robot-name-test.el │ │ └── robot-name.el │ └── word-count │ │ ├── README.md │ │ ├── word-count-test.el │ │ └── word-count.el ├── go │ ├── hello-world │ │ ├── README.md │ │ ├── hello_test.go │ │ └── hello_world.go │ └── leap │ │ ├── README.md │ │ ├── cases_test.go │ │ ├── leap.go │ │ └── leap_test.go ├── haskell │ └── anagram │ │ ├── README.md │ │ ├── package.yaml │ │ ├── src │ │ └── Anagram.hs │ │ ├── stack.yaml │ │ └── test │ │ └── Tests.hs ├── ruby │ └── difference-of-squares │ │ ├── .version │ │ ├── README.md │ │ ├── difference_of_squares.rb │ │ └── difference_of_squares_test.rb └── rust │ ├── beer-song │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── beer-song.rs │ ├── gigasecond │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── gigasecond.rs │ ├── hello-world │ ├── .gitignore │ ├── Cargo.toml │ ├── GETTING_STARTED.md │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── hello-world.rs │ ├── leap │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── leap.rs │ ├── nth-prime │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── nth-prime.rs │ ├── nucleotide-count │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── nucleotide-count.rs │ ├── raindrops │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── raindrops.rs │ ├── reverse-string │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ └── lib.rs │ └── tests │ │ └── reverse-string.rs │ └── sum-of-multiples │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── src │ └── lib.rs │ └── tests │ └── sum-of-multiples.rs ├── leetcode ├── 191-Number-of-1-Bits │ ├── README.md │ └── solution.c ├── 258-Add-Digits │ ├── README.md │ └── solution.c └── 344-Reverse-String │ ├── README.md │ └── solution.c ├── other ├── algorithms │ ├── basic_sorts │ │ └── solution.cpp │ ├── collatz │ │ └── solution.cpp │ ├── eratosthenes │ │ ├── solution.cpp │ │ └── solution.py │ └── selection_sort │ │ └── solution.cpp ├── numbers │ ├── change_return │ │ ├── solution.cpp │ │ └── solution.py │ ├── fibonacci │ │ ├── solution.cpp │ │ └── solution.py │ ├── happy_numbers │ │ ├── solution.cpp │ │ └── solution.py │ └── prime_factors │ │ └── solution.py └── text │ ├── fizzbuzz │ └── solution.py │ ├── piglatin │ └── solution.py │ └── reverse_string │ ├── solution.cpp │ ├── solution.java │ ├── solution.js │ ├── solution.lua │ ├── solution.php │ ├── solution.py │ ├── solution.rb │ └── solution.sh └── projecteuler ├── 001.lisp ├── 002.gvy ├── 003.cpp ├── 004.hs ├── 005.rs ├── 006.go ├── 007.lua ├── 008.php └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .exercism/ 2 | build/ 3 | vendor/ 4 | solution 5 | CMakeLists.txt 6 | Makefile 7 | 8 | .ccls-cache 9 | .cquery_cached_index 10 | *.o 11 | *.pyc 12 | *.out 13 | 14 | .stack-work 15 | *.cabal 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Practice Programming Projects 2 | Practical and prolific problems for programmers that I've patiently pondered and 3 | particularly puzzled over for personal pleasure and programming practice. 4 | 5 | Positively propitious! 6 | 7 | ## Sources 8 | * ~~[CodeEval](http://codeeval.com) ([profile](https://www.codeeval.com/profile/hlissner/))~~ (site shut down) 9 | * [LeetCode](http://leetcode.com) ([profile](https://leetcode.com/hlissner)) 10 | * [Exercism.io](http://exercism.io/) ([profile](http://exercism.io/hlissner)) 11 | * [Project Euler](https://projecteuler.net/) 12 | * https://github.com/karan/Projects 13 | * ["Algorithms, 4th Edition"](http://algs4.cs.princeton.edu/home/) 14 | * [Building Machine Learning Systems with Python](https://www.packtpub.com/big-data-and-business-intelligence/building-machine-learning-systems-python) 15 | -------------------------------------------------------------------------------- /codeeval/.project: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hlissner/practice/da82270546bcf9d65fbc358b1b11103d6f807ef5/codeeval/.project -------------------------------------------------------------------------------- /codeeval/easy/001fizzbuzz/input: -------------------------------------------------------------------------------- 1 | 15 20 49 2 | 7 2 62 3 | 7 15 91 4 | 17 11 27 5 | 19 2 36 6 | 14 2 63 7 | 20 6 30 8 | 15 18 55 9 | 1 7 73 10 | 14 6 87 11 | 11 12 69 12 | 13 11 53 13 | 11 6 81 14 | 6 6 42 15 | 9 1 37 16 | 4 15 37 17 | 11 1 59 18 | 3 3 67 19 | 4 14 53 20 | 2 18 79 21 | -------------------------------------------------------------------------------- /codeeval/easy/001fizzbuzz/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | int a, b; 9 | long long max; 10 | while (infile >> a >> b >> max) { 11 | for (int i = 1; i <= max; ++i) { 12 | if (i % a == 0) cout << "F"; 13 | if (i % b == 0) cout << "B"; 14 | if (i % a != 0 && i % b != 0) cout << i; 15 | cout << " "; 16 | } 17 | cout << endl; 18 | } 19 | 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/001fizzbuzz/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | for test in open(argv[1], "r"): 5 | if test.strip() == "": 6 | continue 7 | x, y, max = test.split(" ") 8 | for i in range(1, int(max) + 1): 9 | out = "" 10 | if i % int(x) == 0: 11 | out += "F" 12 | if i % int(y) == 0: 13 | out += "B" 14 | print(out or i, end=" ") 15 | print() 16 | -------------------------------------------------------------------------------- /codeeval/easy/001fizzbuzz/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.open(ARGV[0]).each_line do |line| 4 | next if line.strip.empty? 5 | 6 | x, y, max = line.split(" ").map { |n| n.to_i } 7 | puts (1..max).map { |n| 8 | out = "#{"F" if n % x == 0}#{"B" if n % y == 0}" 9 | "#{out.empty? ? n : out}" 10 | }.join(" ") 11 | end 12 | -------------------------------------------------------------------------------- /codeeval/easy/004sumofprimes/README.md: -------------------------------------------------------------------------------- 1 | # 004: Sum of primes 2 | 3 | > Source: https://www.codeeval.com/open_challenges/004/ 4 | 5 | Write a program which determines the sum of the first 1000 prime numbers. 6 | 7 | ## Input sample 8 | 9 | There is no input for this program. 10 | 11 | ## Output sample 12 | 13 | Print to stdout the sum of the first 1000 prime numbers. 14 | 15 | ``` 16 | 3682913 17 | ``` 18 | -------------------------------------------------------------------------------- /codeeval/easy/004sumofprimes/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int isprime(int n) { 5 | if (!(n&1)) return 0; 6 | for (int i = 3; i <= (int) sqrt(n); i += 2) { 7 | if (n % i == 0) 8 | return 0; 9 | } 10 | return 1; 11 | } 12 | 13 | const int primes(int n) { 14 | int sum = 2; 15 | for (int i = 3; n > 1; i += 2) { 16 | if (isprime(i)) { 17 | sum += i; 18 | --n; 19 | } 20 | } 21 | return sum; 22 | } 23 | 24 | int main(int argc, char *argv[]) { 25 | printf("%i\n", primes(1000)); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /codeeval/easy/004sumofprimes/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | from math import sqrt 5 | 6 | def isprime(n): 7 | if n & 1 == 0: 8 | return False 9 | for i in range(3, int(sqrt(n))+1, 2): 10 | if n % i == 0: 11 | return False 12 | return True 13 | 14 | def primes(n): 15 | sum = 2 16 | x = 3 17 | for i in range(n-1): 18 | sum += x 19 | x += 2 20 | while not isprime(x): 21 | x += 2 22 | return sum 23 | 24 | print(primes(1000)) 25 | -------------------------------------------------------------------------------- /codeeval/easy/004sumofprimes/solution.r: -------------------------------------------------------------------------------- 1 | 2 | isprime <- function(n) n <= 3L || all(n %% 2L:floor(sqrt(n)) != 0) 3 | 4 | primes <- function(n){ 5 | sum <- 1 6 | x <- -1 7 | for (i in 1:n) { 8 | repeat { 9 | x <- x + 2 10 | if (isprime(x)) { 11 | break 12 | } 13 | } 14 | sum <- sum + x 15 | } 16 | sum 17 | } 18 | 19 | cat(primes(1000)) 20 | # cat(primes(5)) 21 | -------------------------------------------------------------------------------- /codeeval/easy/004sumofprimes/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | def isprime(n) 4 | return false if n&1 == 0 5 | (3..Math.sqrt(n)).step(2) do |i| 6 | return false if n % i == 0 7 | end 8 | true 9 | end 10 | 11 | def primes(n) 12 | i = 1 13 | sum = 2 14 | x = 3 15 | until i >= n 16 | sum += x 17 | x += 2 18 | x += 2 until isprime(x) 19 | i += 1 20 | end 21 | sum 22 | end 23 | 24 | puts primes(1000) 25 | -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/README.md: -------------------------------------------------------------------------------- 1 | # 008: Reverse words 2 | 3 | > Source: https://www.codeeval.com/open_challenges/008/ 4 | 5 | Write a program which reverses the words in an input sentence. 6 | 7 | ## Input sample 8 | 9 | The first argument is a file that contains multiple sentences, one per line. Empty lines 10 | are also possible. 11 | 12 | ``` 13 | Hello World 14 | Hello CodeEval 15 | ``` 16 | 17 | ## Output sample 18 | 19 | Print to stdout each sentence with the reversed words in it, one per line. Empty lines in 20 | the input should be ignored. Ensure that there are no trailing empty spaces in each line 21 | you print. 22 | 23 | ``` 24 | World Hello 25 | CodeEval Hello 26 | ``` 27 | -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/input: -------------------------------------------------------------------------------- 1 | Hello World 2 | Hello CodeEval -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) { 5 | FILE *f = fopen(argv[1], "r"); 6 | char line[128]; 7 | while (fgets(line, 128, f)) { 8 | int end = strlen(line) - 1; 9 | int len = 1; 10 | for (int i = end; i >= 0; --i, ++len) { 11 | if (i == 0 || line[i-1] == ' ') { 12 | printf("%.*s ", 13 | // Make sure newlines aren't included 14 | (line[i + len-1] == '\n' ? len-1 : len), 15 | line + i); 16 | len = 0; 17 | --i; // skip whitespace 18 | } 19 | } 20 | printf("\n"); 21 | } 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | if (line.size() == 0) continue; 11 | 12 | auto y = line.end(); 13 | auto begin = line.begin(); 14 | while (begin != y && *begin == ' ') ++begin; 15 | if (begin == y) continue; 16 | 17 | while (*y == ' ') { --y; } 18 | auto x = line.end(); 19 | 20 | while (x != begin) { 21 | while (x != begin && *(x-1) != ' ') --x; 22 | bool atstart = x == begin; 23 | cout << string(x, y) << (atstart ? "" : " "); 24 | if (!atstart) { 25 | y = x-1; 26 | --x; 27 | } 28 | } 29 | cout << endl; 30 | } 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/solution.js: -------------------------------------------------------------------------------- 1 | console.log(require('fs').readFileSync(process.argv[2]).toString().split("\n").map( 2 | function(line) { 3 | return line.split(" ").reverse().join(" "); 4 | } 5 | ).join("\n")); 6 | -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/solution.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | for line in open(argv[1]): 4 | words = line.strip().split(" ") 5 | words.reverse() 6 | print(" ".join(words)) 7 | -------------------------------------------------------------------------------- /codeeval/easy/008reversewords/solution.rb: -------------------------------------------------------------------------------- 1 | File.open(ARGV[0]).each_line do |line| 2 | puts line.split.reverse.join(" ") 3 | end 4 | -------------------------------------------------------------------------------- /codeeval/easy/018multiplesofanumber/README.md: -------------------------------------------------------------------------------- 1 | # 018: Multiples of a number 2 | 3 | > Source: https://www.codeeval.com/open_challenges/018/ 4 | 5 | Given numbers x and n, where n is a power of 2, print out the smallest multiple 6 | of n which is greater than or equal to x. Do not use division or modulo 7 | operator. 8 | 9 | ## Input sample 10 | 11 | The first argument will be a path to a filename containing a comma separated 12 | list of two integers, one list per line. E.g. 13 | 14 | ``` 15 | 13,8 16 | 17,16 17 | ``` 18 | 19 | ## Output sample: 20 | 21 | Print to stdout, the smallest multiple of n which is greater than or equal to x, 22 | one per line. E.g. 23 | 24 | ``` 25 | 16 26 | 32 27 | ``` 28 | -------------------------------------------------------------------------------- /codeeval/easy/018multiplesofanumber/input: -------------------------------------------------------------------------------- 1 | 13,8 2 | 17,16 -------------------------------------------------------------------------------- /codeeval/easy/018multiplesofanumber/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *f = fopen(argv[1], "r"); 5 | char buf[128]; 6 | int n, x; 7 | while (fscanf(f, "%d,%d", &x, &n) == 2) { 8 | int i = n; 9 | while (i < x) i += n; 10 | printf("%d\n", i); 11 | } 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /codeeval/easy/018multiplesofanumber/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | int n, x; 10 | char _; 11 | while (infile >> x >> _ >> n) { 12 | int i = n; 13 | while (i < x) i += n; 14 | cout << i << endl; 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /codeeval/easy/018multiplesofanumber/solution.rb: -------------------------------------------------------------------------------- 1 | File.open(ARGV[0]).each_line do |line| 2 | x, n = line.strip.split(",").map { |n| n.to_i } 3 | i = n 4 | i += n until i >= x 5 | puts i 6 | end 7 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/README.md: -------------------------------------------------------------------------------- 1 | # 019: Bit positions 2 | 3 | > Source: https://www.codeeval.com/open_challenges/019/ 4 | 5 | Given a number n and two integers p1,p2 determine if the bits in position p1 and 6 | p2 are the same or not. Positions p1 and p2 are 1 based. 7 | 8 | ## Input sample: 9 | 10 | The first argument will be a path to a filename containing a comma separated 11 | list of 3 integers, one list per line. E.g. 12 | 13 | ``` 14 | 86,2,3 15 | 125,1,2 16 | ``` 17 | 18 | ##Output sample: 19 | 20 | Print to stdout, `true` (lowercase) if the bits are the same, else 21 | `false` (lowercase). E.g. 22 | 23 | ``` 24 | true 25 | false 26 | ``` 27 | 28 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/input: -------------------------------------------------------------------------------- 1 | 86,2,3 2 | 125,1,2 -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/output: -------------------------------------------------------------------------------- 1 | true 2 | false -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.bash: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Was not accepted by codeeval. "Unrecognized error" 4 | # Works in Bash 4.3.42 however 5 | 6 | while read line || [[ -n "$line" ]]; do 7 | arrIn=(${line//,/ }) 8 | n=${arrIn[0]} 9 | a=$(( ($n >> (${arrIn[1]} - 1)) & 1 )) 10 | b=$(( ($n >> (${arrIn[2]} - 1)) & 1 )) 11 | (( $a == $b )) && echo true || echo false 12 | done < $1 13 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "bufio" 5 | import "os" 6 | import "strings" 7 | import "strconv" 8 | 9 | func main() { 10 | file, _ := os.Open(os.Args[1]) 11 | scanner := bufio.NewScanner(file) 12 | for scanner.Scan() { 13 | s := strings.Split(scanner.Text(), ",") 14 | n, _ := strconv.ParseUint(s[0], 10, 16) 15 | i, _ := strconv.ParseUint(s[1], 10, 16) 16 | j, _ := strconv.ParseUint(s[2], 10, 16) 17 | 18 | if (n >> (i-1)) & 1 == (n >> (j-1)) & 1 { 19 | fmt.Println("true") 20 | } else { 21 | fmt.Println("false") 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var fs = require("fs"); 4 | fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { 5 | if (line !== "") { 6 | var input = line.split(","); 7 | var n = parseInt(input[0]), 8 | i = parseInt(input[1]), 9 | j = parseInt(input[2]); 10 | 11 | var a = (n >> (i-1)) & 1; 12 | var b = (n >> (j-1)) & 1; 13 | console.log(a == b ? "true" : "false"); 14 | } 15 | }); 16 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | n = {} 5 | for str in line:gmatch("([^,]+)") do 6 | table.insert(n, tonumber(str)) 7 | end 8 | 9 | if bit32.band(bit32.rshift(n[1], n[2]-1), 1) == bit32.band(bit32.rshift(n[1], n[3]-1), 1) then 10 | print("true") 11 | else 12 | print("false") 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | > ((int) $i-1)) & 1; 9 | $b = ($n >> ((int) $j-1)) & 1; 10 | echo (($a == $b) ? "true" : "false") . "\n"; 11 | } 12 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | bool = {True: 'true', False: 'false'} 6 | 7 | for line in open(argv[1], 'r'): 8 | n, i, j = map(int, line.strip().split(",")) 9 | print(bool[(n >> i - 1) & 1 == (n >> j - 1) & 1]) 10 | -------------------------------------------------------------------------------- /codeeval/easy/019bitpositions/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.foreach(ARGV[0]).each do |line| 4 | n,i,j = line.strip.split(",").map { |x| x.to_i } 5 | a = (n >> i-1) & 1 6 | b = (n >> j-1) & 1 7 | puts a == b ? "true" : "false" 8 | end 9 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/README.md: -------------------------------------------------------------------------------- 1 | # 020: Lowercase 2 | 3 | > Source: https://www.codeeval.com/open_challenges/020/ 4 | 5 | Given a string write a program to convert it into lowercase. 6 | 7 | ## Input sample 8 | 9 | The first argument will be a path to a filename containing sentences, one per 10 | line. You can assume all characters are from the english language. E.g. 11 | 12 | ``` 13 | HELLO CODEEVAL 14 | This is some text 15 | ``` 16 | 17 | ## Output sample 18 | 19 | Print to stdout, the lowercase version of the sentence, each on a new line. E.g. 20 | 21 | ``` 22 | hello codeeval 23 | this is some text 24 | ``` 25 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/input: -------------------------------------------------------------------------------- 1 | HELLO CODEEVAL 2 | This is some text 3 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | console.log(require('fs').readFileSync(process.argv[2]).toString().toLowerCase()); 4 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | with open(argv[1], 'r') as f: 5 | print(f.read().lower()) 6 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.open(ARGV[0]).each_line do |line| 4 | next if line.strip.empty? 5 | puts line.downcase 6 | end 7 | -------------------------------------------------------------------------------- /codeeval/easy/020lowercase/solution.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | for file in $@; do 4 | cat "$file" | tr '[:upper:]' '[:lower:]' 5 | done 6 | -------------------------------------------------------------------------------- /codeeval/easy/021sumofdigits/README.md: -------------------------------------------------------------------------------- 1 | # 021: Sum of digits 2 | 3 | > Source: https://www.codeeval.com/open_challenges/021/ 4 | 5 | Given a positive integer, find the sum of its constituent digits. 6 | 7 | ## Input sample 8 | 9 | The first argument will be a path to a filename containing positive integers, 10 | one per line. E.g. 11 | 12 | ``` 13 | 23 14 | 496 15 | ``` 16 | 17 | ## Output sample 18 | 19 | Print to stdout, the sum of the numbers that make up the integer, one per line. 20 | E.g. 21 | 22 | ``` 23 | 5 24 | 19 25 | ``` 26 | -------------------------------------------------------------------------------- /codeeval/easy/021sumofdigits/input: -------------------------------------------------------------------------------- 1 | 23 2 | 496 3 | -------------------------------------------------------------------------------- /codeeval/easy/021sumofdigits/solution.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | Source: https://www.codeeval.com/open_challenges/022/ 4 | 5 | The Fibonacci series is defined as: F(0) = 0; F(1) = 1; F(n) = F(n–1) + F(n–2) 6 | when n>1. Given an integer n≥0, print out the F(n). 7 | 8 | ## Input sample 9 | 10 | The first argument will be a path to a filename containing integer numbers, one 11 | per line. E.g. 12 | 13 | ``` 14 | 5 15 | 12 16 | ``` 17 | 18 | ## Output sample 19 | 20 | Print to stdout, the fibonacci number, F(n). E.g. 21 | 22 | ``` 23 | 5 24 | 144 25 | ``` 26 | 27 | -------------------------------------------------------------------------------- /codeeval/easy/022fibonacciseries/input: -------------------------------------------------------------------------------- 1 | 5 2 | 12 -------------------------------------------------------------------------------- /codeeval/easy/022fibonacciseries/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define FIBP sqrt(5) 5 | #define FIBP_A (1 + FIBP) / 2 6 | #define FIBP_B (1 - FIBP) / 2 7 | 8 | long long fib(int n) { 9 | return floor((pow(FIBP_A, n+1) - pow(FIBP_B, n+1)) / FIBP); 10 | } 11 | 12 | int main(int argc, char *argv[]) { 13 | FILE *f = fopen(argv[1], "r"); 14 | int i; 15 | while (fscanf(f, "%d", &i) == 1) { 16 | printf("%lld\n", fib(i-1)); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /codeeval/easy/022fibonacciseries/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define FIBP sqrt(5) 8 | #define FIBP_A (1 + FIBP) / 2 9 | #define FIBP_B (1 - FIBP) / 2 10 | 11 | long long fib(int n) { 12 | return floor((pow(FIBP_A, n+1) - pow(FIBP_B, n+1)) / FIBP); 13 | } 14 | 15 | int main(int argc, char *argv[]) { 16 | ifstream infile(argv[1]); 17 | long long i; 18 | while (infile >> i) 19 | cout << fib(i-1) << endl; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/024sumofintegersfromfile/input: -------------------------------------------------------------------------------- 1 | 5 2 | 12 3 | -------------------------------------------------------------------------------- /codeeval/easy/024sumofintegersfromfile/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | print(sum([int(x) for x in open(argv[1])])) 5 | -------------------------------------------------------------------------------- /codeeval/easy/024sumofintegersfromfile/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | puts File.open(ARGV.first).each_line.reduce(0) { |sum, x| sum += x.to_i } 4 | -------------------------------------------------------------------------------- /codeeval/easy/025oddnumbers/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | for (int i = 1; i <= 99; i += 2) 5 | printf("%d\n", i); 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /codeeval/easy/025oddnumbers/solution.js: -------------------------------------------------------------------------------- 1 | 2 | for (var i = 1; i <= 99; i += 2) 3 | console.log(i); 4 | -------------------------------------------------------------------------------- /codeeval/easy/025oddnumbers/solution.lua: -------------------------------------------------------------------------------- 1 | 2 | for i=1,99,2 do 3 | print(i) 4 | end 5 | -------------------------------------------------------------------------------- /codeeval/easy/025oddnumbers/solution.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | void print_bit(const int n) { 4 | if (n <= 0) return; 5 | print_bit(n / 2); 6 | printf("%d", n & 1); 7 | } 8 | 9 | int main(int argc, char *argv[]) { 10 | FILE *f = fopen(argv[1], "r"); 11 | int n; 12 | while (fscanf(f, "%d", &n) == 1) { 13 | if (n == 0) { 14 | printf("0\n"); 15 | } else { 16 | print_bit(n); 17 | printf("\n"); 18 | } 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/027decimaltobinary/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | int n; 10 | while (infile >> n) { 11 | if (n == 0) { 12 | cout << 0 << endl; 13 | } else { 14 | string out; 15 | out.reserve(32); 16 | while (n != 0) { 17 | int r = n % 2; 18 | out += r + '0'; 19 | n /= 2; 20 | } 21 | reverse(out.begin(), out.end()); 22 | cout << out << endl; 23 | } 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/input: -------------------------------------------------------------------------------- 1 | 1,1,1,2,2,3,3,4,4 2 | 2,3,4,5,5 -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/input2: -------------------------------------------------------------------------------- 1 | 1,1,1,2,2,3,3,4,4 2 | 2,3,4,5,5 3 | 2,3,8,1,2,3,9,10,12,14,15 4 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) { 5 | FILE *f = fopen(argv[1], "r"); 6 | char line[512]; 7 | while (fgets(line, 512, f)) { 8 | int n = 0, offset; 9 | int last = -1; 10 | short p = 0; 11 | char *lpt = line; 12 | while (sscanf(lpt, "%d%n", &n, &offset) == 1) { 13 | if (last == -1 || n != last) { 14 | printf(p ? ",%d" : "%d", n); 15 | p = 1; 16 | last = n; 17 | } 18 | lpt += offset + 1; 19 | } 20 | printf("\n"); 21 | memset(line, 0, strlen(line)); 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char *argv[]) { 6 | ifstream infile(argv[1]); 7 | string line; 8 | while (getline(infile, line)) { 9 | int n = 0; 10 | string::iterator start = line.begin(); 11 | string::iterator end = line.end(); 12 | for (auto it = line.end(); it != line.begin(); --it) { 13 | if (*it == ' ') { 14 | if (n == 0) { 15 | end = it; 16 | ++n; 17 | } else { 18 | start = it + 1; 19 | break; 20 | } 21 | } 22 | } 23 | cout << string(start, end) << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require("fs").readFileSync(file).toString().trim().split('\n').forEach(function(line) { 4 | if (line.trim() != "") { 5 | var set = line.split(",").filter(function (val, i, io) { return (i==io.indexOf(val)); }); 6 | set.sort(function (x, y) { return x - y; }); 7 | console.log(set.join(",")); 8 | } 9 | }); 10 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | for line in open(argv[1]): 6 | l = list(map(int, set(line.strip().split(",")))) 7 | l.sort() 8 | print(",".join(map(str, l))) 9 | -------------------------------------------------------------------------------- /codeeval/easy/029uniqueelements/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.open(ARGV[0]).each_line do |line| 4 | puts line.split(",").map { |x| x.to_i }.uniq.sort.join(",") 5 | end 6 | -------------------------------------------------------------------------------- /codeeval/easy/030setintersection/input: -------------------------------------------------------------------------------- 1 | 1,2,3,4;4,5,6 2 | 20,21,22;45,46,47 3 | 7,8,9;8,9,10,11,12 4 | 84,85,86,87,88;75,76,77,78,79 5 | 1,2,3,4;3,4,5,6 6 | 83,84,85,86,87,88,89,90,91,92,93;95,96,97,98,99,100,101,102,103,104,105,106,107 7 | -------------------------------------------------------------------------------- /codeeval/easy/030setintersection/input2: -------------------------------------------------------------------------------- 1 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 2 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 3 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 4 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 5 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 6 | 81,82,83,84,85,86;77,78,79,80,81,82,83,84,85,86,87,88,89 7 | -------------------------------------------------------------------------------- /codeeval/easy/030setintersection/output: -------------------------------------------------------------------------------- 1 | 4 2 | 3 | 8,9 -------------------------------------------------------------------------------- /codeeval/easy/030setintersection/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int add(char *str, int *arr) { 6 | int i = 0, n, offset; 7 | while (sscanf(str, "%d%n", &n, &offset) == 1) { 8 | arr[i] = n; 9 | str += offset + 1; 10 | ++i; 11 | } 12 | return i; 13 | } 14 | 15 | int main(int argc, char *argv[]) { 16 | FILE *f = fopen(argv[1], "r"); 17 | char line[128]; 18 | while (fgets(line, 128, f)) { 19 | if (line[0] == '\n') continue; 20 | 21 | int delim = 0; 22 | while (line[delim++] != ';'); 23 | line[delim-1] = '\0'; 24 | 25 | char lhs[128] = "", rhs[128] = ""; 26 | strcpy(lhs, line); 27 | strcpy(rhs, line + delim); 28 | 29 | int a[32] = {0}, b[32] = {0}; 30 | char *lp = lhs, *rp = rhs; 31 | int alen = add(lp, a), 32 | blen = add(rp, b); 33 | 34 | bool found = false; 35 | for (int i = 0; i < alen; ++i) { 36 | for (int j = 0; j < blen; ++j) { 37 | if (a[i] == b[j]) { 38 | printf(found ? ",%d" : "%d", b[j]); 39 | found = true; 40 | break; 41 | } 42 | } 43 | } 44 | printf("\n"); 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /codeeval/easy/030setintersection/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream stream(argv[1]); 10 | string line; 11 | while (getline(stream, line)) { 12 | vector a, b; 13 | vector *cur = &a; 14 | stringstream ss(line); 15 | 16 | // divvy up input into the two arrays 17 | short i; 18 | while (ss >> i) { 19 | cur->push_back(i); 20 | 21 | switch (ss.peek()) { 22 | case ';': cur = &b; 23 | case ',': ss.ignore(); 24 | } 25 | } 26 | 27 | vector result; 28 | 29 | // No need to sort, the input rules say it will always be presorted 30 | // You can use std::set_intersection, but that would be too easy: 31 | // 32 | // #include 33 | // set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(result)); 34 | 35 | for (size_t i = 0; i < a.size(); ++i) { 36 | for (size_t j = 0; j < b.size(); ++j) { 37 | if (a[i] == b[j]) { 38 | result.push_back(b[j]); 39 | break; 40 | } 41 | } 42 | } 43 | 44 | // Print it out 45 | for (size_t i = 0; i < result.size(); ++i) { 46 | if (i != 0) cout << ","; 47 | cout << result[i]; 48 | } 49 | cout << endl; 50 | } 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /codeeval/easy/031rightmostchar/input: -------------------------------------------------------------------------------- 1 | Hello World,r 2 | Hello CodeEval,E 3 | Hello CodeEval,r 4 | eZ4 J7GnAD1W3lthyKxJ35qa1WfftpgPNgSU7svxNcR5,w 5 | z wPRh6SMqPEJrYxvIClAHwc5ypKOmxmKMFB32qaw9mBrQkDVC2nGcwd4Z,H 6 | 0RMfTelhjSAxogOqdENS2ifK5XXw1ST79jg15dJBJAahIet4L9jHO2y3nFcYf6biGe7mzJa3gu9,l 7 | Mo8EbpDaOgvpPwE8MXDE0rsKsC4b,Y 8 | Are you there,z 9 | sAvGMITPzUZ nVTI4bQY1chaZ7DDcKZ0sazEmsw O9 Y8VdrqxTXbv9GFiObC20,R 10 | Hello CodeEval,E 11 | UHG5rN7npPXD2mCxeJPacSAGRz7dB2CBSzCyerVkWmrhFaajTgOy3Z,Y 12 | 8x6nDjW3bil6jA5ZzGurE32wZ4cO8SM9JdrljirCixW0H3S82U dJ7hm1NL0OCcWtE9i9 wBPz7,c 13 | O1vjXLrvcm1v66naVn9U,5 14 | Hello World,r 15 | What is your name,m 16 | t6EKldYNhUVhM2s6Yx ADLbUov2zw8cWie OHK2S7CU,S 17 | zhuPpuM6 hkvIHQCZAyBxS5dqLy5EHIUs,8 18 | How to learn to Cook,C 19 | cqUwX2F6erJEbLsWHHvNB0pLquHvDk rH6ffQU4fH9y,X 20 | QiMZXCHRFbcknZgSHf5dNXZENbT88y,H 21 | X5TOHWAwS6L9hlkOpfMJgFlNv4706Qxt1qJs gu2mz,z 22 | p2ZFq3o 3iHVcRD5 biK,3 23 | AdDKMlCjLuCRV 9FMIDQHH,S 24 | -------------------------------------------------------------------------------- /codeeval/easy/031rightmostchar/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(int argc, const char * argv[]) { 3 | FILE *file = fopen(argv[1], "r"); 4 | char buf[96], str[96], sub; 5 | int n; 6 | while (fgets(buf, sizeof buf, file) != NULL) { 7 | sscanf(buf, "%99[^,]%n,%c", str, &n, &sub); 8 | if (sub == '\n') { 9 | printf("-1\n"); 10 | continue; 11 | } 12 | int found = 0; 13 | for (int i = n; i >= 0 && !found; --i) { 14 | if (str[i] == sub) { 15 | printf("%i\n", i); 16 | found = 1; 17 | } 18 | } 19 | if (!found) printf("-1\n"); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codeeval/easy/031rightmostchar/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | unordered_map src; 11 | char sub; 12 | 13 | int i = 0; 14 | auto it = line.begin(); 15 | while (*it != ',') { 16 | src[*it] = i; 17 | ++it; 18 | ++i; 19 | } 20 | ++it; 21 | if (!(sub = *it)) { 22 | cout << -1 << endl; 23 | continue; 24 | } 25 | 26 | auto search = src.find(sub); 27 | if (search != src.end()) { 28 | cout << src[sub] << endl; 29 | } else { 30 | cout << -1 << endl; 31 | } 32 | } 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /codeeval/easy/031rightmostchar/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for l in io.lines(arg[1]) do 4 | txt, char = l:match("([^,]+),([^,]+)") 5 | print((txt:find(char .. "[^" .. char .. "]*$") or 0) - 1) 6 | end 7 | -------------------------------------------------------------------------------- /codeeval/easy/031rightmostchar/solution.php: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | const int MAX_TRIES = 100; 5 | 6 | int happy_proc(int n) { 7 | int sum = 0; 8 | while (n != 0) { 9 | int digit = n % 10; 10 | sum += digit * digit; 11 | n /= 10; 12 | } 13 | return sum; 14 | } 15 | 16 | bool is_happy(int n) { 17 | for (int i = 0; n != 1 && i < MAX_TRIES; ++i) 18 | n = happy_proc(n); 19 | return n == 1; 20 | } 21 | 22 | int main(int argc, char *argv[]) { 23 | std::ifstream infile(argv[1]); 24 | int i; 25 | while (infile >> i) { 26 | std::cout << (is_happy(i) ? 1 : 0) << std::endl; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /codeeval/easy/039happynumbers/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | def happy_proc(n): 6 | sum = 0 7 | for i in str(n): 8 | sum += int(i) ** 2 9 | return sum 10 | 11 | for line in open(argv[1]): 12 | limit = 30 13 | n = int(line) 14 | while (n != 1 and limit > 0): 15 | n = happy_proc(n) 16 | limit -= 1 17 | print("1" if n == 1 else "0") 18 | -------------------------------------------------------------------------------- /codeeval/easy/039happynumbers/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | def happy_proc(n) 4 | n.to_s.split("").reduce(0) { |sum, x| sum + x.to_i**2 } 5 | end 6 | 7 | File.open(ARGV[0]).each_line do |line| 8 | max = 30 9 | n = line.to_i 10 | until n == 1 or max <= 0 11 | n = happy_proc(n) 12 | max -= 1 13 | end 14 | puts n == 1 ? "1" : "0" 15 | end 16 | -------------------------------------------------------------------------------- /codeeval/easy/040selfdescribingnumbers/input: -------------------------------------------------------------------------------- 1 | 2020 2 | 22 3 | 1210 -------------------------------------------------------------------------------- /codeeval/easy/040selfdescribingnumbers/output: -------------------------------------------------------------------------------- 1 | 1 2 | 0 3 | 1 -------------------------------------------------------------------------------- /codeeval/easy/040selfdescribingnumbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream stream(argv[1]); 8 | string line; 9 | while (getline(stream, line)) { 10 | bool selfdesc = false; 11 | for (size_t i = 0; i < line.size(); ++i) { 12 | int n = (int) line[i] - '0'; 13 | int count = 0; 14 | for (size_t j = 0; j < line.size(); ++j) { 15 | if (line[j] - '0' == (int) i) ++count; 16 | } 17 | 18 | if (n != count) { 19 | selfdesc = false; 20 | break; 21 | } 22 | selfdesc = true; 23 | } 24 | cout << (selfdesc ? '1' : '0') << endl; 25 | } 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/input: -------------------------------------------------------------------------------- 1 | 20,6 2 | 2,3 3 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main(int argc, const char * argv[]) { 3 | FILE *file = fopen(argv[1], "r"); 4 | int x, y; 5 | while (fscanf(file, "%d,%d", &x,&y) == 2) 6 | printf("%d\n", x - y * (int) (x / y)); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char *argv[]) { 6 | ifstream infile(argv[1]); 7 | int x, y; 8 | char delim; 9 | while (infile >> x >> delim >> y) 10 | cout << (x - y * (int) (x / y)) << endl; 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require("fs").readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { 4 | if (line != "") { 5 | var input = line.split(","); 6 | console.log(input[0] % input[1]); 7 | } 8 | }); 9 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | n, m = line:match("([^,]+),([^,]+)") 5 | io.write(n - math.floor(n/m)*m .. '\n') 6 | end 7 | -------------------------------------------------------------------------------- /codeeval/easy/062nmodm/solution.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | short value(char c) { 8 | if (c >= 'a' && c <= 'f') { 9 | return (c - 'a') + 10; 10 | } else if (c >= '0' && c <= '9') { 11 | return c - '0'; 12 | } 13 | return 0; 14 | } 15 | 16 | int main(int argc, char *argv[]) { 17 | int pows[] = { 18 | 1, 19 | 16, 20 | 256, 21 | 4096, 22 | 65536, 23 | 1048576, 24 | 16777216 // 6 25 | }; 26 | 27 | ifstream infile(argv[1]); 28 | 29 | string str; 30 | while (infile >> str) { 31 | auto it = str.begin(); 32 | int len = str.length()-1; 33 | 34 | int n = 0; 35 | for (int i = 0; i <= len; ++i, ++it) { 36 | n += value(*it) * pows[len - i]; 37 | } 38 | 39 | cout << n << endl; 40 | } 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /codeeval/easy/067hextodecimal/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | print(tonumber(line, 16)) 5 | end 6 | -------------------------------------------------------------------------------- /codeeval/easy/067hextodecimal/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | for line in open(argv[1], 'r'): 5 | print(int(line, 16)) 6 | -------------------------------------------------------------------------------- /codeeval/easy/067hextodecimal/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.foreach(ARGV[0]).each do |line| 4 | puts line.to_i(16) 5 | end 6 | -------------------------------------------------------------------------------- /codeeval/easy/082armstrongnumbers/data: -------------------------------------------------------------------------------- 1 | 6 2 | 153 3 | 351 4 | -------------------------------------------------------------------------------- /codeeval/easy/082armstrongnumbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int anum(int x, int digits) { 8 | int sum = 0; 9 | while (x > 0) { 10 | sum += pow(floor(x % 10), digits); 11 | x /= 10; 12 | } 13 | return sum; 14 | } 15 | 16 | int main(int argc, char *argv[]) { 17 | ifstream infile(argv[1]); 18 | int n; 19 | while (infile >> n) { 20 | int y = anum(n, log10(n)+1); 21 | cout << (y == n ? "True" : "False") << endl; 22 | } 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /codeeval/easy/083beautifulstrings/input: -------------------------------------------------------------------------------- 1 | ABbCcc 2 | Good luck in the Facebook Hacker Cup this year! 3 | Ignore punctuation, please :) 4 | Sometimes test cases are hard to make up. 5 | So I just go consult Professor Dalves -------------------------------------------------------------------------------- /codeeval/easy/083beautifulstrings/output: -------------------------------------------------------------------------------- 1 | 152 2 | 754 3 | 491 4 | 729 5 | 646 -------------------------------------------------------------------------------- /codeeval/easy/083beautifulstrings/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int comp(const void *a, const void *b) { 7 | return (*(int*)b - *(int*)a); 8 | } 9 | 10 | int main(int argc, char *argv[]) { 11 | FILE *f = fopen(argv[1], "r"); 12 | char line[512]; 13 | while (fgets(line, 512, f)) { 14 | int occurrences[26] = {0}; 15 | 16 | int len = strlen(line); 17 | for (size_t i = 0; i < len; ++i) { 18 | if (isalpha(line[i])) { 19 | occurrences[tolower(line[i]) - 'a']++; 20 | } 21 | } 22 | 23 | qsort(occurrences, 26, sizeof(int), comp); 24 | 25 | int beauty = 0; 26 | int score = 26; 27 | for (size_t i = 0; i < 26; ++i) { 28 | if (occurrences[i] > 0) { 29 | beauty += score * occurrences[i]; 30 | --score; 31 | } 32 | } 33 | 34 | printf("%d\n", beauty); 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /codeeval/easy/083beautifulstrings/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream stream(argv[1]); 10 | string line; 11 | while (getline(stream, line)) { 12 | int occurrences[26] = {0}; 13 | 14 | for (size_t i = 0; i < line.size(); ++i) { 15 | if (isalpha(line[i])) { 16 | occurrences[tolower(line[i]) - 'a']++; 17 | } 18 | } 19 | 20 | sort(occurrences, occurrences + 26, std::greater()); 21 | 22 | int beauty = 0; 23 | int score = 26; 24 | for (size_t i = 0; i < 26; ++i) { 25 | if (occurrences[i] > 0) { 26 | beauty += score * occurrences[i]; 27 | --score; 28 | } 29 | } 30 | 31 | cout << beauty << endl; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /codeeval/easy/087queryboard/input: -------------------------------------------------------------------------------- 1 | SetCol 32 20 2 | SetRow 15 7 3 | SetRow 16 31 4 | QueryCol 32 5 | SetCol 2 14 6 | QueryRow 10 7 | SetCol 14 0 8 | QueryRow 15 9 | SetRow 10 1 10 | QueryCol 2 -------------------------------------------------------------------------------- /codeeval/easy/091simplesorting/input: -------------------------------------------------------------------------------- 1 | 70.920 -38.797 14.354 99.323 90.374 7.581 2 | -37.507 -3.263 40.079 27.999 65.213 -55.552 -------------------------------------------------------------------------------- /codeeval/easy/091simplesorting/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int comp(const void *a, const void *b) { 5 | return (*(float*)b < *(float*)a); 6 | } 7 | 8 | int main(int argc, char *argv[]) { 9 | FILE *f = fopen(argv[1], "r"); 10 | char line[256]; 11 | while (fgets(line, 256, f)) { 12 | float n, set[64]; 13 | int offset; 14 | 15 | int i = 0; 16 | char *lpt = line; 17 | while (sscanf(lpt, "%f%n", &n, &offset) == 1) { 18 | set[i++] = n; 19 | lpt += offset; 20 | } 21 | 22 | qsort(set, i, sizeof(float), comp); 23 | 24 | for (int j = 0; j < i; ++j) 25 | printf("%.3f ", set[j]); 26 | printf("\n"); 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /codeeval/easy/091simplesorting/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main(int argc, char *argv[]) { 10 | ifstream infile(argv[1]); 11 | string line; 12 | while (getline(infile, line)) { 13 | stringstream ss(line); 14 | float n; 15 | set set; 16 | while (ss >> n) set.insert(n); 17 | auto it = set.begin(); 18 | cout << fixed << setprecision(3) << *it; 19 | for (++it; it != set.end(); ++it) 20 | cout << setprecision(3) << " " << *it; 21 | cout << endl; 22 | } 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /codeeval/easy/092penultimateword/data: -------------------------------------------------------------------------------- 1 | some line with text 2 | another line 3 | -------------------------------------------------------------------------------- /codeeval/easy/092penultimateword/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char *argv[]) { 6 | ifstream infile(argv[1]); 7 | string line; 8 | while (getline(infile, line)) { 9 | int n = 0; 10 | string::iterator start = line.begin(); 11 | string::iterator end = line.end(); 12 | for (auto it = line.end(); it != line.begin(); --it) { 13 | if (*it == ' ') { 14 | if (n == 0) { 15 | end = it; 16 | ++n; 17 | } else { 18 | start = it + 1; 19 | break; 20 | } 21 | } 22 | } 23 | cout << string(start, end) << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/easy/092penultimateword/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | ARGV[0] = "/Users/hlissner/Desktop/data" 4 | 5 | File.open(ARGV[0]).each_line do |line| 6 | puts line.split(" ")[-2] 7 | end 8 | -------------------------------------------------------------------------------- /codeeval/easy/093capitalizewords/input: -------------------------------------------------------------------------------- 1 | Hello world 2 | javaScript language 3 | a letter 4 | 1st thing -------------------------------------------------------------------------------- /codeeval/easy/093capitalizewords/output: -------------------------------------------------------------------------------- 1 | Hello World 2 | JavaScript Language 3 | A Letter 4 | 1st Thing -------------------------------------------------------------------------------- /codeeval/easy/093capitalizewords/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream stream(argv[1]); 9 | string line; 10 | while (getline(stream, line)) { 11 | for (size_t i = 0; i < line.size(); ++i) { 12 | if (isalpha(line[i]) && (i == 0 || line[i-1] == ' ')) { 13 | line[i] = toupper(line[i]); 14 | } 15 | } 16 | cout << line << endl; 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /codeeval/easy/096swapcase/README.md: -------------------------------------------------------------------------------- 1 | # 096: Swap case 2 | 3 | > Source: https://www.codeeval.com/open_challenges/096/ 4 | 5 | Write a program which swaps letters' case in a sentence. All non-letter characters should 6 | remain the same. 7 | 8 | ## Input sample 9 | 10 | Your program should accept as its first argument a path to a filename. Input example is the following 11 | 12 | ``` 13 | Hello world! 14 | JavaScript language 1.8 15 | A letter 16 | ``` 17 | 18 | ## Output sample 19 | 20 | ``` 21 | hELLO WORLD! 22 | jAVAsCRIPT LANGUAGE 1.8 23 | a LETTER 24 | ``` 25 | -------------------------------------------------------------------------------- /codeeval/easy/096swapcase/input: -------------------------------------------------------------------------------- 1 | Hello world! 2 | JavaScript language 1.8 3 | A letter -------------------------------------------------------------------------------- /codeeval/easy/096swapcase/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | FILE *f = fopen(argv[1], "r"); 7 | char buf[64]; 8 | while (fgets(buf, 64, f)) { 9 | int len = strlen(buf); 10 | for (int i = 0; i < len; ++i) { 11 | char c = buf[i]; 12 | if (isalpha(c)) { 13 | buf[i] = isupper(c) ? tolower(c) : toupper(c); 14 | } 15 | } 16 | printf("%s", buf); 17 | } 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /codeeval/easy/096swapcase/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int, char *argv[]) { 8 | ifstream stream(argv[1]); 9 | string line; 10 | while (getline(stream, line)) { 11 | size_t size = line.size(); 12 | for (int i = 0; i < size; ++i) { 13 | char c = line[i]; 14 | if (isalpha(c)) { 15 | line[i] = isupper(c) ? tolower(c) : toupper(c); 16 | } 17 | } 18 | cout << line << endl; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/097findawriter/input: -------------------------------------------------------------------------------- 1 | osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA rLclpg| 3 35 27 62 51 27 46 57 26 10 46 63 57 45 15 43 53 2 | 3 | 3Kucdq9bfCEgZGF2nwx8UpzQJyHiOm0hoaYP6ST1WM7Nks5XjrR4IltBeDLV vA| 2 26 33 55 34 50 33 61 44 28 46 32 28 30 3 50 34 61 40 7 1 31 4 | -------------------------------------------------------------------------------- /codeeval/easy/097findawriter/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | if (line.size() == 0) continue; 12 | 13 | istringstream lhss(line); 14 | string str; 15 | 16 | if (getline(lhss, str, '|')) { 17 | int i; 18 | while (lhss >> i) { 19 | cout << str[i-1]; 20 | } 21 | cout << endl; 22 | } 23 | } 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/easy/099calculatedistance/input: -------------------------------------------------------------------------------- 1 | (25, 4) (1, -6) 2 | (47, 43) (-25, -11) -------------------------------------------------------------------------------- /codeeval/easy/099calculatedistance/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main(int argc, char *argv[]) { 10 | ifstream stream(argv[1]); 11 | string line; 12 | while (getline(stream, line)) { 13 | vector coords; 14 | stringstream ss(line); 15 | 16 | while (1) { 17 | short i; 18 | ss >> i; 19 | if (ss.eof() || ss.bad()) { 20 | break; 21 | } else if (ss.fail()) { 22 | ss.clear(); 23 | ss.ignore(); 24 | } else { 25 | coords.push_back(i); 26 | } 27 | } 28 | 29 | int x = coords[2] - coords[0], 30 | y = coords[3] - coords[1]; 31 | cout << sqrt((x * x) + (y * y)) << endl; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /codeeval/easy/099calculatedistance/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | ax, ay, bx, by = line:match("%(([^,]+), ([^,]+)%) %(([^,]+), ([^,]+)%)") 5 | 6 | x = tonumber(bx) - tonumber(ax) 7 | y = tonumber(by) - tonumber(ay) 8 | io.write(math.sqrt(x*x + y*y) .. '\n') 9 | end 10 | -------------------------------------------------------------------------------- /codeeval/easy/100evennumbers/input: -------------------------------------------------------------------------------- 1 | 701 2 | 4123 3 | 2936 -------------------------------------------------------------------------------- /codeeval/easy/100evennumbers/output: -------------------------------------------------------------------------------- 1 | 0 2 | 0 3 | 1 -------------------------------------------------------------------------------- /codeeval/easy/100evennumbers/solution.hs: -------------------------------------------------------------------------------- 1 | 2 | import Data.List 3 | 4 | main :: IO () 5 | main = putStrLn (intercalate "\n" [ show x | x <- [1,3..99] ]) 6 | -------------------------------------------------------------------------------- /codeeval/easy/100evennumbers/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | if bit32.band(tonumber(line), 1) == 0 then 5 | print(1) 6 | else 7 | print(0) 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /codeeval/easy/103lowestuniquenumber/input: -------------------------------------------------------------------------------- 1 | 3 3 9 1 6 5 8 1 5 3 2 | 9 2 9 9 1 8 8 8 2 1 1 3 | 2 5 2 7 4 4 4 6 4 7 2 6 6 3 4 7 7 4 | 9 8 9 1 3 9 5 2 3 8 7 6 1 4 6 5 | 4 4 2 4 8 9 1 9 6 7 2 3 4 3 3 9 6 | 5 6 4 3 6 4 3 7 6 8 7 7 | 8 7 4 6 3 5 4 5 6 9 9 9 2 5 2 3 8 1 9 8 | 7 8 3 7 4 1 6 3 8 8 6 9 2 6 9 | 9 1 9 7 5 9 1 3 7 6 6 1 6 10 | 5 4 3 6 1 4 2 6 1 5 2 8 7 6 2 2 11 | 7 9 9 7 4 9 5 4 3 4 7 12 | 7 5 8 2 4 6 8 2 9 1 2 1 2 1 5 1 9 1 2 13 | 3 8 3 9 5 7 5 5 8 3 1 2 3 1 14 | 2 4 8 4 8 3 8 8 5 1 2 5 1 9 6 3 15 | 8 3 1 4 9 5 5 1 2 1 5 7 9 7 2 4 6 3 16 | 3 7 2 6 4 6 5 6 4 4 17 | 2 6 4 2 2 7 8 2 8 2 4 1 8 4 7 7 5 7 18 | 6 9 4 5 8 3 5 9 3 2 4 7 3 8 8 9 19 | 8 5 1 4 4 5 9 5 4 4 9 1 3 8 20 | 9 4 2 6 6 3 9 1 2 8 1 5 1 7 21 | 7 1 5 8 6 6 8 8 8 4 8 4 1 3 22 | 4 8 6 1 1 4 2 1 8 6 2 3 7 6 2 23 | -------------------------------------------------------------------------------- /codeeval/easy/103lowestuniquenumber/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream infile(argv[1]); 10 | string line; 11 | while (getline(infile, line)) { 12 | deque num; 13 | 14 | int i; 15 | istringstream ss(line); 16 | while (ss >> i) { num.push_back(i); } 17 | 18 | int lowest = 0, winner = 0; 19 | for (i = 0; i < num.size(); ++i) { 20 | bool unique = true; 21 | for (int j = 0; j < num.size(); ++j) { 22 | if (j == i) continue; 23 | if (num[j] == num[i]) { 24 | unique = false; 25 | break; 26 | } 27 | } 28 | if (unique && (lowest == 0 || lowest > num[i])) { 29 | lowest = num[i]; 30 | winner = i+1; 31 | } 32 | } 33 | cout << winner << endl; 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /codeeval/easy/104wordtodigit/input: -------------------------------------------------------------------------------- 1 | zero;two;five;seven;eight;four 2 | three;seven;eight;nine;two -------------------------------------------------------------------------------- /codeeval/easy/104wordtodigit/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | unordered_map prefix = { 9 | {"nine" , 9}, 10 | {"eight", 8}, 11 | {"seven", 7}, 12 | {"six" , 6}, 13 | {"five" , 5}, 14 | {"four" , 4}, 15 | {"three", 3}, 16 | {"two" , 2}, 17 | {"one" , 1}, 18 | {"zero" , 0} 19 | }; 20 | 21 | int main(int argc, char *argv[]) { 22 | ifstream infile(argv[1]); 23 | string line; 24 | while (getline(infile, line)) { 25 | if (line.size() == 0) continue; 26 | 27 | istringstream ss(line); 28 | string str; 29 | while (getline(ss, str, ';')) { 30 | cout << prefix[str]; 31 | } 32 | cout << endl; 33 | } 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /codeeval/easy/104wordtodigit/solution.rb: -------------------------------------------------------------------------------- 1 | PREFIXES = { 2 | 'nine' => 9, 3 | 'eight' => 8, 4 | 'seven' => 7, 5 | 'six' => 6, 6 | 'five' => 5, 7 | 'four' => 4, 8 | 'three' => 3, 9 | 'two' => 2, 10 | 'one' => 1, 11 | 'zero' => 0 12 | } 13 | 14 | File.open(ARGV[0]).each_line do |line| 15 | puts line.strip.split(";").map { |n| PREFIXES[n] }.join("") 16 | end 17 | -------------------------------------------------------------------------------- /codeeval/easy/106romannumerals/input: -------------------------------------------------------------------------------- 1 | 159 2 | 296 3 | 3992 -------------------------------------------------------------------------------- /codeeval/easy/106romannumerals/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int div(int *n, int value) { 9 | if (*n > value) { 10 | int m = floor(*n / value); 11 | *n %= value; 12 | cout << *n << " "; 13 | return m; 14 | } 15 | return 0; 16 | } 17 | 18 | int main(int argc, char *argv[]) { 19 | deque> roman = { 20 | {'M', 1000}, 21 | {'D', 500}, 22 | {'C', 100}, 23 | {'L', 50}, 24 | {'X', 10}, 25 | {'V', 5}, 26 | {'I', 1} 27 | }; 28 | 29 | ifstream infile(argv[1]); 30 | int n; 31 | while (infile >> n) { 32 | for (const auto kv : roman) { 33 | cout << kv.first << ' '; 34 | } 35 | cout << endl; 36 | int m = div(&n, 1000), 37 | d = div(&n, 500), 38 | c = div(&n, 100), 39 | l = div(&n, 50), 40 | x = div(&n, 10), 41 | v = div(&n, 5), 42 | i = div(&n, 1); 43 | 44 | cout << n << endl; 45 | } 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /codeeval/easy/111longestword/input: -------------------------------------------------------------------------------- 1 | some line with text 2 | another line -------------------------------------------------------------------------------- /codeeval/easy/111longestword/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | istringstream ss(line); 12 | string word, longest; 13 | while (getline(ss, word, ' ')) { 14 | if (word.size() > longest.size()) longest = word; 15 | } 16 | cout << longest << endl; 17 | } 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /codeeval/easy/112swapelements/input: -------------------------------------------------------------------------------- 1 | 1 2 3 4 5 6 7 8 9 : 0-8 2 | 1 2 3 4 5 6 7 8 9 10 : 0-1, 1-3 3 | -------------------------------------------------------------------------------- /codeeval/easy/112swapelements/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream infile(argv[1]); 10 | string line; 11 | while (getline(infile, line)) { 12 | auto it = line.begin(); 13 | while (*it != ':') { ++it; } 14 | 15 | string lhs(line.begin(), it-1); 16 | string rhs(it+2, line.end()); 17 | 18 | istringstream lhss(lhs); 19 | vector num; 20 | int i; 21 | while (lhss >> i) { 22 | num.push_back(i); 23 | } 24 | 25 | istringstream rhss(rhs); 26 | char sep; 27 | int x, y; 28 | while (rhss >> x >> sep >> y) { 29 | std::swap(num[x], num[y]); 30 | if (rhss.peek() == ',') rhss.ignore(); 31 | } 32 | 33 | // Display results 34 | for (int i = 0; i < (int) num.size(); ++i) { 35 | cout << num[i] << ' '; 36 | } 37 | cout << endl; 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /codeeval/easy/113multiplylists/input: -------------------------------------------------------------------------------- 1 | 9 0 6 | 15 14 9 2 | 5 | 8 3 | 13 4 15 1 15 5 | 1 4 15 14 8 2 -------------------------------------------------------------------------------- /codeeval/easy/113multiplylists/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | string::size_type n = line.find('|'); 12 | string lhs = line.substr(0, n-1); 13 | string rhs = line.substr(n+2, line.size()); 14 | 15 | istringstream lhss(lhs); 16 | istringstream rhss(rhs); 17 | int x, y; 18 | while (lhss >> x && rhss >> y) { 19 | cout << (x * y) << ' '; 20 | } 21 | cout << endl; 22 | } 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /codeeval/easy/116morsecode/input: -------------------------------------------------------------------------------- 1 | .- ...- ..--- .-- .... .. . -.-. -..- ....- ..... 2 | -... .... ...-- -------------------------------------------------------------------------------- /codeeval/easy/116morsecode/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | MORSE = { 4 | '' => ' ', 5 | '.-' => 'A', 6 | '-...' => 'B', 7 | '-.-.' => 'C', 8 | '-..' => 'D', 9 | '.' => 'E', 10 | '..-.' => 'F', 11 | '--.' => 'G', 12 | '....' => 'H', 13 | '..' => 'I', 14 | '.---' => 'J', 15 | '-.-' => 'K', 16 | '.-..' => 'L', 17 | '--' => 'M', 18 | '-.' => 'N', 19 | '---' => 'O', 20 | '.--.' => 'P', 21 | '--.-' => 'Q', 22 | '.-.' => 'R', 23 | '...' => 'S', 24 | '-' => 'T', 25 | '..-' => 'U', 26 | '...-' => 'V', 27 | '.--' => 'W', 28 | '-..-' => 'X', 29 | '-.--' => 'Y', 30 | '--..' => 'Z', 31 | 32 | '.----' => '1', 33 | '..---' => '2', 34 | '...--' => '3', 35 | '....-' => '4', 36 | '.....' => '5', 37 | '-....' => '6', 38 | '--...' => '7', 39 | '---..' => '8', 40 | '----.' => '9', 41 | '-----' => '0' 42 | } 43 | 44 | File.open(ARGV[0]).each_line do |line| 45 | next if line.strip.empty? 46 | puts line.strip.split(/ /).map{ |code| MORSE[code] }.join("") 47 | end 48 | -------------------------------------------------------------------------------- /codeeval/easy/128compressedsequence/input: -------------------------------------------------------------------------------- 1 | 40 40 40 40 29 29 29 29 29 29 29 29 57 57 92 92 92 92 92 86 86 86 86 86 86 86 86 86 86 2 | 73 73 73 73 41 41 41 41 41 41 41 41 41 41 3 | 1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2 4 | 7 -------------------------------------------------------------------------------- /codeeval/easy/128compressedsequence/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | istringstream ss(line); 12 | 13 | int n, last = -1, count = 0; 14 | while (ss >> n) { 15 | if (last != -1 && last != n) { 16 | cout << count << ' ' << last << ' '; 17 | count = 0; 18 | } 19 | ++count; 20 | last = n; 21 | } 22 | cout << count << ' ' << last << ' '; 23 | cout << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/easy/139workingexperience/input: -------------------------------------------------------------------------------- 1 | Feb 2004-Dec 2009; Sep 2004-Jul 2008 2 | Aug 2013-Mar 2014; Apr 2013-Aug 2013; Jun 2014-Aug 2015; Apr 2003-Nov 2004; Apr 2014-Jan 2015 3 | Mar 2003-Jul 2003; Nov 2003-Jan 2004; Apr 1999-Nov 1999 4 | Apr 1992-Dec 1993; Feb 1996-Sep 1997; Jan 2002-Jun 2002; Sep 2003-Apr 2004; Feb 2010-Nov 2011 5 | Feb 2004-May 2004; Jun 2004-Jul 2004 -------------------------------------------------------------------------------- /codeeval/easy/139workingexperience/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | map months = { 10 | {"Jan", 0}, 11 | {"Feb", 1}, 12 | {"Mar", 2}, 13 | {"Apr", 3}, 14 | {"May", 4}, 15 | {"Jun", 5}, 16 | {"Jul", 6}, 17 | {"Aug", 7}, 18 | {"Sep", 8}, 19 | {"Oct", 9}, 20 | {"Nov", 10}, 21 | {"Dec", 11} 22 | }; 23 | 24 | struct Date { 25 | short month; 26 | int year; 27 | 28 | Date(string str) { 29 | istringstream ss(str); 30 | string month; 31 | ss >> month; 32 | ss >> this->year; 33 | 34 | this->month = months[month]; 35 | } 36 | }; 37 | 38 | int main(int, char *argv[]) { 39 | ifstream infile(argv[1]); 40 | string line; 41 | while (getline(infile, line)) { 42 | istringstream ss(line); 43 | 44 | string date; 45 | int months = 0; 46 | while (getline(ss, date, ';')) { 47 | ss.ignore(); // ignore whitespace 48 | 49 | istringstream dss(date); 50 | 51 | string str; 52 | getline(dss, str, '-'); 53 | Date from(str); 54 | 55 | getline(dss, str, '\n'); 56 | Date to(str); 57 | 58 | months += (abs(to.year - from.year) * 12) + (to.month - from.month); 59 | } 60 | 61 | cout << floor(months / 12) << endl; 62 | } 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /codeeval/easy/147lettercasepercentageratio/input: -------------------------------------------------------------------------------- 1 | thisTHIS 2 | AAbbCCDDEE 3 | N 4 | UkJ -------------------------------------------------------------------------------- /codeeval/easy/147lettercasepercentageratio/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | FILE *f = fopen(argv[1], "r"); 7 | char line[64]; 8 | while (fgets(line, 64, f)) { 9 | double up = 0, down = 0; 10 | int size = strlen(line); 11 | for (int i = 0; i < size; ++i) { 12 | if (line[i] >= 'a' && line[i] <= 'z') { 13 | ++down; 14 | } else if (line[i] >= 'A' && line[i] <= 'Z') { 15 | ++up; 16 | } 17 | } 18 | if (line[size-1] == '\n') 19 | --size; 20 | 21 | float downp = (down / size) * 100; 22 | float upp = (up / size) * 100; 23 | 24 | printf("lowercase: %.2f uppercase: %.2f\n", downp, upp); 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /codeeval/easy/147lettercasepercentageratio/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | float up = 0, down = 0; 12 | int size = line.size(); 13 | for (int i = 0; i < size; ++i) { 14 | if (line[i] >= 'a' && line[i] <= 'z') { 15 | ++down; 16 | } else if (line[i] >= 'A' && line[i] <= 'Z') { 17 | ++up; 18 | } 19 | } 20 | 21 | float downp = (down / size) * 100; 22 | float upp = (up / size) * 100; 23 | 24 | cout << setprecision(2) << fixed 25 | << "lowercase: " << downp 26 | << " uppercase: " << upp 27 | << endl;; 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /codeeval/easy/156rollercoaster/input: -------------------------------------------------------------------------------- 1 | To be, or not to be: that is the question. 2 | Whether 'tis nobler in the mind to suffer. 3 | The slings and arrows of outrageous fortune. 4 | Or to take arms against a sea of troubles. 5 | And by opposing end them, to die: to sleep. -------------------------------------------------------------------------------- /codeeval/easy/156rollercoaster/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | int size = line.size(); 12 | bool up = true; 13 | for (int i = 0; i < size; ++i) { 14 | if (!isalpha(line[i])) continue; 15 | if (up) line[i] = toupper(line[i]); 16 | up = !up; 17 | } 18 | cout << line << endl; 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/167readmore/input: -------------------------------------------------------------------------------- 1 | Tom exhibited. 2 | Amy Lawrence was proud and glad, and she tried to make Tom see it in her face - but he wouldn't look. 3 | Tom was tugging at a button-hole and looking sheepish. 4 | Two thousand verses is a great many - very, very great many. 5 | Tom's mouth watered for the apple, but he stuck to his work. 6 | Tom's mouth watered four the apple, but he stuck to his work. 7 | 123456789A123456789B123456789C123456789D123456789E123456 8 | -------------------------------------------------------------------------------- /codeeval/easy/167readmore/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | argv = [None, "/Users/hlissner/Desktop/data"] 6 | 7 | for line in open(argv[1]): 8 | line = line.strip() 9 | if len(line) > 55: 10 | line = line[0:40] 11 | lsi = line.rfind(" ") 12 | if lsi != -1: 13 | line = line[0:lsi+1] 14 | line = line.strip() 15 | line += "... " 16 | print(line) 17 | -------------------------------------------------------------------------------- /codeeval/easy/167readmore/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | File.foreach(ARGV.first) do |line| 4 | line = line.strip() 5 | if line.size <= 55 6 | puts line 7 | else 8 | line = line[0,40] 9 | lsi = line.rindex(" ") 10 | line = line[0,lsi] if lsi 11 | puts "#{line}... " 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /codeeval/easy/173withoutrepetitions/input: -------------------------------------------------------------------------------- 1 | But as he spake he drew the good sword from its scabbard, and smote a heathen knight, Jusssstin of thee Iron Valley. 2 | No matttter whom you choose, she deccccclared, I will abide by your decision. 3 | Wwwhat is your will? 4 | At his magic speech the ground oppened and he began the path of descent. 5 | I should fly away and you would never see me again. -------------------------------------------------------------------------------- /codeeval/easy/173withoutrepetitions/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *f = fopen(argv[1], "r"); 5 | char line[1024]; 6 | while (fgets(line, 1024, f)) { 7 | if (line[0] == '\0') continue; 8 | 9 | char last = line[0]; 10 | printf("%c", line[0]); 11 | for (int i = 1; line[i] != '\0'; ++i) { 12 | if (line[i] != last) { 13 | last = line[i]; 14 | printf("%c", last); 15 | } 16 | } 17 | printf("\n"); 18 | } 19 | return 0; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /codeeval/easy/173withoutrepetitions/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int main(int argc, char *argv[]) { 6 | ifstream infile(argv[1]); 7 | string line; 8 | while (getline(infile, line)) { 9 | if (line[0] == '\0') continue; 10 | 11 | char last = line[0]; 12 | cout << line[0]; 13 | for (int i = 1; line[i] != '\0'; ++i) { 14 | if (line[i] != last) { 15 | last = line[i]; 16 | cout << last; 17 | } 18 | } 19 | cout << endl; 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/output: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet. Mea et habeo doming praesent, yeah! Te inani utroque recteque has, sea ne fugit verterem! 2 | Usu ei scripta phaedrum, an sed salutatus definiebas, this is crazy, I tell ya. Qui ut recteque gloriatur reformidans. Qui solum aeque sapientem cu, can U believe this? 3 | Eu nam nusquam quaestio principes. -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const char slang[][32] = { 5 | ", yeah!", 6 | ", this is crazy, I tell ya.", 7 | ", can U believe this?", 8 | ", eh?", 9 | ", aw yea.", 10 | ", yo.", 11 | "? No way!", 12 | ". Awesome!" 13 | }; 14 | 15 | int main(int argc, char *argv[]) { 16 | FILE *file = fopen(argv[1], "r"); 17 | 18 | short slang_id = 0; 19 | short other = 0; 20 | 21 | char buf[128]; 22 | char c; 23 | while (fgets(buf, sizeof buf, file) != NULL) { 24 | for (int i = 0; i < (int) strlen(buf); ++i) { 25 | c = buf[i]; 26 | if (c == '.' || c == '?' || c == '!') { 27 | if (other) { 28 | printf("%s", slang[slang_id++]); 29 | if (slang_id > 7) { 30 | slang_id = 0; 31 | } 32 | } else { 33 | putchar(c); 34 | } 35 | other = !other; 36 | } else { 37 | putchar(c); 38 | } 39 | } 40 | } 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const string slang[] = { 7 | ", yeah!", 8 | ", this is crazy, I tell ya.", 9 | ", can U believe this?", 10 | ", eh?", 11 | ", aw yea.", 12 | ", yo.", 13 | "? No way!", 14 | ". Awesome!" 15 | }; 16 | 17 | int main(int argc, char *argv[]) { 18 | ifstream file(argv[1]); 19 | 20 | short slang_id = 0; 21 | bool other = false; 22 | string line; 23 | while (getline(file, line)) { 24 | auto it = line.begin(); 25 | auto end = line.end(); 26 | while (it != end) { 27 | char c = *it; 28 | if (c == '.' || c == '?' || c == '!') { 29 | if (other) { 30 | cout << slang[slang_id++]; 31 | if (slang_id > 7) { 32 | slang_id = 0; 33 | } 34 | } else { 35 | cout << c; 36 | } 37 | other = !other; 38 | } else { 39 | cout << c; 40 | } 41 | ++it; 42 | } 43 | cout << endl; 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | SLANG = { 4 | ", yeah!", 5 | ", this is crazy, I tell ya.", 6 | ", can U believe this?", 7 | ", eh?", 8 | ", aw yea.", 9 | ", yo.", 10 | "? No way!", 11 | ". Awesome!" 12 | } 13 | 14 | slang_id = 0 15 | other = false 16 | for line in io.lines(arg[1]) do 17 | for c in line:gmatch"." do 18 | if c == '.' or c == '?' or c == '!' then 19 | if other then 20 | io.write(SLANG[math.fmod(slang_id, 8) + 1]) 21 | slang_id = slang_id + 1 22 | else 23 | io.write(c) 24 | end 25 | other = not other 26 | else 27 | io.write(c) 28 | end 29 | end 30 | io.write("\n") 31 | end 32 | -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv, stdout 4 | 5 | SLANG = [ 6 | ", yeah!", 7 | ", this is crazy, I tell ya.", 8 | ", can U believe this?", 9 | ", eh?", 10 | ", aw yea.", 11 | ", yo.", 12 | "? No way!", 13 | ". Awesome!" 14 | ] 15 | 16 | slang_id = 0 17 | other = False 18 | for line in open(argv[1], "r"): 19 | for c in line: 20 | if c in '.?!': 21 | if other: 22 | stdout.write(SLANG[slang_id % 8]) 23 | slang_id += 1 24 | else: 25 | stdout.write(c) 26 | other = not other 27 | else: 28 | stdout.write(c) 29 | 30 | -------------------------------------------------------------------------------- /codeeval/easy/174slangflavor/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | ARGV[0] = "/Users/hlissner/tmp/data" 4 | 5 | slang = [ 6 | ', yeah!', 7 | ', this is crazy, I tell ya.', 8 | ', can U believe this?', 9 | ', eh?', 10 | ', aw yea.', 11 | ', yo.', 12 | '? No way!', 13 | '. Awesome!' 14 | ] 15 | 16 | i = 0 17 | n = -1 18 | ss = slang.size 19 | puts File.read(ARGV.first).gsub(/[.!?]/) { |match| 20 | n += 1 21 | if (n&1).zero? 22 | match 23 | else 24 | i += 1 25 | slang[(i-1) % ss] 26 | end 27 | }.to_s 28 | -------------------------------------------------------------------------------- /codeeval/easy/192comparepoints/input: -------------------------------------------------------------------------------- 1 | 0 0 1 5 2 | 12 13 12 13 3 | 0 1 0 5 -------------------------------------------------------------------------------- /codeeval/easy/192comparepoints/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | istringstream ss(line); 12 | 13 | int o, p; 14 | int q, r; 15 | ss >> o >> p; 16 | ss >> q >> r; 17 | 18 | int x = q - o, 19 | y = r - p; 20 | 21 | if (x == 0 && y == 0) { 22 | cout << "here"; 23 | } else { 24 | if (y > 0) cout << 'N'; 25 | else if (y < 0) cout << 'S'; 26 | if (x > 0) cout << 'E'; 27 | else if (x < 0) cout << 'W'; 28 | } 29 | cout << endl; 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /codeeval/easy/196swapnumbers/input: -------------------------------------------------------------------------------- 1 | 4Always0 5look8 4on9 7the2 4bright8 9side7 3of8 5life5 2 | 5Nobody5 7expects3 5the4 6Spanish4 9inquisition0 -------------------------------------------------------------------------------- /codeeval/easy/196swapnumbers/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, const char * argv[]) { 4 | FILE *file = fopen(argv[1], "r"); 5 | char line[256]; 6 | while (fgets(line, 256, file)) { 7 | int i = 0, j = 0; 8 | while (line[j] != '\0' && line[j] != '\n') { 9 | while (line[j] != ' ' && line[j] != '\0' && line[j] != '\n' && j < 256) { ++j; } 10 | char c = line[i]; 11 | line[i] = line[j-1]; 12 | line[j-1] = c; 13 | i = j+1; 14 | ++j; 15 | } 16 | 17 | printf("%s", line); 18 | } 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /codeeval/easy/196swapnumbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | istringstream ss(line); 12 | string word; 13 | while (getline(ss, word, ' ')) { 14 | int end = word.size()-1; 15 | char tmp = word[0]; 16 | word[0] = word[end]; 17 | word[end] = tmp; 18 | 19 | cout << word << ' '; 20 | } 21 | cout << endl; 22 | } 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /codeeval/easy/199stringmask/input: -------------------------------------------------------------------------------- 1 | hello 11001 2 | world 10000 3 | cba 111 -------------------------------------------------------------------------------- /codeeval/easy/199stringmask/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, const char * argv[]) { 5 | FILE *file = fopen(argv[1], "r"); 6 | char line[48]; 7 | while (fgets(line, 48, file)) { 8 | int i = 0, j = 0, end; 9 | while (line[j] != ' ') ++j; 10 | end = j; 11 | ++j; 12 | 13 | for (int i = 0; line[i] != '\0'; ++i, ++j) { 14 | if (line[j] == '1') 15 | line[i] = toupper(line[i]); 16 | } 17 | 18 | printf("%.*s\n", end, line); 19 | } 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /codeeval/easy/199stringmask/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string str; 10 | while (getline(infile, str, ' ')) { 11 | string mask; 12 | getline(infile, mask, '\n'); 13 | 14 | for (int i = 0; i < str.size(); ++i) { 15 | if (mask[i] == '1') 16 | str[i] = toupper(str[i]); 17 | } 18 | cout << str << endl; 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codeeval/easy/202stepwiseword/input: -------------------------------------------------------------------------------- 1 | cat dog hello 2 | stop football play 3 | music is my life -------------------------------------------------------------------------------- /codeeval/easy/202stepwiseword/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | istringstream ss(line); 12 | string word; 13 | string longest; 14 | while (getline(ss, word, ' ')) { 15 | if (word.size() > longest.size()) { 16 | longest = word; 17 | } 18 | } 19 | 20 | for (int i = 0; i < longest.size(); ++i) { 21 | for (int j = 0; j != i; ++j) { 22 | cout << '*'; 23 | } 24 | cout << longest[i] << ' '; 25 | } 26 | 27 | cout << endl; 28 | } 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /codeeval/easy/203stringandarrows/input: -------------------------------------------------------------------------------- 1 | <--<<--<<----- 2 | <<>>--><--<<--<<>>>-->< 3 | <-->> 4 | -------------------------------------------------------------------------------- /codeeval/easy/203stringandarrows/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAXLEN 192 4 | 5 | int main(int argc, char *argv[]) { 6 | FILE *file = fopen(argv[1], "r"); 7 | 8 | char buf[MAXLEN]; 9 | while(fgets(buf, sizeof buf, file) != NULL) { 10 | int arrows = 0; 11 | for (int i = 0; i < (MAXLEN-5) && buf[i] != '\0'; ++i) { 12 | char c = buf[i]; 13 | if ((c == '<' && buf[i+1] == '-' && buf[i+2] == '-' && buf[i+3] == c && buf[i+4] == c) 14 | || (c == '>' && buf[i+1] == c && buf[i+2] == '-' && buf[i+3] == '-' && buf[i+4] == c)) { 15 | ++arrows; 16 | } 17 | } 18 | printf("%d\n", arrows); 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codeeval/easy/203stringandarrows/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | int arrows = 0; 11 | int strlen = line.size(); 12 | for (int i = 0; i < strlen; ++i) { 13 | if (line[i] == '<' && i+5 <= strlen && line.substr(i, 5) == "<--<<") { 14 | ++arrows; 15 | } 16 | if (line[i] == '>' && i+5 <= strlen && line.substr(i, 5) == ">>-->") { 17 | ++arrows; 18 | } 19 | } 20 | cout << arrows << endl; 21 | } 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /codeeval/easy/203stringandarrows/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | for line in io.lines(arg[1]) do 4 | arrows = 0 5 | for i = 1,#line do 6 | local c = line:sub(i,i) 7 | if (c == "<" and line:sub(i,i+4) == "<--<<") or 8 | (c == ">" and line:sub(i,i+4) == ">>-->") then 9 | arrows = arrows + 1 10 | end 11 | end 12 | print(arrows) 13 | end 14 | -------------------------------------------------------------------------------- /codeeval/easy/205cleanupthewords/input: -------------------------------------------------------------------------------- 1 | (--9Hello----World...--) 2 | Can 0$9 ---you~ 3 | 13What213are;11you-123+138doing7 -------------------------------------------------------------------------------- /codeeval/easy/205cleanupthewords/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | FILE *f = fopen(argv[1], "r"); 7 | char buf[128]; 8 | while (fgets(buf, 128, f)) { 9 | bool last = false; 10 | for (int i = 0; buf[i] != '\0'; i++) { 11 | if (isalpha(buf[i])) { 12 | printf("%c", tolower(buf[i])); 13 | last = true; 14 | } else { 15 | if (last) { 16 | printf(" "); 17 | last = false; 18 | } 19 | } 20 | } 21 | printf("\n"); 22 | } 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /codeeval/easy/208highestscore/data: -------------------------------------------------------------------------------- 1 | 72 64 150 | 100 18 33 | 13 250 -6 2 | 10 25 -30 44 | 5 16 70 8 | 13 1 31 12 3 | 100 6 300 20 10 | 5 200 6 9 500 | 1 10 3 400 143 4 | -------------------------------------------------------------------------------- /codeeval/easy/208highestscore/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *file = fopen(argv[1], "r"); 5 | 6 | char buf[128]; 7 | while (fgets(buf, sizeof buf, file)) { 8 | char score[5]; 9 | int scores[20][10]; 10 | 11 | int i = 0; 12 | while (i < (int) sizeof buf) { 13 | 14 | } 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /codeeval/easy/208highestscore/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream infile(argv[1]); 10 | string line; 11 | while (getline(infile, line)) { 12 | stringstream ss(line); 13 | vector tokens; 14 | int cols = 0; 15 | int rows = 0; 16 | string x; 17 | for (int i = 0; ss >> x; ++i) { 18 | if (x == "|") { 19 | if (cols == 0) cols = i; 20 | ++rows; 21 | continue; 22 | } 23 | tokens.push_back(strtol(x.c_str(), NULL, 10)); 24 | } 25 | 26 | for (int i = 0; i < cols; ++i) { 27 | int m = tokens[i]; 28 | for (int j = 1; j <= rows; ++j) { 29 | m = max(m, tokens[i+(cols*j)]); 30 | } 31 | cout << m << (i == cols-1 ? "" : " "); 32 | } 33 | cout << endl; 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /codeeval/easy/225testing/input: -------------------------------------------------------------------------------- 1 | Heelo Codevval | Hello Codeeval 2 | hELLO cODEEVAL | Hello Codeeval 3 | Hello Codeeval | Hello Codeeval -------------------------------------------------------------------------------- /codeeval/easy/225testing/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *f = fopen(argv[1], "r"); 5 | char buf[128]; 6 | while (fgets(buf, 128, f)) { 7 | int j = 0; 8 | while (buf[j] != '|') ++j; 9 | int end = j - 1; 10 | j += 2; 11 | 12 | int bugs = 0; 13 | for (int i = 0; i < end; ++i, ++j) { 14 | if (buf[i] != buf[j]) ++bugs; 15 | } 16 | 17 | if (bugs > 6) { 18 | printf("Critical"); 19 | } else if (bugs > 4) { 20 | printf("High"); 21 | } else if (bugs > 2) { 22 | printf("Medium"); 23 | } else if (bugs > 0) { 24 | printf("Low"); 25 | } else { 26 | printf("Done"); 27 | } 28 | printf("\n"); 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /codeeval/easy/225testing/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string test; 10 | while (getline(infile, test, '|')) { 11 | string design; 12 | getline(infile, design, '\n'); 13 | 14 | int bugs = 0; 15 | for (int i = 0; i < test.size() - 1; ++i) { 16 | if (test[i] != design[i+1]) ++bugs; 17 | } 18 | 19 | if (bugs > 6) { 20 | cout << "Critical"; 21 | } else if (bugs > 4) { 22 | cout << "High"; 23 | } else if (bugs > 2) { 24 | cout << "Medium"; 25 | } else if (bugs > 0) { 26 | cout << "Low"; 27 | } else { 28 | cout << "Done"; 29 | } 30 | cout << endl; 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /codeeval/easy/227realfake/input: -------------------------------------------------------------------------------- 1 | 9999 9999 9999 9999 2 | 9999 9999 9999 9993 -------------------------------------------------------------------------------- /codeeval/easy/227realfake/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | int sum = 0, j = 0; 11 | for (int i = 0; i < line.size(); ++i) { 12 | if (line[i] == ' ') { 13 | j = 0; 14 | continue; 15 | } 16 | short n = line[i] - '0'; 17 | sum += (j%2 == 0 ? n * 2 : n); 18 | ++j; 19 | } 20 | cout << (sum % 10 == 0 ? "Real" : "Fake") << endl;; 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/README.md: -------------------------------------------------------------------------------- 1 | # 014: String permutations 2 | 3 | > Source: https://www.codeeval.com/open_challenges/014/ 4 | 5 | Write a program which prints all the permutations of a string in alphabetical order. We 6 | consider that digits < upper case letters < lower case letters. The sorting should be 7 | performed in ascending order. 8 | 9 | ## Input sample 10 | 11 | Your program should accept a file as its first argument. The file contains input strings, 12 | one per line. 13 | 14 | ``` 15 | hat 16 | abc 17 | Zu6 18 | ``` 19 | 20 | ## Output sample 21 | 22 | Print to stdout the permutations of the string separated by comma, in alphabetical order. 23 | 24 | ``` 25 | aht,ath,hat,hta,tah,tha 26 | abc,acb,bac,bca,cab,cba 27 | 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6 28 | ``` 29 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/input: -------------------------------------------------------------------------------- 1 | hat 2 | abc 3 | Zu6 4 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/output: -------------------------------------------------------------------------------- 1 | aht,ath,hat,hta,tah,tha 2 | abc,acb,bac,bca,cab,cba 3 | 6Zu,6uZ,Z6u,Zu6,u6Z,uZ6 4 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | -- 2ms 118.303kb 99.708 4 | 5 | function permutations(word) 6 | if #word == 1 then 7 | return {word} 8 | end 9 | 10 | local first_letter = word:sub(1, 1) 11 | local perms = permutations(word:sub(2, #word)) 12 | result = {} 13 | for i = 1,#perms do 14 | local perm = perms[i] 15 | for j = 1,(#perm+1) do 16 | table.insert(result, perm:sub(1, j-1) .. first_letter .. perm:sub(j, #perm)) 17 | end 18 | end 19 | return result 20 | end 21 | 22 | for line in io.lines(arg[1]) do 23 | local p = permutations(line) 24 | table.sort(p) 25 | print(table.concat(p, ",")) 26 | end 27 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | def permutations(word): 6 | if len(word) == 1: 7 | return [word] 8 | first = word[0] 9 | perms = permutations(word[1:]) 10 | result = [] 11 | for perm in perms: 12 | for i in range(len(perm)+1): 13 | result.append(perm[:i] + first + perm[i:]) 14 | return result 15 | 16 | for line in open(argv[1], 'r'): 17 | line = line.strip() 18 | if line == "": 19 | continue 20 | print(",".join(sorted(permutations(line)))) 21 | -------------------------------------------------------------------------------- /codeeval/hard/014stringpermutations/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | def permutations(word) 4 | return [word] if word.length == 1 5 | perms = permutations(word[1..-1]) 6 | result = [] 7 | perms.each do |perm| 8 | (perm.length+1).times do |i| 9 | result.push("#{perm[0...i]}#{word[0]}#{perm[i..-1]}") 10 | end 11 | end 12 | return result 13 | end 14 | 15 | File.open(ARGV[0]).each_line do |line| 16 | line.strip! 17 | next if line.empty? 18 | puts permutations(line).sort.join(",") 19 | end 20 | -------------------------------------------------------------------------------- /codeeval/hard/028stringsearch/README.md: -------------------------------------------------------------------------------- 1 | # 028: String search 2 | 3 | > Source: https://www.codeeval.com/open_challenges/028/ 4 | 5 | You are given two strings. Determine if the second string is a substring of the first (Do 6 | NOT use any substr type library function). The second string may contain an asterisk(*) 7 | which should be treated as a regular expression i.e. matches zero or more characters. The 8 | asterisk can be escaped by a \ char in which case it should be interpreted as a regular 9 | '*' character. To summarize: the strings can contain alphabets, numbers, * and \ 10 | characters. 11 | 12 | ## Input sample 13 | 14 | Your program should accept as its first argument a path to a filename. The input file 15 | contains two comma delimited strings per line. E.g. 16 | 17 | ``` 18 | Hello,ell 19 | This is good, is 20 | CodeEval,C*Eval 21 | Old,Young 22 | ``` 23 | 24 | ## Output sample 25 | 26 | If the second string is indeed a substring of the first, print out a 'true'(lowercase), 27 | else print out a 'false'(lowercase), one per line. E.g. 28 | 29 | ``` 30 | true 31 | true 32 | true 33 | false 34 | ``` 35 | -------------------------------------------------------------------------------- /codeeval/hard/028stringsearch/input: -------------------------------------------------------------------------------- 1 | Hello,ell 2 | This is good, is 3 | CodeEval,C*Eval 4 | Old,Young 5 | What a star* he is,ar\* 6 | Hello,el* 7 | Hello,*el 8 | Hello,e*o 9 | -------------------------------------------------------------------------------- /codeeval/hard/028stringsearch/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | -- A little cheat-ey, but the C++ one is the real solution. Check that one out. Here I'm 4 | -- leveraging Lua's own pattern system (it doesn't have a regex library; one would 5 | -- likely be larger than lua itself). 6 | 7 | for line in io.lines(arg[1]) do 8 | data = {} 9 | for str in line:gmatch("([^,]+)") do 10 | table.insert(data, str) 11 | end 12 | pat = data[2]:gsub("[^\\]([*-?+%.[$()])", ".%1") 13 | if pat:sub(1,1) == "*" then 14 | pat = "." .. pat 15 | end 16 | print(not not data[1]:find(pat)) 17 | end 18 | 19 | -------------------------------------------------------------------------------- /codeeval/hard/028stringsearch/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # A little cheat-ey, but I solved this in C++ already. Here I'm just experimenting with 4 | # the language. 5 | 6 | File.open(ARGV[0]).each_line do |line| 7 | str, query = line.strip.split(",") 8 | puts str =~ /#{query.gsub(/(? Source: https://www.codeeval.com/open_challenges/110/ 4 | 5 | You have a sting which contains a number represented as English text. Your task is to 6 | translate these numbers into their integer representation. The numbers can range from 7 | negative 999,999,999 to positive 999,999,999. The following is an exhaustive list of 8 | English words that your program must account for: 9 | 10 | + Negative numbers will be preceded by the word negative. 11 | + The word "hundred" is not used when "thousand" could be. e.g. 1500 is written "one 12 | thousand five hundred", not "fifteen hundred". 13 | 14 | ``` 15 | negative, 16 | zero, one, two, three, four, five, six, seven, eight, nine, 17 | ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, 18 | twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety, 19 | hundred, 20 | thousand, 21 | million 22 | ``` 23 | 24 | ## Input sample 25 | 26 | Your program should accept as its first argument a path to a filename. Input example is 27 | the following: 28 | 29 | ``` 30 | fifteen 31 | negative six hundred thirty eight 32 | zero 33 | two million one hundred seven 34 | ``` 35 | 36 | - Negative numbers will be preceded by the word negative. 37 | - The word "hundred" is not used when "thousand" could be. E.g. 1500 is written "one 38 | thousand five hundred", not "fifteen hundred". 39 | 40 | ## Output sample 41 | 42 | Print results in the following way. 43 | 44 | ``` 45 | 15 46 | -638 47 | 0 48 | 2000107 49 | ``` 50 | 51 | -------------------------------------------------------------------------------- /codeeval/hard/110texttonumber/input: -------------------------------------------------------------------------------- 1 | fifteen 2 | negative six hundred thirty eight 3 | zero 4 | two million one hundred seven 5 | five million twenty thousand forty two 6 | one thousand five hundred 7 | nine hundred ninety nine million 8 | negative nine hundred ninety nine million 9 | nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine 10 | fifteen hundred 11 | six hundred twenty two 12 | twenty five thousand two hundred ninety six 13 | -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/README.md: -------------------------------------------------------------------------------- 1 | # 002: Longest Lines 2 | 3 | > Source: https://www.codeeval.com/open_challenges/2/ 4 | 5 | Write a program which reads a file and prints to stdout the specified number of the 6 | longest lines that are sorted based on their length in descending order. 7 | 8 | ## Input sample 9 | 10 | Your program should accept a path to a file as its first argument. The file contains 11 | multiple lines. The first line indicates the number of lines you should output, the other 12 | lines are of different length and are presented randomly. You may assume that the input 13 | file is formatted correctly and the number in the first line is a valid positive integer. 14 | 15 | For example: 16 | 17 | ``` 18 | 2 19 | Hello World 20 | CodeEval 21 | Quick Fox 22 | A 23 | San Francisco 24 | ``` 25 | 26 | ## Output sample 27 | 28 | Print out the longest lines limited by specified number and sorted by their length in descending order. 29 | 30 | For example: 31 | 32 | ``` 33 | San Francisco 34 | Hello World 35 | ``` 36 | -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/input: -------------------------------------------------------------------------------- 1 | 2 2 | Hello World 3 | CodeEval 4 | Quick Fox 5 | A 6 | San Francisco 7 | -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define ROWS 64 6 | #define MAXLEN 256 7 | 8 | int complen(const void* a, const void* b) { 9 | size_t fa = strlen((const char *)a); 10 | size_t fb = strlen((const char *)b); 11 | return (fa < fb) - (fa > fb); 12 | } 13 | 14 | int main(int argc, char *argv[]) { 15 | FILE *file = fopen(argv[1], "r"); 16 | 17 | char nbuf[8]; 18 | if (fgets(nbuf, 8, file) == NULL) { 19 | return 1; 20 | } 21 | int n = atoi(nbuf); 22 | 23 | int i = 0; 24 | char lines[ROWS][MAXLEN]; 25 | char buf[MAXLEN]; 26 | while (fgets(buf, MAXLEN, file)) { 27 | strncpy(lines[i++], buf, MAXLEN); 28 | } 29 | 30 | qsort(lines, ROWS, MAXLEN, complen); 31 | for (int i = 0; i < n; ++i) { 32 | printf("%s", lines[i]); 33 | } 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | list lines; 9 | string line; 10 | int n; 11 | infile >> n; 12 | while (getline(infile, line)) { 13 | if (lines.size() == 0) { 14 | lines.push_back(line); 15 | } else { 16 | for (auto it = lines.begin(); it != lines.end(); ++it) { 17 | if (line.size() > it->size()) { 18 | lines.insert(it, line); 19 | break; 20 | } 21 | } 22 | } 23 | } 24 | int i = 0; 25 | for (auto& l : lines) { 26 | if (i == n) break; 27 | cout << l << endl; 28 | ++i; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var lines = require("fs").readFileSync(process.argv[2]).toString().trim().split('\n'); 4 | var n = lines.shift(); 5 | lines.sort(function(a, b) { 6 | return a.length >= b.length ? -1 : 1; 7 | }); 8 | 9 | console.log(lines.slice(0, n).join("\n")); 10 | -------------------------------------------------------------------------------- /codeeval/medium/002longestlines/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | with open(argv[1]) as f: 6 | n = int(f.readline()) 7 | lines = [line.strip() for line in f] 8 | lines.sort(key=len, reverse=True) 9 | print("\n".join(lines[0:n])) 10 | -------------------------------------------------------------------------------- /codeeval/medium/005detectingcycles/input: -------------------------------------------------------------------------------- 1 | 2 0 6 3 1 6 3 1 6 3 1 2 | 3 4 8 0 11 9 7 2 5 6 10 1 49 49 49 49 3 | 1 2 3 1 2 3 1 2 3 -------------------------------------------------------------------------------- /codeeval/medium/005detectingcycles/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *f = fopen(argv[1], "r"); 5 | char buf[128]; 6 | while (fgets(buf, 128, f)) { 7 | int n, offset; 8 | char *lpt = buf; 9 | while (sscanf(lpt, "%d%n", &n, &offset) == 1) { 10 | printf("%d ", n); 11 | lpt += offset; 12 | } 13 | printf("\n"); 14 | } 15 | return 0; 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /codeeval/medium/009stackimplementation/input: -------------------------------------------------------------------------------- 1 | 1 2 3 4 2 | 10 -2 3 4 3 | 5 10 -2 3 4 4 | -49 49 97 76 -69 -58 -65 -37 -52 -70 -31 56 96 -10 66 28 -72 53 -19 93 53 -84 81 -16 40 -6 28 -58 -12 -19 -75 7 5 | -------------------------------------------------------------------------------- /codeeval/medium/009stackimplementation/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) { 4 | FILE *f = fopen(argv[1], "r"); 5 | char line[512]; 6 | while (fgets(line, 512, f)) { 7 | int size = 0; 8 | int x, offset; 9 | int n[128]; 10 | char *lpt = line; 11 | while (sscanf(lpt, "%d%n", &x, &offset) == 1 && size < 128) { 12 | n[size++] = x; 13 | lpt += offset; 14 | } 15 | 16 | for (int i = 0; size > 0; ++i, --size) { 17 | if ((i&1) == 0) printf("%d ", n[size-1]); 18 | } 19 | printf("\n"); 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /codeeval/medium/009stackimplementation/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream infile(argv[1]); 10 | string line; 11 | while (getline(infile, line)) { 12 | deque nums; 13 | 14 | istringstream ss(line); 15 | int n; 16 | while (ss >> n) { nums.push_back(n); } 17 | 18 | for (int i = 0; nums.size() > 0; ++i) { 19 | if ((i&1) == 0) cout << nums.back() << ' '; 20 | nums.pop_back(); 21 | } 22 | cout << endl; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /codeeval/medium/010mthtolastelement/input: -------------------------------------------------------------------------------- 1 | a b c d 4 2 | e f g h 2 3 | a b c d e f g h i j k l m n o p 12 4 | e f g h 8 5 | -------------------------------------------------------------------------------- /codeeval/medium/010mthtolastelement/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) { 5 | FILE *f = fopen(argv[1], "r"); 6 | char line[128]; 7 | while (fgets(line, 128, f)) { 8 | char *lpt = line; 9 | char chars[64]; 10 | 11 | char c; 12 | int n, offset, size = 0; 13 | 14 | while (sscanf(lpt, "%c%n", &c, &offset)) { 15 | if (c >= '0' && c <= '9') { 16 | sscanf(lpt, "%d", &n); 17 | break; 18 | } else if (!isalpha(c)) { 19 | lpt += offset; 20 | continue; 21 | } 22 | 23 | lpt += offset; 24 | chars[size] = c; 25 | ++size; 26 | } 27 | 28 | int i = (size - 1) - (n - 1); 29 | if (i < 0) continue; 30 | printf("%c\n", (i < 0 ? ' ' : chars[i])); 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /codeeval/medium/010mthtolastelement/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main(int argc, char *argv[]) { 9 | ifstream infile(argv[1]); 10 | string line; 11 | while (getline(infile, line)) { 12 | istringstream ss(line); 13 | deque chars; 14 | 15 | char c; 16 | while (ss >> c) { 17 | if (c >= '0' && c <= '9') { 18 | ss.unget(); 19 | break; 20 | } 21 | 22 | chars.push_back(c); 23 | } 24 | 25 | int n; 26 | ss >> n; 27 | 28 | int i = (chars.size() - 1) - (n - 1); 29 | cout << (i < 0 ? ' ' : chars[i]) << endl; 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /codeeval/medium/012firstnonrepeatedchar/input: -------------------------------------------------------------------------------- 1 | yellow 2 | tooth -------------------------------------------------------------------------------- /codeeval/medium/012firstnonrepeatedchar/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | char c; 11 | for (int i = 0; i < line.size(); ++i) { 12 | bool isRepeated = false; 13 | c = line[i]; 14 | for (int j = 0; j < line.size(); ++j) { 15 | if (j == i) continue; 16 | if (line[i] == line[j]) { 17 | isRepeated = true; 18 | break; 19 | } 20 | } 21 | if (!isRepeated) break; 22 | } 23 | cout << c << endl; 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/README.md: -------------------------------------------------------------------------------- 1 | # 013: Remove Characters 2 | 3 | > Source: https://www.codeeval.com/open_challenges/013/ 4 | 5 | Write a program which removes specific characters from a string. 6 | 7 | The first argument is a path to a file. The file contains the source strings and the 8 | characters that need to be scrubbed. Each source string and characters you need to scrub 9 | are delimited by comma. 10 | 11 | ## Input sample 12 | 13 | The first argument is a path to a file. The file contains the source strings and the 14 | characters that need to be scrubbed. Each source string and characters you need to scrub 15 | are delimited by comma. 16 | 17 | ``` 18 | how are you, abc 19 | hello world, def 20 | ``` 21 | 22 | ## Output sample 23 | 24 | Print to stdout the scrubbed strings, one per line. Ensure that there are no trailing 25 | empty spaces on each line you print. 26 | 27 | ``` 28 | how re you 29 | hllo worl 30 | ``` 31 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/input: -------------------------------------------------------------------------------- 1 | how are you, abc 2 | hello world, def 3 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string line; 9 | while (getline(infile, line)) { 10 | string src, sub; 11 | auto it = line.begin(); 12 | while (*it != ',') ++it; 13 | src = string(line.begin(), it); 14 | sub = string(it+2, line.end()); 15 | 16 | auto x = src.begin(); 17 | auto y = sub.begin(); 18 | 19 | while (x != src.end()) { 20 | bool found = false; 21 | do { 22 | if (*x == *y) { 23 | found = true; 24 | break; 25 | } 26 | ++y; 27 | } 28 | while (y != sub.end()); 29 | if (!found) cout << *x; 30 | 31 | ++x; 32 | y = sub.begin(); 33 | } 34 | cout << endl; 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | require("fs").readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { 4 | line = line.trim(); 5 | if (line != "") { 6 | var res = line.split(", "); 7 | var re = new RegExp("["+res[1].trim()+"]", 'ig'); 8 | res[0] = res[0].replace(re, ""); 9 | console.log(res[0].trim()); 10 | } 11 | }); 12 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | for line in open(argv[1]): 6 | src, sub = line.split(", ") 7 | for l in sub: 8 | src = src.replace(l, "") 9 | print(src) 10 | -------------------------------------------------------------------------------- /codeeval/medium/013removechars/solution.rb: -------------------------------------------------------------------------------- 1 | File.open(ARGV[0]).each_line do |line| 2 | text, rep = line.split(", ") 3 | puts text.gsub(/[#{Regexp.escape(rep)}]/, "") 4 | end 5 | -------------------------------------------------------------------------------- /codeeval/medium/027decimaltobinary/input: -------------------------------------------------------------------------------- 1 | 2 2 | 10 3 | 67 -------------------------------------------------------------------------------- /codeeval/medium/027decimaltobinary/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | int n; 10 | while (infile >> n) { 11 | if (n == 0) { 12 | cout << 0 << endl; 13 | } else { 14 | string out; 15 | out.reserve(32); 16 | while (n != 0) { 17 | int r = n % 2; 18 | out += r + '0'; 19 | n /= 2; 20 | } 21 | reverse(out.begin(), out.end()); 22 | cout << out << endl; 23 | } 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /codeeval/medium/032trailingstring/input2: -------------------------------------------------------------------------------- 1 | Hello World,World 2 | Hello CodeEval,CodeEval 3 | San Francisco,San Jose -------------------------------------------------------------------------------- /codeeval/medium/032trailingstring/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc, char *argv[]) { 6 | FILE *f = fopen(argv[1], "r"); 7 | char buf[256]; 8 | while (fgets(buf, 256, f)) { 9 | int i = 0; 10 | int j = strlen(buf) - 2; 11 | if (j == 0) continue; 12 | 13 | while (buf[i+1] != ',') ++i; 14 | int jBeg = i + 2; 15 | 16 | bool atEnd = true; 17 | 18 | if (i+1 < (j - jBeg)+1) { 19 | atEnd = false; 20 | } else { 21 | while (i >= 0 && j >= jBeg) { 22 | if (buf[i] != buf[j]) { 23 | atEnd = false; 24 | break; 25 | } 26 | --i; --j; 27 | } 28 | } 29 | printf("%d\n", (atEnd ? 1 : 0)); 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /codeeval/medium/032trailingstring/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char *argv[]) { 7 | ifstream infile(argv[1]); 8 | string a; 9 | while (getline(infile, a, ',')) { 10 | string b; 11 | getline(infile, b, '\n'); 12 | 13 | bool atEnd = true; 14 | int i = a.size()-1; 15 | int j = b.size()-1; 16 | int iEnd = (i+1) - (j+1); 17 | if (iEnd < 0) { 18 | atEnd = false; 19 | } else { 20 | while (i >= iEnd && j >= 0) { 21 | if (a[i] != b[j]) { 22 | atEnd = false; 23 | break; 24 | } 25 | --i; --j; 26 | } 27 | } 28 | cout << (atEnd ? 1 : 0) << endl; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /codeeval/medium/035emailvalidation/input: -------------------------------------------------------------------------------- 1 | foo@bar.com 2 | this is not an email id 3 | admin#codeeval.com 4 | good123@bad.com 5 | hello_henrik@howare.com 6 | -------------------------------------------------------------------------------- /codeeval/medium/035emailvalidation/input2: -------------------------------------------------------------------------------- 1 | a.little.lengthy.but.fine@dept.example.com 2 | "very.unusual.@.unusual.com"@example.com 3 | disposable.style.email.with+symbol@example.com 4 | niceandsimple@example.com 5 | a"b(c)d,e:f;gi[j\k]l@example.com 6 | hfij#kjdfvkl 7 | 1@d.net 8 | b@domain.net 9 | this\ still\"not\\allowed@example.com 10 | A@b@c@example.com 11 | this is not true 12 | this is"not\allowed@example.com 13 | just"not"right@example.com 14 | @foo.com 15 | disposable.style.email.with+156@example.com 16 | very.common@example.com 17 | b@d.net 18 | asterisk_domain@foo.* 19 | bob123@alice123.com 20 | Abc.example.com 21 | -------------------------------------------------------------------------------- /codeeval/medium/035emailvalidation/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import re 4 | from sys import argv 5 | 6 | # Regular expressions are a poor way of validating emails. These patterns were designed 7 | # solely for this problem and should never be used in production. 8 | 9 | with open(argv[1], 'r') as f: 10 | for line in f: 11 | line = line.strip() 12 | if line: 13 | if re.match('^(' + 14 | '\w[\w.+-]*' + 15 | '|((^|\.)"\w[\w@.+ -]+")+' + 16 | ')@\w[\w+.]*\.(com|org|net)$', 17 | line): 18 | print("true") 19 | else: 20 | print("false") 21 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/README.md: -------------------------------------------------------------------------------- 1 | # 046 Prime Numbers 2 | 3 | > Source: https://www.codeeval.com/open_challenges/46/ 4 | 5 | Print out the prime numbers less than a given number N. For bonus points your solution 6 | should run in `N*(log(N))` time or better. You may assume that N is always a positive 7 | integer. 8 | 9 | ## Input sample 10 | 11 | Your program should accept as its first argument a path to a filename. Each line in this 12 | file is one test case. Each test case will contain an integer n < 4,294,967,295. E.g. 13 | 14 | ``` 15 | 10 16 | 20 17 | 100 18 | ``` 19 | 20 | ## Output sample 21 | 22 | For each line of input, print out the prime numbers less than N, in ascending order, comma 23 | delimited. (There should not be any spaces between the comma and numbers) E.g. 24 | 25 | ``` 26 | 2,3,5,7 27 | 2,3,5,7,11,13,17,19 28 | 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 29 | ``` 30 | 31 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/input: -------------------------------------------------------------------------------- 1 | 10 2 | 20 3 | 100 4 | 200 5 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // The fast inverse square root, courtesy of the Quake 3 8 | // source code and Carmack's genius. 9 | float fInvSqrt(float x) { 10 | float xhalf = 0.5f * x; 11 | int i = *(int*)&x; // store floating-point bits in integer 12 | i = 0x5f3759df - (i >> 1); // initial guess for Newton's method 13 | x = *(float*)&i; // convert new bits into float 14 | x = x*(1.5f - xhalf*x*x); // One round of Newton's method 15 | return x; 16 | } 17 | 18 | bool isprime(int n) { 19 | if (!(n&1)) return 0; 20 | int sqt = 1/fInvSqrt(n); 21 | for (int i = 3; i <= sqt; i += 2) { 22 | if (n % i == 0) 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | void getPrimes(long long max) { 29 | if (max > 2) cout << 2; 30 | for (int i = 3; i < max; i += 2) { 31 | if (isprime(i)) { 32 | cout << ',' << i; 33 | } 34 | } 35 | cout << endl; 36 | } 37 | 38 | int main(int, char *argv[]) { 39 | ifstream infile(argv[1]); 40 | long long max; 41 | while (infile >> max) { 42 | getPrimes(max); 43 | } 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | function write(s) { 4 | process.stdout.write(s); 5 | } 6 | 7 | function isprime(n) { 8 | if (n % 2 === 0) return false; 9 | var sqt = parseInt(Math.sqrt(n)); 10 | for (var i = 3; i <= sqt; i += 2) { 11 | if (n % i === 0) return false; 12 | } 13 | return true; 14 | } 15 | 16 | function primes(n) { 17 | if (n > 2) write("2"); 18 | for (var i = 3; i < n; i += 2) { 19 | if (isprime(i)) write("," + i.toString()); 20 | } 21 | write("\n"); 22 | } 23 | 24 | require("fs").readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { 25 | line = line.trim(); 26 | if (line !== "") { 27 | primes(parseInt(line)); 28 | } 29 | }); 30 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | from math import sqrt 5 | 6 | def isprime(n): 7 | if n % 2 == 0: 8 | return False 9 | for i in range(3, int(sqrt(n))+1, 2): 10 | if n % i == 0: 11 | return False 12 | return True 13 | 14 | def primes(n): 15 | for i in range(3, n, 2): 16 | if isprime(i): 17 | yield i 18 | 19 | for test in open(argv[1], 'r'): 20 | m = int(test.strip()) 21 | if m > 2: 22 | s = "2" 23 | for p in primes(m): 24 | s += "," + str(p) 25 | print s 26 | -------------------------------------------------------------------------------- /codeeval/medium/046primenumbers/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | def isprime(n) 4 | return false if n % 2 == 0 5 | (3..Math.sqrt(n).to_i).step(2) { |i| return false if n % i == 0 } 6 | return true 7 | end 8 | 9 | def primes(n) 10 | (3...n).step(2) { |i| yield i if isprime(i) } 11 | end 12 | 13 | File.open(ARGV[0]).each_line do |line| 14 | n = line.to_i 15 | if n > 2 16 | print 2 17 | primes(n) { |i| print ",", i } 18 | end 19 | puts 20 | end 21 | -------------------------------------------------------------------------------- /codeeval/medium/054cashregister/data: -------------------------------------------------------------------------------- 1 | 15.94;16.00 2 | 17;16 3 | 35;35 4 | 45;50 5 | 190;240 6 | 19.00;240.01 7 | 39;49 8 | 19.11;20.00 9 | -------------------------------------------------------------------------------- /codeeval/medium/074minimumcoins/input: -------------------------------------------------------------------------------- 1 | 11 2 | 20 3 | 31 4 | 15 5 | -------------------------------------------------------------------------------- /codeeval/medium/074minimumcoins/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Why a C-style array and not a vector? Just cause. 7 | const int COINS[] = {5, 3, 1}; 8 | const int COINSC = (sizeof(COINS)/sizeof(*COINS)); 9 | 10 | int main(int argc, char *argv[]) { 11 | if (argc > 1) { 12 | ifstream infile(argv[1]); 13 | int amount; 14 | while (infile >> amount) { 15 | int coins = 0; 16 | for (int i = 0; i < COINSC; ++i) { 17 | if (amount <= 0) break; 18 | int count = (int) amount / COINS[i]; 19 | coins += count; 20 | if (count != 0) { 21 | amount -= COINS[i] * count; 22 | } 23 | } 24 | cout << coins << endl; 25 | } 26 | } else { 27 | cout << "Usage: " << argv[0] << " [data-file]" << endl; 28 | return 1; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /codeeval/medium/074minimumcoins/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from sys import argv 4 | 5 | DENOM = [5, 3, 1] 6 | 7 | for x in open(argv[1]): 8 | amt = int(x) 9 | coins = 0 10 | for d in DENOM: 11 | qty = int(amt / d) 12 | amt -= qty * d 13 | coins += qty 14 | print(coins) 15 | -------------------------------------------------------------------------------- /codeeval/medium/074minimumcoins/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | denom = [5, 3, 1] 4 | 5 | File.open(ARGV[0]).each_line do |line| 6 | amt = line.to_i 7 | coins = 0 8 | denom.each do |n| 9 | qty = (amt / n).to_i 10 | amt -= qty * n 11 | coins += qty 12 | end 13 | puts coins 14 | end 15 | -------------------------------------------------------------------------------- /codeeval/medium/097findawriter/README.md: -------------------------------------------------------------------------------- 1 | # 097: Find a Writer 2 | 3 | > Source: https://www.codeeval.com/open_challenges/97/ 4 | 5 | You have a set of rows with names of famous writers encoded inside. Each row is divided 6 | into 2 parts by pipe char (|). The first part has a writer's name. The second part is a 7 | "key" to generate a name. 8 | 9 | Your goal is to go through each number in the key (numbers are separated by space) 10 | left-to-right. Each number represents a position in the 1st part of a row. This way you 11 | collect a writer's name which you have to output. 12 | 13 | ## Input sample 14 | 15 | Your program should accept as its first argument a path to a filename. Input example is 16 | the following 17 | 18 | ``` 19 | osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA rLclpg| 3 35 27 62 51 27 46 57 26 10 46 63 57 45 15 43 53 20 | 21 | 3Kucdq9bfCEgZGF2nwx8UpzQJyHiOm0hoaYP6ST1WM7Nks5XjrR4IltBeDLV vA| 2 26 33 55 34 50 33 61 44 28 46 32 28 30 3 50 34 61 40 7 1 31 22 | ``` 23 | 24 | This input had 2 rows. 25 | 26 | ## Output sample 27 | 28 | Print results in the following way. 29 | 30 | ``` 31 | Stephen King 1947 32 | Kyotaro Nishimura 1930 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /codeeval/medium/097findawriter/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) { 8 | ifstream infile(argv[1]); 9 | string line; 10 | while (getline(infile, line)) { 11 | if (!line.size()) continue; 12 | 13 | istringstream lhss(line); 14 | string str; 15 | if (getline(lhss, str, '|')) { 16 | int i; 17 | while (lhss >> i) cout << str[i-1]; 18 | cout << endl; 19 | } 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /codeeval/medium/193magicnumbers/input: -------------------------------------------------------------------------------- 1 | 10 100 2 | 8382 8841 3 | 6225 6233 4 | 1 20 5 | 9000 10000 6 | 1 10000 7 | 1 10000 8 | 1 10000 9 | 1 10000 10 | 1 10000 11 | -------------------------------------------------------------------------------- /codeeval/medium/193magicnumbers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | const int MASK[] = {2, 4, 8, 16, 32, 64, 128, 256, 512}; 9 | 10 | bool isvalid(int n, int digits) { 11 | int mask = 0; 12 | while (n >= 1) { 13 | if (n % digits == 0) return false; 14 | 15 | int mi = (n % 10) - 1; 16 | if (mi == -1) return false; 17 | mask = MASK[mi] | mask; 18 | // If this number has already been visited... 19 | if ((MASK[mi] & mask) == MASK[mi]) { 20 | return false; 21 | } 22 | n = (int) n / 10; 23 | } 24 | return true; 25 | } 26 | 27 | bool ismagic(int num) { 28 | const int digits = log10(num); 29 | if (num % digits == 0 || !isvalid(num, digits)) 30 | return false; 31 | 32 | int i = 0; 33 | int visited[5] = {0}; 34 | while (!visited[i]) { 35 | i = (i + n) 36 | } 37 | 38 | return true; 39 | } 40 | 41 | int main(int argc, char *argv[]) { 42 | ifstream infile(argv[1]); 43 | string line; 44 | while (getline(infile, line)) { 45 | stringstream ss(line); 46 | int x, y; 47 | ss >> x >> y; 48 | int c = 0; 49 | for (int i = x; i <= y; ++i) { 50 | if (ismagic(i)) { 51 | cout << (c == 0 ? "" : " ") << i; 52 | ++c; 53 | } 54 | } 55 | cout << (c == 0 ? "-1" : "") << endl; 56 | } 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /exercism/README.md: -------------------------------------------------------------------------------- 1 | # Exercism 2 | 3 | > http://exercism.io 4 | > [My profile](http://exercism.io/hlissner) 5 | 6 | Used to learn new languages, like Go, Rust, Swift and MIPS Assembly. 7 | 8 | Or to test new workflows or dev environments. 9 | -------------------------------------------------------------------------------- /exercism/c/all-your-base/src/all_your_base.c: -------------------------------------------------------------------------------- 1 | #include "all_your_base.h" 2 | 3 | void reverse(int8_t digits[], uint16_t length) { 4 | for (int i = 0, j = length-1; i < j; ++i, --j) { 5 | int temp = digits[i]; 6 | digits[i] = digits[j]; 7 | digits[j] = temp; 8 | } 9 | } 10 | 11 | int invalid_base(int base) { 12 | return base <= 1 || base > INT16_MAX; 13 | } 14 | 15 | size_t rebase(int8_t digits[], uint16_t input_base, uint16_t output_base, size_t input_length) { 16 | if (invalid_base(input_base) || 17 | invalid_base(output_base) || 18 | (input_length && digits[0] == 0)) 19 | return 0; 20 | 21 | // base N => base 10 22 | int number = 0; 23 | int i = 0; 24 | while (i < (int) input_length) { 25 | if (digits[i] >= input_base) 26 | return 0; 27 | 28 | number += digits[i] * pow(input_base, (input_length-1)-i); 29 | digits[i] = 0; 30 | ++i; 31 | } 32 | 33 | // base 10 => base M 34 | for (i = 0; number > 0; ++i) { 35 | digits[i] = number % output_base; // filled in reverse 36 | number = floor(number / output_base); 37 | } 38 | reverse(digits, i); 39 | return i; 40 | } 41 | -------------------------------------------------------------------------------- /exercism/c/all-your-base/src/all_your_base.h: -------------------------------------------------------------------------------- 1 | #ifndef ALL_YOUR_BASE_H 2 | #define ALL_YOUR_BASE_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define DIGITS_ARRAY_SIZE 64 9 | 10 | size_t rebase(int8_t digits[], uint16_t input_base, uint16_t output_base, size_t input_length); 11 | 12 | #endif 13 | -------------------------------------------------------------------------------- /exercism/c/anagram/src/anagram.c: -------------------------------------------------------------------------------- 1 | #include "anagram.h" 2 | #include 3 | #include 4 | #include 5 | 6 | int cmp_char (const void* a, const void *b) { 7 | return *(char*)a - *(char*)b; 8 | } 9 | 10 | char* str_copy_lower (char* src) { 11 | char* dest = malloc(sizeof(char) * MAX_STR_LEN); 12 | for (int i = 0; src[i] != '\0'; ++i) { 13 | dest[i] = tolower(src[i]); 14 | } 15 | return dest; 16 | } 17 | 18 | int is_anagram_of(char* str, char* other) { 19 | int len = strlen(str); 20 | if (len != (int) strlen(other)) 21 | return 0; 22 | 23 | char* _str = str_copy_lower(str); 24 | char* _other = str_copy_lower(other); 25 | int result = 0; 26 | if (strncmp(_str, _other, MAX_STR_LEN)) { 27 | qsort(_str, len, sizeof(char), cmp_char); 28 | qsort(_other, len, sizeof(char), cmp_char); 29 | 30 | result = strncmp(_str, _other, MAX_STR_LEN) == 0; 31 | } 32 | 33 | free(_str); 34 | free(_other); 35 | return result; 36 | } 37 | 38 | struct Vector anagrams_for(char* str, struct Vector inputs) { 39 | struct Vector result; 40 | result.vec = (char(*)[MAX_STR_LEN]) malloc(sizeof(char) * MAX_STR_LEN * 32); 41 | result.size = 0; 42 | 43 | for (int i = 0; i < inputs.size; ++i) { 44 | if (is_anagram_of(str, inputs.vec[i])) { 45 | strncpy(result.vec[result.size++], inputs.vec[i], MAX_STR_LEN); 46 | } 47 | } 48 | 49 | return result; 50 | } 51 | 52 | -------------------------------------------------------------------------------- /exercism/c/anagram/src/anagram.h: -------------------------------------------------------------------------------- 1 | #ifndef ANAGRAM_H 2 | #define ANAGRAM_H 3 | 4 | #define MAX_STR_LEN 20 5 | 6 | struct Vector { 7 | char (*vec)[MAX_STR_LEN]; 8 | int size; 9 | }; 10 | 11 | struct Vector anagrams_for(char *, struct Vector); 12 | 13 | #endif 14 | -------------------------------------------------------------------------------- /exercism/c/atbash-cipher/src/atbash_cipher.c: -------------------------------------------------------------------------------- 1 | #include "atbash_cipher.h" 2 | 3 | #define STRLEN 64 4 | 5 | char flipchar(char c) { 6 | if (isalpha(c)) 7 | return 'z' - (tolower(c) - 'a'); 8 | return c; 9 | } 10 | 11 | char* atbash(char* input, int group_size) { 12 | char* output = (char*) calloc(STRLEN, sizeof(char)); 13 | char* pt = output; 14 | for (int s = group_size; *input; ++input) { 15 | if (isalnum(*input)) { 16 | *(pt++) = flipchar(*input); 17 | if (--s == 0) { 18 | *(pt++) = ' '; 19 | s = group_size; 20 | } 21 | } 22 | } 23 | if (*(--pt) == ' ') *pt = '\0'; 24 | return output; 25 | } 26 | 27 | 28 | char* atbash_encode(char* input) { return atbash(input, 5); } 29 | char* atbash_decode(char* input) { return atbash(input, 0); } 30 | -------------------------------------------------------------------------------- /exercism/c/atbash-cipher/src/atbash_cipher.h: -------------------------------------------------------------------------------- 1 | #ifndef __ATBASH_CIPHER_H_ 2 | #define __ATBASH_CIPHER_H_ 3 | 4 | #include 5 | #include 6 | 7 | char* atbash_encode(char* input); 8 | char* atbash_decode(char* input); 9 | 10 | #endif // __ATBASH_CIPHER_H_ 11 | -------------------------------------------------------------------------------- /exercism/c/bob/src/bob.c: -------------------------------------------------------------------------------- 1 | #include "bob.h" 2 | 3 | int is_addressing(const char* input, int len) { 4 | return len == 0; 5 | } 6 | 7 | int is_questioning(const char* input, int len) { 8 | return input[len-1] == '?'; 9 | } 10 | 11 | int is_shouting(const char* input, int len) { 12 | int hasUpper = 0; 13 | for (int i = 0; i < len; ++i) { 14 | const char c = (input)[i]; 15 | if (!isalpha(c)) continue; 16 | // The speaker is shouting if all alphabetical characters are uppercase. 17 | if (isupper(c)) 18 | hasUpper = 1; 19 | // Even one lower-case character indicates the speaker isn't shouting 20 | if (c >= 'a' && c <= 'z') 21 | return 0; 22 | } 23 | return hasUpper; 24 | } 25 | 26 | // 27 | const char *hey_bob(const char* statement) { 28 | // Make a copy; don't mutate original 29 | char input[128]; 30 | strncpy(input, statement, 128); 31 | 32 | if (input[0] != '\0') { 33 | // rtrim input 34 | int i = strlen(input)-1; 35 | for (; i > 0; --i) { 36 | if (input[i] != ' ') { 37 | input[i+1] = '\0'; 38 | break; 39 | } 40 | } 41 | // Handle input that is all spaces 42 | if (i == 0) input[0] = '\0'; 43 | } 44 | 45 | const int len = strlen(input); 46 | if (is_addressing(input, len)) { 47 | return "Fine. Be that way!"; 48 | } else if (is_shouting(input, len)) { 49 | return "Whoa, chill out!"; 50 | } else if (is_questioning(input, len)) { 51 | return "Sure."; 52 | } 53 | 54 | return "Whatever."; 55 | } 56 | -------------------------------------------------------------------------------- /exercism/c/bob/src/bob.h: -------------------------------------------------------------------------------- 1 | #ifndef __BOB_H_ 2 | #define __BOB_H_ 3 | 4 | #include 5 | #include 6 | 7 | const char *hey_bob(const char*); 8 | 9 | #endif // __BOB_H_ 10 | -------------------------------------------------------------------------------- /exercism/c/hello-world/src/hello_world.c: -------------------------------------------------------------------------------- 1 | #include "hello_world.h" 2 | 3 | void hello(char *buffer, int length, const char *name) { 4 | snprintf(buffer, length, "Hello, %s!", strlen(name) > 0 ? name : "World"); 5 | } 6 | -------------------------------------------------------------------------------- /exercism/c/hello-world/src/hello_world.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void hello(char *buffer, int length, const char *name); 5 | -------------------------------------------------------------------------------- /exercism/c/hello-world/test/test_hello_world.c: -------------------------------------------------------------------------------- 1 | #include "vendor/unity.h" 2 | #include "../src/hello_world.h" 3 | 4 | #define BUFFER_LENGTH 128 5 | 6 | char buffer[BUFFER_LENGTH]; 7 | 8 | void test_hello_no_name(void) { 9 | hello(buffer, BUFFER_LENGTH, ""); 10 | TEST_ASSERT_EQUAL_STRING("Hello, World!", buffer); 11 | } 12 | 13 | void test_hello_alice(void) { 14 | hello(buffer, BUFFER_LENGTH, "Alice"); 15 | TEST_ASSERT_EQUAL_STRING("Hello, Alice!", buffer); 16 | } 17 | 18 | void test_hello_bob(void){ 19 | hello(buffer, BUFFER_LENGTH, "Bob"); 20 | TEST_ASSERT_EQUAL_STRING("Hello, Bob!", buffer); 21 | } 22 | 23 | void test_no_buffer_overflow_for_small_buffer(void){ 24 | buffer[8] = '?'; 25 | hello(buffer, 8, "Mr. President"); 26 | TEST_ASSERT_EQUAL('?', buffer[8]); 27 | } 28 | 29 | int main(void) 30 | { 31 | 32 | UnityBegin("test/test_hello_world.c"); 33 | 34 | RUN_TEST(test_hello_no_name); 35 | RUN_TEST(test_hello_alice); 36 | RUN_TEST(test_hello_bob); 37 | RUN_TEST(test_no_buffer_overflow_for_small_buffer); 38 | 39 | UnityEnd(); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /exercism/c/isogram/src/isogram.c: -------------------------------------------------------------------------------- 1 | #include "isogram.h" 2 | 3 | bool is_isogram(const char str[]) { 4 | if (str == NULL) { 5 | return false; 6 | } 7 | 8 | char found[26] = {0}; 9 | for (char c; (c = *str); ++str) { 10 | if (isalpha(c) && found[tolower(c) - 'a']++) { 11 | return false; 12 | } 13 | } 14 | return true; 15 | } 16 | -------------------------------------------------------------------------------- /exercism/c/isogram/src/isogram.h: -------------------------------------------------------------------------------- 1 | #ifndef ISOGRAM_H 2 | #define ISOGRAM_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | bool is_isogram(const char[]); 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /exercism/c/leap/src/leap.c: -------------------------------------------------------------------------------- 1 | #include "leap.h" 2 | 3 | int is_leap_year(int y) { 4 | return y % 4 == 0 && ((y % 100 != 0) || (y % 400 == 0)); 5 | } 6 | -------------------------------------------------------------------------------- /exercism/c/leap/src/leap.h: -------------------------------------------------------------------------------- 1 | #ifndef __LEAP_H_ 2 | #define __LEAP_H_ 3 | 4 | int is_leap_year(int); 5 | 6 | #endif // __LEAP_H_ 7 | -------------------------------------------------------------------------------- /exercism/c/leap/test/test_leap.c: -------------------------------------------------------------------------------- 1 | #include "vendor/unity.h" 2 | #include "../src/leap.h" 3 | 4 | void resetTest(void) 5 | { 6 | } 7 | 8 | void test_a_known_leap_year(void) 9 | { 10 | TEST_ASSERT_TRUE(is_leap_year(1996)); 11 | } 12 | 13 | void test_any_old_year(void) 14 | { 15 | TEST_ASSERT_FALSE(is_leap_year(1997)); 16 | } 17 | 18 | void test_turn_of_the_20th_century(void) 19 | { 20 | TEST_ASSERT_FALSE(is_leap_year(1900)); 21 | } 22 | 23 | void test_turn_of_the_21st_century(void) 24 | { 25 | TEST_ASSERT_TRUE(is_leap_year(2000)); 26 | } 27 | 28 | void test_turn_of_the_25th_century(void) 29 | { 30 | TEST_ASSERT_TRUE(is_leap_year(2400));; 31 | } 32 | 33 | int main(void) 34 | { 35 | UnityBegin("test/test_leap.c"); 36 | 37 | RUN_TEST(test_a_known_leap_year); 38 | RUN_TEST(test_any_old_year); 39 | RUN_TEST(test_turn_of_the_20th_century); 40 | RUN_TEST(test_turn_of_the_21st_century); 41 | RUN_TEST(test_turn_of_the_25th_century); 42 | 43 | UnityEnd(); 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /exercism/c/run-length-encoding/src/run_length_encoding.c: -------------------------------------------------------------------------------- 1 | #include "run_length_encoding.h" 2 | 3 | #define BUFFER_SIZE 128 4 | 5 | int nextcount(char c, const char* input) { 6 | if (c == *input) 7 | return nextcount(c, ++input) + 1; 8 | return 0; 9 | } 10 | 11 | char* encode(const char* input) { 12 | char* output = (char*) malloc(BUFFER_SIZE); 13 | char ch; 14 | int n, i = 0; 15 | while ((ch = *input) != '\0') { 16 | if ((n = nextcount(ch, input)) > 0) { 17 | i += n > 1 18 | ? sprintf(output + i, "%d%c", n, ch) 19 | : sprintf(output + i, "%c", ch); 20 | } 21 | ch = *input; 22 | input += n; 23 | } 24 | return output; 25 | } 26 | 27 | char* decode(const char* input) { 28 | char* output = (char*) malloc(BUFFER_SIZE); 29 | char* out = output; 30 | while (*input != '\0') { 31 | char ch; 32 | int n = 1, p = 1; 33 | isdigit(*input) 34 | ? sscanf(input, "%d%c%n", &n, &ch, &p) 35 | : sscanf(input, "%c", &ch); 36 | input += p; 37 | while (n--) *(out++) = ch; 38 | } 39 | *out = '\0'; 40 | return output; 41 | } 42 | -------------------------------------------------------------------------------- /exercism/c/run-length-encoding/src/run_length_encoding.h: -------------------------------------------------------------------------------- 1 | #ifndef __RUN_LENGTH_ENCODING_H_ 2 | #define __RUN_LENGTH_ENCODING_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | char* encode(const char*); 10 | char* decode(const char*); 11 | 12 | #endif // __RUN_LENGTH_ENCODING_H_ 13 | -------------------------------------------------------------------------------- /exercism/c/sum-of-multiples/src/sum_of_multiples.c: -------------------------------------------------------------------------------- 1 | #include "sum_of_multiples.h" 2 | 3 | int sum_of_multiples(const unsigned int* nums, const size_t len, const unsigned max) { 4 | if (nums == NULL) { 5 | return 0; 6 | } 7 | 8 | unsigned int sum = 0; 9 | for (unsigned int n = nums[0]; n < max; ++n) { // assume nums is sorted 10 | for (size_t i = 0; i < len; ++i) { 11 | if (nums[i] && !(n % nums[i])) { 12 | sum += n; 13 | break; 14 | } 15 | } 16 | } 17 | return sum; 18 | } 19 | -------------------------------------------------------------------------------- /exercism/c/sum-of-multiples/src/sum_of_multiples.h: -------------------------------------------------------------------------------- 1 | #ifndef __SUM_OF_MULTIPLES_H_ 2 | #define __SUM_OF_MULTIPLES_H_ 3 | 4 | #include 5 | 6 | int sum_of_multiples(const unsigned int*, const size_t, const unsigned int); 7 | 8 | #endif // __SUM_OF_MULTIPLES_H_ 9 | -------------------------------------------------------------------------------- /exercism/elisp/anagram/README.md: -------------------------------------------------------------------------------- 1 | # Anagram 2 | 3 | Given a word and a list of possible anagrams, select the correct sublist. 4 | 5 | Given `"listen"` and a list of candidates like `"enlists" "google" 6 | "inlets" "banana"` the program should return a list containing 7 | `"inlets"`. 8 | ## Source 9 | 10 | Inspired by the Extreme Startup game [https://github.com/rchatley/extreme_startup](https://github.com/rchatley/extreme_startup) 11 | 12 | ## Submitting Incomplete Solutions 13 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 14 | -------------------------------------------------------------------------------- /exercism/elisp/anagram/anagram.el: -------------------------------------------------------------------------------- 1 | ;;; anagram.el --- Anagram (exercism) 2 | 3 | (defun anagrams-for (word candidates) 4 | (cl-loop with sorted = (cl-sort (downcase word) #'<) 5 | for cand in candidates 6 | if (and (not (string= word cand)) 7 | (string= (cl-sort (downcase cand) #'<) 8 | sorted)) 9 | collect cand)) 10 | 11 | (provide 'anagram) 12 | ;;; anagram.el ends here 13 | -------------------------------------------------------------------------------- /exercism/elisp/bob/README.md: -------------------------------------------------------------------------------- 1 | # Bob 2 | 3 | Bob is a lackadaisical teenager. In conversation, his responses are very limited. 4 | 5 | Bob answers 'Sure.' if you ask him any question, such as "How are you?". 6 | 7 | He answers 'Whoa, chill out!' if you YELL AT HIM (in all capitals). 8 | 9 | He answers 'Calm down, I know what I'm doing!' if you yell a question at him. 10 | 11 | He says 'Fine. Be that way!' if you address him without actually saying 12 | anything. 13 | 14 | He answers 'Whatever.' to anything else. 15 | 16 | Implement a function `response-for` that takes a string as argument 17 | and returns the appropriate response. 18 | 19 | ## Source 20 | 21 | Inspired by the 'Deaf Grandma' exercise in Chris Pine's Learn to Program tutorial. [http://pine.fm/LearnToProgram/?Chapter=06](http://pine.fm/LearnToProgram/?Chapter=06) 22 | 23 | ## Submitting Incomplete Solutions 24 | 25 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 26 | -------------------------------------------------------------------------------- /exercism/elisp/bob/bob.el: -------------------------------------------------------------------------------- 1 | ;;; bob.el --- Bob exercise (exercism) 2 | 3 | ;; I intentionally avoid the subr-x library 4 | 5 | (defun yelling-p (sentence) 6 | (and (string= (upcase sentence) sentence) 7 | (not (string= (downcase sentence) sentence)))) 8 | 9 | (defun response-for (sentence) 10 | (let ((sentence (replace-regexp-in-string "\\(?:^\\s-+\\|\\s-+$\\)" "" sentence))) 11 | (cond ((string= "" sentence) 12 | "Fine. Be that way!") 13 | ((string= (substring sentence -1) "?") 14 | (if (yelling-p sentence) 15 | "Calm down, I know what I'm doing!" 16 | "Sure.")) 17 | ((yelling-p sentence) 18 | "Whoa, chill out!") 19 | ("Whatever.")))) 20 | 21 | (provide 'bob) 22 | ;;; bob.el ends here 23 | -------------------------------------------------------------------------------- /exercism/elisp/difference-of-squares/README.md: -------------------------------------------------------------------------------- 1 | # Difference Of Squares 2 | 3 | Find the difference between the square of the sum and the sum of the squares of the first N natural numbers. 4 | 5 | The square of the sum of the first ten natural numbers is 6 | (1 + 2 + ... + 10)² = 55² = 3025. 7 | 8 | The sum of the squares of the first ten natural numbers is 9 | 1² + 2² + ... + 10² = 385. 10 | 11 | Hence the difference between the square of the sum of the first 12 | ten natural numbers and the sum of the squares of the first ten 13 | natural numbers is 3025 - 385 = 2640. 14 | ## Source 15 | 16 | Problem 6 at Project Euler [http://projecteuler.net/problem=6](http://projecteuler.net/problem=6) 17 | 18 | ## Submitting Incomplete Solutions 19 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 20 | -------------------------------------------------------------------------------- /exercism/elisp/difference-of-squares/difference-of-squares-test.el: -------------------------------------------------------------------------------- 1 | ;;; difference-of-squares-test.el --- Tests for difference-of-squares (exercism) 2 | 3 | ;;; Commentary: 4 | 5 | ;;; Code: 6 | 7 | (load-file "difference-of-squares.el") 8 | 9 | (ert-deftest square-of-sum-to-5 () 10 | (should (= 225 (square-of-sum 5)))) 11 | 12 | (ert-deftest sum-of-squares-to-5 () 13 | (should (= 55 (sum-of-squares 5)))) 14 | 15 | (ert-deftest difference-of-squares-to-5 () 16 | (should (= 170 (difference 5)))) 17 | 18 | 19 | (ert-deftest square-of-sum-to-10 () 20 | (should (= 3025 (square-of-sum 10)))) 21 | 22 | (ert-deftest sum-of-squares-to-10 () 23 | (should (= 385 (sum-of-squares 10)))) 24 | 25 | (ert-deftest difference-of-squares-to-10 () 26 | (should (= 2640 (difference 10)))) 27 | 28 | 29 | (ert-deftest square-of-sum-to-100 () 30 | (should (= 25502500 (square-of-sum 100)))) 31 | 32 | (ert-deftest sum-of-squares-to-100 () 33 | (should (= 338350 (sum-of-squares 100)))) 34 | 35 | (ert-deftest difference-of-squares-to-100 () 36 | (should (= 25164150 (difference 100)))) 37 | 38 | 39 | (provide 'difference-of-squares-test) 40 | ;;; difference-of-squares-test.el ends here 41 | -------------------------------------------------------------------------------- /exercism/elisp/difference-of-squares/difference-of-squares.el: -------------------------------------------------------------------------------- 1 | ;;; difference-of-squares.el --- Difference of Squares (exercism) 2 | 3 | (defun sum-of-squares (n) 4 | (/ (* (1+ (* 2 n)) (1+ n) n) 6)) 5 | 6 | (defun square-of-sum (n) 7 | (expt (/ (* n (1+ n)) 2) 2)) 8 | 9 | (defun difference (n) 10 | (- (square-of-sum n) 11 | (sum-of-squares n))) 12 | 13 | (provide 'difference-of-squares) 14 | ;;; difference-of-squares.el ends here 15 | -------------------------------------------------------------------------------- /exercism/elisp/gigasecond/README.md: -------------------------------------------------------------------------------- 1 | # Gigasecond 2 | 3 | Calculate the moment when someone has lived for 10^9 seconds. 4 | 5 | A gigasecond is 10^9 (1,000,000,000) seconds. 6 | ## Source 7 | 8 | Chapter 9 in Chris Pine's online Learn to Program tutorial. [http://pine.fm/LearnToProgram/?Chapter=09](http://pine.fm/LearnToProgram/?Chapter=09) 9 | 10 | ## Submitting Incomplete Solutions 11 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 12 | -------------------------------------------------------------------------------- /exercism/elisp/gigasecond/gigasecond-test.el: -------------------------------------------------------------------------------- 1 | ;;; gigasecond-test.el --- ERT tests for gigasecond (exercism) 2 | 3 | ;;; Commentary: 4 | ;; 5 | ;; Tests ported from Common Lisp gigasecond: 6 | ;; https://github.com/exercism/xlisp/blob/master/gigasecond/gigasecond-test.lisp 7 | ;; 8 | ;; To run tests individually: M-x eval-buffer RET, M-x ert RET test-name. 9 | ;; If you're using helm or something similar, you should get a menu of test names. 10 | ;; 11 | ;; To run tests in batch mode, from the command line run: 12 | ;; emacs -batch -l ert -l gigasecond-test.el -f ert-run-tests-batch-and-exit 13 | 14 | ;;; Code: 15 | 16 | (load-file "gigasecond.el") 17 | 18 | (ert-deftest from-lisp-epoch () 19 | (should 20 | (equal '(40 46 1 10 9 1931) (from 0 0 0 1 1 1900)))) 21 | 22 | (ert-deftest from-unix-epoch () 23 | (should 24 | (equal '(40 46 1 9 9 2001) (from 0 0 0 1 1 1970)))) 25 | 26 | (ert-deftest from-20110425T120000Z () 27 | (should 28 | (equal '(40 46 13 1 1 2043) (from 0 0 12 25 4 2011)))) 29 | 30 | (ert-deftest from-19770613T235959Z () 31 | (should 32 | (equal '(39 46 1 20 2 2009) (from 59 59 23 13 6 1977)))) 33 | 34 | (ert-deftest from-19590719T123030Z () 35 | (should 36 | (equal '(10 17 14 27 3 1991) (from 30 30 12 19 7 1959)))) 37 | 38 | ; customize this test to test your birthday and find your gigasecond date: 39 | ; (ert-deftest your-birthday () 40 | ; (should 41 | ; (equal '(0 0 0 day2 month2 year2) (from 0 0 0 day1 month1 year1)))) 42 | 43 | 44 | 45 | (provide 'gigasecond-test) 46 | ;;; gigasecond-test.el ends here 47 | -------------------------------------------------------------------------------- /exercism/elisp/gigasecond/gigasecond.el: -------------------------------------------------------------------------------- 1 | ;;; gigasecond.el --- Gigasecond exercise (exercism) 2 | 3 | (defun from (s m h D M Y) 4 | (nbutlast ; discard dow, dst & utcoff 5 | (decode-time (encode-time (+ s (expt 10 9)) m h D M Y 0) 6 | 0) 7 | 3)) 8 | 9 | (provide 'gigasecond) 10 | ;;; gigasecond.el ends here 11 | -------------------------------------------------------------------------------- /exercism/elisp/hamming/hamming.el: -------------------------------------------------------------------------------- 1 | ;;; hamming.el --- Hamming (exercism) 2 | 3 | (defun hamming-distance (a b) 4 | (unless (= (length a) 5 | (length b)) 6 | (error nil)) 7 | (cl-count nil (cl-mapcar #'= a b))) 8 | 9 | (provide 'hamming) 10 | ;;; hamming.el ends here 11 | -------------------------------------------------------------------------------- /exercism/elisp/hello-world/README.md: -------------------------------------------------------------------------------- 1 | # Hello World 2 | 3 | The classical introductory exercise. Just say "Hello, World!". 4 | 5 | ["Hello, World!"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is 6 | the traditional first program for beginning programming in a new language 7 | or environment. 8 | 9 | The objectives are simple: 10 | 11 | - Write a function that returns the string "Hello, World!". 12 | - Run the test suite and make sure that it succeeds. 13 | - Submit your solution and check it at the website. 14 | 15 | If everything goes well, you will be ready to fetch your first real exercise. 16 | ## Source 17 | 18 | This is an exercise to introduce users to using Exercism [http://en.wikipedia.org/wiki/%22Hello,_world!%22_program](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) 19 | 20 | ## Submitting Incomplete Solutions 21 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 22 | -------------------------------------------------------------------------------- /exercism/elisp/hello-world/hello-world-test.el: -------------------------------------------------------------------------------- 1 | ;;; hello-world-test.el --- Tests for Hello World (exercism) 2 | 3 | ;;; Commentary: 4 | ;; Common test data version: 1.1.0 be3ae66 5 | 6 | ;;; Code: 7 | 8 | (load-file "hello-world.el") 9 | 10 | (ert-deftest hello-world-test () 11 | (should (equal (hello) "Hello, World!"))) 12 | 13 | (provide 'hello-world-test) 14 | 15 | ;;; hello-world-test.el ends here 16 | -------------------------------------------------------------------------------- /exercism/elisp/hello-world/hello-world.el: -------------------------------------------------------------------------------- 1 | (defun hello () 2 | "Hello, World!") 3 | -------------------------------------------------------------------------------- /exercism/elisp/leap/README.md: -------------------------------------------------------------------------------- 1 | # Leap 2 | 3 | Given a year, report if it is a leap year. 4 | 5 | The tricky thing here is that a leap year in the Gregorian calendar occurs: 6 | 7 | ```plain 8 | on every year that is evenly divisible by 4 9 | except every year that is evenly divisible by 100 10 | unless the year is also evenly divisible by 400 11 | ``` 12 | 13 | For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap 14 | year, but 2000 is. 15 | 16 | If your language provides a method in the standard library that does 17 | this look-up, pretend it doesn't exist and implement it yourself. 18 | 19 | ## Notes 20 | 21 | Though our exercise adopts some very simple rules, there is more to 22 | learn! 23 | 24 | For a delightful, four minute explanation of the whole leap year 25 | phenomenon, go watch [this youtube video][video]. 26 | 27 | [video]: http://www.youtube.com/watch?v=xX96xng7sAE 28 | ## Source 29 | 30 | JavaRanch Cattle Drive, exercise 3 [http://www.javaranch.com/leap.jsp](http://www.javaranch.com/leap.jsp) 31 | 32 | ## Submitting Incomplete Solutions 33 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 34 | -------------------------------------------------------------------------------- /exercism/elisp/leap/leap-test.el: -------------------------------------------------------------------------------- 1 | ;;; leap-test.el --- Tests for Leap exercise (exercism) 2 | 3 | ;;; Commentary: 4 | 5 | ;;; Code: 6 | (load-file "leap.el") 7 | 8 | (ert-deftest vanilla-leap-year () 9 | (should (leap-year-p 1996))) 10 | 11 | (ert-deftest any-old-year () 12 | (should-not (leap-year-p 1997))) 13 | 14 | (ert-deftest non-leap-even-year () 15 | (should-not (leap-year-p 1997))) 16 | 17 | (ert-deftest century () 18 | (should-not (leap-year-p 1900))) 19 | 20 | (ert-deftest exceptional-century () 21 | (should (leap-year-p 2000))) 22 | 23 | (provide 'leap-test) 24 | ;;; leap-test.el ends here 25 | -------------------------------------------------------------------------------- /exercism/elisp/leap/leap.el: -------------------------------------------------------------------------------- 1 | ;;; leap.el --- Leap exercise (exercism) 2 | 3 | ;;; Commentary: 4 | 5 | ;;; Code: 6 | 7 | (defun leap-year-p (year) 8 | (and (zerop (% year 4)) 9 | (or (not (zerop (% year 100))) 10 | (zerop (% year 400))))) 11 | 12 | ;; Or use `date-leap-year-p' 13 | 14 | (provide 'leap) 15 | ;;; leap.el ends here 16 | -------------------------------------------------------------------------------- /exercism/elisp/pangram/README.md: -------------------------------------------------------------------------------- 1 | # Pangram 2 | 3 | Determine if a sentence is a pangram. A pangram (Greek: παν γράμμα, pan gramma, 4 | "every letter") is a sentence using every letter of the alphabet at least once. 5 | The best known English pangram is: 6 | > The quick brown fox jumps over the lazy dog. 7 | 8 | The alphabet used consists of ASCII letters `a` to `z`, inclusive, and is case 9 | insensitive. Input will not contain non-ASCII symbols. 10 | 11 | ## Source 12 | 13 | Wikipedia [https://en.wikipedia.org/wiki/Pangram](https://en.wikipedia.org/wiki/Pangram) 14 | 15 | ## Submitting Incomplete Solutions 16 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 17 | -------------------------------------------------------------------------------- /exercism/elisp/pangram/pangram.el: -------------------------------------------------------------------------------- 1 | ;;; pangram.el --- Pangram (exercism) 2 | 3 | (defun is-pangram (str) 4 | (cl-loop with chars = (string-to-list (downcase str)) 5 | for i from ?a to ?z 6 | unless (memq i chars) return nil 7 | finally return t)) 8 | 9 | (provide 'pangram) 10 | ;;; pangram.el ends here 11 | -------------------------------------------------------------------------------- /exercism/elisp/raindrops/README.md: -------------------------------------------------------------------------------- 1 | # Raindrops 2 | 3 | Convert a number to a string, the contents of which depend on the number's factors. 4 | 5 | - If the number has 3 as a factor, output 'Pling'. 6 | - If the number has 5 as a factor, output 'Plang'. 7 | - If the number has 7 as a factor, output 'Plong'. 8 | - If the number does not have 3, 5, or 7 as a factor, 9 | just pass the number's digits straight through. 10 | 11 | ## Examples 12 | 13 | - 28's factors are 1, 2, 4, **7**, 14, 28. 14 | - In raindrop-speak, this would be a simple "Plong". 15 | - 30's factors are 1, 2, **3**, **5**, 6, 10, 15, 30. 16 | - In raindrop-speak, this would be a "PlingPlang". 17 | - 34 has four factors: 1, 2, 17, and 34. 18 | - In raindrop-speak, this would be "34". 19 | ## Source 20 | 21 | A variation on a famous interview question intended to weed out potential candidates. [http://jumpstartlab.com](http://jumpstartlab.com) 22 | 23 | ## Submitting Incomplete Solutions 24 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 25 | -------------------------------------------------------------------------------- /exercism/elisp/raindrops/raindrops.el: -------------------------------------------------------------------------------- 1 | ;;; raindrops.el --- Raindrops (exercism) 2 | 3 | (defun convert (n) 4 | "Convert integer N to its raindrops string." 5 | (let ((str (concat (if (= 0 (% n 3)) "Pling") 6 | (if (= 0 (% n 5)) "Plang") 7 | (if (= 0 (% n 7)) "Plong")))) 8 | (if (string= str "") 9 | (number-to-string n) 10 | str))) 11 | 12 | (provide 'raindrops) 13 | ;;; raindrops.el ends here 14 | -------------------------------------------------------------------------------- /exercism/elisp/robot-name/README.md: -------------------------------------------------------------------------------- 1 | # Robot Name 2 | 3 | Manage robot factory settings. 4 | 5 | When robots come off the factory floor, they have no name. 6 | 7 | The first time you boot them up, a random name is generated in the format 8 | of two uppercase letters followed by three digits, such as RX837 or BC811. 9 | 10 | Every once in a while we need to reset a robot to its factory settings, 11 | which means that their name gets wiped. The next time you ask, it will 12 | respond with a new random name. 13 | 14 | The names must be random: they should not follow a predictable sequence. 15 | Random names means a risk of collisions. Your solution must ensure that 16 | every existing robot has a unique name. 17 | ## Source 18 | 19 | A debugging session with Paul Blackwell at gSchool. [http://gschool.it](http://gschool.it) 20 | 21 | ## Submitting Incomplete Solutions 22 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 23 | -------------------------------------------------------------------------------- /exercism/elisp/robot-name/robot-name-test.el: -------------------------------------------------------------------------------- 1 | ;;; robot-name-test.el --- Tests for Robot Name (exercism) 2 | 3 | ;;; Commentary: 4 | 5 | ;; Ported pretty much directly from the xlisp version :) 6 | 7 | ;;; Code: 8 | 9 | (require 'rx) 10 | 11 | (load-file "robot-name.el") 12 | 13 | (defconst *robbie* (build-robot)) 14 | (defconst *clutz* (build-robot)) 15 | 16 | (defvar robot-name-re 17 | (rx string-start 18 | (= 2 upper-case) 19 | (= 3 digit) 20 | string-end)) 21 | 22 | (ert-deftest name-matches-expected-pattern () 23 | (let ((name (robot-name *robbie*))) 24 | (should (string-match-p robot-name-re name)))) 25 | 26 | (ert-deftest name-is-persistent () 27 | "Test that robot name is persistent." 28 | (should (equal (robot-name *robbie*) (robot-name *robbie*)))) 29 | 30 | (ert-deftest different-robots-have-different-names () 31 | (should-not (equal (robot-name *robbie*) (robot-name *clutz*)))) 32 | 33 | (ert-deftest name-can-be-reset () 34 | (let* ((robot (build-robot)) 35 | (original-name (robot-name robot))) 36 | (reset-robot robot) 37 | (should-not (equal original-name (robot-name robot))))) 38 | 39 | (provide 'robot-name-test) 40 | ;;; robot-name-test.el ends here 41 | -------------------------------------------------------------------------------- /exercism/elisp/robot-name/robot-name.el: -------------------------------------------------------------------------------- 1 | ;;; robot-name.el --- Robot Name (exercism) 2 | 3 | ;;; Commentary: 4 | ;; 5 | ;; Build a robot with a name like AA000, that can be reset 6 | ;; to a new name. Instructions are in README.md 7 | ;; 8 | 9 | ;;; Code: 10 | 11 | (defun build-robot () 12 | (reset-robot (cons 'robot nil))) 13 | 14 | (defun robot-name (robot) 15 | (cdr robot)) 16 | 17 | (defun reset-robot (robot) 18 | (setcdr robot (format "%c%c%d" 19 | (+ ?A (random 26)) 20 | (+ ?A (random 26)) 21 | (random 1000))) 22 | robot) 23 | 24 | (provide 'robot-name) 25 | ;;; robot-name.el ends here 26 | -------------------------------------------------------------------------------- /exercism/elisp/word-count/README.md: -------------------------------------------------------------------------------- 1 | # Word Count 2 | 3 | Given a phrase, count the occurrences of each word in that phrase. 4 | 5 | For example for the input `"olly olly in come free"` 6 | 7 | ```plain 8 | olly: 2 9 | in: 1 10 | come: 1 11 | free: 1 12 | ``` 13 | 14 | ## Source 15 | 16 | This is a classic toy problem, but we were reminded of it by seeing it in the Go Tour. 17 | 18 | ## Submitting Incomplete Solutions 19 | It's possible to submit an incomplete solution so you can see how others have completed the exercise. 20 | -------------------------------------------------------------------------------- /exercism/elisp/word-count/word-count.el: -------------------------------------------------------------------------------- 1 | ;;; word-count.el --- word-count Exercise (exercism) 2 | 3 | (defun word-count (text) 4 | (let (alist) 5 | (with-temp-buffer 6 | (save-excursion 7 | (insert text)) 8 | (while (re-search-forward "[[:alnum:]]+" nil t) 9 | (let* ((word (downcase (match-string 0)))) 10 | (setf (alist-get word alist nil nil #'equal) 11 | (1+ (or (cdr (assoc word alist)) 0)))))) 12 | alist)) 13 | 14 | (provide 'word-count) 15 | ;;; word-count.el ends here 16 | -------------------------------------------------------------------------------- /exercism/go/hello-world/hello_test.go: -------------------------------------------------------------------------------- 1 | package hello 2 | 3 | import "testing" 4 | 5 | // Define a function HelloWorld(string) string. 6 | // 7 | // Also define a testVersion with a value that matches 8 | // the targetTestVersion here. 9 | 10 | const targetTestVersion = 2 11 | 12 | func TestHelloWorld(t *testing.T) { 13 | tests := []struct { 14 | name, expected string 15 | }{ 16 | {"", "Hello, World!"}, 17 | {"Gopher", "Hello, Gopher!"}, 18 | } 19 | for _, test := range tests { 20 | observed := HelloWorld(test.name) 21 | if observed != test.expected { 22 | t.Fatalf("HelloWorld(%s) = %v, want %v", test.name, observed, test.expected) 23 | } 24 | } 25 | 26 | if testVersion != targetTestVersion { 27 | t.Fatalf("Found testVersion = %v, want %v", testVersion, targetTestVersion) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /exercism/go/hello-world/hello_world.go: -------------------------------------------------------------------------------- 1 | package hello 2 | 3 | const testVersion = 2 4 | 5 | func HelloWorld(name string) string { 6 | if name == "" { 7 | name = "World" 8 | } 9 | return "Hello, " + name + "!" 10 | } 11 | -------------------------------------------------------------------------------- /exercism/go/leap/README.md: -------------------------------------------------------------------------------- 1 | # Leap 2 | 3 | Write a program that will take a year and report if it is a leap year. 4 | 5 | The tricky thing here is that a leap year in the Gregorian calendar occurs: 6 | 7 | ```plain 8 | on every year that is evenly divisible by 4 9 | except every year that is evenly divisible by 100 10 | unless the year is also evenly divisible by 400 11 | ``` 12 | 13 | For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap 14 | year, but 2000 is. 15 | 16 | If your language provides a method in the standard library that does 17 | this look-up, pretend it doesn't exist and implement it yourself. 18 | 19 | ## Notes 20 | 21 | For a delightful, four minute explanation of the whole leap year 22 | phenomenon, go watch [this youtube video][video]. 23 | 24 | [video]: http://www.youtube.com/watch?v=xX96xng7sAE 25 | 26 | To run the tests simply run the command `go test` in the exercise directory. 27 | 28 | If the test suite contains benchmarks, you can run these with the `-bench` 29 | flag: 30 | 31 | go test -bench . 32 | 33 | For more detailed info about the Go track see the [help 34 | page](http://exercism.io/languages/go). 35 | 36 | ## Source 37 | 38 | JavaRanch Cattle Drive, exercise 3 [http://www.javaranch.com/leap.jsp](http://www.javaranch.com/leap.jsp) 39 | -------------------------------------------------------------------------------- /exercism/go/leap/cases_test.go: -------------------------------------------------------------------------------- 1 | package leap 2 | 3 | // Source: exercism/x-common 4 | // Commit: 945d08e Merge pull request #50 from soniakeys/master 5 | 6 | var testCases = []struct { 7 | year int 8 | expected bool 9 | description string 10 | }{ 11 | {1996, true, "leap year"}, 12 | {1997, false, "non-leap year"}, 13 | {1998, false, "non-leap even year"}, 14 | {1900, false, "century"}, 15 | {2400, true, "fourth century"}, 16 | {2000, true, "Y2K"}, 17 | } 18 | -------------------------------------------------------------------------------- /exercism/go/leap/leap.go: -------------------------------------------------------------------------------- 1 | package leap 2 | 3 | const testVersion = 2 4 | 5 | func IsLeapYear(y int) bool { 6 | return (y%4 == 0) && (y%100 != 0 || y%400 == 0) 7 | } 8 | -------------------------------------------------------------------------------- /exercism/go/leap/leap_test.go: -------------------------------------------------------------------------------- 1 | package leap 2 | 3 | import "testing" 4 | 5 | // Define a function IsLeapYear(int) bool. 6 | // 7 | // Also define a testVersion with a value that matches 8 | // the targetTestVersion here. 9 | 10 | const targetTestVersion = 2 11 | 12 | func TestLeapYears(t *testing.T) { 13 | if testVersion != targetTestVersion { 14 | t.Fatalf("Found testVersion = %v, want %v", testVersion, targetTestVersion) 15 | } 16 | for _, test := range testCases { 17 | observed := IsLeapYear(test.year) 18 | if observed != test.expected { 19 | t.Fatalf("IsLeapYear(%d) = %t, want %t (%s)", 20 | test.year, observed, test.expected, test.description) 21 | } 22 | } 23 | } 24 | 25 | // Benchmark 400 year interval to get fair weighting of different years. 26 | func Benchmark400(b *testing.B) { 27 | for i := 0; i < b.N; i++ { 28 | for y := 1600; y < 2000; y++ { 29 | IsLeapYear(y) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /exercism/haskell/anagram/package.yaml: -------------------------------------------------------------------------------- 1 | name: anagram 2 | version: 1.0.1.4 3 | 4 | dependencies: 5 | - base 6 | 7 | library: 8 | exposed-modules: Anagram 9 | source-dirs: src 10 | dependencies: 11 | # - foo # List here the packages you 12 | # - bar # want to use in your solution. 13 | 14 | tests: 15 | test: 16 | main: Tests.hs 17 | source-dirs: test 18 | dependencies: 19 | - anagram 20 | - hspec 21 | -------------------------------------------------------------------------------- /exercism/haskell/anagram/src/Anagram.hs: -------------------------------------------------------------------------------- 1 | module Anagram (anagramsFor) where 2 | 3 | import Data.Char (toLower, isAlpha) 4 | import Data.List (sort) 5 | 6 | downcase :: String -> String 7 | downcase s = [ toLower c | c <- s, isAlpha c ] 8 | 9 | isAnagram :: String -> String -> Bool 10 | isAnagram s o 11 | | length s /= length o = False 12 | | str == other = False 13 | | otherwise = sort str == sort other 14 | where str = downcase s 15 | other = downcase o 16 | 17 | anagramsFor :: String -> [String] -> [String] 18 | anagramsFor str xs = filter (isAnagram str) xs 19 | -------------------------------------------------------------------------------- /exercism/haskell/anagram/stack.yaml: -------------------------------------------------------------------------------- 1 | resolver: lts-8.21 2 | -------------------------------------------------------------------------------- /exercism/ruby/difference-of-squares/.version: -------------------------------------------------------------------------------- 1 | 2 -------------------------------------------------------------------------------- /exercism/ruby/difference-of-squares/difference_of_squares.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | class Squares 4 | VERSION = 2 5 | 6 | def initialize(n) 7 | @n = n 8 | end 9 | 10 | def square_of_sum 11 | (@n * (@n + 1) / 2) ** 2 12 | end 13 | 14 | def sum_of_squares 15 | ((2 * @n) + 1) * (@n + 1) * @n / 6 16 | end 17 | 18 | def difference 19 | square_of_sum - sum_of_squares 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /exercism/rust/beer-song/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/beer-song/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "beer-song" 3 | version = "0.0.0" 4 | -------------------------------------------------------------------------------- /exercism/rust/beer-song/src/lib.rs: -------------------------------------------------------------------------------- 1 | fn head(n: i32, cap: bool) -> String { 2 | match n { 3 | 0 => format!("{}o more bottles", if cap { 'N' } else { 'n' }), 4 | 1 => "1 bottle".to_string(), 5 | -1 => "99 bottles".to_string(), 6 | _ => format!("{} bottles", n) 7 | } 8 | } 9 | 10 | fn tail(n: i32) -> String { 11 | match n { 12 | 0 => "Go to the store and buy some more,".to_string(), 13 | _ => format!("Take {} down and pass it around,", if n == 1 { "it" } else { "one" }) 14 | } 15 | } 16 | 17 | pub fn verse(n: i32) -> String { 18 | format!("{} of beer on the wall, {} of beer.\n{} {} of beer on the wall.\n", 19 | head(n, true), 20 | head(n, false), 21 | tail(n), 22 | head(n-1, false)) 23 | } 24 | 25 | pub fn sing(start: i32, end: i32) -> String { 26 | (end..start+1) 27 | .rev() 28 | .map(verse) 29 | .collect::>() 30 | .join("\n") 31 | } 32 | -------------------------------------------------------------------------------- /exercism/rust/gigasecond/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/gigasecond/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "gigasecond" 3 | version = "1.1.0" 4 | 5 | [dependencies] 6 | chrono = "0.4" 7 | 8 | -------------------------------------------------------------------------------- /exercism/rust/gigasecond/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate chrono; 2 | use chrono::*; 3 | 4 | // Returns a Utc DateTime one billion seconds after start. 5 | pub fn after(start: DateTime) -> DateTime { 6 | start + Duration::seconds(1_000_000_000) 7 | } 8 | -------------------------------------------------------------------------------- /exercism/rust/hello-world/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/hello-world/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hello-world" 3 | version = "0.0.0" 4 | -------------------------------------------------------------------------------- /exercism/rust/hello-world/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn hello(name: Option<&str>) -> String { 2 | format!("Hello, {}!", name.unwrap_or("World")) 3 | } 4 | -------------------------------------------------------------------------------- /exercism/rust/hello-world/tests/hello-world.rs: -------------------------------------------------------------------------------- 1 | extern crate hello_world; 2 | 3 | #[test] 4 | fn test_no_name() { 5 | assert_eq!("Hello, World!", hello_world::hello(None)); 6 | } 7 | 8 | #[test] 9 | fn test_sample_name() { 10 | assert_eq!("Hello, Alice!", hello_world::hello(Some("Alice"))); 11 | } 12 | 13 | #[test] 14 | fn test_other_same_name() { 15 | assert_eq!("Hello, Bob!", hello_world::hello(Some("Bob"))); 16 | } 17 | -------------------------------------------------------------------------------- /exercism/rust/leap/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/leap/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "leap" 3 | version = "1.0.0" 4 | -------------------------------------------------------------------------------- /exercism/rust/leap/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn is_leap_year(year: i32) -> bool { 2 | year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) 3 | } 4 | -------------------------------------------------------------------------------- /exercism/rust/leap/tests/leap.rs: -------------------------------------------------------------------------------- 1 | extern crate leap; 2 | 3 | #[test] 4 | fn test_vanilla_leap_year() { 5 | assert_eq!(leap::is_leap_year(1996), true); 6 | } 7 | 8 | #[test] 9 | fn test_any_old_year() { 10 | assert_eq!(leap::is_leap_year(1997), false); 11 | } 12 | 13 | #[test] 14 | fn test_century() { 15 | assert_eq!(leap::is_leap_year(1900), false); 16 | } 17 | 18 | #[test] 19 | fn test_exceptional_centuries() { 20 | assert_eq!(leap::is_leap_year(2000), true); 21 | assert_eq!(leap::is_leap_year(2400), true); 22 | } 23 | -------------------------------------------------------------------------------- /exercism/rust/nth-prime/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | **/*.rs.bk 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 8 | Cargo.lock 9 | -------------------------------------------------------------------------------- /exercism/rust/nth-prime/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "nth_prime" 4 | version = "2.1.0" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /exercism/rust/nth-prime/src/lib.rs: -------------------------------------------------------------------------------- 1 | fn is_prime(n: u32) -> bool { 2 | ! (2..3).chain((3..(n as f32).sqrt() as u32 + 1).step_by(2)) 3 | .any(|x| n % x == 0) 4 | } 5 | 6 | pub fn nth(n: u32) -> u32 { 7 | (2..3).chain((3..).filter(|x| is_prime(*x))) 8 | .nth(n as usize) 9 | .unwrap() 10 | } 11 | -------------------------------------------------------------------------------- /exercism/rust/nth-prime/tests/nth-prime.rs: -------------------------------------------------------------------------------- 1 | use nth_prime as np; 2 | 3 | #[test] 4 | fn test_first_prime() { 5 | assert_eq!(np::nth(0), 2); 6 | } 7 | 8 | #[test] 9 | fn test_second_prime() { 10 | assert_eq!(np::nth(1), 3); 11 | } 12 | 13 | #[test] 14 | fn test_sixth_prime() { 15 | assert_eq!(np::nth(5), 13); 16 | } 17 | 18 | #[test] 19 | fn test_big_prime() { 20 | assert_eq!(np::nth(10000), 104743); 21 | } 22 | -------------------------------------------------------------------------------- /exercism/rust/nucleotide-count/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/nucleotide-count/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nucleotide-count" 3 | version = "0.0.0" 4 | -------------------------------------------------------------------------------- /exercism/rust/nucleotide-count/src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | const ALLOWED: [char; 4] = ['A', 'T', 'C', 'G']; 4 | 5 | type DNAResult = Result; 6 | 7 | fn is_valid_char(c: char) -> bool { 8 | ALLOWED.contains(&c) 9 | } 10 | 11 | fn is_valid_str(str: &str) -> bool { 12 | str.chars().all(is_valid_char) 13 | } 14 | 15 | pub fn count(c: char, s: &str) -> DNAResult { 16 | if is_valid_char(c) && is_valid_str(&s) { 17 | Ok(s.matches(c).count()) 18 | } else { 19 | Err(()) 20 | } 21 | } 22 | 23 | pub fn nucleotide_counts(s: &str) -> DNAResult> { 24 | if is_valid_str(&s) { 25 | Ok(ALLOWED.into_iter().map(|ch| (*ch, count(*ch, &s).unwrap())).collect()) 26 | } else { 27 | Err(()) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /exercism/rust/raindrops/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /exercism/rust/raindrops/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "raindrops" 3 | version = "1.1.0" 4 | -------------------------------------------------------------------------------- /exercism/rust/raindrops/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn raindrops(n: usize) -> String { 2 | let factors = vec![(3, "Pling"), (5, "Plang"), (7, "Plong")] 3 | .iter() 4 | .filter_map(|&(f,s)| if n % f == 0 {Some(s)} else {None}) 5 | .collect::(); 6 | if factors.is_empty() {n.to_string()} else {factors} 7 | } 8 | -------------------------------------------------------------------------------- /exercism/rust/reverse-string/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Cargo.lock if creating a library 2 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /exercism/rust/reverse-string/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "reverse_string" 3 | version = "1.0.0" 4 | authors = ["Peter Goodspeed-Niklaus "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /exercism/rust/reverse-string/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub fn reverse(s: &str) -> String { 2 | s.chars().rev().collect::() 3 | } 4 | -------------------------------------------------------------------------------- /exercism/rust/reverse-string/tests/reverse-string.rs: -------------------------------------------------------------------------------- 1 | //! Tests for reverse-string 2 | //! 3 | //! Generated by [script][script] using [canonical data][canonical-data] 4 | //! 5 | //! [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py 6 | //! [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json 7 | 8 | 9 | extern crate reverse_string; 10 | use reverse_string::*; 11 | 12 | /// Process a single test case for the property `reverse` 13 | fn process_reverse_case(input: &str, expected: &str) { 14 | assert_eq!( 15 | &reverse(input), 16 | expected 17 | ) 18 | } 19 | 20 | 21 | #[test] 22 | /// empty string 23 | fn test_empty_string() { 24 | process_reverse_case("", ""); 25 | } 26 | 27 | 28 | #[test] 29 | /// a word 30 | fn test_a_word() { 31 | process_reverse_case("robot", "tobor"); 32 | } 33 | 34 | 35 | #[test] 36 | /// a capitalized word 37 | fn test_a_capitalized_word() { 38 | process_reverse_case("Ramen", "nemaR"); 39 | } 40 | 41 | 42 | #[test] 43 | /// a sentence with punctuation 44 | fn test_a_sentence_with_punctuation() { 45 | process_reverse_case("I'm hungry!", "!yrgnuh m'I"); 46 | } 47 | 48 | 49 | #[test] 50 | /// a palindrome 51 | fn test_a_palindrome() { 52 | process_reverse_case("racecar", "racecar"); 53 | } 54 | 55 | #[test] 56 | /// wide characters 57 | fn test_wide_characters() { 58 | process_reverse_case("子猫", "猫子"); 59 | } 60 | -------------------------------------------------------------------------------- /exercism/rust/sum-of-multiples/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | **/*.rs.bk 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock 8 | Cargo.lock 9 | -------------------------------------------------------------------------------- /exercism/rust/sum-of-multiples/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2018" 3 | name = "sum-of-multiples" 4 | version = "1.5.0" 5 | -------------------------------------------------------------------------------- /exercism/rust/sum-of-multiples/src/lib.rs: -------------------------------------------------------------------------------- 1 | fn is_multiple(n: u32, of: u32) -> bool { 2 | of != 0 && n % of == 0 3 | } 4 | 5 | pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { 6 | (1..limit).filter(|&i| factors.iter().any(|&j| is_multiple(i, j))) 7 | .sum() 8 | } 9 | -------------------------------------------------------------------------------- /leetcode/191-Number-of-1-Bits/README.md: -------------------------------------------------------------------------------- 1 | # 191. Number of 1 Bits 2 | 3 | > Source: https://leetcode.com/problems/number-of-1-bits/ 4 | 5 | Write a function that takes an unsigned integer and returns the number of `1` bits it has 6 | (also known as the Hamming weight). 7 | 8 | **For example:** 9 | 10 | The 32-bit integer `11` has binary representation `00000000000000000000000000001011`, so 11 | the function should return `3`. 12 | -------------------------------------------------------------------------------- /leetcode/191-Number-of-1-Bits/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int hammingWeight(uint32_t n) { 5 | int count = 0; 6 | while (n > 0) { 7 | if (n&1) ++count; 8 | n = n >> 1; 9 | } 10 | return count; 11 | } 12 | 13 | int main() { 14 | printf("%d\n", hammingWeight(11)); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/258-Add-Digits/README.md: -------------------------------------------------------------------------------- 1 | # 258. Add Digits 2 | 3 | > Source: https://leetcode.com/problems/add-digits/ 4 | 5 | Given a non-negative integer num, repeatedly add all its digits until the result has only 6 | one digit. 7 | 8 | **For example:** 9 | 10 | Given `num = 38`, the process is like: `3 + 8 = 11`, `1 + 1 = 2`. Since `2` has only one 11 | digit, return it. 12 | -------------------------------------------------------------------------------- /leetcode/258-Add-Digits/solution.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | // Naive solution: O(n log n) 6 | int naiveAddDigits(int num) { 7 | if (num < 0) num = abs(num); 8 | if (num < 10) return num; 9 | int sum = 0; 10 | while (num > 0) { 11 | sum += num % 10; 12 | num /= 10; 13 | } 14 | return naiveAddDigits(sum); 15 | } 16 | 17 | // O(1) solution 18 | int addDigits(int num) { 19 | return 1 + ((abs(num)-1) % 9); 20 | } 21 | 22 | 23 | int main() { 24 | // Positive 25 | printf("%d %d\n", addDigits(38), naiveAddDigits(38) ); 26 | printf("%d %d\n", addDigits(199), naiveAddDigits(199)); 27 | printf("%d %d\n", addDigits(4), naiveAddDigits(4) ); 28 | // Negatives 29 | printf("%d %d\n", addDigits(-38), naiveAddDigits(-38) ); 30 | printf("%d %d\n", addDigits(-199), naiveAddDigits(-199)); 31 | printf("%d %d\n", addDigits(-4), naiveAddDigits(-4) ); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /leetcode/344-Reverse-String/README.md: -------------------------------------------------------------------------------- 1 | # 344. Reverse String 2 | 3 | Write a function that takes a string as input and returns the string reversed. 4 | 5 | **Example:** 6 | 7 | Given s = "hello", return "olleh". 8 | -------------------------------------------------------------------------------- /leetcode/344-Reverse-String/solution.c: -------------------------------------------------------------------------------- 1 | char* reverseString(char* s) { 2 | int len = strlen(s); 3 | if (len <= 1) return s; 4 | int mid = floor(len / 2); 5 | --len; 6 | for (int i = 0; i < mid; ++i) { 7 | char temp = s[i]; 8 | s[i] = s[len - i]; 9 | s[len - i] = temp; 10 | } 11 | return s; 12 | } -------------------------------------------------------------------------------- /other/algorithms/collatz/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int compute_collatz(int n) { 7 | int steps = 0; 8 | while (n != 1) { 9 | n = n % 2 ? (n * 3) + 1 : n / 2; 10 | ++steps; 11 | } 12 | return steps; 13 | } 14 | 15 | int main(int argc, char *argv[]) { 16 | if (argc > 1) { 17 | int n = strtol(argv[1], NULL, 10); 18 | cout << "Steps to " << n << ": " << compute_collatz(n) << endl; 19 | } else { 20 | cout << "Usage: " << argv[0] << " [N]" << endl; 21 | return 1; 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /other/algorithms/eratosthenes/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void eratosthenes(bool *nums, unsigned int max) { 4 | nums[0] = nums[1] = 1; 5 | for (unsigned int i = 2; i < max; ++i) { 6 | if (!nums[i]) { 7 | std::cout << i << std::endl; 8 | for (auto j = i*i; j < max; j+=i) { 9 | nums[j] = 1; 10 | } 11 | } 12 | } 13 | } 14 | 15 | int main() { 16 | const unsigned int max = 10e6; 17 | bool *nums = new bool[max]; 18 | eratosthenes(nums, max); 19 | delete[] nums; 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /other/algorithms/eratosthenes/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | def eratosthenes(max): 4 | nums = [False, False] + ([True] * (max - 2)) 5 | for (i, prime) in enumerate(nums): 6 | if prime: 7 | yield i 8 | for n in range(i * i, max, i): # use xrange in python 2 9 | nums[n] = False 10 | 11 | 12 | if __name__ == '__main__': 13 | for i in eratosthenes(int(10e6)): 14 | print(i) 15 | -------------------------------------------------------------------------------- /other/algorithms/selection_sort/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void swap(int &a, int &b) { 6 | int temp = a; 7 | a = b; 8 | b = temp; 9 | } 10 | 11 | void selection_sort(int *items, const int len) { 12 | for (int i = 0; i < len-1; ++i) { 13 | int min = i; 14 | for (int j = i+1; j < len; ++j) { 15 | if (items[min] > items[j]) { 16 | min = j; 17 | } 18 | } 19 | 20 | if (items[i] != items[min]) { 21 | swap(items[i], items[min]); 22 | } 23 | } 24 | } 25 | 26 | int main(int argc, char *argv[]) { 27 | int A[] = {4, 8, 2, 1, 5, 3, 6, 9, 7, 10}; 28 | const int len = (sizeof(A)/sizeof(*A)); 29 | 30 | selection_sort(A, len); 31 | for (int i = 0; i < len; ++i) 32 | cout << A[i] << ' '; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /other/numbers/change_return/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | 5 | COINS = [ 6 | ("Toonies", 2.00), 7 | ("Loonies", 1.00), 8 | ("Quarters", 0.25), 9 | ("Dimes", 0.10), 10 | ("Nickels", 0.05), 11 | ("Pennies", 0.01) 12 | ] 13 | 14 | # Presentation 15 | def divider(): 16 | print("="*40) 17 | 18 | def header(): 19 | print("{0:<25}{1:<5}{2:>10}".format("Coin", "QTY", "Value")) 20 | divider() 21 | 22 | def row(coin_type, count, value): 23 | print("{0:<25}{1:<5}{2:>10.2f}".format(coin_type, int(count), value)) 24 | 25 | def footer(amt): 26 | divider() 27 | print("{0:>40.2f}".format(amt)) 28 | 29 | # Calculation 30 | def calculate_change(amount): 31 | total = amount 32 | header() 33 | for (coin_type, base_value) in COINS: 34 | count = total // base_value 35 | if count > 0: 36 | value = count * base_value 37 | row(coin_type, count, value) 38 | total -= value 39 | footer(amount) 40 | 41 | if len(sys.argv) > 1: 42 | # add 0.001 to fix miniscule precision loss 43 | calculate_change(float(sys.argv[1]) + 0.001) 44 | else: 45 | print("Usage: {0} [amount]".format(sys.argv[0])) 46 | -------------------------------------------------------------------------------- /other/numbers/fibonacci/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // O(log n)-ish and (theoretically) imprecise solution 5 | long long fast_fib(int n) { 6 | float p = sqrt(5); 7 | return floor((pow((1 + p) / 2, n+1) - pow((1 - p) / 2, n+1)) / p); 8 | } 9 | 10 | // O(n^2) solution 11 | int slow_fib(int n) { 12 | if (n <= 1) return 1; 13 | return slow_fib(n-1) + slow_fib(n-2); 14 | } 15 | 16 | int main(int argc, char *argv[]) { 17 | if (argc > 1) { 18 | int max = atoi(argv[1]); 19 | 20 | if (max > 92) { 21 | max = 92; 22 | std::cout << "92+ fibs exceed a long long's capacity. Capping at 92." << std::endl; 23 | // TODO: implement bignum? 24 | } 25 | 26 | for (int i = 0; i < max; i++) { 27 | std::cout << fast_fib(i) << std::endl; 28 | } 29 | } else { 30 | std::cout << "Usage: " << argv[0] << " [amount]" << std::endl; 31 | return 1; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /other/numbers/fibonacci/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | import time 5 | 6 | # Fast method: O(log n)-ish (depending on the speed of exponent operations. Also 7 | # (theoretically) imprecise 8 | def fast_fib(n): 9 | p = 5**.5 10 | a = (1 + p)/2 11 | b = (1 - p)/2 12 | return int((a**(n+1) - b**(n+1)) / p) 13 | 14 | # Slow method: O(n^2) 15 | def slow_fib(n): 16 | if n <= 1: 17 | return 1 18 | return slow_fib(n-1) + slow_fib(n-2) 19 | 20 | argc = len(sys.argv) 21 | if argc > 1: 22 | print("(Using {0} method)".format("fast" if argc > 2 else "slow")) 23 | 24 | start = time.perf_counter() 25 | for i in range(int(sys.argv[1])): 26 | print(fast_fib(i) if argc > 2 else slow_fib(i)) 27 | print("\nDone in: {0:.6f}s".format(time.perf_counter() - start)) 28 | else: 29 | print("Usage: {0} [N]".format(sys.argv[0])) 30 | -------------------------------------------------------------------------------- /other/numbers/happy_numbers/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | 5 | # How to use: 6 | # python solution.py 10 11 12 7 | # Checks if 10, 11 and 12 are happy numbers 8 | # python solution.py 10-12 15 19-30 9 | # Checks if 10-12, 15 and 19-30 are happy numbers 10 | # python solution.py 11 | # Get's first 8 happy numbers 12 | 13 | def happy_proc(n): 14 | sum = 0 15 | 16 | # I exploit the properties of strings because I extra digits w/ modulus in the 17 | # C++ solution. 18 | for i in str(n): 19 | sum += int(i)**2 20 | return sum 21 | 22 | def happy_check(n, max_tries=100): 23 | for i in range(max_tries): 24 | n = happy_proc(n) 25 | if n == 1: return True 26 | return False 27 | 28 | def is_happy(n): 29 | print(n, "Happy!" if happy_check(n) else "Unhappy.") 30 | 31 | if len(sys.argv) > 1: 32 | for num in sys.argv[1:]: 33 | if num.find("-") == -1: 34 | is_happy(int(num)) 35 | else: 36 | nums = num.split('-') 37 | for i in range(int(nums[0]), int(nums[1])+1): 38 | is_happy(i) 39 | else: 40 | print("Printing first 8 happy numbers") 41 | n = 1 42 | happy = 0 43 | while happy <= 8: 44 | if happy_check(n): 45 | print(n) 46 | happy += 1 47 | n += 1 48 | -------------------------------------------------------------------------------- /other/numbers/prime_factors/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Lists all the prime factors of a number. Written for python 3. For python 2, switch 4 | # range out for xrange. 5 | 6 | import sys 7 | from math import sqrt 8 | 9 | def is_prime(n): 10 | for i in range(2, int(sqrt(n))+1): 11 | if n % i == 0: 12 | return False 13 | return True 14 | 15 | def pfactors(n): 16 | factors = [1] 17 | if n % 2 == 0: 18 | factors.append(2) 19 | for x in range(3, int(sqrt(n))+1, 2): 20 | if n % x == 0: 21 | if is_prime(x): 22 | factors.append(x) 23 | return factors + [n] 24 | 25 | 26 | argc = len(sys.argv) 27 | if argc > 1: 28 | for i in sys.argv[1:]: 29 | print(pfactors(int(i))) 30 | else: 31 | print("Usage {0} [number1] [[number2] ...]") 32 | -------------------------------------------------------------------------------- /other/text/fizzbuzz/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Since this problem is so simple, I'm only doing a python solution 4 | 5 | for num in range(1, 101): 6 | words = "" 7 | if num % 3 == 0: 8 | words += "Fizz" 9 | if num % 5 == 0: 10 | words += "Buzz" 11 | print(words or num) 12 | -------------------------------------------------------------------------------- /other/text/piglatin/solution.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | 5 | def pig_latinify(text): 6 | words = text.split() 7 | for i in range(len(words)): 8 | append = "" 9 | if words[i][-1] in ",.!?": 10 | append = words[i][-1] 11 | word = words[i][0:-1] 12 | else: 13 | word = words[i] 14 | if word[0] in "aeiou": 15 | words[i] += "way" 16 | # Take consonant clusters into account 17 | elif word[0:2].lower() in ['bl', 'br', 'ch', 'cl', 'fl', 'fr', 'gl', 'gr', 'ph', 'pl', 'sh', 'sl', 'st', 'tr']: 18 | words[i] = word[2:] + word[0:2].lower() + "ay" 19 | else: 20 | words[i] = word[1:] + word[0].lower() + "ay" 21 | words[i] += append 22 | return " ".join(words) 23 | 24 | if len(sys.argv) > 1: 25 | print(pig_latinify(sys.argv[1])) 26 | else: 27 | print("Usage {0} [sentence]".format(sys.argv[0])) 28 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | std::string input; 7 | std::getline(std::cin, input); 8 | std::reverse(input.begin(), input.end()); 9 | std::cout << input << std::endl; 10 | 11 | return 0; 12 | } 13 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.IOException; 3 | import java.io.InputStreamReader; 4 | 5 | // Ah Java, you and your verbosity. At least you handle unicode well. 6 | 7 | public class solution { 8 | public static void main(String[] args) { 9 | try{ 10 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 11 | String input = br.readLine(); 12 | System.out.println(new StringBuilder(input).reverse().toString()); 13 | }catch(IOException io){ 14 | io.printStackTrace(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | process.stdin.once('data', function(line) { 4 | line = line.toString().trim(); 5 | 6 | process.stdout.write("Naive reverse: " + line.split("").reverse().join("") + "\n"); 7 | 8 | process.stdout.write("Proper reverse: " + reverse(line)); 9 | 10 | process.exit(); 11 | }); 12 | 13 | // So why not just use line.split("").reverse().join("")? Because of the way 14 | // javascript represents four-byte astral symbols (as surrogate pairs in 15 | // Javascript, see: https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs) 16 | // doesn't handle four-byte astral characters. Worst. Possible. Thing! 17 | function reverse(str) { 18 | str = str.replace(/([\0-\u02FF\u0370-\u1DBF\u1E00-\u20CF\u2100-\uD7FF\uDC00-\uFE1F\uFE30-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF])([\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]+)/g, function($0, $1, $2) { 19 | return reverse($2) + $1; 20 | }).replace(/([\uD800-\uDBFF])([\uDC00-\uDFFF])/g, '$2$1'); 21 | 22 | var result = ''; 23 | var index = str.length; 24 | while (index--) 25 | result += str[index]; 26 | return result; 27 | } 28 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | 3 | -- Yet another situation where regex saves the day when it comes to unicode! 4 | 5 | input = io.stdin:read("*l") 6 | input = input:gsub('[%z\1-\127\194-\244][\128-\191]*', function (c) return #c > 1 and c:reverse() end) 7 | print(input:reverse()) 8 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env php 2 | 0: 24 | newstr += "".join(batch) 25 | batch = [] 26 | newstr += text[i] 27 | 28 | print(newstr) 29 | else: 30 | # PYTHON 3.4.1 SOLUTION 31 | 32 | # raw_input is now input in python 3, and unicode support is built right in 33 | # (even handles surrogate pairs! Glorious!) 34 | print(input()[::-1]) 35 | # Easy! 36 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # Handles anything I can throw at it. I love you Ruby. 4 | puts gets.reverse 5 | -------------------------------------------------------------------------------- /other/text/reverse_string/solution.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # First solution - works in bash 4 | read string 5 | for ((i=${#string}-1; i>=0; i--)); do 6 | echo -n "${string:i:1}" 7 | done 8 | 9 | echo 10 | 11 | # Second solution (for sh) 12 | # the -n flag doesn't work in sh, so here's an alternative: 13 | reversed="" 14 | for ((i=${#string}-1; i>=0; i--)); do 15 | reversed="$reversed${string:i:1}" 16 | done 17 | 18 | echo $reversed 19 | -------------------------------------------------------------------------------- /projecteuler/001.lisp: -------------------------------------------------------------------------------- 1 | ; 001: Multiples of 3 and 5 - Common Lisp 2 | ; https://projecteuler.net/problem=1 3 | ; 4 | ; If we list all the natural numbers below 10 that are multiples of 3 or 5, we 5 | ; get 3, 5, 6 and 9. The sum of these multiples is 23. 6 | ; 7 | ; Find the sum of all the multiples of 3 or 5 below 1000. 8 | 9 | (defun sum-multiples (d ai max) 10 | (let ((af (* (floor (/ (1- max) d)) d))) 11 | (* (/ af d) (+ ai af) .5))) 12 | 13 | (let ((a 3) 14 | (b 5) 15 | (max 1000)) 16 | (write (+ (sum-multiples a a max) 17 | (sum-multiples b b max) 18 | (- (sum-multiples (* a b) (* a b) max))))) 19 | 20 | -------------------------------------------------------------------------------- /projecteuler/002.gvy: -------------------------------------------------------------------------------- 1 | // 002: Even Fibonacci numbers - Groovy 2 | // https://projecteuler.net/problem=2 3 | // 4 | // Each new term in the Fibonacci sequence is generated by adding the previous 5 | // two terms. By starting with 1 and 2, the first 10 terms will be: 6 | // 7 | // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 8 | // 9 | // By considering the terms in the Fibonacci sequence whose values do not exceed 10 | // four million, find the sum of the even-valued terms. 11 | 12 | phi = (1+Math.sqrt(5))/2 // easier to remember than the decimal 13 | 14 | def evenFibSum(max) { 15 | // Note: Phi (the golden ratio) is the limit of ratios between fibonacci 16 | // terms. The ratio between consecutive EVEN numbers is phi^3 (every 3rd 17 | // term is even), we exploit this to optimize the loop. 18 | def sum = 0 19 | def n = 2 20 | while (n < max) { 21 | sum += n 22 | n = Math.round(n*phi**3) 23 | } 24 | return sum 25 | } 26 | 27 | println evenFibSum(4e6) 28 | -------------------------------------------------------------------------------- /projecteuler/004.hs: -------------------------------------------------------------------------------- 1 | -- 004: Largest palindrom product - Haskell 2 | -- https://projecteuler.net/problem=4 3 | -- 4 | -- A palindromic number reads the same both ways. The largest palindrome made from the 5 | -- product of two 2-digit numbers is 9009 = 91 x 99. 6 | -- 7 | -- Find the largest palindrome made from the product of two 3-digit numbers. 8 | 9 | largestPalindrome = 10 | maximum [n | x <- [999,998..100], y <- [999,998..x], 11 | let n = x*y, let str = show n, str == reverse str] 12 | -------------------------------------------------------------------------------- /projecteuler/005.rs: -------------------------------------------------------------------------------- 1 | // 005: Smallest multiple - Rust 2 | // https://projecteuler.net/problem=5 3 | // 4 | // 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 5 | // without any remainder. 6 | // 7 | // What is the smallest positive number that is evenly divisible by all of the numbers 8 | // from 1 to 20? 9 | 10 | fn even_div(n: &i32) -> bool { 11 | (3..20).find(|x| n*20 % x > 0) == None 12 | } 13 | 14 | fn main() { 15 | let n = (200..).filter(|n| even_div(n)).take(1).nth(0).unwrap(); 16 | println!("{}", n * 20); 17 | } 18 | -------------------------------------------------------------------------------- /projecteuler/006.go: -------------------------------------------------------------------------------- 1 | // 006: Sum square difference - Go 2 | // https://projecteuler.net/problem=6 3 | // 4 | // The sum of the squares of the first ten natural numbers is, 5 | // 6 | // 1^2 + 2^2 + ... + 10^2 = 385 7 | // 8 | // The square of the sum of the first ten natural numbers is, 9 | // 10 | // (1 + 2 + ... + 10)^2 = 55^2 = 3025 11 | // 12 | // Hence the difference between the sum of the squares of the first ten natural numbers 13 | // and the square of the sum is 3025 − 385 = 2640. 14 | // 15 | // Find the difference between the sum of the squares of the first one hundred natural 16 | // numbers and the square of the sum. 17 | 18 | package main 19 | import "fmt" 20 | 21 | // O(n) 22 | func naive(limit int) int { 23 | sumSq := 0 24 | sqSum := 0 25 | for i := 1; i <= limit; i++ { 26 | sumSq += i * i; 27 | sqSum += i; 28 | } 29 | return (sqSum * sqSum) - sumSq 30 | } 31 | 32 | // O(1) 33 | func fast(limit int) int { 34 | sumSq := ((2 * limit) + 1) * (limit + 1) * limit / 6 35 | sqSum := limit * (limit + 1) / 2 36 | return (sqSum * sqSum) - sumSq 37 | } 38 | 39 | func main() { 40 | fmt.Printf("%d\n", naive(100)) 41 | fmt.Printf("%d\n", fast(100)) 42 | } 43 | 44 | -------------------------------------------------------------------------------- /projecteuler/007.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env lua 2 | -- 007: 10,001st prime - Lua 3 | -- https://projecteuler.net/problem=7 4 | -- 5 | -- By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th 6 | -- prime is 13. 7 | -- 8 | -- What is the 10 001st prime number? 9 | 10 | -- NOTE: let P be the set of all primes 11 | -- + 1 ∉ P 12 | -- + if p = 3k or p = 2k then p not a prime 13 | -- + ∀p ∈ P, p >= 3: p is odd 14 | -- + ∀p ∈ P, p = 6k±1 15 | -- + n ∈ P if n mod 6k±1 == 0 where 3 <= k < sqrt(n) 16 | 17 | function isPrime(n) 18 | if n == 1 then 19 | return false 20 | elseif n <= 3 then 21 | return true 22 | elseif (n % 2) == 0 or (n % 3) == 0 then 23 | return false 24 | elseif n < 9 then 25 | return true 26 | else 27 | for i=6, math.sqrt(n)+1, 6 do 28 | if (n % (i-1)) == 0 or (n % (i+1)) == 0 then 29 | return false 30 | end 31 | end 32 | 33 | return true 34 | end 35 | end 36 | 37 | function nthPrime(i) 38 | j = 2 39 | n = 3 40 | while j < i do 41 | n = n + 2 42 | 43 | if isPrime(n) then 44 | j = j + 1 45 | end 46 | end 47 | return n 48 | end 49 | 50 | print(nthPrime(10001)) 51 | -------------------------------------------------------------------------------- /projecteuler/README.md: -------------------------------------------------------------------------------- 1 | # Project Euler 2 | 3 | > Note: I did not post the answers! 4 | 5 | Solutions to the problems on [Project Euler](https://projecteuler.net/), written in an 6 | assortment of languages. 7 | 8 | --------------------------------------------------------------------------------