├── epi ├── ch12 │ ├── .gitignore │ ├── generate_large_file.py │ ├── partition_dictionary_by_anagrams.py │ └── sort_large_file.py ├── ch10 │ ├── mergek │ │ ├── .gitignore │ │ └── generate.py │ └── online_median │ │ ├── output1.txt │ │ ├── input1.txt │ │ ├── output3.txt │ │ └── input3.txt ├── README.md ├── ch11 │ ├── FirstLarger.java │ ├── SortedArrayIdenticalToIndex.java │ └── kth_largest_element.py ├── ch5 │ ├── SpreadsheetColumnEncoding.java │ ├── ParityTest.java │ ├── PowersetTest.java │ └── BaseConvert.java ├── ch6 │ └── DutchFlagPartition.java └── ch8 │ └── TowersOfHanoi.java ├── interview ├── .gitignore ├── Messing.java ├── maximum_subarray.py ├── fisher_yates_shuffle.py ├── anagrams.py ├── customer.log ├── towers_of_hanoi.py ├── cracking_ch1_matrix_rotation.py ├── geeksforgeeks │ ├── geeksforgeeks_permutations.py │ ├── geeksforgeeks_iterative_difference.py │ ├── geeksforgeeks_check_if_all_leaves_at_same_level.py │ └── geeksforgeeks_left_view_of_binary_tree.py ├── glassdoor │ ├── glassdoor_max_subarray.py │ ├── glassdoor_anagrams.py │ ├── glassdoor_sorted_rotated_find.py │ ├── glassdoor_sum_tree.py │ ├── glassdoor_reverse_singly_linked_list.py │ └── SortedArrayFindMinimumInserts.java ├── interviewcake_duplicate_number.py ├── MaximumSubarray.java ├── oreilly_counting_sort.py ├── leapfrog.py ├── interviewcake_matching_parens.py ├── SortedArrayBinarySearch.java ├── cracking_set_row_col_to_zero.py ├── interviewcake_reverse_string_in_place.py ├── cracking_sorted_to_tree.py ├── WindowAverageTest.java ├── GlassdoorTrimExtraSpaces.java ├── cracking_bst_to_lists.py ├── StringsByLength.java ├── TopCoderTopFox.java ├── careercup_array_two_numbers_odd_times.py ├── cracking_is_balanced.py ├── mergesort.py ├── CrackingAllPairs.java ├── cracking_queue_with_two_stacks.py ├── split_lines.py ├── cracking_stack_with_min.py ├── QuicksortTest.java ├── KMPTest.java ├── SubstringPalindromes.java ├── RPNCalculator.java ├── three_sum.py ├── Comparators.java ├── cracking_all_paths_with_sum.py ├── ShuffleSongs.java ├── topcoder_lcs.py ├── MergeSortTest.java ├── tree_bfs.py ├── Anagrams.java └── skiplist.py ├── codeeval ├── codeeval_5.txt ├── codeeval_mth_to_last.txt ├── beautiful_strings_test_output.txt ├── string_substitution.txt ├── codeeval_2.txt ├── codeeval_37.txt ├── beautiful_strings_test.txt ├── codeeval_35.txt ├── codeeval_37.py ├── codeeval_5.py ├── codeeval_2.py ├── codeeval_mth_to_last.py └── codeeval_89.py ├── codingforinterviews ├── coin_change_output1.txt ├── coin_change_output2.txt ├── coin_change_output3.txt ├── coin_change_input1.txt ├── coin_change_input2.txt ├── coin_change_input3.txt ├── emailaddress │ ├── .gitignore │ ├── test │ │ └── tests.html │ ├── package.json │ ├── bower.json │ ├── .jshintrc │ ├── README.md │ ├── Gruntfile.js │ └── doc │ │ └── local-part-fsm.gv ├── CodingForInterviewsSingleton.java ├── codingforinterviews_is_bst.py ├── CodingForInterviewsBitManipulation.java ├── CodingForInterviewsNQueens.java ├── coin_change.py └── CodingForInterviewsReverseWords.java ├── topcoder ├── problems │ ├── 12578_ShoutterDiv2 │ │ └── __init__.py │ └── 12545_GooseInZooDivTwo │ │ └── __init__.py ├── srm613_div2_250 │ ├── .gitignore │ ├── gradle.properties │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── settings.gradle │ ├── src │ │ ├── test │ │ │ └── java │ │ │ │ └── TestTaroString.java │ │ └── main │ │ │ └── java │ │ │ └── TaroString.java │ └── build.gradle ├── srm538_div1_450 │ ├── .classpath │ ├── .project │ └── src │ │ └── ai │ │ └── topcoder │ │ └── TurtleSpy │ │ └── TurtleSpyTest.java └── srm538_div2_300 │ ├── .classpath │ ├── .project │ └── src │ └── LeftOrRightTest.java ├── rosalind ├── bins │ ├── gradle.properties │ ├── src │ │ ├── test │ │ │ └── resources │ │ │ │ ├── test_2.input │ │ │ │ ├── test_3.input │ │ │ │ ├── test_6.input │ │ │ │ ├── test_4.input │ │ │ │ ├── test_5.input │ │ │ │ ├── test_7.input │ │ │ │ └── test_1.input │ │ └── main │ │ │ └── java │ │ │ └── CommandLineInterface.java │ ├── README.md │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── settings.gradle │ └── build.gradle ├── fibo │ ├── gradle.properties │ ├── src │ │ ├── main │ │ │ └── java │ │ │ │ ├── Fibonacci.java │ │ │ │ └── CommandLineInterface.java │ │ └── test │ │ │ └── java │ │ │ └── TestFibonacci.java │ ├── README.md │ ├── gradle │ │ └── wrapper │ │ │ └── gradle-wrapper.properties │ ├── .gitignore │ ├── settings.gradle │ └── build.gradle ├── prot │ └── test.txt ├── revp │ └── build.sbt ├── hamm │ └── problem.txt ├── subs │ ├── subs.py │ └── problem.txt ├── mprt │ └── problem.txt ├── perm │ └── perm.py ├── gc │ ├── gc.py │ └── problem.txt ├── lcs │ └── problem.txt ├── grph │ └── grph.py └── iprb │ └── iprb.py ├── hackerrank ├── codesprint5 │ ├── is_fibo_input_1.txt │ ├── special_multiple_input_1.txt │ ├── matrix_tracing_input_1.txt │ ├── special_multiple.py │ ├── SpecialMultiple.java │ ├── a_story_of_people_and_places.py │ └── IsFibo.java ├── hackerrank_candies.txt ├── hackerrank_chocolate_feast.txt ├── BotClean │ ├── input1.txt │ ├── input2.txt │ ├── input3.txt │ ├── input4.txt │ ├── input5.txt │ └── input6.txt ├── hackerrank_two_arrays.txt ├── HackerRankFraudPreventionInput.txt ├── hackerrank_chocolate_feast.py ├── hackerrank_two_arrays.py └── hackerrank_candies.py ├── projecteuler ├── src │ ├── problem1 │ │ ├── project │ │ │ └── build.properties │ │ ├── src │ │ │ ├── test │ │ │ │ └── scala │ │ │ │ │ └── Problem1Suite.scala │ │ │ └── main │ │ │ │ └── scala │ │ │ │ └── Problem1.scala │ │ └── build.sbt │ ├── problem2 │ │ ├── project │ │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ │ ├── test │ │ │ └── scala │ │ │ │ └── Problem2Suite.scala │ │ │ └── main │ │ │ └── scala │ │ │ └── Problem2.scala │ ├── problem3 │ │ ├── project │ │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ │ └── test │ │ │ └── scala │ │ │ └── Problem3Suite.scala │ ├── problem4 │ │ ├── project │ │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ │ ├── test │ │ │ └── scala │ │ │ │ └── Problem4Suite.scala │ │ │ └── main │ │ │ └── scala │ │ │ └── Problem4.scala │ ├── problem5 │ │ ├── project │ │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ │ ├── test │ │ │ └── scala │ │ │ │ └── Problem5Suite.scala │ │ │ └── main │ │ │ └── scala │ │ │ └── Problem5.scala │ ├── problem6 │ │ ├── project │ │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ │ ├── test │ │ │ └── scala │ │ │ │ └── Problem6Suite.scala │ │ │ └── main │ │ │ └── scala │ │ │ └── Problem6.scala │ └── problem7 │ │ ├── project │ │ └── build.properties │ │ ├── build.sbt │ │ └── src │ │ ├── test │ │ └── scala │ │ │ └── Problem7Suite.scala │ │ └── main │ │ └── scala │ │ └── Problem7.scala ├── .gitignore └── README.md ├── googlecodejam ├── alien_language │ ├── sample.out │ ├── sample.in │ ├── A-small-practice.out │ ├── .classpath │ ├── .project │ └── A-small-practice.in ├── reverse_words │ ├── src │ │ ├── B-small-practice.in │ │ ├── B-small-practice.out │ │ └── ReverseWords.java │ ├── .classpath │ └── .project └── store_credit │ ├── src │ ├── small_example.txt │ ├── A-small-practice.out │ ├── A-large-practice.out │ └── A-small-practice.in │ ├── .classpath │ └── .project ├── clrs ├── 05_heapsort │ ├── src │ │ └── ai │ │ │ └── heapsort │ │ │ └── PriorityQueue.java │ ├── .classpath │ └── .project ├── 07_quicksort │ ├── .classpath │ ├── .project │ └── src │ │ ├── QuickTest.java │ │ └── Quick.java └── 02_getting_started │ ├── .classpath │ ├── src │ └── ai │ │ └── sort │ │ ├── IntegerComparatorAscending.java │ │ └── IntegerComparatorDescending.java │ └── .project ├── sedgwick ├── .classpath ├── scramble │ ├── .classpath │ ├── .project │ └── src │ │ └── ai │ │ └── graph │ │ ├── Node.java │ │ └── Graph.java ├── redblack │ ├── .classpath │ └── .project └── .project ├── pearls ├── 01_oyster │ └── mlfsr │ │ ├── README.md │ │ ├── test │ │ └── ai │ │ │ └── mlfsr │ │ │ ├── AllTests.java │ │ │ └── MlfsrTest.java │ │ ├── .classpath │ │ ├── .project │ │ └── src │ │ └── ai │ │ └── mlfsr │ │ └── Mlfsr16.java └── 02_algorithms │ ├── .classpath │ ├── .project │ └── src │ └── AnagramsTest.java ├── spoj ├── README.md ├── TEST │ ├── src │ │ └── problem1.py │ └── test │ │ └── test.py └── JOHNNY │ ├── README.md │ └── src │ └── stackoverflow.py ├── cracking ├── ch05_bit_manipulation │ ├── .classpath │ ├── src │ │ └── ai │ │ │ └── cracking │ │ │ └── bitmanipulation │ │ │ ├── Problem2.java │ │ │ ├── Problem1.java │ │ │ └── ProblemTest.java │ └── .project ├── ch08 │ ├── CoinTest.java │ └── EightQueens.java └── ch09 │ ├── SearchInSparseStringArray.java │ ├── SearchRotatedArray.java │ └── Circus.java ├── exposed └── 03_linkedlist │ ├── .classpath │ ├── .project │ ├── src │ └── ai │ │ └── exposed │ │ └── Node.java │ └── test │ └── ai │ └── exposed │ └── LinkedListTest.java ├── .gitignore ├── README.md ├── projecteuler_python └── 66 │ └── 66.py └── codingbat └── CountYZ.java /epi/ch12/.gitignore: -------------------------------------------------------------------------------- 1 | *.txt -------------------------------------------------------------------------------- /epi/ch10/mergek/.gitignore: -------------------------------------------------------------------------------- 1 | *.txt -------------------------------------------------------------------------------- /interview/.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | -------------------------------------------------------------------------------- /codeeval/codeeval_5.txt: -------------------------------------------------------------------------------- 1 | 2 0 6 3 1 6 3 1 6 3 1 -------------------------------------------------------------------------------- /codingforinterviews/coin_change_output1.txt: -------------------------------------------------------------------------------- 1 | 4 -------------------------------------------------------------------------------- /codingforinterviews/coin_change_output2.txt: -------------------------------------------------------------------------------- 1 | 5 -------------------------------------------------------------------------------- /topcoder/problems/12578_ShoutterDiv2/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /codingforinterviews/coin_change_output3.txt: -------------------------------------------------------------------------------- 1 | 227491942 -------------------------------------------------------------------------------- /rosalind/bins/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.daemon=True -------------------------------------------------------------------------------- /rosalind/fibo/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.daemon=True -------------------------------------------------------------------------------- /topcoder/problems/12545_GooseInZooDivTwo/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | .gradle -------------------------------------------------------------------------------- /codeeval/codeeval_mth_to_last.txt: -------------------------------------------------------------------------------- 1 | a b c d 4 2 | e f g h 2 -------------------------------------------------------------------------------- /codingforinterviews/coin_change_input1.txt: -------------------------------------------------------------------------------- 1 | 1, 2, 3 2 | 4 -------------------------------------------------------------------------------- /codingforinterviews/coin_change_input2.txt: -------------------------------------------------------------------------------- 1 | 2, 5, 3, 6 2 | 10 -------------------------------------------------------------------------------- /hackerrank/codesprint5/is_fibo_input_1.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 5 3 | 7 4 | 8 -------------------------------------------------------------------------------- /hackerrank/hackerrank_candies.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 3 3 | 2 4 | 1 5 | 2 6 | 3 -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_2.input: -------------------------------------------------------------------------------- 1 | 1 2 | 1 3 | 10 4 | 10 -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_3.input: -------------------------------------------------------------------------------- 1 | 1 2 | 1 3 | 10 4 | 9 -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_6.input: -------------------------------------------------------------------------------- 1 | 2 2 | 1 3 | 10 11 4 | 9 -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.daemon=True -------------------------------------------------------------------------------- /epi/README.md: -------------------------------------------------------------------------------- 1 | # Elements of Programming Interviews 2 | 3 | In Java 4 | -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_4.input: -------------------------------------------------------------------------------- 1 | 2 2 | 1 3 | 10 11 4 | 10 -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_5.input: -------------------------------------------------------------------------------- 1 | 2 2 | 1 3 | 10 11 4 | 11 -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_7.input: -------------------------------------------------------------------------------- 1 | 2 2 | 1 3 | 10 11 4 | 12 -------------------------------------------------------------------------------- /codeeval/beautiful_strings_test_output.txt: -------------------------------------------------------------------------------- 1 | 152 2 | 754 3 | 491 4 | 729 5 | 646 -------------------------------------------------------------------------------- /hackerrank/codesprint5/special_multiple_input_1.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 5 3 | 7 4 | 1 5 | 499 -------------------------------------------------------------------------------- /hackerrank/hackerrank_chocolate_feast.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 10 2 5 3 | 12 4 4 4 | 6 2 2 -------------------------------------------------------------------------------- /projecteuler/src/problem1/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem2/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem3/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem4/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem5/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem6/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /projecteuler/src/problem7/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.11.2 2 | 3 | -------------------------------------------------------------------------------- /rosalind/prot/test.txt: -------------------------------------------------------------------------------- 1 | AUGGCCAUGGCGCCCAGAACUGAGAUCAAUAGUACCCGUAUUAACGGGUGA 2 | -------------------------------------------------------------------------------- /hackerrank/BotClean/input1.txt: -------------------------------------------------------------------------------- 1 | 0 0 2 | b---d 3 | -d--d 4 | --dd- 5 | --d-- 6 | ----d -------------------------------------------------------------------------------- /hackerrank/BotClean/input2.txt: -------------------------------------------------------------------------------- 1 | 2 3 2 | ----- 3 | ----- 4 | ---b- 5 | ----- 6 | --d-d -------------------------------------------------------------------------------- /hackerrank/BotClean/input3.txt: -------------------------------------------------------------------------------- 1 | 0 0 2 | bd--- 3 | -d--- 4 | ---d- 5 | ---d- 6 | --d-d -------------------------------------------------------------------------------- /codeeval/string_substitution.txt: -------------------------------------------------------------------------------- 1 | 10011011001;0110,1001,1001,0,10,11 2 | 0000000000;00,11 -------------------------------------------------------------------------------- /codingforinterviews/coin_change_input3.txt: -------------------------------------------------------------------------------- 1 | 2, 5, 3, 6, 10, 7, 8, 12, 17, 19, 20 2 | 250 -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/.gitignore: -------------------------------------------------------------------------------- 1 | bower_components 2 | node_modules 3 | *.png -------------------------------------------------------------------------------- /epi/ch10/online_median/output1.txt: -------------------------------------------------------------------------------- 1 | Wrong! 2 | 1 3 | 1.5 4 | 1 5 | 1.5 6 | 1 7 | Wrong! -------------------------------------------------------------------------------- /epi/ch10/online_median/input1.txt: -------------------------------------------------------------------------------- 1 | 7 2 | r 1 3 | a 1 4 | a 2 5 | a 1 6 | r 1 7 | r 2 8 | r 1 -------------------------------------------------------------------------------- /hackerrank/BotClean/input4.txt: -------------------------------------------------------------------------------- 1 | 0 0 2 | 5 5 3 | b---d 4 | -d--d 5 | --dd- 6 | --d-- 7 | ----d -------------------------------------------------------------------------------- /hackerrank/BotClean/input5.txt: -------------------------------------------------------------------------------- 1 | 4 4 2 | 5 5 3 | ----- 4 | ----- 5 | ----- 6 | ----- 7 | --d-b -------------------------------------------------------------------------------- /hackerrank/BotClean/input6.txt: -------------------------------------------------------------------------------- 1 | 4 2 2 | 5 5 3 | ----- 4 | ----- 5 | ----- 6 | ----- 7 | --d-- -------------------------------------------------------------------------------- /rosalind/bins/src/test/resources/test_1.input: -------------------------------------------------------------------------------- 1 | 5 2 | 6 3 | 10 20 30 40 50 4 | 40 10 35 15 40 20 -------------------------------------------------------------------------------- /codeeval/codeeval_2.txt: -------------------------------------------------------------------------------- 1 | 2 2 | Hello World 3 | 4 | CodeEval 5 | Quick Fox 6 | A 7 | San Francisco -------------------------------------------------------------------------------- /hackerrank/hackerrank_two_arrays.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 3 10 3 | 2 1 3 4 | 7 8 9 5 | 4 5 6 | 1 2 2 1 7 | 3 3 3 4 -------------------------------------------------------------------------------- /googlecodejam/alien_language/sample.out: -------------------------------------------------------------------------------- 1 | Case #1: 2 2 | Case #2: 1 3 | Case #3: 3 4 | Case #4: 0 5 | -------------------------------------------------------------------------------- /hackerrank/codesprint5/matrix_tracing_input_1.txt: -------------------------------------------------------------------------------- 1 | 2 2 | 2 3 3 | 5 7 4 | 100000 100000 5 | 1000000 1000000 -------------------------------------------------------------------------------- /rosalind/bins/README.md: -------------------------------------------------------------------------------- 1 | # ROSALIND bins 2 | 3 | Binary search. 4 | 5 | http://rosalind.info/problems/bins/ -------------------------------------------------------------------------------- /codeeval/codeeval_37.txt: -------------------------------------------------------------------------------- 1 | A quick brown fox jumps over the lazy dog 2 | A slow yellow fox crawls under the proactive dog -------------------------------------------------------------------------------- /clrs/05_heapsort/src/ai/heapsort/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | package ai.heapsort; 2 | 3 | public class PriorityQueue { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /googlecodejam/reverse_words/src/B-small-practice.in: -------------------------------------------------------------------------------- 1 | 5 2 | this is a test 3 | foobar 4 | all your base 5 | class 6 | pony along 7 | -------------------------------------------------------------------------------- /googlecodejam/alien_language/sample.in: -------------------------------------------------------------------------------- 1 | 3 5 4 2 | abc 3 | bca 4 | dac 5 | dbc 6 | cba 7 | (ab)(bc)(ca) 8 | abc 9 | (abc)(abc)(abc) 10 | (zyx)bc 11 | -------------------------------------------------------------------------------- /googlecodejam/store_credit/src/small_example.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 100 3 | 3 4 | 5 75 25 5 | 200 6 | 7 7 | 150 24 79 50 88 345 3 8 | 8 9 | 8 10 | 2 1 9 4 4 56 90 3 11 | -------------------------------------------------------------------------------- /googlecodejam/reverse_words/src/B-small-practice.out: -------------------------------------------------------------------------------- 1 | Case #1: test a is this 2 | Case #2: foobar 3 | Case #3: base your all 4 | Case #4: class 5 | Case #5: along pony 6 | -------------------------------------------------------------------------------- /googlecodejam/alien_language/A-small-practice.out: -------------------------------------------------------------------------------- 1 | Case #1: 0 2 | Case #2: 1 3 | Case #3: 0 4 | Case #4: 1 5 | Case #5: 6 6 | Case #6: 7 7 | Case #7: 1 8 | Case #8: 8 9 | Case #9: 1 10 | Case #10: 8 11 | -------------------------------------------------------------------------------- /codeeval/beautiful_strings_test.txt: -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- /interview/Messing.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | class Messing { 5 | public static void main(String[] args) { 6 | List foo = new ArrayList<>(); 7 | } 8 | } -------------------------------------------------------------------------------- /sedgwick/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /projecteuler/.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # sbt specific 5 | dist/* 6 | target/ 7 | lib_managed/ 8 | src_managed/ 9 | project/boot/ 10 | project/plugins/project/ 11 | 12 | # Scala-IDE specific 13 | .scala_dependencies -------------------------------------------------------------------------------- /codeeval/codeeval_35.txt: -------------------------------------------------------------------------------- 1 | foo@bar.com 2 | this is not an email id 3 | admin#codeeval.com 4 | good123@bad.com 5 | foo.@bar.com 6 | foo.bar@bar.com 7 | foo.bar.@bar.com 8 | foo.bar@bar.com. 9 | foo..bar@bar.com. 10 | foo..bar@@bar.com. -------------------------------------------------------------------------------- /googlecodejam/store_credit/src/A-small-practice.out: -------------------------------------------------------------------------------- 1 | Case #1: 2 3 2 | Case #2: 1 4 3 | Case #3: 4 5 4 | Case #4: 29 46 5 | Case #5: 11 56 6 | Case #6: 4 5 7 | Case #7: 40 46 8 | Case #8: 16 35 9 | Case #9: 55 74 10 | Case #10: 7 9 11 | -------------------------------------------------------------------------------- /rosalind/fibo/src/main/java/Fibonacci.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | public static int calculate(int n) { 3 | if (n == 0 || n == 1) 4 | return n; 5 | return calculate(n - 1) + calculate(n - 2); 6 | } 7 | } -------------------------------------------------------------------------------- /rosalind/fibo/src/main/java/CommandLineInterface.java: -------------------------------------------------------------------------------- 1 | public class CommandLineInterface { 2 | public static void main(String[] args) { 3 | int n = new Integer(args[0]); 4 | System.out.println(Fibonacci.calculate(n)); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /interview/maximum_subarray.py: -------------------------------------------------------------------------------- 1 | def max_subarray(arr): 2 | max_ending_here = max_so_far = 0 3 | for x in arr: 4 | max_ending_here = max(0, max_ending_here + x) 5 | max_so_far = max(max_so_far, max_ending_here) 6 | return max_so_far 7 | -------------------------------------------------------------------------------- /rosalind/fibo/README.md: -------------------------------------------------------------------------------- 1 | # FIBO 2 | 3 | http://rosalind.info/problems/fibo/ 4 | 5 | Given n return the nth Fibonacci number. 6 | 7 | ## Continuous integration 8 | 9 | watchmedo shell-command -p "*.gradle;*.java" -R -w -c "clear; date; gradle test --info" -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/README.md: -------------------------------------------------------------------------------- 1 | # Maximal Linear Feedback Shift Registers (MLFSRs) 2 | 3 | Code and tests of using MLFSRs to generate non-repeating sequences of integers. One method of solving integer-sampling-without-replacement problems, as required by _Pearls Part 1_. -------------------------------------------------------------------------------- /sedgwick/scramble/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /interview/fisher_yates_shuffle.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def shuffle(arr): 5 | for i in xrange(len(arr)-1, 1, -1): 6 | j = random.randint(0, i) 7 | arr[j], arr[i] = arr[i], arr[j] 8 | 9 | arr = [1, 2, 3, 4, 5] 10 | shuffle(arr) 11 | print arr 12 | -------------------------------------------------------------------------------- /googlecodejam/reverse_words/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /googlecodejam/alien_language/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /rosalind/bins/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Mar 20 09:12:49 GMT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-bin.zip 7 | -------------------------------------------------------------------------------- /rosalind/fibo/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Mar 19 11:59:43 GMT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-bin.zip 7 | -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Mar 22 11:04:48 GMT 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.9-bin.zip 7 | -------------------------------------------------------------------------------- /hackerrank/HackerRankFraudPreventionInput.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 1,1,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689010 3 | 2,1,elmer@fudd.com,123 Sesame St.,New York,NY,10011,10987654321 4 | 3,2,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689010 5 | 4,2,bugs@bunny.com,123 Sesame St.,New York,NY,10011,12345689011 6 | -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/test/ai/mlfsr/AllTests.java: -------------------------------------------------------------------------------- 1 | package ai.mlfsr; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.junit.runners.Suite; 5 | import org.junit.runners.Suite.SuiteClasses; 6 | 7 | @RunWith(Suite.class) 8 | @SuiteClasses({ MlfsrTest.class }) 9 | public class AllTests { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /rosalind/bins/.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | 3 | .gradle 4 | build/ 5 | 6 | # Java 7 | 8 | *.class 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | 18 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 19 | hs_err_pid* -------------------------------------------------------------------------------- /rosalind/fibo/.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | 3 | .gradle 4 | build/ 5 | 6 | # Java 7 | 8 | *.class 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | 18 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 19 | hs_err_pid* -------------------------------------------------------------------------------- /clrs/05_heapsort/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /spoj/README.md: -------------------------------------------------------------------------------- 1 | # SPOJ 2 | 3 | ## Introduction 4 | 5 | Solutions to the [Sphere Online Judge](https://www.spoj.pl). 6 | 7 | ## Contents 8 | 9 | - [`TEST`](https://www.spoj.pl/problems/TEST/): 1. Life, the Universe, and Everything. In **Python**. 10 | - [`JOHNNY`](https://www.spoj.pl/problems/JOHNNY/): 127. Johnny goes shopping. In **Python**. -------------------------------------------------------------------------------- /clrs/07_quicksort/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /pearls/02_algorithms/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /sedgwick/redblack/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /googlecodejam/store_credit/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /topcoder/srm538_div1_450/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /topcoder/srm538_div2_300/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /cracking/ch05_bit_manipulation/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /interview/anagrams.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import collections 4 | import pprint 5 | 6 | lookup = collections.defaultdict(list) 7 | with open("anagrams.txt") as f_in: 8 | lines = (line.strip() for line in f_in) 9 | for line in lines: 10 | key = ''.join(sorted(line)) 11 | lookup[key].append(line) 12 | pprint.pprint(lookup.values()) 13 | -------------------------------------------------------------------------------- /interview/customer.log: -------------------------------------------------------------------------------- 1 | 2013-11-12 15:00:00.000 : customer5 : page0 2 | 2013-11-10 16:00:00.000 : customer0 : page0 3 | 2013-11-10 15:00:00.000 : customer0 : page0 4 | 2013-11-10 15:00:00.000 : customer1 : page0 5 | 2013-11-10 15:00:00.000 : customer2 : page0 6 | 2013-11-10 15:00:00.000 : customer3 : page0 7 | 2013-11-10 15:00:00.000 : customer4 : page0 8 | 2013-11-10 15:00:00.000 : customer5 : page0 -------------------------------------------------------------------------------- /clrs/02_getting_started/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /exposed/03_linkedlist/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /cracking/ch05_bit_manipulation/src/ai/cracking/bitmanipulation/Problem2.java: -------------------------------------------------------------------------------- 1 | package ai.cracking.bitmanipulation; 2 | 3 | import java.util.Arrays; 4 | import java.util.Map; 5 | import java.util.HashMap; 6 | import java.util.Collections; 7 | 8 | 9 | public class Problem2 { 10 | public static String printBinaryString(double n) { 11 | int[] count = new int[256]; 12 | 13 | 14 | return ""; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /spoj/TEST/src/problem1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | 6 | def main(): 7 | while True: 8 | next_line = sys.stdin.readline() 9 | if not next_line: 10 | break 11 | if next_line.strip() == "42": 12 | break 13 | sys.stdout.write(next_line) 14 | sys.stdout.flush() 15 | 16 | if __name__ == "__main__": 17 | main() 18 | 19 | -------------------------------------------------------------------------------- /clrs/02_getting_started/src/ai/sort/IntegerComparatorAscending.java: -------------------------------------------------------------------------------- 1 | package ai.sort; 2 | 3 | import java.util.Comparator; 4 | 5 | public class IntegerComparatorAscending implements Comparator { 6 | 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | if (o1 > o2) { 10 | return 1; 11 | } else if (o1 == o2) { 12 | return 0; 13 | } else { 14 | return -1; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /clrs/02_getting_started/src/ai/sort/IntegerComparatorDescending.java: -------------------------------------------------------------------------------- 1 | package ai.sort; 2 | 3 | import java.util.Comparator; 4 | 5 | public class IntegerComparatorDescending implements Comparator { 6 | 7 | @Override 8 | public int compare(Integer o1, Integer o2) { 9 | if (o1 > o2) { 10 | return -1; 11 | } else if (o1 == o2) { 12 | return 0; 13 | } else { 14 | return 1; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /epi/ch12/generate_large_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env pypy 2 | 3 | """Generate a large file of lines of varying length, unsorted.""" 4 | 5 | import random 6 | import string 7 | 8 | with open('large_file.txt', 'w') as f_out: 9 | for i in xrange(1000000): 10 | length = random.randint(1, 78) 11 | line = [random.choice(string.ascii_lowercase) for i in xrange(length)] 12 | f_out.write("%s\n" % ''.join(line)) 13 | -------------------------------------------------------------------------------- /rosalind/revp/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.8" % "test" 10 | 11 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 12 | 13 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 14 | 15 | 16 | -------------------------------------------------------------------------------- /interview/towers_of_hanoi.py: -------------------------------------------------------------------------------- 1 | def recursive_move_tower(height, from_pole, to_pole, with_pole): 2 | if height >= 1: 3 | recursive_move_tower(height - 1, from_pole, with_pole, to_pole) 4 | recursive_move_disk(from_pole, to_pole) 5 | recursive_move_tower(height - 1, with_pole, to_pole, from_pole) 6 | 7 | 8 | def recursive_move_disk(from_pole, to_pole): 9 | print("moving disk from %s to %s" % (from_pole, to_pole)) 10 | -------------------------------------------------------------------------------- /projecteuler/src/problem1/src/test/scala/Problem1Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem1.test 2 | 3 | import org.scalatest.FunSuite 4 | import com.euler.problem1.main.Problem1 5 | 6 | class Problem1Suite extends FunSuite { 7 | test("sum of natural numbers that are multiples of 3 and 5 up to 10 is 23") { 8 | val sum = Problem1.sumNaturalNumbers(10) 9 | assert(sum === 23) 10 | } 11 | } 12 | 13 | // vim: set ts=4 sw=4 et: 14 | -------------------------------------------------------------------------------- /projecteuler/src/problem4/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 12 | 13 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 14 | 15 | 16 | -------------------------------------------------------------------------------- /projecteuler/src/problem5/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 12 | 13 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 14 | 15 | 16 | -------------------------------------------------------------------------------- /projecteuler/src/problem6/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 12 | 13 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 14 | 15 | 16 | -------------------------------------------------------------------------------- /projecteuler/src/problem7/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 12 | 13 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 14 | 15 | 16 | -------------------------------------------------------------------------------- /rosalind/hamm/problem.txt: -------------------------------------------------------------------------------- 1 | Problem 2 | 3 | Given two strings s and t of equal length, the Hamming distance between s and t, denoted dH(s,t), is the number of corresponding symbols that differ in s and t. See Figure 2. 4 | 5 | Given: Two DNA strings s and t of equal length (not exceeding 1 kbp). 6 | 7 | Return: The Hamming distance dH(s,t). 8 | 9 | Sample Dataset 10 | 11 | GAGCCTACTAACGGGAT 12 | CATCGTAATGACGGCCT 13 | Sample Output 14 | 15 | 7 16 | -------------------------------------------------------------------------------- /sedgwick/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | scramble 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /clrs/05_heapsort/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | heapsort 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /clrs/07_quicksort/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | quicksort 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | mlfsr 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /pearls/02_algorithms/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | anagrams 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /sedgwick/redblack/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | redblack 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /sedgwick/scramble/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | scramble 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /clrs/02_getting_started/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | mergesort 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /exposed/03_linkedlist/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | linkedlist 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /googlecodejam/store_credit/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | store_credit 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /topcoder/srm538_div1_450/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | srm538_div1_450 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /topcoder/srm538_div2_300/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | srm538_div2_300 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /googlecodejam/alien_language/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | alien_language 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /googlecodejam/reverse_words/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | reverse_words 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /cracking/ch05_bit_manipulation/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | bit_manipulation 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /interview/cracking_ch1_matrix_rotation.py: -------------------------------------------------------------------------------- 1 | import pprint 2 | 3 | arr = [[1, 2, 3, 4], 4 | [5, 6, 7, 8], 5 | [9, 10, 11, 12], 6 | [13, 14, 15, 16]] 7 | pprint.pprint(arr) 8 | 9 | 10 | def rotated(arr): 11 | N = len(arr) 12 | rarr = [[None for i in xrange(N)] for i in xrange(N)] 13 | for i in xrange(N): 14 | for j in xrange(N): 15 | rarr[i][j] = arr[N - j - 1][i] 16 | return rarr 17 | 18 | pprint.pprint(rotated(arr)) 19 | -------------------------------------------------------------------------------- /codeeval/codeeval_37.py: -------------------------------------------------------------------------------- 1 | import string 2 | import sys 3 | 4 | all_ascii_lowercase = set(string.ascii_lowercase) 5 | with open(sys.argv[1], 'r') as f_in: 6 | for line in f_in: 7 | letters = set(letter for letter in line.lower().strip() 8 | if letter in all_ascii_lowercase) 9 | missing = all_ascii_lowercase - letters 10 | if len(missing) == 0: 11 | print 'NULL' 12 | else: 13 | print ''.join(sorted(list(missing))) 14 | -------------------------------------------------------------------------------- /hackerrank/codesprint5/special_multiple.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | 4 | pattern = re.compile("^[09]+$") 5 | 6 | 7 | def special_multiple(n): 8 | cnt = n 9 | while True: 10 | if cnt % 9 == 0 or cnt % 10 == 0: 11 | if pattern.match(str(cnt)): 12 | break 13 | cnt += n 14 | print(cnt) 15 | 16 | 17 | if __name__ == "__main__": 18 | lines = (int(line.strip()) for line in sys.stdin) 19 | lines.next() 20 | map(special_multiple, lines) 21 | -------------------------------------------------------------------------------- /hackerrank/hackerrank_chocolate_feast.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def count(N, C, M): 5 | chocolates = N // C 6 | wrappers = chocolates 7 | while wrappers >= M: 8 | more = wrappers // M 9 | wrappers = wrappers % M + more 10 | chocolates += more 11 | return chocolates 12 | 13 | sys.stdin.readline() 14 | 15 | lines = (map(int, line.strip().split()) for line in sys.stdin 16 | if len(line.strip()) != 0) 17 | for line in lines: 18 | print(count(*line)) 19 | -------------------------------------------------------------------------------- /interview/geeksforgeeks/geeksforgeeks_permutations.py: -------------------------------------------------------------------------------- 1 | def permutations(input): 2 | if len(input) == 1: 3 | return [input] 4 | letter = input[0] 5 | return_value = [] 6 | for permutation in permutations(input[1:]): 7 | elems = list(permutation) 8 | for i in xrange(len(elems)+1): 9 | temp = elems[:] 10 | temp.insert(i, letter) 11 | return_value.append(''.join(temp)) 12 | return return_value 13 | 14 | 15 | print permutations('ABC') 16 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/test/tests.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | QUnit Example 6 | 7 | 8 | 9 |
10 |
11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /hackerrank/hackerrank_two_arrays.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import sys 3 | 4 | 5 | def readline_ints(): 6 | return [int(elem) for elem in sys.stdin.readline().strip().split()] 7 | 8 | N = int(sys.stdin.readline().strip()) 9 | for i in xrange(N): 10 | _, K = readline_ints() 11 | A = readline_ints() 12 | B = readline_ints() 13 | A.sort() 14 | B.sort(reverse=True) 15 | if all(sum([a, b]) >= K for (a, b) in itertools.izip(A, B)): 16 | print 'YES' 17 | else: 18 | print 'NO' 19 | -------------------------------------------------------------------------------- /interview/glassdoor/glassdoor_max_subarray.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | arr = [1, 5, -10, 6, 1] 4 | maxes = [1, 6, 6, 6, 7] 5 | 6 | arr = [0, -1, 1, 5, -1, 3, -7] 7 | maxes = [0, 0, 1, 6, 5, 8, 1] 8 | 9 | """ 10 | 11 | def max_subarray_sum(arr): 12 | max_so_far = max_sum = 0 13 | for x in arr: 14 | max_so_far = max(0, x + max_so_far) 15 | max_sum = max(max_so_far, max_sum) 16 | return max_sum 17 | 18 | print max_subarray_sum([1, 5, -10, 6, 1]) 19 | print max_subarray_sum([0, -1, 1, 5, -1, 3, -7]) 20 | -------------------------------------------------------------------------------- /projecteuler/src/problem1/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0.1" 12 | 13 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 14 | 15 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 16 | 17 | 18 | -------------------------------------------------------------------------------- /projecteuler/src/problem2/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0.1" 12 | 13 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 14 | 15 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 16 | 17 | 18 | -------------------------------------------------------------------------------- /projecteuler/src/problem3/build.sbt: -------------------------------------------------------------------------------- 1 | name := "euler" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.9.2" 6 | 7 | resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" 8 | 9 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.7.2" % "test" 10 | 11 | libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0.1" 12 | 13 | javacOptions ++= Seq("-Xlint:all", "-deprecation") 14 | 15 | scalacOptions ++= Seq("-unchecked", "-deprecation", "-optimise", "-explaintypes") 16 | 17 | 18 | -------------------------------------------------------------------------------- /interview/interviewcake_duplicate_number.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def get_duplicate_number(array): 5 | bitvector = 0 6 | for number in array: 7 | mask = 1 << number 8 | if bitvector & mask: 9 | return number 10 | bitvector |= mask 11 | assert(False) 12 | 13 | 14 | class GetDuplicateNumberTestCase(unittest.TestCase): 15 | 16 | def test_1(self): 17 | self.assertEqual(get_duplicate_number([1, 5, 6, 3, 1]), 1) 18 | 19 | if __name__ == '__main__': 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "engines": { 3 | "node": ">= 0.10.0" 4 | }, 5 | "devDependencies": { 6 | "grunt": "~0.4.2", 7 | "grunt-contrib-jshint": "~0.7.2", 8 | "grunt-contrib-watch": "~0.5.3", 9 | "grunt-contrib-nodeunit": "~0.2.2", 10 | "nodeunit": "~0.8.2", 11 | "watch": "~0.8.0", 12 | "gaze": "~0.4.3", 13 | "tiny-lr": "0.0.5", 14 | "qunit": "~0.5.18", 15 | "grunt-contrib-qunit": "~0.3.0" 16 | }, 17 | "dependencies": { 18 | "grunt": "~0.4.2" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "emailaddress", 3 | "version": "0.0.0", 4 | "homepage": "https://github.com/asimihsan/challenges", 5 | "authors": [ 6 | "Asim Ihsan " 7 | ], 8 | "license": "Apache", 9 | "private": true, 10 | "ignore": [ 11 | "**/.*", 12 | "node_modules", 13 | "bower_components", 14 | "test", 15 | "tests" 16 | ], 17 | "dependencies": { 18 | "jasmine": "~2.0.0" 19 | }, 20 | "devDependencies": { 21 | "qunit": "~1.13.0" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /projecteuler/src/problem5/src/test/scala/Problem5Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.test 2 | 3 | import com.euler.problem4.main.Problem5 4 | 5 | import org.scalatest.FunSuite 6 | import org.scalatest.BeforeAndAfter 7 | 8 | class Problem5Suite extends FunSuite with BeforeAndAfter { 9 | test("count works") { assert( Problem5.count(10, 10).take(5).toList === List(10, 20, 30, 40, 50) ) } 10 | test("smallest number divisible 1->10") { 11 | assert(Problem5.getAnswer(10) === 2520) 12 | } 13 | } 14 | 15 | // vim: set ts=4 sw=4 et: 16 | -------------------------------------------------------------------------------- /projecteuler/src/problem6/src/test/scala/Problem6Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.test 2 | 3 | import com.euler.problem4.main.Problem6 4 | 5 | import org.scalatest.FunSuite 6 | import org.scalatest.BeforeAndAfter 7 | 8 | class Problem6Suite extends FunSuite with BeforeAndAfter { 9 | test("sum of squares -> 10") { assert(Problem6.sumOfSquares(10) === 385) } 10 | test("square of sum -> 10") { assert(Problem6.squareOfSum(10) === 3025) } 11 | test("answer for 10 = 2640") { assert(Problem6.getAnswer(10) === 2640) } 12 | } 13 | 14 | // vim: set ts=4 sw=4 et: 15 | -------------------------------------------------------------------------------- /pearls/02_algorithms/src/AnagramsTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import java.util.List; 4 | 5 | import org.junit.Test; 6 | 7 | 8 | public class AnagramsTest { 9 | Anagrams tester = new Anagrams(); 10 | 11 | @Test 12 | public void testGetAnagrams() { 13 | List anagrams = tester.getAnagrams("caret"); 14 | assertTrue(anagrams.contains("cater")); 15 | assertTrue(anagrams.contains("crate")); 16 | assertTrue(anagrams.contains("react")); 17 | assertTrue(anagrams.contains("recta")); 18 | assertTrue(anagrams.contains("trace")); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /projecteuler/src/problem1/src/main/scala/Problem1.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem1.main 2 | 3 | object Problem1 { 4 | def sumNaturalNumbers(limit: Int) = { 5 | val numbers = for { 6 | i <- 1 until limit 7 | if ((i % 3 == 0) || (i % 5 == 0)) 8 | } yield i 9 | numbers.sum 10 | } // sumNaturalNumbers 11 | 12 | def main(args: Array[String]) = { 13 | val answer = Problem1.sumNaturalNumbers(1000) 14 | println("Problem 1 answer: %s".format(answer)) 15 | } 16 | } // class Problem1 17 | 18 | // vim: set ts=4 sw=4 et: 19 | -------------------------------------------------------------------------------- /epi/ch10/online_median/output3.txt: -------------------------------------------------------------------------------- 1 | -2147483648 2 | -2147483648 3 | -2147483648 4 | -2147483647.5 5 | -2147483647 6 | 0 7 | 10 8 | 10 9 | 10 10 | 10 11 | 10 12 | 0 13 | Wrong! 14 | Wrong! 15 | Wrong! 16 | Wrong! 17 | -2147483647 18 | Wrong! 19 | -1073741823 20 | -1 21 | 0 22 | -1 23 | -1 24 | -1 25 | -1073741823 26 | Wrong! 27 | Wrong! 28 | -2147483647 29 | Wrong! 30 | Wrong! 31 | -1073741823.5 32 | 0 33 | 0.5 34 | 1 35 | 1 36 | 2 37 | 1073741823 38 | 2147483640 39 | 1073741825 40 | Wrong! 41 | Wrong! 42 | Wrong! 43 | Wrong! 44 | Wrong! 45 | Wrong! 46 | 2147483640 47 | 2147483640 48 | 2147483640 49 | 1073741825 50 | 10 -------------------------------------------------------------------------------- /interview/geeksforgeeks/geeksforgeeks_iterative_difference.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def iterateSequence(arr, n): 5 | arr_copy = arr[:] 6 | for i in xrange(n): 7 | arr_copy = [j - i for (i, j) in zip(arr_copy, arr_copy[1:])] 8 | return sum(arr_copy) 9 | 10 | 11 | class IterateSequenceTest(unittest.TestCase): 12 | def test1(self): 13 | self.assertEqual(iterateSequence([5, 6, 3, 9, -1], 1), -6) 14 | 15 | def test2(self): 16 | self.assertEqual(iterateSequence([5, 6, 3, 9, -1], 4), -38) 17 | 18 | 19 | if __name__ == '__main__': 20 | unittest.main() 21 | -------------------------------------------------------------------------------- /interview/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | class MaximumSubarray { 2 | public static int maximumSubarray(int[] array) { 3 | Integer maximumSoFar = null; 4 | Integer maxSum = maximumSoFar; 5 | for (int i : array) { 6 | maximumSoFar = (maximumSoFar == null) ? i : Math.max(i, maximumSoFar + i); 7 | maxSum = (maxSum == null) ? maximumSoFar : Math.max(maxSum, maximumSoFar); 8 | } 9 | return maxSum; 10 | } 11 | 12 | public static void main(String[] args) { 13 | System.out.println(maximumSubarray( 14 | new int[] { -1, 5, 6, -2, 20, -50, 4 })); 15 | } 16 | } -------------------------------------------------------------------------------- /projecteuler/src/problem6/src/main/scala/Problem6.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.main 2 | 3 | import scala.annotation.tailrec 4 | import scala.math 5 | 6 | object Problem6 { 7 | def sumOfSquares(limit: Int): Int = (1 to limit).map(i => i * i).sum 8 | def squareOfSum(limit: Int): Int = math.pow(1 to limit sum, 2).toInt 9 | def getAnswer(limit: Int): Int = squareOfSum(limit) - sumOfSquares(limit) 10 | 11 | def main(args: Array[String]) { 12 | val answer = getAnswer(100) 13 | println("Problem 6 answer: %s".format(answer)) 14 | } 15 | } // object Problem6 16 | 17 | // vim: set ts=4 sw=4 et: 18 | -------------------------------------------------------------------------------- /epi/ch10/online_median/input3.txt: -------------------------------------------------------------------------------- 1 | 50 2 | a -2147483648 3 | a -2147483648 4 | a -2147483647 5 | r -2147483648 6 | a 2147483647 7 | r -2147483648 8 | a 10 9 | a 10 10 | a 10 11 | r 10 12 | r 10 13 | r 10 14 | r 100 15 | r 100 16 | r 100 17 | r -2147483648 18 | r 2147483647 19 | r 10 20 | a 1 21 | a -1 22 | a 1 23 | a -1 24 | r 1 25 | r -1 26 | r -1 27 | r -1 28 | r -1 29 | r 1 30 | r 1 31 | r 0 32 | a 0 33 | a 1 34 | a 2147483647 35 | a 2 36 | r 1 37 | a 2147483646 38 | r 2 39 | a 2147483640 40 | a 10 41 | r 2 42 | r 2 43 | r 2 44 | r 1 45 | r 1 46 | r 1 47 | a 2147483640 48 | a 2147483640 49 | a -2147483648 50 | a -2147483640 51 | r 2147483640 -------------------------------------------------------------------------------- /interview/oreilly_counting_sort.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def counting_sort(arr, k): 5 | B = [0 for i in xrange(k)] 6 | for elem in arr: 7 | B[elem] += 1 8 | idx = 0 9 | for i in xrange(k): 10 | while B[i] > 0: 11 | arr[idx] = i 12 | idx += 1 13 | B[i] -= 1 14 | 15 | return arr 16 | 17 | 18 | class CountingSortTest(unittest.TestCase): 19 | 20 | def test1(self): 21 | self.assertEqual(counting_sort([1, 4, 5, 2, 3, 1, 1, 1], 6), 22 | [1, 1, 1, 1, 2, 3, 4, 5]) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /hackerrank/hackerrank_candies.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import sys 3 | 4 | sys.stdin.readline() 5 | 6 | children = map(int, (line.strip() for line in sys.stdin)) 7 | minimum_left = [1] * len(children) 8 | minimum_right = [1] * len(children) 9 | for i in xrange(len(children) - 2, -1, -1): 10 | if children[i] > children[i+1]: 11 | minimum_right[i] = 1 + minimum_right[i+1] 12 | for i in xrange(0, len(children) - 1): 13 | if children[i+1] > children[i]: 14 | minimum_left[i+1] = 1 + minimum_left[i] 15 | candies = [max([l, r]) 16 | for (l, r) in itertools.izip(minimum_left, minimum_right)] 17 | print sum(candies) 18 | -------------------------------------------------------------------------------- /codeeval/codeeval_5.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def process_seq(seq): 5 | for i in xrange(1, len(seq)): 6 | for j in xrange(1, len(seq)): 7 | if any(elem > len(seq) for elem in [i+j, i+2*j]): 8 | continue 9 | sub = seq[i:i+j] 10 | cand = seq[i+j:i+2*j] 11 | if sub == cand: 12 | print ' '.join(sub) 13 | return 14 | 15 | with open(sys.argv[1], 'r') as f_in: 16 | lines = (line.strip() for line in f_in if len(line.strip()) > 0) 17 | for line in lines: 18 | seq = [elem for elem in line.strip().split()] 19 | process_seq(seq) 20 | -------------------------------------------------------------------------------- /codingforinterviews/CodingForInterviewsSingleton.java: -------------------------------------------------------------------------------- 1 | class Singleton { 2 | private static final Singleton instance; 3 | static { 4 | try { 5 | instance = new Singleton(); 6 | } catch (Exception e) { 7 | throw new RuntimeException("d'ooooohh!!!"); 8 | } 9 | } 10 | private Singleton() { } 11 | public static Singleton getInstance() { 12 | return instance; 13 | } 14 | } 15 | 16 | class CodingForInterviewsSingleton { 17 | public static void main(String[] args) { 18 | //Singleton instance = new Singleton(); 19 | Singleton instance = Singleton.getInstance(); 20 | } 21 | } -------------------------------------------------------------------------------- /interview/leapfrog.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | from arr[0] to arr[len(arr)-1] 4 | 5 | works! [2, 2, -1, 1, 0] 6 | 7 | OOB [1, 1, 1, 100, 0] 8 | 9 | cycle 1 [1, -1, 0, 0, 0] 10 | 11 | cycle 2 [1, 0, 0, 0, 0] 12 | 13 | """ 14 | 15 | def leapfrog(arr): 16 | visited = {} 17 | i = 0 18 | maximum = len(arr) - 1 19 | while i != maximum: 20 | if visited.get(i, False) is True: 21 | return False 22 | visited[i] = True 23 | i += arr[i] 24 | if i < 0 or i > maximum: 25 | return False 26 | return True 27 | 28 | print leapfrog([2, 2, -1, 1, 0]) 29 | print leapfrog([1, 0, 0, 0, 0]) 30 | print leapfrog([0]) 31 | -------------------------------------------------------------------------------- /rosalind/fibo/src/test/java/TestFibonacci.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | import static org.junit.Assert.assertThat; 3 | import static org.hamcrest.CoreMatchers.is; 4 | 5 | public class TestFibonacci { 6 | @Test 7 | public void testZero() { 8 | assertThat(Fibonacci.calculate(0), is(0)); 9 | } 10 | 11 | @Test 12 | public void testOne() { 13 | assertThat(Fibonacci.calculate(1), is(1)); 14 | } 15 | 16 | @Test 17 | public void testNine() { 18 | assertThat(Fibonacci.calculate(9), is(34)); 19 | } 20 | 21 | @Test 22 | public void testMax() { 23 | assertThat(Fibonacci.calculate(25), is(75025)); 24 | } 25 | } -------------------------------------------------------------------------------- /interview/interviewcake_matching_parens.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def find_matching_paren(input, pos): 5 | cnt = 0 6 | for i in xrange(pos, len(input)): 7 | if input[i] == '(': 8 | cnt += 1 9 | elif input[i] == ')': 10 | cnt -= 1 11 | if cnt == 0: 12 | return i 13 | return None 14 | 15 | 16 | class FindMatchingParenTestCase(unittest.TestCase): 17 | 18 | def test_1(self): 19 | self.assertEqual(find_matching_paren('i am (foo(foo))', 5), 14) 20 | 21 | def test_2(self): 22 | self.assertEqual(find_matching_paren('i am (foo(foo))', 9), 13) 23 | 24 | if __name__ == '__main__': 25 | unittest.main() 26 | -------------------------------------------------------------------------------- /interview/SortedArrayBinarySearch.java: -------------------------------------------------------------------------------- 1 | class SortedArrayBinarySearch { 2 | public static int binarySearch(int[] array, int value) { 3 | int lo = 0; 4 | int hi = array.length - 1; 5 | while (lo <= hi) { 6 | int mid = lo + (hi - lo) / 2; 7 | if (array[mid] > value) 8 | hi = mid - 1; 9 | else if (array[mid] < value) 10 | lo = mid + 1; 11 | else 12 | return mid; 13 | } 14 | return -1; 15 | } 16 | 17 | public static void main(String[] args) { 18 | int[] array = {-10, -2, 1, 5, 5, 8, 20, 21}; 19 | System.out.println(binarySearch(array, 5)); 20 | System.out.println(binarySearch(array, 10)); 21 | } 22 | } -------------------------------------------------------------------------------- /codeeval/codeeval_2.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | import operator 3 | import sys 4 | 5 | with open(sys.argv[1], 'r') as f_in: 6 | next_line = f_in.readline().strip() 7 | if len(next_line) == 0: 8 | sys.exit(0) 9 | N = int(next_line) 10 | longest_lines = [(0, None)] * N 11 | heapq.heapify(longest_lines) 12 | 13 | lines = (line.strip() for line in f_in if len(line.strip()) > 0) 14 | for line in lines: 15 | if len(line) > longest_lines[0][0]: 16 | heapq.heapreplace(longest_lines, (len(line), line)) 17 | 18 | longest_lines.sort(key=operator.itemgetter(0), reverse=True) 19 | print '\n'.join(elem[1] for elem in longest_lines 20 | if elem[1] is not None) 21 | -------------------------------------------------------------------------------- /rosalind/bins/src/main/java/CommandLineInterface.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.InputStream; 3 | import java.io.InputStreamReader; 4 | import java.io.IOException; 5 | 6 | public class CommandLineInterface { 7 | public static void main(String[] args) throws IOException { 8 | try ( 9 | InputStream in = CommandLineInterface.class.getResourceAsStream("/problem.input"); 10 | InputStreamReader inr = new InputStreamReader(in); 11 | BufferedReader br = new BufferedReader(inr); 12 | ) { 13 | System.out.println(BinarySearch.solve(br)); 14 | } catch (IOException e) { 15 | throw e; 16 | } 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /projecteuler/src/problem2/src/test/scala/Problem2Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem2.test 2 | 3 | import com.euler.problem2.main.Problem2 4 | 5 | import org.scalatest.FunSuite 6 | import org.scalatest.BeforeAndAfter 7 | 8 | class Problem2Suite extends FunSuite with BeforeAndAfter { 9 | 10 | var problem2: Problem2 = _ 11 | 12 | before { 13 | problem2 = new Problem2 14 | } 15 | 16 | test("first 10 Fibonnaci numbers sum") { 17 | val sum = problem2.getAnswer(limit = 100) 18 | val terms = List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89) 19 | val actual_sum = terms.filter(x => x % 2 == 0).sum 20 | assert(sum === actual_sum) 21 | } 22 | } 23 | 24 | // vim: set ts=4 sw=4 et: 25 | -------------------------------------------------------------------------------- /interview/cracking_set_row_col_to_zero.py: -------------------------------------------------------------------------------- 1 | arr = [[1, 2, 3], 2 | [0, 5, 0], 3 | [7, 8, 9], 4 | [10, 11, 12]] 5 | 6 | 7 | def set_row_col_to_zero(arr): 8 | rows_to_zero = set() 9 | cols_to_zero = set() 10 | number_rows = len(arr) 11 | number_cols = len(arr[0]) 12 | for i in xrange(number_rows): 13 | for j in xrange(number_cols): 14 | if arr[i][j] == 0: 15 | rows_to_zero.add(i) 16 | cols_to_zero.add(j) 17 | for i in xrange(number_rows): 18 | for j in xrange(number_cols): 19 | if i in rows_to_zero or j in cols_to_zero: 20 | arr[i][j] = 0 21 | return arr 22 | 23 | print set_row_col_to_zero(arr) 24 | -------------------------------------------------------------------------------- /rosalind/bins/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * by 'asim.ihsan' at '20/03/14 09:12' with Gradle 1.10 4 | * 5 | * The settings file is used to specify which projects to include in your build. 6 | * In a single project build this file can be empty or even removed. 7 | * 8 | * Detailed information about configuring a multi-project build in Gradle can be found 9 | * in the user guide at http://gradle.org/docs/1.10/userguide/multi_project_builds.html 10 | */ 11 | 12 | /* 13 | // To declare projects as part of a multi-project build use the 'include' method 14 | include 'shared' 15 | include 'api' 16 | include 'services:webservice' 17 | */ 18 | 19 | rootProject.name = 'bins' 20 | -------------------------------------------------------------------------------- /rosalind/fibo/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * by 'asim.ihsan' at '19/03/14 11:59' with Gradle 1.10 4 | * 5 | * The settings file is used to specify which projects to include in your build. 6 | * In a single project build this file can be empty or even removed. 7 | * 8 | * Detailed information about configuring a multi-project build in Gradle can be found 9 | * in the user guide at http://gradle.org/docs/1.10/userguide/multi_project_builds.html 10 | */ 11 | 12 | /* 13 | // To declare projects as part of a multi-project build use the 'include' method 14 | include 'shared' 15 | include 'api' 16 | include 'services:webservice' 17 | */ 18 | 19 | rootProject.name = 'fibo' 20 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | // Enforcing 3 | "bitwise": true, 4 | "camelcase": true, 5 | "curly": true, 6 | "eqeqeq": true, 7 | "immed": true, 8 | "indent": 4, 9 | "latedef": true, 10 | "newcap": true, 11 | "noarg": true, 12 | "quotmark": true, 13 | "strict": true, 14 | "trailing": true, 15 | "undef": true, 16 | "unused": true, 17 | 18 | // Relaxing 19 | "esnext": true, 20 | "smarttabs": true, 21 | 22 | // Environments 23 | "browser": true, 24 | "jquery": true, 25 | "node": true, 26 | 27 | // Custom globals 28 | "globals": { 29 | "emailAddress": true, 30 | "ok": false, 31 | "test": false 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This settings file was auto generated by the Gradle buildInit task 3 | * by 'ai' at '22/03/14 11:04' with Gradle 1.9 4 | * 5 | * The settings file is used to specify which projects to include in your build. 6 | * In a single project build this file can be empty or even removed. 7 | * 8 | * Detailed information about configuring a multi-project build in Gradle can be found 9 | * in the user guide at http://gradle.org/docs/1.9/userguide/multi_project_builds.html 10 | */ 11 | 12 | /* 13 | // To declare projects as part of a multi-project build use the 'include' method 14 | include 'shared' 15 | include 'api' 16 | include 'services:webservice' 17 | */ 18 | 19 | rootProject.name = 'srm613_div2_250' 20 | -------------------------------------------------------------------------------- /codeeval/codeeval_mth_to_last.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program to determine the Mth to last element of a list. 3 | 4 | The first argument will be a text file containing a series of space delimited 5 | characters followed by an integer representing a index into the list (1 6 | based), one per line. E.g. 7 | 8 | a b c d 4 9 | e f g h 2 10 | 11 | Print to stdout, the Mth element from the end of the list, one per line. If 12 | the index is larger than the list size, ignore that input. E.g. 13 | 14 | a 15 | g 16 | """ 17 | 18 | import sys 19 | with open(sys.argv[1], 'r') as f_in: 20 | for test in f_in: 21 | elems = test.split() 22 | (chars, m) = (elems[:-1], int(elems[-1])) 23 | if m > len(chars): 24 | continue 25 | print chars[-m] 26 | -------------------------------------------------------------------------------- /codeeval/codeeval_89.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def memoize(f): 5 | class memodict(dict): 6 | def __getitem__(self, *key): 7 | return dict.__getitem__(self, key) 8 | 9 | def __missing__(self, key): 10 | ret = self[key] = f(*key) 11 | return ret 12 | 13 | return memodict().__getitem__ 14 | 15 | 16 | @memoize 17 | def pass_sum(i=0, j=0): 18 | if i == len(triangle) - 1: 19 | return triangle[i][j] 20 | left = pass_sum(i+1, j) 21 | right = pass_sum(i+1, j+1) 22 | return max(left, right) + triangle[i][j] 23 | 24 | global triangle 25 | with open(sys.argv[1], 'r') as f_in: 26 | triangle = [[int(elem) for elem in line.strip().split()] 27 | for line in f_in.readlines()] 28 | print pass_sum() 29 | -------------------------------------------------------------------------------- /projecteuler/src/problem4/src/test/scala/Problem4Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.test 2 | 3 | import com.euler.problem4.main.Problem4 4 | 5 | import org.scalatest.FunSuite 6 | import org.scalatest.BeforeAndAfter 7 | 8 | class Problem4Suite extends FunSuite with BeforeAndAfter { 9 | test("isPalindrome identifies palindromes") { 10 | val palindrome = 9009 11 | assert(Problem4.isPalindrome(palindrome)) 12 | } 13 | 14 | test("isPalindrome rejects non-palindromes") { 15 | val nonPalindrome = 9010 16 | assert(!Problem4.isPalindrome(nonPalindrome)) 17 | } 18 | 19 | test("largest palindrome from product of two 2-digit numbers is 9009") { 20 | assert(Problem4.getAnswer(2) === 9009) 21 | } 22 | } 23 | 24 | // vim: set ts=4 sw=4 et: 25 | -------------------------------------------------------------------------------- /codingforinterviews/codingforinterviews_is_bst.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | def is_bst(node, min_value, max_value): 9 | if node is None: 10 | return True 11 | if node.left is None and node.right is None: 12 | return True 13 | if node.value < min_value or node.value > max_value: 14 | return False 15 | return (is_bst(node.left, min_value, node.value) and 16 | is_bst(node.right, node.value, max_value)) 17 | 18 | 19 | a = Node(6) 20 | b = Node(3) 21 | c = Node(7) 22 | d = Node(2) 23 | e = Node(59) 24 | 25 | a.left = b 26 | a.right = c 27 | a.left.left = d 28 | a.left.right = e 29 | 30 | print is_bst(a, a.value, a.value) 31 | 32 | -------------------------------------------------------------------------------- /rosalind/subs/subs.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def find_locations(string, substring): 4 | """ Find all _overlapping_ instances of substring in string. 5 | 6 | By default regexp's return non-overlapping results. This is 7 | far simpler under-the-covers. To get overlapping results 8 | we need to use lookaheads, which are much more expensive.""" 9 | 10 | result = [] 11 | pattern = r'(?=%s)' % substring 12 | for match in re.finditer(pattern, string): 13 | result.append(match.start() + 1) 14 | print " ".join(str(elem) for elem in result) 15 | 16 | if __name__ == "__main__": 17 | with open("rosalind_subs.txt") as f: 18 | lines = f.readlines() 19 | string = lines[0].strip() 20 | substring = lines[1].strip() 21 | find_locations(string, substring) 22 | 23 | -------------------------------------------------------------------------------- /interview/interviewcake_reverse_string_in_place.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def reverse(input): 5 | input = [ord(elem) for elem in input] 6 | i = 0 7 | j = len(input) - 1 8 | while i < j: 9 | input[i] = input[i] ^ input[j] # i = i ^ j 10 | input[j] = input[j] ^ input[i] # j = i 11 | input[i] = input[i] ^ input[j] # i = j 12 | i += 1 13 | j -= 1 14 | return ''.join([chr(elem) for elem in input]) 15 | 16 | 17 | class TestReverse(unittest.TestCase): 18 | 19 | def test_1(self): 20 | self.assertEqual(reverse('foobar'), 'raboof') 21 | 22 | def test_2(self): 23 | self.assertEqual(reverse(''), '') 24 | 25 | def test_3(self): 26 | self.assertEqual(reverse('foo1bar'), 'rab1oof') 27 | 28 | if __name__ == '__main__': 29 | unittest.main() 30 | -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/src/test/java/TestTaroString.java: -------------------------------------------------------------------------------- 1 | import org.junit.Test; 2 | import static org.junit.Assert.*; 3 | 4 | public class TestTaroString { 5 | @Test 6 | public void test1() { 7 | assertEquals(TaroString.getAnswer("XCYAZTX"), "Possible"); 8 | } 9 | 10 | @Test 11 | public void test2() { 12 | assertEquals(TaroString.getAnswer("CTA"), "Impossible"); 13 | } 14 | 15 | @Test 16 | public void test3() { 17 | assertEquals(TaroString.getAnswer("ACBBAT"), "Impossible"); 18 | } 19 | 20 | @Test 21 | public void test4() { 22 | assertEquals(TaroString.getAnswer("SGHDJHFIOPUFUHCHIOJBHAUINUIT"), "Possible"); 23 | } 24 | 25 | @Test 26 | public void test5() { 27 | assertEquals(TaroString.getAnswer("CCCATT"), "Impossible"); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /interview/glassdoor/glassdoor_anagrams.py: -------------------------------------------------------------------------------- 1 | def anagrams(arr, input_string): 2 | """What is an anagram? A string that is a permutation of another. 3 | 4 | Rather than exhaustively generate all permuatations of input_string 5 | and comparse them to arr, use a small dictionary to count letters 6 | per word in arr vs. input_string. 7 | """ 8 | count = {} 9 | for char in input_string: 10 | count[char] = count.get(char, 0) + 1 11 | return_value = [] 12 | for i, candidate in enumerate(arr): 13 | candidate_count = {} 14 | for char in candidate: 15 | candidate_count[char] = candidate_count.get(char, 0) + 1 16 | if count == candidate_count: 17 | return_value.append(i) 18 | return return_value 19 | 20 | print anagrams(['fred', 'food', 'derf'], 'dref') 21 | -------------------------------------------------------------------------------- /projecteuler/src/problem7/src/test/scala/Problem7Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem7.test 2 | 3 | import com.euler.problem7.main.Problem7 4 | 5 | import org.scalatest.FunSuite 6 | import org.scalatest.BeforeAndAfter 7 | 8 | class Problem7Suite extends FunSuite with BeforeAndAfter { 9 | test("getElementAtIndex") { 10 | val elems = List(1,2,3,4,5) 11 | assert(Problem7.getElementAtIndex(elems iterator, 1) === 1) 12 | assert(Problem7.getElementAtIndex(elems iterator, 2) === 2) 13 | assert(Problem7.getElementAtIndex(elems iterator, 3) === 3) 14 | assert(Problem7.getElementAtIndex(elems iterator, 4) === 4) 15 | assert(Problem7.getElementAtIndex(elems iterator, 5) === 5) 16 | } 17 | 18 | test("6th prime") { assert(Problem7.getAnswer(6) === 13) } 19 | } 20 | 21 | // vim: set ts=4 sw=4 et: 22 | -------------------------------------------------------------------------------- /epi/ch10/mergek/generate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from string import Template 4 | import os 5 | import random 6 | import sys 7 | 8 | CURRENT_DIR = os.path.dirname(__file__) 9 | TEMPL = Template("${timestamp},${symbol},${number},${price}\n") 10 | start_timestamp = 10000 11 | 12 | 13 | def do_symbol(symbol): 14 | timestamp = start_timestamp 15 | with open("%s.txt" % symbol.lower(), "w") as f_out: 16 | for i in xrange(500): 17 | timestamp += random.randint(1, 10) 18 | f_out.write(TEMPL.substitute( 19 | timestamp=timestamp, 20 | symbol=symbol, 21 | number=random.randint(1, 200), 22 | price=random.random() * 100)) 23 | 24 | 25 | def main(): 26 | map(do_symbol, ["AAPL", "IBM", "GOOG", "AMZN"]) 27 | 28 | 29 | if __name__ == '__main__': 30 | sys.exit(main()) 31 | -------------------------------------------------------------------------------- /epi/ch11/FirstLarger.java: -------------------------------------------------------------------------------- 1 | class FirstLarger { 2 | static int firstLarger(int[] array, int value) { 3 | int lo = 0, hi = array.length - 1, mid; 4 | value += 1; 5 | while (lo <= hi) { 6 | mid = lo + (hi - lo) / 2; 7 | if (array[mid] < value) 8 | lo = mid + 1; 9 | else if (array[mid] > value) 10 | hi = mid - 1; 11 | else 12 | return mid; 13 | } 14 | if (lo >= array.length) 15 | return -1; 16 | return lo; 17 | } 18 | 19 | public static void main(String[] args) { 20 | int[] array = {-14, -10, 2, 108, 108, 243, 285, 285, 285, 401}; 21 | System.out.println(firstLarger(array, 500)); 22 | System.out.println(firstLarger(array, 101)); 23 | System.out.println(firstLarger(array, 108)); 24 | } 25 | } -------------------------------------------------------------------------------- /projecteuler/src/problem3/src/test/scala/Problem3Suite.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem3.test 2 | 3 | import com.euler.problem3.main.Problem3 4 | import org.scalatest.FunSuite 5 | import org.scalatest.BeforeAndAfter 6 | import scala.math.BigInt 7 | 8 | class Problem3Suite extends FunSuite with BeforeAndAfter { 9 | 10 | var problem3: Problem3 = _ 11 | before { 12 | problem3 = new Problem3 13 | } 14 | 15 | test("prime factors of 13195") { 16 | val input = BigInt(13195) 17 | val largestPrimeFactor = Problem3.primeFactors2(input) 18 | val numbers = List(29, 13, 7, 5) 19 | assert(largestPrimeFactor === numbers.max) 20 | } 21 | 22 | def compareSeqs(list1: Seq[_], list2: Seq[_]): Boolean = { 23 | (list1, list2).zipped.forall(_.equals(_)) 24 | } // compareBigNumberLists 25 | } 26 | 27 | // vim: set ts=4 sw=4 et: 28 | -------------------------------------------------------------------------------- /interview/cracking_sorted_to_tree.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | def __str__(self): 8 | return '{value: %s, left: %s, right: %s}' % \ 9 | (self.value, self.left, self.right) 10 | 11 | 12 | def getBinaryTree(arr): 13 | if len(arr) == 0: 14 | return None 15 | if len(arr) == 1: 16 | return Node(arr[0]) 17 | mid = (len(arr) - 1) // 2 18 | root = Node(arr[mid]) 19 | root.left = getBinaryTree(arr[:mid]) 20 | root.right = getBinaryTree(arr[mid+1:]) 21 | return root 22 | 23 | 24 | print getBinaryTree([1,2,3,4,5,6]) 25 | 26 | # root = Node(3), left = gBT([1,2]), right = gBT([4,5,6]) 27 | # gBT([1,2]), root = Node(2), left = gBT([1]), right=gBT([]) 28 | # gBT([4,5,6]), root = Node(5), left = gBT([5]), right = gBT([6]) 29 | -------------------------------------------------------------------------------- /interview/WindowAverageTest.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | 4 | class WindowAverage { 5 | private Deque data; 6 | private int n; 7 | private double mean = 0.0; 8 | 9 | WindowAverage(int n) { 10 | this.n = n; 11 | data = new ArrayDeque(n); 12 | for (int i = 0; i < n; i++) { 13 | data.addLast(0); 14 | } 15 | } 16 | 17 | public double add(int x) { 18 | double first = (double)data.removeFirst(); 19 | data.addLast(x); 20 | mean = mean - first/n + ((double)x)/n; 21 | return mean; 22 | } 23 | } 24 | 25 | class WindowAverageTest { 26 | public static void main(String[] args) { 27 | WindowAverage w = new WindowAverage(2); 28 | int[] array = {5, 4, 7, 8}; 29 | for (int i : array) 30 | System.out.println(w.add(i)); 31 | } 32 | } -------------------------------------------------------------------------------- /epi/ch5/SpreadsheetColumnEncoding.java: -------------------------------------------------------------------------------- 1 | class SpreadsheetColumnEncoding { 2 | public static int ssDecodeColID(String input) { 3 | if (input.length() == 0) 4 | throw new IllegalArgumentException("input cannot be zero-length"); 5 | int value = 0; 6 | for (int i = input.length() - 1, power = 0; i >= 0; i--, power++) { 7 | char c = input.charAt(i); 8 | int multiple = (int)Math.pow(26, power); 9 | value += multiple * (c - 'A' + 1); 10 | } 11 | return value; 12 | } 13 | 14 | public static void main(String[] args) { 15 | System.out.println(ssDecodeColID("A")); // 1 16 | System.out.println(ssDecodeColID("B")); // 2 17 | System.out.println(ssDecodeColID("Z")); // 26 18 | System.out.println(ssDecodeColID("AA")); // 27 19 | System.out.println(ssDecodeColID("AB")); // 28 20 | } 21 | } -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/src/ai/mlfsr/Mlfsr16.java: -------------------------------------------------------------------------------- 1 | package ai.mlfsr; 2 | 3 | import java.lang.Math; 4 | 5 | public class Mlfsr16 { 6 | /* 7 | * 16 => x^16 + x^14 + x^13 + x^11 + 1 8 | */ 9 | private static int size = 16; 10 | private static int tap1 = 16; 11 | private static int tap2 = 14; 12 | private static int tap3 = 13; 13 | private static int tap4 = 11; 14 | 15 | private int period = 0; 16 | private final int maximumPeriod = (int) (Math.pow(2, size) - 2); 17 | private int lfsr; 18 | 19 | public Mlfsr16(int seed) { 20 | this.lfsr = seed; 21 | } 22 | 23 | public int next() { 24 | if (period >= maximumPeriod) { 25 | return -1; 26 | } 27 | int bit = ((lfsr >> (size - tap1)) ^ 28 | (lfsr >> (size - tap2)) ^ 29 | (lfsr >> (size - tap3)) ^ 30 | (lfsr >> (size - tap4))) & 1; 31 | lfsr = (lfsr >> 1) | (bit << 15); 32 | period++; 33 | return lfsr; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /cracking/ch05_bit_manipulation/src/ai/cracking/bitmanipulation/Problem1.java: -------------------------------------------------------------------------------- 1 | package ai.cracking.bitmanipulation; 2 | 3 | public class Problem1 { 4 | public static int applySubstring(long N, long M, int i, int j) { 5 | //System.out.println("N: " + N + ", M : " + M + ", i: " + i + ", j " + j); 6 | for (int k = i; k <= j; k++) { 7 | int maskM = 1 << (k - i); 8 | long bitM = (M & maskM) >> (k-i); 9 | if (bitM == 1) 10 | N |= (bitM << k); 11 | else 12 | N &= ~(1 << k); 13 | } 14 | return (int)N; 15 | 16 | /* 17 | int max = ~0; 18 | int left = max - ((1 << j) - 1); 19 | int right = ((1 << i) - 1); 20 | int mask = left | right; 21 | System.out.println("left: " + Integer.toBinaryString(left)); 22 | System.out.println("right: " + Integer.toBinaryString(right)); 23 | System.out.println("mask: " + Integer.toBinaryString(mask)); 24 | return (int)((N & mask) | (M << i)); 25 | */ 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /cracking/ch08/CoinTest.java: -------------------------------------------------------------------------------- 1 | class Solver { 2 | static int numberOfWays(int n) { 3 | return numberOfWays(n, 25); 4 | } 5 | 6 | private static int numberOfWays(int n, int denom) { 7 | int nextDenom = 0; 8 | switch (denom) { 9 | case 25: 10 | nextDenom = 10; 11 | break; 12 | case 10: 13 | nextDenom = 5; 14 | break; 15 | case 5: 16 | nextDenom = 1; 17 | break; 18 | case 1: 19 | return 1; 20 | } 21 | int ways = 0; 22 | for (int i = 0; i * denom <= n; i++) { 23 | ways += numberOfWays(n - i * denom, nextDenom); 24 | } 25 | return ways; 26 | } 27 | } 28 | 29 | class CoinTest { 30 | public static void main(String[] args) { 31 | System.out.println(Solver.numberOfWays(10)); 32 | } 33 | } -------------------------------------------------------------------------------- /topcoder/srm538_div2_300/src/LeftOrRightTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import org.junit.Test; 4 | 5 | 6 | public class LeftOrRightTest { 7 | LeftOrRight test = new LeftOrRight(); 8 | 9 | @Test 10 | public void testMaxDistance1() { 11 | assertEquals(test.maxDistance("LLLRLRRR"), 3); 12 | } 13 | 14 | @Test 15 | public void testMaxDistance2() { 16 | assertEquals(test.maxDistance("R???L"), 4); 17 | } 18 | 19 | @Test 20 | public void testMaxDistance3() { 21 | assertEquals(test.maxDistance("??????"), 6); 22 | } 23 | 24 | @Test 25 | public void testMaxDistance4() { 26 | assertEquals(test.maxDistance("LL???RRRRRRR???"), 11); 27 | } 28 | 29 | 30 | @Test 31 | public void testMaxDistance5() { 32 | assertEquals(test.maxDistance("L?L?"), 4); 33 | } 34 | 35 | @Test 36 | public void testMaxDistance6() { 37 | assertEquals(test.maxDistance("LRLRRRLRRLL?RRR?L??L?R???L?R?RLL"), 14); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/README.md: -------------------------------------------------------------------------------- 1 | # email-address 2 | 3 | Verify email addresses in JavaScript. 4 | 5 | ## TODO 6 | 7 | - IPv4/IPv6 IP address validation in the domain-part. 8 | - Limit of 64 chars for the local-part. 9 | - Limit of 255 chars for the domain-part. 10 | - Limit of 254 chars for entire email address. 11 | 12 | ## How to run tests 13 | 14 | - Clone the repo. 15 | - Make sure the Node Package Manager (npm) is installed. 16 | - Use Homebrew on Mac, Linux package manager otherwise. 17 | - Don't sudo install packages! Put `~/npm/bin` into `$PATH` then 18 | run `npm config set prefix ~/npm`. 19 | - Make sure bower is installed. 20 | 21 | npm install -g bower 22 | 23 | - Make sure grunt-cli is installed. 24 | 25 | npm install -g grunt-cli 26 | 27 | - Install dependencies: 28 | 29 | npm install 30 | bower install 31 | 32 | - Run tests 33 | 34 | grunt 35 | -------------------------------------------------------------------------------- /interview/GlassdoorTrimExtraSpaces.java: -------------------------------------------------------------------------------- 1 | class GlassdoorTrimExtraSpaces { 2 | public static String trim(String input) { 3 | StringBuilder output = new StringBuilder(); 4 | boolean inSpace = false; 5 | for (int i = 0; i < input.length(); i++) { 6 | int current = input.codePointAt(i); 7 | if (Character.isWhitespace(current) && inSpace == false) { 8 | output.appendCodePoint(current); 9 | inSpace = true; 10 | } else if (Character.isWhitespace(current)) { 11 | continue; 12 | } else { 13 | inSpace = false; 14 | output.appendCodePoint(current); 15 | } 16 | } 17 | return output.toString(); 18 | } 19 | 20 | public static void main(String[] args) { 21 | String input = "i am a delicious mmmmm string!"; 22 | System.out.println(trim(input)); 23 | } 24 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------------------- 2 | # Java. 3 | # ---------------------------------------------------------------------------- 4 | *.class 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | # ---------------------------------------------------------------------------- 11 | 12 | # ---------------------------------------------------------------------------- 13 | # Python. 14 | # ---------------------------------------------------------------------------- 15 | *.py[cod] 16 | 17 | # C extensions 18 | *.so 19 | 20 | # Packages 21 | *.egg 22 | *.egg-info 23 | 24 | # Installer logs 25 | pip-log.txt 26 | 27 | # Unit test / coverage reports 28 | .coverage 29 | .tox 30 | nosetests.xml 31 | 32 | #Translations 33 | *.mo 34 | 35 | #Mr Developer 36 | .mr.developer.cfg 37 | # ---------------------------------------------------------------------------- 38 | rosalind/revp/target 39 | 40 | *.sublime* 41 | -------------------------------------------------------------------------------- /interview/cracking_bst_to_lists.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value, left=None, right=None): 3 | self.value = value 4 | self.left = left 5 | self.right = right 6 | 7 | def __str__(self): 8 | return '{value: %s}' % self.value 9 | 10 | def __repr__(self): 11 | return str(self) 12 | 13 | 14 | def get_level_lists(root): 15 | levels = [[root]] 16 | while True: 17 | old_level = levels[-1] 18 | new_level = [] 19 | for node in old_level: 20 | if node.left is not None: 21 | new_level.append(node.left) 22 | if node.right is not None: 23 | new_level.append(node.right) 24 | if len(new_level) == 0: 25 | break 26 | levels.append(new_level) 27 | return levels 28 | 29 | a = Node(1) 30 | b = Node(4) 31 | c = Node(2, a) 32 | d = Node(5, b) 33 | e = Node(3, c, d) 34 | 35 | print get_level_lists(e) 36 | -------------------------------------------------------------------------------- /codingforinterviews/CodingForInterviewsBitManipulation.java: -------------------------------------------------------------------------------- 1 | class CodingForInterviewsBitManipulation { 2 | public static int setBit(int number, int index, boolean set) { 3 | if (set) 4 | return number | (1 << index); 5 | else 6 | return number & (~(1 << index)); 7 | } 8 | 9 | public static boolean getBit(int number, int index) { 10 | int result = (number & (1 << index)) >> index; 11 | return (result == 1); 12 | } 13 | 14 | public static void main(String[] args) { 15 | int input = 0b11100110; 16 | 17 | // = 0b11101110 18 | System.out.println(Integer.toString(setBit(input, 3, true), 2)); 19 | 20 | // = 0b11100100 21 | System.out.println(Integer.toString(setBit(input, 1, false), 2)); 22 | 23 | // false 24 | System.out.println(getBit(input, 0)); 25 | 26 | // true 27 | System.out.println(getBit(input, 7)); 28 | } 29 | } -------------------------------------------------------------------------------- /epi/ch11/SortedArrayIdenticalToIndex.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Q11.3: Take sorted array of distinct elements A and return index i 3 | * such that A[i] = i, or return -1 if no such index exists. 4 | */ 5 | 6 | class SortedArrayIdenticalToIndex { 7 | public static int find(int[] A) { 8 | int lo = 0; 9 | int hi = A.length - 1; 10 | while (lo <= hi) { 11 | int mid = lo + (hi - lo) / 2; 12 | if (A[mid] > mid) 13 | hi = mid - 1; 14 | else if (A[mid] < mid) 15 | lo = mid + 1; 16 | else 17 | return mid; 18 | } 19 | return -1; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] A = {-5, -4, 0, 3, 5}; 24 | System.out.println(find(A)); // 3 25 | 26 | int[] B = {-5, -4, 0, 1, 5}; // -1 27 | System.out.println(find(B)); 28 | 29 | int[] C = {}; // -1 30 | System.out.println(find(C)); 31 | } 32 | } -------------------------------------------------------------------------------- /exposed/03_linkedlist/src/ai/exposed/Node.java: -------------------------------------------------------------------------------- 1 | package ai.exposed; 2 | 3 | public class Node { 4 | private T mData; 5 | private Node mNext; 6 | 7 | // ----------------------------------------------------------------------- 8 | // Constructors 9 | // ----------------------------------------------------------------------- 10 | public Node(T data) { 11 | this(data, null); 12 | } 13 | 14 | public Node(Node other) { 15 | this(other.getData(), other.getNext()); 16 | } 17 | 18 | public Node(T data, Node next) { 19 | this.mData = data; 20 | this.mNext = next; 21 | } 22 | // ----------------------------------------------------------------------- 23 | 24 | public T getData() { 25 | return this.mData; 26 | } 27 | 28 | public void setData(T data) { 29 | this.mData = data; 30 | } 31 | 32 | public Node getNext() { 33 | return this.mNext; 34 | } 35 | 36 | public void setNext(Node next) { 37 | this.mNext = next; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /interview/StringsByLength.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.Collections; 4 | import java.util.Comparator; 5 | import java.util.List; 6 | 7 | class StringLengthComparator implements Comparator { 8 | public int compare(String o1, String o2) { 9 | if (o1.length() < o2.length()) 10 | return -1; 11 | else if (o1.length() == o2.length()) 12 | return 0; 13 | else 14 | return 1; 15 | } 16 | } 17 | 18 | class StringsByLength { 19 | public static void main(String[] args) { 20 | List strings = new ArrayList(); 21 | strings.addAll(Arrays.asList(new String[] 22 | {"foobar", 23 | "elephant", 24 | "dingo", 25 | "1"} 26 | )); 27 | 28 | // sort by string length! 29 | Collections.sort(strings, new StringLengthComparator()); 30 | System.out.println(strings); 31 | } 32 | } -------------------------------------------------------------------------------- /sedgwick/scramble/src/ai/graph/Node.java: -------------------------------------------------------------------------------- 1 | package ai.graph; 2 | 3 | import com.google.common.base.*; 4 | import java.util.List; 5 | import java.util.ArrayList; 6 | 7 | public class Node { 8 | private final char data; 9 | public char getData() { return data; } 10 | 11 | public static List stringToNodes(String input) { 12 | List rv = new ArrayList(input.length()); 13 | for (int i = 0; i < input.length(); i++) { 14 | Character c = input.charAt(i); 15 | if (Character.isLetter(c)) 16 | rv.add(new Node(c)); 17 | } 18 | return rv; 19 | } 20 | 21 | Node(char data) { 22 | this.data = data; 23 | } 24 | 25 | @Override 26 | public String toString() { 27 | return Objects.toStringHelper(this) 28 | .add("data", data) 29 | .toString(); 30 | } 31 | 32 | @Override 33 | public boolean equals(Object other) { 34 | if (!(other instanceof Node)) return false; 35 | Node o = (Node)other; 36 | return Objects.equal(this.data, o.getData()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /codingforinterviews/CodingForInterviewsNQueens.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | class CodingForInterviewsNQueens { 6 | public static int[][] getPlacements(int n) { 7 | List placements = new ArrayList(); 8 | int[] current = new int[n]; 9 | return placements.toArray(new int[placements.size()][n]); 10 | } 11 | 12 | private static int[][] getPlacements(int[] current, int currentColumn) { 13 | 14 | } 15 | 16 | public static void printPlacements(int[][] placements) { 17 | System.out.println(String.format( 18 | "Number of placements is %d",placements.length)); 19 | for (int i = 0; i < placements.length; i++) 20 | System.out.println(String.format( 21 | "Placement %d: %s", i, Arrays.toString(placements[i]))); 22 | } 23 | 24 | public static void main(String[] args) { 25 | printPlacements(getPlacements(8)); 26 | } 27 | } -------------------------------------------------------------------------------- /rosalind/bins/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This build file was auto generated by running the Gradle 'init' task 3 | * by 'asim.ihsan' at '20/03/14 09:12' with Gradle 1.10 4 | * 5 | * This generated file contains a commented-out sample Java project to get you started. 6 | * For more details take a look at the Java Quickstart chapter in the Gradle 7 | * user guide available at http://gradle.org/docs/1.10/userguide/tutorial_java_projects.html 8 | */ 9 | 10 | apply plugin: 'java' 11 | apply plugin: 'application' 12 | mainClassName = "CommandLineInterface" 13 | 14 | // In this section you declare where to find the dependencies of your project 15 | repositories { 16 | // Use 'maven central' for resolving your dependencies. 17 | // You can declare any Maven/Ivy/file repository here. 18 | mavenCentral() 19 | } 20 | 21 | // In this section you declare the dependencies for your production and test code 22 | dependencies { 23 | compile 'org.slf4j:slf4j-api:1.7.5' 24 | testCompile "junit:junit:4.11" 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## challenges 2 | 3 | ### Introduction 4 | 5 | Solutions and assorted through whilst working through textbooks, online problems, and random ideas. 6 | 7 | ### Contents 8 | 9 | - `clrs`: Implementation of material from _Introduction to Algorithms_ by CLRS in **Java**. 10 | - `cracking`: Implementation of material from _Cracking the Coding Interview_ by Laakmann in **Java**. 11 | - `exposed`: Implementation of material and associated thoughts from _Programming Interviews Exposed_ by Mongan et. al. in **Java**. 12 | - `googlecodejam`: Solutions to Google Code Jam problems in **Python** and **Scala**. 13 | - `pearls`: Implementation of material and associated thoughts from _Programming Pearls_ by Jon Bentley in **Java**. 14 | - `projecteuler`: Test-driven solutions to Project Euler in **Scala**. 15 | - `sedgwick`: Work and toys derived from _Algorithms_ by Sedgwick in **Java**. 16 | - `spoj`: Sphere Online Judge problems in **Python** and **Scala**. 17 | - `topcoder`: Solutions to TopCoder problems in **Java** and **Python**. 18 | -------------------------------------------------------------------------------- /interview/TopCoderTopFox.java: -------------------------------------------------------------------------------- 1 | /** 2 | * http://community.topcoder.com/stat?c=problem_statement&pm=12643&rd=15696 3 | * http://apps.topcoder.com/wiki/display/tc/SRM+584 4 | */ 5 | 6 | import java.util.Set; 7 | import java.util.HashSet; 8 | 9 | public class TopFox { 10 | public int possibleHandles(String familyName, String givenName) { 11 | Set handles = new HashSet(); 12 | for (int i = 0, n = familyName.length(); i < n; i++) { 13 | for (int j = 0, m = givenName.length(); j < m; j++) { 14 | String handle = familyName.substring(0, i+1) + 15 | givenName.substring(0, j+1); 16 | handles.add(handle); 17 | } 18 | } 19 | return handles.size(); 20 | } 21 | } 22 | 23 | class TopCoderTopFox { 24 | public static void main(String[] args) { 25 | TopFox topFox = new TopFox(); 26 | System.out.println(topFox.possibleHandles( 27 | "abb", 28 | "bbc" 29 | )); 30 | } 31 | } -------------------------------------------------------------------------------- /interview/careercup_array_two_numbers_odd_times.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are given an integer array, where all numbers except for TWO numbers 3 | appear even number of times. 4 | 5 | Q: Find out the two numbers which appear odd number of times. 6 | """ 7 | 8 | import unittest 9 | 10 | 11 | def two_numbers_odd_times(arr): 12 | def xor(a, b): 13 | return a ^ b 14 | 15 | xor_1 = reduce(xor, arr) 16 | bit_position = 1 17 | while xor_1 != 0: 18 | bit = xor_1 & 1 19 | if bit == 1: 20 | break 21 | xor_1 >> 1 22 | bit_position += 1 23 | 24 | mask = (1 << bit_position) 25 | xor_2 = reduce(xor, (elem for elem in arr if elem & mask != 0)) 26 | xor_3 = reduce(xor, (elem for elem in arr if elem & mask == 0)) 27 | return sorted([xor_2, xor_3]) 28 | 29 | 30 | class ArrayWithTwoNumbersOddTimesTestCase(unittest.TestCase): 31 | def test1(self): 32 | self.assertEqual(two_numbers_odd_times([1, 2, 1, 2, 3, 4]), [3, 4]) 33 | 34 | 35 | if __name__ == '__main__': 36 | unittest.main() 37 | -------------------------------------------------------------------------------- /rosalind/subs/problem.txt: -------------------------------------------------------------------------------- 1 | Problem 2 | 3 | Given two strings s and t, t is a substring of s if t is contained as a contiguous collection of symbols in s (as a result, t must be no longer than s). 4 | 5 | The position of a symbol in a string is the total number of symbols found to its left, including itself (e.g., the positions of all occurrences of 'U' in "AUGCUUCAGAAAGGUCUUACG" are 2, 5, 6, 15, 17, and 18). The symbol at position i of s is denoted by s[i]. 6 | 7 | A substring of s can be represented as s[j:k], where j and k represent the starting and ending positions of the substring in s; for example, if s = "AUGCUUCAGAAAGGUCUUACG", then s[2:5] = "UGCU". 8 | 9 | The location of a substring s[j:k] is its beginning position j; note that t will have multiple locations in s if it occurs more than once as a substring of s (see the Sample below). 10 | 11 | Given: Two DNA strings s and t (each of length at most 1 kbp). 12 | 13 | Return: All locations of t as a substring of s. 14 | 15 | Sample Dataset 16 | 17 | ACGTACGTACGTACGT 18 | GTA 19 | Sample Output 20 | 21 | 3 7 11 22 | -------------------------------------------------------------------------------- /projecteuler_python/66/66.py: -------------------------------------------------------------------------------- 1 | import cdecimal 2 | import sys 3 | 4 | 5 | def main(): 6 | D_to_x = {} 7 | x_squared_minus_one_is_square = {} 8 | for D in xrange(2, 1000 + 1): 9 | D_decimal = cdecimal.Decimal(D) 10 | if D_decimal.sqrt().is_integer(): 11 | continue 12 | x_squared_minus_one = D_decimal 13 | while True: 14 | #print x_squared_minus_one 15 | if x_squared_minus_one not in x_squared_minus_one_is_square: 16 | x_squared_minus_one_is_square[x_squared_minus_one] = (x_squared_minus_one + 1).sqrt().is_integer() 17 | if x_squared_minus_one_is_square[x_squared_minus_one] and \ 18 | ((x_squared_minus_one / D_decimal).sqrt().is_integer()): 19 | break 20 | x_squared_minus_one += D_decimal 21 | 22 | x = (x_squared_minus_one + 1).sqrt() 23 | print "D: %s, x: %s" % (D, x) 24 | D_to_x[D] = x 25 | 26 | import ipdb; ipdb.set_trace() 27 | pass 28 | 29 | if __name__ == "__main__": 30 | sys.exit(main()) 31 | -------------------------------------------------------------------------------- /codingforinterviews/coin_change.py: -------------------------------------------------------------------------------- 1 | import cPickle as pickle 2 | import sys 3 | 4 | 5 | def memoize(func): 6 | cache = {} 7 | 8 | def wrapper(*args, **kwargs): 9 | key = pickle.dumps(args) + pickle.dumps(kwargs) 10 | if key not in cache: 11 | cache[key] = func(*args, **kwargs) 12 | return cache[key] 13 | return wrapper 14 | 15 | 16 | @memoize 17 | def solve(coins, amount): 18 | if len(coins) == 0: 19 | return 0 20 | if len(coins) == 1: 21 | return 1 if amount % coins[0] == 0 else 0 22 | ways = 0 23 | current_coin, rest_of_coins = coins[0], coins[1:] 24 | i = 0 25 | while amount - i * current_coin >= 0: 26 | ways += solve(rest_of_coins, amount - i * current_coin) 27 | i += 1 28 | return ways 29 | 30 | 31 | def main(): 32 | coins = sorted(map(int, sys.stdin.readline().strip().split(",")), 33 | reverse=True) 34 | amount = int(sys.stdin.readline().strip()) 35 | ways = solve(coins, amount) 36 | print(ways) 37 | 38 | if __name__ == "__main__": 39 | main() 40 | -------------------------------------------------------------------------------- /interview/glassdoor/glassdoor_sorted_rotated_find.py: -------------------------------------------------------------------------------- 1 | arr = [3, 4, 5, 6, 7, 8, 9, 10, 1, 2] 2 | 3 | 4 | def find(arr, elem): 5 | lo = 0 6 | hi = len(arr) - 1 7 | while lo < hi: 8 | mid = (hi + lo) // 2 9 | first = arr[lo] 10 | middle = arr[mid] 11 | last = arr[hi] 12 | 13 | if first <= middle and elem >= first and elem <= middle: 14 | return binary_search(arr, elem, lo, mid) 15 | elif last >= middle and elem >= middle and elem <= last: 16 | return binary_search(arr, elem, mid+1, hi) 17 | elif elem >= first and elem <= middle: 18 | hi = mid 19 | else: 20 | lo = mid + 1 21 | 22 | if arr[lo] == elem: 23 | return lo 24 | return None 25 | 26 | 27 | def binary_search(arr, elem, lo, hi): 28 | while lo < hi: 29 | mid = (hi + lo) // 2 30 | if arr[mid] < elem: 31 | lo = mid + 1 32 | else: 33 | hi = mid 34 | if arr[lo] == elem: 35 | return lo 36 | return None 37 | 38 | 39 | print find(arr, 0) # 8 40 | -------------------------------------------------------------------------------- /epi/ch5/ParityTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * q5.1: parity checking 3 | */ 4 | 5 | class ParityTest { 6 | static int[] parity_lookup = new int[65536]; 7 | static { 8 | for (int i = 0; i < 65536; i++) 9 | parity_lookup[i] = naive(i); 10 | } 11 | 12 | public static int naive(long input) { 13 | int parity; 14 | for (parity = 0; input != 0; input >>= 1) 15 | if ((input & 1) == 1) parity ^= 1; 16 | return parity; 17 | } 18 | 19 | public static int parity1(long input) { 20 | final int mask = 0xFFFF; 21 | int parity; 22 | for (parity = 0; input != 0; input >>= 16) { 23 | parity ^= parity_lookup[(int)(input & mask)]; 24 | } 25 | return parity; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(naive(0b00000001)); 30 | System.out.println(naive(0b00000011)); 31 | System.out.println(naive(0b00000111)); 32 | 33 | System.out.println(parity1(0b00001111)); 34 | System.out.println(parity1(0b00011111)); 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /googlecodejam/store_credit/src/A-large-practice.out: -------------------------------------------------------------------------------- 1 | Case #1: 2 3 2 | Case #2: 1 4 3 | Case #3: 4 5 4 | Case #4: 29 46 5 | Case #5: 11 56 6 | Case #6: 84 240 7 | Case #7: 413 584 8 | Case #8: 28 80 9 | Case #9: 380 633 10 | Case #10: 190 242 11 | Case #11: 450 667 12 | Case #12: 7 126 13 | Case #13: 208 636 14 | Case #14: 301 831 15 | Case #15: 243 649 16 | Case #16: 258 429 17 | Case #17: 18 49 18 | Case #18: 7 32 19 | Case #19: 750 965 20 | Case #20: 196 718 21 | Case #21: 292 1236 22 | Case #22: 539 935 23 | Case #23: 20 263 24 | Case #24: 30 107 25 | Case #25: 3 94 26 | Case #26: 425 484 27 | Case #27: 623 923 28 | Case #28: 219 656 29 | Case #29: 133 242 30 | Case #30: 691 800 31 | Case #31: 317 338 32 | Case #32: 207 485 33 | Case #33: 63 64 34 | Case #34: 13 206 35 | Case #35: 407 421 36 | Case #36: 654 972 37 | Case #37: 205 275 38 | Case #38: 499 883 39 | Case #39: 471 633 40 | Case #40: 371 393 41 | Case #41: 25 170 42 | Case #42: 64 521 43 | Case #43: 28 78 44 | Case #44: 949 1590 45 | Case #45: 1 1043 46 | Case #46: 636 773 47 | Case #47: 240 908 48 | Case #48: 6 47 49 | Case #49: 81 288 50 | Case #50: 274 983 51 | -------------------------------------------------------------------------------- /interview/cracking_is_balanced.py: -------------------------------------------------------------------------------- 1 | def max_depth(node): 2 | if node is None: 3 | return 0 4 | return 1 + max(max_depth(node.left), max_depth(node.right)) 5 | 6 | 7 | def min_depth(node): 8 | if node is None: 9 | return 0 10 | return 1 + min(min_depth(node.left), min_depth(node.right)) 11 | 12 | 13 | def is_balanced(root): 14 | return max_depth(root) - min_depth(root) <= 1 15 | 16 | 17 | class Node(object): 18 | def __init__(self, label, left=None, right=None): 19 | self.label = label 20 | self.left = left 21 | self.right = right 22 | 23 | def __str__(self): 24 | return '{label: %s, left: %s, right: %s}' % \ 25 | (self.label, self.left, self.right) 26 | 27 | def __repr__(self): 28 | return str(self) 29 | 30 | 31 | e = Node('e') 32 | g = Node('g') 33 | d = Node('d', e, g) 34 | c = Node('c', d) 35 | b = Node('b', c) 36 | f = Node('f') 37 | a = Node('a', b, f) 38 | 39 | print is_balanced(a) 40 | 41 | 42 | d = Node('d') 43 | b = Node('b', d) 44 | e = Node('e') 45 | c = Node('c', None, e) 46 | a = Node('a', b, c) 47 | 48 | print is_balanced(a) 49 | -------------------------------------------------------------------------------- /pearls/01_oyster/mlfsr/test/ai/mlfsr/MlfsrTest.java: -------------------------------------------------------------------------------- 1 | package ai.mlfsr; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | import java.lang.Math; 7 | import java.util.Set; 8 | import java.util.HashSet; 9 | 10 | public class MlfsrTest { 11 | 12 | @Test 13 | public void testNext() { 14 | int seed = 0xACE1; 15 | Mlfsr16 tester = new Mlfsr16(seed); 16 | assertEquals("Next value from 0xACE1", 0x5670, tester.next()); 17 | 18 | } 19 | 20 | @Test 21 | public void testExhaustion() { 22 | Mlfsr16 tester = new Mlfsr16(1); 23 | int maximum = (int)(Math.pow(2, 16) - 1); 24 | for(int i = 0; i < maximum; i++) { 25 | int value = tester.next(); 26 | assert(value != -1); 27 | } 28 | assertEquals(tester.next(), -1); 29 | } 30 | 31 | @Test 32 | public void testUniqueness() { 33 | Mlfsr16 tester = new Mlfsr16(1); 34 | int maximum = (int)(Math.pow(2, 16) - 1); 35 | Set intsSeen = new HashSet(); 36 | for (int i = 0; i < maximum; i++) { 37 | Integer value = tester.next(); 38 | assertFalse(intsSeen.contains(value)); 39 | intsSeen.add(value); 40 | } 41 | } 42 | 43 | } // public class MlfsrTest 44 | -------------------------------------------------------------------------------- /rosalind/mprt/problem.txt: -------------------------------------------------------------------------------- 1 | Problem 2 | 3 | To allow for the presence of its varying forms, a protein motif is represented by a shorthand as follows: [XY] means "either X or Y" and {X} means "any amino acid except X." For example, the N-glycosylation motif is written as N{P}[ST]{P}. 4 | 5 | You can see the complete description and features of a particular protein by its access ID "uniprot_id" in the UniProt database, by following this link. Alternatively, you can obtain a protein sequence in FASTA format by following this link. For example, the data for protein B5ZC00 can be found at http://www.uniprot.org/uniprot/B5ZC00. 6 | 7 | Given: At most 15 UniProt Protein Database access IDs. 8 | 9 | Return: For each protein possessing the N-glycosylation motif, output its given access ID followed by a list of locations in the protein string where the motif can be found. 10 | 11 | Sample Dataset 12 | 13 | A2Z669 14 | B5ZC00 15 | P20840_SAG1_YEAST 16 | Sample Output 17 | 18 | B5ZC00 19 | 85 118 142 306 395 20 | P20840_SAG1_YEAST 21 | 79 109 135 248 306 348 364 402 485 501 614 22 | 23 | !!AI note that the online judge requires the file to be terminated by a blank line. 24 | 25 | -------------------------------------------------------------------------------- /codingbat/CountYZ.java: -------------------------------------------------------------------------------- 1 | /** Given a string, count the number of words ending in 'y' or 'z' -- 2 | * so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in 3 | * "yellow" (not case sensitive). We'll say that a y or z is at the end 4 | * of a word if there is not an alphabetic letter immediately following 5 | * it. (Note: Character.isLetter(char) tests if a char is an alphabetic 6 | * letter.) 7 | * 8 | * countYZ("fez day") -> 2 9 | * countYZ("day fez") -> 2 10 | * countYZ("day fyyyz") -> 2 11 | */ 12 | 13 | import java.util.regex.*; 14 | 15 | class CountYZ { 16 | 17 | public static int countYZ(String str) { 18 | Pattern pattern = Pattern.compile("(?:y|z)(?:[^a-z]|\\Z)", 19 | Pattern.CASE_INSENSITIVE); 20 | Matcher matcher = pattern.matcher(str); 21 | int count = 0; 22 | while (matcher.find()) 23 | count++; 24 | return count; 25 | } 26 | 27 | public static void main(String[] args) { 28 | System.out.println(countYZ("fez day")); 29 | System.out.println(countYZ("day fez")); 30 | System.out.println(countYZ("day fyyyz")); 31 | } 32 | } -------------------------------------------------------------------------------- /rosalind/perm/perm.py: -------------------------------------------------------------------------------- 1 | 2 | def permutations(size, acc=None, current_integer=None): 3 | if acc is None: 4 | acc = range(1, size+1) 5 | if len(acc) == 1: 6 | return [acc] 7 | else: 8 | result = [] 9 | for i, integer in enumerate(acc): 10 | current_integer = integer 11 | newacc = acc[0:i] + acc[i+1:] 12 | subperms = permutations(size, newacc, current_integer) 13 | for subperm in subperms: 14 | result.append([current_integer] + subperm) 15 | return result 16 | 17 | def permutations2(size, elements=None): 18 | if elements is None: 19 | elements = range(1, size+1) 20 | if len(elements) <= 1: 21 | yield elements 22 | else: 23 | for perm in permutations2(size, elements[1:]): 24 | for i in xrange(len(elements)): 25 | yield perm[:i] + elements[0:1] + perm[i:] 26 | 27 | if __name__ == "__main__": 28 | integer = 5 29 | results = [elem for elem in permutations2(integer)] 30 | results.sort() 31 | print len(results) 32 | for result in results: 33 | print ' '.join([str(elem) for elem in result]) 34 | 35 | 36 | -------------------------------------------------------------------------------- /interview/glassdoor/glassdoor_sum_tree.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | def get_sum(node): 9 | if node.left is None and node.right is None: 10 | return node.value 11 | children = [elem for elem in [node.left, node.right] 12 | if elem is not None] 13 | return node.value + sum(get_sum(child) for child in children) 14 | 15 | 16 | def is_valid_sum_tree(node): 17 | if node.left is None and node.right is None: 18 | return True 19 | if node.left is not None and not is_valid_sum_tree(node.left): 20 | return False 21 | if node.right is not None and not is_valid_sum_tree(node.right): 22 | return False 23 | children = [elem for elem in [node.left, node.right] 24 | if elem is not None] 25 | return node.value == sum(get_sum(child) for child in children) 26 | 27 | 28 | a = Node(26) 29 | b = Node(10) 30 | c = Node(3) 31 | d = Node(4) 32 | e = Node(6) 33 | f = Node(3) 34 | 35 | a.left = b 36 | a.right = c 37 | b.left = d 38 | b.right = e 39 | c.right = f 40 | 41 | print is_valid_sum_tree(a) 42 | -------------------------------------------------------------------------------- /epi/ch6/DutchFlagPartition.java: -------------------------------------------------------------------------------- 1 | class DutchFlagPartition { 2 | private static void swap(int[] array, int i, int j) { 3 | int temp = array[i]; 4 | array[i] = array[j]; 5 | array[j] = temp; 6 | } 7 | 8 | private static void print(int[] array) { 9 | System.out.print("["); 10 | for (int i = 0; i < array.length - 1; i++) 11 | System.out.print(String.format("%s, ", array[i])); 12 | System.out.println(String.format("%s]", array[array.length - 1])); 13 | } 14 | 15 | public static void parition(int[] A, int i) { 16 | int smaller = 0, equal = 0, larger = A.length - 1; 17 | int pivot = A[i]; 18 | while (equal <= larger) { 19 | if (A[equal] < pivot) 20 | swap(A, smaller++, equal++); 21 | else if (A[equal] == pivot) 22 | equal++; 23 | else 24 | swap(A, equal, larger--); 25 | } 26 | } 27 | 28 | public static void main(String[] args) { 29 | int[] array = {3, 2, -2, 3, 0, 5, 6, 3, 3, 1, 3}; 30 | int pivot = 3; // = 3 31 | // _unstable_ sort! but should be partitioned into thirds. 32 | 33 | parition(array, 3); 34 | print(array); 35 | } 36 | } -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This build file was auto generated by running the Gradle 'init' task 3 | * by 'ai' at '22/03/14 11:04' with Gradle 1.9 4 | * 5 | * This generated file contains a commented-out sample Java project to get you started. 6 | * For more details take a look at the Java Quickstart chapter in the Gradle 7 | * user guide available at http://gradle.org/docs/1.9/userguide/tutorial_java_projects.html 8 | */ 9 | 10 | // Apply the java plugin to add support for Java 11 | apply plugin: 'java' 12 | 13 | // In this section you declare where to find the dependencies of your project 14 | repositories { 15 | // Use 'maven central' for resolving your dependencies. 16 | // You can declare any Maven/Ivy/file repository here. 17 | mavenCentral() 18 | } 19 | 20 | // In this section you declare the dependencies for your production and test code 21 | dependencies { 22 | // Declare the dependency for your favourite test framework you want to use in your tests. 23 | // TestNG is also supported by the Gradle Test task. Just change the 24 | // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add 25 | // 'test.useTestNG()' to your build script. 26 | testCompile "junit:junit:4.11" 27 | } 28 | -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/Gruntfile.js: -------------------------------------------------------------------------------- 1 | /*global module:false*/ 2 | module.exports = function(grunt) { 3 | 'use strict'; 4 | 5 | // Project configuration. 6 | grunt.initConfig({ 7 | // Task configuration. 8 | jshint: { 9 | options: { 10 | jshintrc: '.jshintrc' 11 | }, 12 | gruntfile: { 13 | src: 'Gruntfile.js' 14 | }, 15 | libTest: { 16 | src: ['lib/*.js', 'test/*.js'] 17 | } 18 | }, 19 | qunit: { 20 | files: ['test/*.html'] 21 | }, 22 | watch: { 23 | gruntfile: { 24 | files: 'Gruntfile.js', 25 | tasks: ['jshint:gruntfile'] 26 | }, 27 | libTest: { 28 | files: ['lib/*.js', 'test/*.js'], 29 | tasks: ['jshint:libTest', 'jshint', 'qunit'] 30 | } 31 | } 32 | }); 33 | 34 | // These plugins provide necessary tasks. 35 | grunt.loadNpmTasks('grunt-contrib-qunit'); 36 | grunt.loadNpmTasks('grunt-contrib-jshint'); 37 | grunt.loadNpmTasks('grunt-contrib-watch'); 38 | 39 | // Default task. 40 | grunt.registerTask('default', ['jshint', 'qunit']); 41 | }; 42 | -------------------------------------------------------------------------------- /projecteuler/README.md: -------------------------------------------------------------------------------- 1 | #Test Driven Euler 2 | 3 | ## Introduction 4 | 5 | This repository is me learning test-driven development in Scala by solving Project Euler problems. 6 | 7 | ## Methodology 8 | 9 | - Write a test for the problem's hint, which is typically a trivial subset of the problem. Use [ScalaTest FunSuite](http://www.scalatest.org/getting_started_with_fun_suite). Put the test in `src/test/scala/ProblemXXXSuite.scala`. 10 | - Write a trivial problem solution that, in a hard-coded fashion, returns the expected trivial answer. 11 | - Run the test by executing `sbt test`. It should pass. 12 | - Remove the hard-coded answer. Run the test. It should fail. 13 | - Solve the problem. Call the solution from the main method. Put the code in `src/main/scala/ProblemXXX.scala`. 14 | - Run both the test and solution by executing: `sbt test run`. 15 | - ?? 16 | - Profit. 17 | 18 | ## TODO 19 | 20 | - Annoying, but I can't figure out how to tell `sbt` to only test/run a particular main function. It's forcing me to run all tests, pick a main function, run a particular main function. 21 | - I don't want to make masses of sub-projects; I want one project with masses of main functions. If I have masses of sub-projects I think I need to explicitly state the existence of all sub-projects, which sucks. 22 | 23 | -------------------------------------------------------------------------------- /spoj/TEST/test/test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import unittest 4 | import subprocess 5 | 6 | src_path = os.path.abspath(os.path.join(__file__, os.pardir, os.pardir, "src")) 7 | assert(os.path.isdir(src_path)) 8 | solver_path = os.path.join(src_path, "problem1.py") 9 | assert(os.path.isfile(solver_path)) 10 | 11 | class TestProblem1(unittest.TestCase): 12 | def setUp(self): 13 | self.proc = subprocess.Popen(solver_path, 14 | shell = True, 15 | stdin = subprocess.PIPE, 16 | stdout = subprocess.PIPE) 17 | self.assertTrue(self.proc.poll() is None) 18 | 19 | def tearDown(self): 20 | if self.proc.poll() is None: 21 | self.proc.terminate() 22 | 23 | def test_terminates_on_42(self): 24 | for number in ["1", "2", "3", "4", "5"]: 25 | self.assertTrue(self.proc.poll() is None) 26 | self.proc.stdin.write("%s\n" % number) 27 | output = self.proc.stdout.readline() 28 | self.assertEqual(output.strip(), number) 29 | self.assertTrue(self.proc.poll() is None) 30 | self.proc.stdin.write("42\n") 31 | self.proc.wait() 32 | self.assertTrue(self.proc.poll() is not None) 33 | 34 | -------------------------------------------------------------------------------- /interview/mergesort.py: -------------------------------------------------------------------------------- 1 | def mergesort(arr): 2 | if len(arr) == 1: 3 | return (0, arr) 4 | left = arr[:len(arr)//2] 5 | (inversions_left, left) = mergesort(left) 6 | right = arr[len(arr)//2:] 7 | (inversions_right, right) = mergesort(right) 8 | 9 | inversions_merge = 0 10 | merged = [] 11 | i = 0 12 | j = 0 13 | while True: 14 | if len(merged) == len(arr): 15 | inv = inversions_left + inversions_right + inversions_merge 16 | return (inv, merged) 17 | if i > len(left) - 1: 18 | merged.append(right[j]) 19 | j += 1 20 | elif j > len(right) - 1: 21 | merged.append(left[i]) 22 | i += 1 23 | else: 24 | if left[i] <= right[j]: 25 | merged.append(left[i]) 26 | i += 1 27 | else: 28 | merged.append(right[j]) 29 | j += 1 30 | inversions_merge += len(left) - i 31 | 32 | 33 | def get_inversions(arr): 34 | return mergesort(arr)[0] 35 | 36 | import sys 37 | T = int(sys.stdin.readline().strip()) 38 | for i in xrange(T): 39 | sys.stdin.readline() 40 | print get_inversions([int(elem) 41 | for elem in sys.stdin.readline().strip().split()]) 42 | -------------------------------------------------------------------------------- /projecteuler/src/problem5/src/main/scala/Problem5.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.main 2 | 3 | import scala.annotation.tailrec 4 | import scala.math 5 | 6 | object Problem5 { 7 | val primes = List(2, 3, 5, 7, 11, 13, 17, 19) 8 | def count(from: Int, step: Int): Iterator[Int] = { 9 | class Counter(from: Int, step: Int) extends Iterator[Int] { 10 | var count = from - step 11 | def hasNext = true 12 | def next = { count += step; count } 13 | } 14 | new Counter(from, step) 15 | } 16 | def divisible(i: Int, xs: List[Int]): Boolean = xs.forall(i % _ == 0) 17 | def getAnswer(max: Int): Int = { 18 | val xs: List[Int] = (primes.filter(_ <= max) ::: 19 | (1 to max).toList) 20 | .distinct 21 | .filter(max % _ != 0) 22 | val our_count: Iterator[Int] = count(from = max, step = max) 23 | our_count.find(divisible(_, xs)) match { 24 | case Some(i) => i 25 | case None => -1 26 | } 27 | } 28 | 29 | def main(args: Array[String]) { 30 | val answer = getAnswer(20) 31 | println("Problem 5 answer: %s".format(answer)) 32 | } 33 | } // object Problem2 34 | 35 | // vim: set ts=4 sw=4 et: 36 | -------------------------------------------------------------------------------- /clrs/07_quicksort/src/QuickTest.java: -------------------------------------------------------------------------------- 1 | import static org.junit.Assert.*; 2 | 3 | import java.util.Arrays; 4 | 5 | import org.junit.Test; 6 | import java.util.List; 7 | 8 | public class QuickTest { 9 | Quick tester = new Quick(); 10 | 11 | @Test 12 | public void testPartition() { 13 | List input = Arrays.asList(5, 7, 9, 1, 3, 4); 14 | List expectedOutput = Arrays.asList(1, 3, 4, 5, 7, 9); 15 | int newPivot = tester.partition(input, 0, input.size() - 1); 16 | assertEquals(2, newPivot); 17 | assertArrayEquals(expectedOutput.toArray(), input.toArray()); 18 | } 19 | 20 | @Test 21 | public void testQuicksort() { 22 | List input = Arrays.asList(7, 3, 1, 0, 2, 9, 10, 1); 23 | List expectedOutput = Arrays.asList(0, 1, 1, 2, 3, 7, 9, 10); 24 | tester.quicksort(input, 0, input.size() - 1); 25 | assertArrayEquals(expectedOutput.toArray(), input.toArray()); 26 | } 27 | 28 | @Test 29 | public void testRandomizedQuicksort() { 30 | List input = Arrays.asList(7, 3, 1, 0, 2, 9, 10, 1); 31 | List expectedOutput = Arrays.asList(0, 1, 1, 2, 3, 7, 9, 10); 32 | for (int i = 0; i < 10; i++) { 33 | tester.quicksort(input, 0, input.size() - 1); 34 | assertArrayEquals(expectedOutput.toArray(), input.toArray()); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /interview/CrackingAllPairs.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | class CrackingAllPairs { 8 | static List allPairs(int n) { 9 | if (n == 1) return new ArrayList(Arrays.asList(new String[] {"()"})); 10 | Set returnValue = new HashSet(); 11 | for (String combination : allPairs(n - 1)) { 12 | for (int i = 0; i < combination.length(); i++) { 13 | for (int j = i; j < combination.length(); j++) { 14 | StringBuilder result = new StringBuilder(); 15 | for (int k = 0; k < combination.length(); k++) { 16 | if (k == i) 17 | result.append("("); 18 | if (k == j) 19 | result.append(")"); 20 | result.append(combination.charAt(k)); 21 | } 22 | returnValue.add(result.toString()); 23 | } 24 | } 25 | } 26 | return new ArrayList(returnValue); 27 | } 28 | 29 | public static void main(String[] args) { 30 | System.out.println(allPairs(2)); 31 | System.out.println(allPairs(3)); 32 | } 33 | } -------------------------------------------------------------------------------- /codingforinterviews/CodingForInterviewsReverseWords.java: -------------------------------------------------------------------------------- 1 | class CodingForInterviewsReverseWords { 2 | public static void swap(byte[] input, int i, int j) { 3 | byte temp = input[i]; 4 | input[i] = input[j]; 5 | input[j] = temp; 6 | } 7 | 8 | public static int findNextWordBoundary(byte[] input, int i) { 9 | while (i < input.length && input[i] != ' ') 10 | i++; 11 | return (i - 1); 12 | } 13 | 14 | public static void reverseWord(byte[] input, int i, int j) { 15 | while (i < j) 16 | swap(input, i++, j--); 17 | } 18 | 19 | public static void reverseString(byte[] input) { 20 | for (int i = 0, j = input.length - 1; i < j; i++, j--) 21 | swap(input, i, j); 22 | int i = 0, j; 23 | while (true) { 24 | j = findNextWordBoundary(input, i); 25 | reverseWord(input, i, j); 26 | if (j == input.length - 1) 27 | break; 28 | i = j + 2; 29 | } 30 | } 31 | 32 | public static void reverseWords(byte[] input) { 33 | reverseString(input); 34 | } 35 | 36 | public static void main(String[] args) { 37 | byte[] input = "a big fluffy hippo".getBytes(); 38 | reverseWords(input); 39 | System.out.println(new String(input)); 40 | } 41 | } -------------------------------------------------------------------------------- /interview/cracking_queue_with_two_stacks.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Stack(object): 5 | def __init__(self): 6 | self.data = [] 7 | 8 | def push(self, value): 9 | self.data.append(value) 10 | 11 | def pop(self): 12 | return self.data.pop() 13 | 14 | def peek(self): 15 | return self.data[-1] 16 | 17 | def __len__(self): 18 | return len(self.data) 19 | 20 | 21 | class Queue(object): 22 | def __init__(self): 23 | self.stack1 = Stack() 24 | self.stack2 = Stack() 25 | 26 | def push(self, value): 27 | while len(self.stack1) != 0: 28 | self.stack2.push(self.stack1.pop()) 29 | self.stack1.push(value) 30 | while len(self.stack2) != 0: 31 | self.stack1.push(self.stack2.pop()) 32 | 33 | def pop(self): 34 | return self.stack1.pop() 35 | 36 | 37 | class QueueTest(unittest.TestCase): 38 | def setUp(self): 39 | self.queue = Queue() 40 | 41 | def test1(self): 42 | self.queue.push(1) 43 | self.queue.push(2) 44 | self.queue.push(3) 45 | self.assertEqual(self.queue.pop(), 1) 46 | self.assertEqual(self.queue.pop(), 2) 47 | self.assertEqual(self.queue.pop(), 3) 48 | 49 | 50 | if __name__ == '__main__': 51 | unittest.main() 52 | -------------------------------------------------------------------------------- /projecteuler/src/problem2/src/main/scala/Problem2.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem2.main 2 | 3 | import scala.annotation.tailrec 4 | 5 | class Problem2 { 6 | var term_1 = 1 7 | var term_2 = 2 8 | 9 | def nextFibonacciTerm: Int = { 10 | val term_3 = term_1 + term_2 11 | term_1 = term_2 12 | term_2 = term_3 13 | term_2 14 | } 15 | 16 | def getFibonacciTerms(limit: Int): List[Int] = { 17 | val initial = List(term_1, term_2) 18 | val numbers = for { 19 | i <- 1 to limit - 2 20 | x = nextFibonacciTerm 21 | } yield x 22 | initial ++ numbers 23 | } 24 | 25 | def getAnswer(limit: Int): Int = { 26 | getAnswer(limit, term_2) 27 | } 28 | 29 | @tailrec final def getAnswer(limit: Int, acc: Int): Int = { 30 | nextFibonacciTerm 31 | if (term_2 > limit) 32 | return acc 33 | if (term_2 % 2 == 0) 34 | getAnswer(limit, acc + term_2) 35 | else 36 | getAnswer(limit, acc) 37 | } 38 | } 39 | 40 | object Problem2 { 41 | def main(args: Array[String]) { 42 | val problem2 = new Problem2 43 | val answer = problem2.getAnswer(limit = 4000000) 44 | println("Problem 2 answer: %s".format(answer)) 45 | } 46 | } // object Problem2 47 | 48 | // vim: set ts=4 sw=4 et: 49 | -------------------------------------------------------------------------------- /interview/split_lines.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import unittest 4 | 5 | 6 | def split_lines(text, length): 7 | """Split text along word boundaries bounded by a maximum column 8 | length.""" 9 | return_value = [] 10 | current_line = [] 11 | current_length = 0 12 | for word in text.split(): 13 | if current_length > 0 and current_length + len(word) + 1 > length: 14 | return_value.append(" ".join(current_line)) 15 | current_line = [] 16 | current_length = 0 17 | current_line.append(word) 18 | current_length += len(word) + 1 19 | return_value.append(" ".join(current_line)) 20 | return return_value 21 | 22 | 23 | class SplitLinesTests(unittest.TestCase): 24 | def test_shortest_than_maximum(self): 25 | self.assertEqual(split_lines('Short', 10), ['Short']) 26 | 27 | def test_text_of_exactly_max_length(self): 28 | self.assertEqual(split_lines('Short', 5), ['Short']) 29 | 30 | def test_text_one(self): 31 | self.assertEqual(split_lines('This is a fairly long text', 6), 32 | ['This', 'is a', 'fairly', 'long', 'text']) 33 | 34 | def test_extremely_long_word_is_untouched(self): 35 | self.assertEqual(split_lines('abracadabra!!!', 6), ['abracadabra!!!']) 36 | 37 | if __name__ == "__main__": 38 | unittest.main() 39 | -------------------------------------------------------------------------------- /rosalind/fibo/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This build file was auto generated by running the Gradle 'init' task 3 | * by 'asim.ihsan' at '19/03/14 11:59' with Gradle 1.10 4 | * 5 | * This generated file contains a commented-out sample Java project to get you started. 6 | * For more details take a look at the Java Quickstart chapter in the Gradle 7 | * user guide available at http://gradle.org/docs/1.10/userguide/tutorial_java_projects.html 8 | */ 9 | 10 | // Apply the java plugin to add support for Java 11 | apply plugin: 'java' 12 | 13 | // Running and bundling applications 14 | apply plugin: 'application' 15 | mainClassName = "CommandLineInterface" 16 | 17 | // In this section you declare where to find the dependencies of your project 18 | repositories { 19 | // Use 'maven central' for resolving your dependencies. 20 | // You can declare any Maven/Ivy/file repository here. 21 | mavenCentral() 22 | } 23 | 24 | // In this section you declare the dependencies for your production and test code 25 | dependencies { 26 | // Declare the dependency for your favourite test framework you want to use in your tests. 27 | // TestNG is also supported by the Gradle Test task. Just change the 28 | // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add 29 | // 'test.useTestNG()' to your build script. 30 | testCompile "junit:junit:4.11" 31 | } 32 | -------------------------------------------------------------------------------- /hackerrank/codesprint5/SpecialMultiple.java: -------------------------------------------------------------------------------- 1 | import java.util.BitSet; 2 | import java.util.Scanner; 3 | 4 | class SpecialMultiple { 5 | private static final int MAX_BITS = 32; 6 | 7 | public static long bitSetToLong(BitSet b) { 8 | long returnValue = 0; 9 | for (int i = b.nextSetBit(0); i >= 0; i = b.nextSetBit(i+1)) { 10 | long increment = 9; 11 | for (int j = i; j > 0; j--) { 12 | increment *= 10; 13 | } 14 | returnValue += increment; 15 | } 16 | return returnValue; 17 | } 18 | 19 | public static long solve(int input) { 20 | BitSet b = new BitSet(MAX_BITS); 21 | b.set(0); 22 | long current; 23 | while (true) { 24 | current = bitSetToLong(b); 25 | if (current % input == 0) 26 | break; 27 | 28 | // Increment the BitSet 29 | int ncb = b.nextClearBit(0); 30 | b.set(ncb); 31 | b.clear(0, ncb); 32 | } 33 | return current; 34 | } 35 | 36 | public static void main(String[] args) { 37 | Scanner scanner = new Scanner(System.in); 38 | scanner.nextInt(); 39 | while (scanner.hasNextInt()) { 40 | int input = scanner.nextInt(); 41 | System.out.println(solve(input)); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /interview/cracking_stack_with_min.py: -------------------------------------------------------------------------------- 1 | class Stack(object): 2 | def __init__(self): 3 | self.data = [] 4 | 5 | def push(self, value): 6 | self.data.append(value) 7 | 8 | def pop(self): 9 | return self.data.pop() 10 | 11 | def peek(self): 12 | return self.data[-1] 13 | 14 | def __len__(self): 15 | return len(self.data) 16 | 17 | 18 | class StackWithMin(Stack): 19 | def __init__(self): 20 | super(StackWithMin, self).__init__() 21 | self.minimums = Stack() 22 | 23 | def push(self, value): 24 | super(StackWithMin, self).push(value) 25 | if len(self.minimums) == 0 or value < self.minimums.peek(): 26 | self.minimums.push(value) 27 | 28 | def pop(self): 29 | return_value = super(StackWithMin, self).pop() 30 | if len(self) == 0 or self.peek() > self.minimums.peek(): 31 | self.minimums.pop() 32 | return return_value 33 | 34 | def min(self): 35 | return self.minimums.peek() 36 | 37 | stack = StackWithMin() 38 | stack.push(3) 39 | stack.push(2) 40 | stack.push(1) 41 | stack.push(1) 42 | assert(stack.min() == 1) 43 | assert(stack.pop() == 1) 44 | assert(stack.min() == 1) 45 | assert(stack.pop() == 1) 46 | assert(stack.min() == 2) 47 | assert(stack.pop() == 2) 48 | assert(stack.min() == 3) 49 | assert(stack.pop() == 3) 50 | -------------------------------------------------------------------------------- /topcoder/srm538_div1_450/src/ai/topcoder/TurtleSpy/TurtleSpyTest.java: -------------------------------------------------------------------------------- 1 | package ai.topcoder.TurtleSpy; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import java.lang.Math; 11 | 12 | public class TurtleSpyTest { 13 | TurtleSpy tester; 14 | static double PRECISION = Math.pow(10, -9); 15 | 16 | @Before 17 | public void setUp() { 18 | tester = new TurtleSpy(); 19 | } 20 | 21 | @Test 22 | public void testLocation() { 23 | TurtleSpy.Location origin = new TurtleSpy.Location(0, 0, 0); 24 | TurtleSpy.Location location = new TurtleSpy.Location(100, -100, 225); 25 | double distance = location.distance(origin); 26 | assertEquals(141.4213562373095, distance, PRECISION); 27 | } 28 | 29 | @Test 30 | public void testEvaluateDistance1() { 31 | String[] commands = (String[]) Arrays.asList("forward 100", "left 90", "backward 100").toArray(); 32 | Double distance = tester.evaluateDistance(commands); 33 | assertEquals(141.4213562373095, distance, PRECISION); 34 | 35 | } 36 | 37 | @Test 38 | public void testMaxDistance1() { 39 | String[] commands = (String[]) Arrays.asList("forward 100", "backward 100", "left 90").toArray(); 40 | Double distance = tester.maxDistance(commands); 41 | assertEquals(141.4213562373095, distance, PRECISION); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /interview/QuicksortTest.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.Collections; 4 | import java.util.List; 5 | 6 | class Quicksort { 7 | static > void sort(List array) { 8 | Collections.shuffle(array); 9 | sort(array, 0, array.size() - 1); 10 | } 11 | 12 | private static > void sort(List array, int lo, int hi) { 13 | if (hi <= lo) return; 14 | int j = partition(array, lo, hi); 15 | sort(array, lo, j-1); 16 | sort(array, j+1, hi); 17 | } 18 | 19 | private static > int partition(List array, int lo, int hi) { 20 | int i = lo, j = hi + 1; 21 | T pivot = array.get(lo); 22 | while (true) { 23 | while (array.get(++i).compareTo(pivot) < 0) if (i == hi) break; 24 | while (array.get(--j).compareTo(pivot) > 0) if (j == lo) break; 25 | if (i >= j) break; 26 | Collections.swap(array, i, j); 27 | } 28 | Collections.swap(array, lo, j); 29 | return j; 30 | } 31 | } 32 | 33 | class QuicksortTest { 34 | public static void main(String[] args) { 35 | List list = Arrays.asList(2, -1, 5, 3, 0, 2, 9); 36 | System.out.println(list); 37 | Quicksort.sort(list); 38 | System.out.println(list); 39 | } 40 | } -------------------------------------------------------------------------------- /interview/geeksforgeeks/geeksforgeeks_check_if_all_leaves_at_same_level.py: -------------------------------------------------------------------------------- 1 | class BinaryTree(object): 2 | def __init__(self, key): 3 | self.key = key 4 | self.left = None 5 | self.right = None 6 | 7 | 8 | class Sentinel(object): 9 | pass 10 | 11 | 12 | def are_leaves_same_level(tree): 13 | dequeue = [Sentinel(), tree] 14 | leaf_level = None 15 | current_level = 0 16 | while len(dequeue) != 0: 17 | current = dequeue.pop() 18 | if isinstance(current, Sentinel): 19 | if len(dequeue) == 0: 20 | break 21 | current_level += 1 22 | dequeue.insert(0, Sentinel()) 23 | continue 24 | if current.right is None and current.left is None: 25 | # leaf node. 26 | if leaf_level is None: 27 | leaf_level = current_level 28 | elif leaf_level != current_level: 29 | return False 30 | if current.right is not None: 31 | dequeue.insert(0, current.right) 32 | if current.left is not None: 33 | dequeue.insert(0, current.left) 34 | return True 35 | 36 | 37 | 38 | a = BinaryTree('a') 39 | b = BinaryTree('b') 40 | c = BinaryTree('c') 41 | d = BinaryTree('d') 42 | e = BinaryTree('e') 43 | 44 | a.left = b 45 | a.right = c 46 | b.left = d 47 | c.right = e 48 | 49 | print are_leaves_same_level(a) 50 | -------------------------------------------------------------------------------- /hackerrank/codesprint5/a_story_of_people_and_places.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import cPickle as pickle 3 | import codecs 4 | import zlib 5 | 6 | 7 | def create_names(): 8 | with codecs.open("allCountries.txt", encoding="ascii", errors="replace") as f_in: 9 | with open("names.txt", "w") as f_out: 10 | for line in f_in: 11 | elems = line.split(u'\t') 12 | try: 13 | f_out.write("%s\n" % elems[2].strip()) 14 | except: 15 | continue 16 | 17 | 18 | def is_word_not_in_bloom_filter(word, array, k=3): 19 | m = len(array) 20 | for i in xrange(1, k + 1): 21 | key = word * i 22 | bit = (abs(hash(key))) % m 23 | if array[bit] is False: 24 | return True 25 | return False 26 | 27 | 28 | def create_bloom_filter(m=12000000, k=2): 29 | array = [False] * m 30 | with open("names.txt") as f_in: 31 | lines = (line.strip() for line in f_in) 32 | for line in lines: 33 | for i in xrange(1, k + 1): 34 | key = line * i 35 | bit = (abs(hash(key))) % m 36 | array[bit] = True 37 | serialized = base64.encodestring(zlib.compress(pickle.dumps(array, -1), 9)) 38 | with open("serialized.txt", "w") as f_out: 39 | f_out.write(serialized) 40 | 41 | 42 | if __name__ == "__main__": 43 | create_bloom_filter() 44 | -------------------------------------------------------------------------------- /interview/KMPTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Knuth-Morris-Pratt (KMP) string search, is O(m) to compute fail[] and 3 | * O(n) to search, so O(m + n) time and O(m) space. 4 | */ 5 | class KMP { 6 | private String pattern; 7 | private int[] fail; 8 | 9 | public KMP(String pattern) { 10 | this.pattern = pattern; 11 | int M = pattern.length(); 12 | fail = new int[M]; 13 | for (int i = 0, j = -1; i < M; i++) { 14 | if (i == 0) 15 | fail[i] = -1; 16 | else if (pattern.charAt(i) != pattern.charAt(j)) 17 | fail[i] = j; 18 | else 19 | fail[i] = fail[j]; 20 | while (j >= 0 && pattern.charAt(i) != pattern.charAt(j)) 21 | j = fail[j]; 22 | j++; 23 | } 24 | } 25 | 26 | public int search(String text) { 27 | int M = pattern.length(); 28 | int N = text.length(); 29 | int i, j; 30 | for (i = 0, j = 0; i < N && j < M; i++) { 31 | while (j >= 0 && text.charAt(i) != pattern.charAt(j)) 32 | j = fail[j]; 33 | j++; 34 | } 35 | if (j == M) return i - M; 36 | return -1; 37 | } 38 | } 39 | 40 | class KMPTest { 41 | public static void main(String[] args) { 42 | KMP kmp = new KMP("abaab"); 43 | System.out.println(kmp.search("aaaaaabbbaabbaaabababbabaabbbba")); 44 | } 45 | } -------------------------------------------------------------------------------- /rosalind/gc/gc.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from decimal import Decimal 3 | import operator 4 | 5 | LETTERS = set(["A", "C", "T", "G"]) 6 | 7 | def calculate_gc_content(string): 8 | count = {} 9 | for letter in string: 10 | if letter in LETTERS: 11 | count[letter] = count.get(letter, 0) + 1 12 | numerator = Decimal(count["G"]) + Decimal(count["C"]) 13 | denomenator = sum(Decimal(elem) for elem in count.values()) 14 | return numerator / denomenator * 100 15 | 16 | def parse_file(filepath): 17 | return_value = {} 18 | current_string = [] 19 | current_block_id = "" 20 | with open(filepath) as f: 21 | for line in f: 22 | if line.startswith(">"): 23 | if current_string != []: 24 | return_value[current_block_id] = "".join(current_string) 25 | current_string = [] 26 | current_block_id = line.strip()[1:] 27 | continue 28 | current_string.append(line.strip()) 29 | return_value[current_block_id] = "".join(current_string) 30 | return return_value 31 | 32 | if __name__ == "__main__": 33 | input_data = parse_file(sys.argv[1]) 34 | gc_data = [(identifier, calculate_gc_content(string)) for (identifier, string) in input_data.iteritems()] 35 | gc_data.sort(key=operator.itemgetter(1), reverse=True) 36 | print gc_data[0][0] 37 | print "%.3f%%" % gc_data[0][1] 38 | 39 | -------------------------------------------------------------------------------- /cracking/ch09/SearchInSparseStringArray.java: -------------------------------------------------------------------------------- 1 | class SearchInSparseStringArray { 2 | public static int find(String[] array, String value) { 3 | int lo = 0, hi = array.length - 1; 4 | while (hi >= lo) { 5 | if (array[hi].compareTo("") == 0) 6 | hi--; 7 | else 8 | break; 9 | } 10 | while (lo <= hi) { 11 | if (array[lo].compareTo("") == 0) 12 | lo++; 13 | else 14 | break; 15 | } 16 | while (lo <= hi) { 17 | int mid = lo + (hi - lo) / 2; 18 | while (array[mid].compareTo("") == 0) 19 | mid++; 20 | if (mid < lo || mid > hi) 21 | return -1; 22 | if (array[mid].compareTo(value) < 0) 23 | lo = mid + 1; 24 | else if (array[mid].compareTo(value) > 0) 25 | hi = mid - 1; 26 | else 27 | return mid; 28 | } 29 | return -1; 30 | } 31 | 32 | public static void main(String[] args) { 33 | String[] array = {"at", "", "", "" , "ball", "", "", "car", "", "", 34 | "dad", "", ""}; 35 | System.out.println(find(array, "ball")); 36 | System.out.println(find(array, "ballcar")); 37 | System.out.println(find(array, "dad")); 38 | System.out.println(find(array, "dad2")); 39 | } 40 | } -------------------------------------------------------------------------------- /epi/ch11/kth_largest_element.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import random 4 | import unittest 5 | 6 | 7 | def swap(A, i, j): 8 | A[i], A[j] = A[j], A[i] 9 | 10 | 11 | def partition(A, lo, hi): 12 | pivot = random.randint(lo, hi) 13 | pivotValue = A[pivot] 14 | storeIndex = lo 15 | swap(A, pivot, hi) 16 | for i in xrange(lo, hi): 17 | if A[i] <= pivotValue: 18 | swap(A, i, storeIndex) 19 | storeIndex += 1 20 | swap(A, storeIndex, hi) 21 | return storeIndex 22 | 23 | 24 | def kth_largest(A, k, lo=None, hi=None): 25 | """If A were sorted, return the (k+1)th largest element. If k is 26 | 0 return the minimum. Does so in O(n) average time.""" 27 | if lo is None: 28 | lo = 0 29 | if hi is None: 30 | hi = len(A) - 1 31 | while lo <= hi: 32 | i = partition(A, lo, hi) 33 | if i == k - 1: 34 | return A[i] 35 | elif i < k - 1: 36 | lo = i + 1 37 | else: 38 | hi = i - 1 39 | return A[lo] 40 | 41 | 42 | class KthLargestTestCase(unittest.TestCase): 43 | def test_1(self): 44 | self.assertEqual(kth_largest([5, -1, 0, 6, 3, 4], 2), 0) 45 | 46 | def test_2(self): 47 | self.assertEqual(kth_largest([1], 0), 1) 48 | 49 | def test_3(self): 50 | self.assertEqual(kth_largest([1, 1, 1, 1, 1, 1], 3), 1) 51 | 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /topcoder/srm613_div2_250/src/main/java/TaroString.java: -------------------------------------------------------------------------------- 1 | /* Cat Taro has a string S. He wants to obtain the string "CAT" from the string S. In a single turn 2 | he can choose any character and erase all occurrences of this character in S. He can do as many 3 | turns as he wants (possibly zero). 4 | 5 | You are given the String S. Return "Possible" (quotes for clarity) if it is possible to obtain the 6 | string "CAT" and "Impossible" otherwise. */ 7 | 8 | public class TaroString { 9 | public static String getAnswer(String input) { 10 | String returnValue = "Impossible"; 11 | int cIndex = -1; 12 | int aIndex = -1; 13 | int tIndex = -1; 14 | for (int i = 0; i < input.length(); i++) { 15 | char c = input.charAt(i); 16 | switch(c) { 17 | case 'C': 18 | if (cIndex != -1 || aIndex != -1 || tIndex != -1) 19 | return returnValue; 20 | cIndex = i; 21 | break; 22 | case 'A': 23 | if (cIndex == -1 || aIndex != -1 || tIndex != -1) 24 | return returnValue; 25 | aIndex = i; 26 | break; 27 | case 'T': 28 | if (cIndex == -1 || aIndex == -1 || tIndex != -1) 29 | return returnValue; 30 | tIndex = i; 31 | break; 32 | } 33 | } 34 | returnValue = "Possible"; 35 | return returnValue; 36 | } 37 | } -------------------------------------------------------------------------------- /rosalind/lcs/problem.txt: -------------------------------------------------------------------------------- 1 | Searching Through the Haystackclick to collapse 2 | 3 | In “Finding a Motif in DNA”, we searched a given genetic string for a motif; however, this problem assumed that we know the motif in advance. In practice, biologists often do not know exactly what they are looking for. Rather, they must hunt through several different genomes at the same time to identify regions of similarity that may indicate genes shared by different organisms or species. 4 | 5 | The simplest such region of similarity is a motif occurring without mutation in every one of a collection of genetic strings taken from a database; such a motif corresponds to a substring shared by all the strings. We want to search for long shared substrings, as a longer motif will likely indicate a greater shared function. 6 | 7 | Problem 8 | 9 | A common substring of a collection of strings is a substring of every member of the collection. We say that a common substring is a longest common substring if a longer common substring of the collection does not exist. For example, CG is a common substring of ACGTACGT and AACCGGTATA, whereas GTA is a longest common substring. Note that multiple longest common substrings may exist. 10 | 11 | Given: A collection of k DNA strings (of length at most 1 kbp each; k≤100). 12 | 13 | Return: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.) 14 | 15 | Sample Dataset 16 | 17 | GATTACA 18 | TAGACCA 19 | ATACA 20 | Sample Output 21 | 22 | AC 23 | 24 | -------------------------------------------------------------------------------- /exposed/03_linkedlist/test/ai/exposed/LinkedListTest.java: -------------------------------------------------------------------------------- 1 | package ai.exposed; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class LinkedListTest { 8 | 9 | @Test 10 | public void testEmpty() { 11 | LinkedList test = new LinkedList(); 12 | assertEquals(test.isEmpty(), true); 13 | assertEquals(test.size(), 0); 14 | } 15 | 16 | @Test 17 | public void testOnePushPop() { 18 | LinkedList test = new LinkedList(); 19 | Integer datum = 1; 20 | test.push(datum); 21 | assertEquals(test.isEmpty(), false); 22 | assertEquals(test.size(), 1); 23 | 24 | Integer datumOut = test.pop(); 25 | assertEquals(datum, datumOut); 26 | assertEquals(test.isEmpty(), true); 27 | assertEquals(test.size(), 0); 28 | } 29 | 30 | @Test 31 | public void testTwoPushPop() { 32 | LinkedList test = new LinkedList(); 33 | Integer datum1 = 1; 34 | Integer datum2 = 2; 35 | 36 | test.push(datum1); 37 | assertEquals(test.isEmpty(), false); 38 | assertEquals(test.size(), 1); 39 | 40 | test.push(datum2); 41 | assertEquals(test.isEmpty(), false); 42 | assertEquals(test.size(), 2); 43 | 44 | Integer datum2Out = test.pop(); 45 | assertEquals(test.isEmpty(), false); 46 | assertEquals(test.size(), 1); 47 | assertEquals(datum2Out, datum2); 48 | 49 | Integer datum1Out = test.pop(); 50 | assertEquals(test.isEmpty(), true); 51 | assertEquals(test.size(), 0); 52 | assertEquals(datum1Out, datum1); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /spoj/JOHNNY/README.md: -------------------------------------------------------------------------------- 1 | ## Problem code: JOHNNY 2 | 3 | Johnny visited his favourite supermarket to purchase as many sweets as he could afford. Since daddy had left his credit card at home untended, this was not really a problem. Once he had (barely) managed to push the trolley laden with chocolate bars past the cash desk, he began to wonder how to carry all the shopping home without breaking his back. 4 | 5 | You must know that Johnny is a perfectly normal child, and has exactly 2 hands. Help him distribute his load between both hands so as to minimise the difference in load between both hands. 6 | 7 | ### Input 8 | 9 | The first line of input contains a single integer n<= 10000 denoting the number of sweet packets Johnny has bought. In each of the next n lines a single positive integer is given, describing the weight of the respective packet (the weight is an integer value never exceeding 1014). 10 | 11 | ### Output 12 | 13 | In separate lines, output the numbers of the packets which Johnny should carry in his left hand. Assume packets are numbered in the input order from 1 to n. 14 | 15 | ### Scoring 16 | 17 | Your program shall receive log10 (s/(|d|+1)) points, where s is the total weight of all parcels, while d denotes the difference in weight between the load carried in Johnny's left and right hand. 18 | 19 | ### Example 20 | 21 | For the sample input: 22 | 23 | ``` 24 | 3 25 | 5 26 | 8 27 | 4 28 | ``` 29 | 30 | a program outputting: 31 | 32 | ``` 33 | 2 34 | 3 35 | ``` 36 | 37 | will score `log10 ((5+8+4)/(|8+4-5|+1)) = 0.327` points. -------------------------------------------------------------------------------- /interview/glassdoor/glassdoor_reverse_singly_linked_list.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.next = None 5 | 6 | def __str__(self): 7 | return '{value: %s}' % self.value 8 | 9 | def __repr__(self): 10 | return str(self) 11 | 12 | 13 | class SinglyLinkedList(object): 14 | def __init__(self): 15 | self.head = None 16 | 17 | def append(self, value): 18 | node = Node(value) 19 | if self.head is None: 20 | self.head = node 21 | return 22 | current = self.head 23 | while current.next is not None: 24 | current = current.next 25 | current.next = node 26 | 27 | def reverse(self): 28 | if self.head is None or self.head.next is None: 29 | return 30 | previous = None 31 | next = None 32 | while self.head is not None: 33 | next = self.head.next 34 | self.head.next = previous 35 | previous = self.head 36 | self.head = next 37 | self.head = previous 38 | 39 | def __iter__(self): 40 | if self.head is None: 41 | return 42 | current = self.head 43 | while current is not None: 44 | yield current.value 45 | current = current.next 46 | 47 | 48 | sll = SinglyLinkedList() 49 | sll.append(1) 50 | sll.append(2) 51 | sll.append(3) 52 | print [e for e in sll] 53 | sll.reverse() 54 | print [e for e in sll] 55 | 56 | -------------------------------------------------------------------------------- /rosalind/gc/problem.txt: -------------------------------------------------------------------------------- 1 | Problem 2 | 3 | The GC-content of a DNA string is given by the percentage of symbols in the string that are 'C' or 'G'. For example, the GC-content of "AGCTATAG" is 37.5%. Note that the reverse complement of any DNA string has the same GC-content. 4 | 5 | DNA strings must be labeled when they are consolidated into a database. A commonly used method of string labeling is called FASTA format. In this format, the string is introduced by a line that begins with '>', followed by some labeling information. Subsequent lines contain the string itself; the first line to begin with '>' indicates the label of the next string. 6 | 7 | In Rosalind's implementation, a string in FASTA format will be labeled by the ID "Rosalind_xxxx", where "xxxx" denotes a four-digit code between 0000 and 9999. 8 | 9 | Given: At most 10 DNA strings in FASTA format (of length at most 1 kbp each). 10 | 11 | Return: The ID of the string having the highest GC-content, followed by the GC-content of that string. The GC-content should have an accuracy of 3 decimal places (please refer to the note below on decimal accuracy). 12 | 13 | Sample Dataset 14 | 15 | >Rosalind_6404 16 | CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC 17 | TCCCACTAATAATTCTGAGG 18 | >Rosalind_5959 19 | CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT 20 | ATATCCATTTGTCAGCAGACACGC 21 | >Rosalind_0808 22 | CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC 23 | TGGGAACCTGCGGGCAGTAGGTGGAAT 24 | Sample Output 25 | 26 | Rosalind_0808 27 | 60.919540% 28 | 29 | -------------------------------------------------------------------------------- /sedgwick/scramble/src/ai/graph/Graph.java: -------------------------------------------------------------------------------- 1 | package ai.graph; 2 | 3 | import java.util.Set; 4 | import java.util.HashSet; 5 | import java.util.Map; 6 | import java.util.HashMap; 7 | import java.util.Collections; 8 | import java.util.List; 9 | import java.util.ArrayList; 10 | 11 | public class Graph { 12 | private List> adj; // adjacency sets 13 | private List vertices; 14 | private int V; // number of vertices 15 | private int E; // number of edges 16 | 17 | public Graph(Iterable nodes) { 18 | vertices = new ArrayList(); 19 | adj = new ArrayList>(); 20 | for (Node node : nodes) { 21 | adj.add(new HashSet()); 22 | vertices.add(node); 23 | } 24 | V = vertices.size(); 25 | } 26 | 27 | public int V() { return V; } 28 | public int E() { return E; } 29 | 30 | public Graph addEdge(int v, int w) { 31 | adj.get(v).add(w); 32 | adj.get(w).add(v); 33 | E++; 34 | return this; 35 | } 36 | 37 | public Iterable adj(int v) { 38 | return Collections.unmodifiableSet(adj.get(v)); 39 | } 40 | 41 | public Node intToNode(int v) { 42 | return vertices.get(v); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | StringBuilder s = new StringBuilder(); 48 | s.append(V + " vertices, " + E + " edges\n"); 49 | for (int v = 0; v < V(); v++) { 50 | s.append("v: " + v + ", " + intToNode(v) + " "); 51 | for (int w : this.adj(v)) 52 | s.append(intToNode(w) + " "); 53 | s.append("\n"); 54 | } 55 | return s.toString(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /interview/SubstringPalindromes.java: -------------------------------------------------------------------------------- 1 | import java.util.Collection; 2 | import java.util.HashSet; 3 | 4 | class SubstringPalindromes { 5 | public static Collection palindromes(String input) { 6 | HashSet returnValue = new HashSet(); 7 | String inputReversed = new StringBuilder(input).reverse().toString(); 8 | int maxIndex = input.length() - 1; 9 | for (int substringSize = 0; substringSize <= maxIndex; substringSize++) { 10 | for (int i = 0; i <= maxIndex - substringSize; i++) { 11 | String substring = input.substring(i, 12 | i + substringSize + 1); 13 | String substringReversed = inputReversed.substring(maxIndex - i - substringSize, 14 | maxIndex - i + 1); 15 | if (substring.equals(substringReversed)) 16 | returnValue.add(substring); 17 | } 18 | } 19 | return returnValue; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(palindromes("abba")); // [a, b, bb, abba] 24 | System.out.println(palindromes("abccbd")); // [d, b, c, bccb, a, cc] 25 | System.out.println(palindromes("aaabbb")); // [a, b, aa, bb, aaa, bbb] 26 | System.out.println(palindromes("abcdefgh")); // [a, b, c, d, e, f, g, h] 27 | System.out.println(palindromes("")); // [] 28 | System.out.println(palindromes("a")); // [a] 29 | } 30 | } -------------------------------------------------------------------------------- /cracking/ch08/EightQueens.java: -------------------------------------------------------------------------------- 1 | class EightQueens { 2 | static int[] solve() { 3 | int[] queenCols = new int[8]; 4 | solve(queenCols, 0); 5 | return queenCols; 6 | } 7 | 8 | static boolean isConflict(int[] queenCols, int currentRow) { 9 | if (currentRow == 0) return false; 10 | for (int i = 0; i < currentRow; i++) { 11 | for (int j = 0; j < currentRow; j++) { 12 | if (i == j) 13 | continue; 14 | if (queenCols[i] == queenCols[j]) 15 | return true; 16 | if (Math.abs(queenCols[j] - queenCols[i]) == Math.abs(j - i)) 17 | return true; 18 | } 19 | } 20 | return false; 21 | } 22 | 23 | static boolean solve(int[] queenCols, int currentRow) { 24 | if (isConflict(queenCols, currentRow)) 25 | return false; 26 | if (currentRow == queenCols.length) 27 | return true; 28 | for (int i = 0; i < queenCols.length; i++) { 29 | queenCols[currentRow] = i; 30 | if (solve(queenCols, currentRow + 1)) 31 | return true; 32 | } 33 | return false; 34 | } 35 | 36 | static void print(int[] array) { 37 | for (int i = 0; i < array.length - 1; i++) 38 | System.out.print(String.format("%s ", array[i])); 39 | System.out.println(array[array.length - 1]); 40 | } 41 | 42 | public static void main(String[] args) { 43 | print(solve()); 44 | } 45 | } -------------------------------------------------------------------------------- /rosalind/grph/grph.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from pprint import pprint 3 | 4 | MATCH_LENGTH = 3 5 | 6 | def get_dna_strings_from_fasta_file(lines): 7 | dna_strings = {} 8 | with open("rosalind_grph.txt") as f: 9 | current_dna_name = None 10 | current_dna_string = [] 11 | for line in f: 12 | if line.startswith(">"): 13 | if current_dna_name is not None: 14 | dna_strings[current_dna_name] = "".join(current_dna_string) 15 | current_dna_name = line.strip().strip(">") 16 | current_dna_string = [] 17 | continue 18 | current_dna_string.append(line.strip()) 19 | dna_strings[current_dna_name] = "".join(current_dna_string) 20 | return dna_strings 21 | 22 | def get_adjacency_list(dna_strings): 23 | adjacency_list = [] 24 | for (dna_name, dna_string) in dna_strings.items(): 25 | for (prospective_dna_name, prospective_dna_string) in dna_strings.items(): 26 | if dna_string == prospective_dna_string: 27 | continue 28 | if dna_string[-MATCH_LENGTH:] != prospective_dna_string[:MATCH_LENGTH]: 29 | continue 30 | adjacency_list.append((dna_name, prospective_dna_name)) 31 | return adjacency_list 32 | 33 | if __name__ == "__main__": 34 | dna_strings = get_dna_strings_from_fasta_file("rosalind_grph.txt") 35 | adjacency_list = get_adjacency_list(dna_strings) 36 | for (key, value) in adjacency_list: 37 | print "%s %s" % (key, value) 38 | 39 | -------------------------------------------------------------------------------- /interview/RPNCalculator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | import java.util.Scanner; 4 | 5 | class RPNCalculator { 6 | public static int parse(String input) { 7 | Scanner scanner = new Scanner(input); 8 | Deque stack = new ArrayDeque(); 9 | while (scanner.hasNext()) { 10 | String next = scanner.next(); 11 | Integer left, right; 12 | switch(next) { 13 | case "+": 14 | right = stack.pop(); 15 | left = stack.pop(); 16 | stack.push(left + right); 17 | break; 18 | case "-": 19 | right = stack.pop(); 20 | left = stack.pop(); 21 | stack.push(left - right); 22 | break; 23 | case "*": 24 | right = stack.pop(); 25 | left = stack.pop(); 26 | stack.push(left * right); 27 | break; 28 | case "/": 29 | right = stack.pop(); 30 | left = stack.pop(); 31 | stack.push(left / right); 32 | break; 33 | default: 34 | stack.push(new Integer(next)); 35 | break; 36 | } 37 | } 38 | return stack.pop(); 39 | } 40 | 41 | public static void main(String[] args) { 42 | System.out.println(parse("3 4 + 5 *")); 43 | } 44 | } -------------------------------------------------------------------------------- /epi/ch5/PowersetTest.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | class Powerset { 6 | public static void printPowerset(List elements) { 7 | boolean[] mask = new boolean[elements.size()]; 8 | for (int i = 0; i < Math.pow(2, elements.size()); i++) { 9 | List output = new ArrayList<>(); 10 | for (int j = 0; j < mask.length; j++) { 11 | if (mask[j] == true) output.add(elements.get(j)); 12 | } 13 | System.out.println(output); 14 | incrementMask(mask); 15 | } 16 | } 17 | 18 | private static void incrementMask(boolean[] mask) { 19 | if (mask[mask.length - 1] == false) { 20 | mask[mask.length - 1] = true; 21 | return; 22 | } 23 | mask[mask.length - 1] = false; 24 | boolean carry = true; 25 | for (int i = mask.length - 2; i >= 0; i--) { 26 | if (mask[i] == true && carry == true) { 27 | mask[i] = false; 28 | carry = true; 29 | } 30 | else if (carry == true) { 31 | mask[i] = true; 32 | break; 33 | } else { 34 | break; 35 | } 36 | } 37 | } 38 | } 39 | 40 | class PowersetTest { 41 | public static void main(String[] args) { 42 | List elements = new ArrayList<>(); 43 | elements.add("A"); elements.add("B"); elements.add("C"); 44 | Powerset.printPowerset(elements); 45 | } 46 | } -------------------------------------------------------------------------------- /interview/three_sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array, e.g. 3 | 4 | [1, 5, -3, 2, 6, 3] 5 | 6 | print all (a, b, c) distinct members of the array such that a + b + c = 0 7 | """ 8 | 9 | 10 | def three_sum_naive(arr): 11 | """Given a desired subset size k there is an O(n^k) solution. Just 12 | generate all possible combinations, sum them, and if 0 print it out. 13 | """ 14 | for i in xrange(len(arr)): 15 | for j in xrange(i, len(arr)): 16 | for k in xrange(j, len(arr)): 17 | if arr[i] + arr[j] + arr[k] == 0: 18 | print((arr[i], arr[j], arr[k])) 19 | 20 | 21 | def three_sum_better(arr): 22 | """Given a desired subset size k there is a better O(n^(k-1)) solution. 23 | How? For the three-sum case we are looking for: 24 | 25 | a + b + c = 0 26 | 27 | this is equivalent to: 28 | 29 | c = -(a + b) 30 | 31 | So if we build up a dictionary of all sums of all pairs (a, b) in O(n^2) 32 | time, and then spend O(n) comparing the _negative_ of each array element 33 | to see if it's in the set, we can do the same problem in O(n^2). 34 | """ 35 | 36 | sums_of_pairs = {} 37 | for i in xrange(len(arr)): 38 | for j in xrange(i, len(arr)): 39 | sums_of_pairs[arr[i]+arr[j]] = (i, j) 40 | for k in xrange(len(arr)): 41 | if -arr[k] in sums_of_pairs: 42 | pair = sums_of_pairs[-arr[k]] 43 | print((arr[pair[0]], arr[pair[1]], arr[k])) 44 | 45 | 46 | arr = [1, 5, -3, 2, 6, 3] 47 | three_sum_naive(arr) 48 | print '-' * 79 49 | three_sum_better(arr) 50 | -------------------------------------------------------------------------------- /googlecodejam/reverse_words/src/ReverseWords.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.Collections; 3 | import java.util.Arrays; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.FileWriter; 7 | import java.io.BufferedWriter; 8 | 9 | import com.google.common.base.Charsets; 10 | import com.google.common.io.Files; 11 | 12 | public class ReverseWords { 13 | public static void main(String[] args) throws IOException { 14 | String inputFilepath = "/Users/ai/Programming/javakata/codejam/reverse_words/src/B-large-practice.in"; 15 | String outputFilepath = "/Users/ai/Programming/javakata/codejam/reverse_words/src/B-large-practice.out"; 16 | List lines; 17 | try { 18 | lines = Files.readLines(new File(inputFilepath), Charsets.UTF_8); 19 | } catch (IOException e) { 20 | throw new IllegalStateException("can't read input: " + e); 21 | } 22 | int i = 1; 23 | FileWriter fw; 24 | try { 25 | fw = new FileWriter(outputFilepath); 26 | } catch (IOException e) { 27 | throw new IllegalStateException("can't write to file: " + e); 28 | } 29 | BufferedWriter bw = new BufferedWriter(fw); 30 | for (String line: lines.subList(1, lines.size())) { 31 | List elems = Arrays.asList(line.split("\\s")); 32 | Collections.reverse(elems); 33 | StringBuilder outputLine = new StringBuilder(); 34 | outputLine.append("Case #" + i + ":"); 35 | for (String elem: elems) 36 | outputLine.append(" " + elem); 37 | bw.write(outputLine.toString() + "\n"); 38 | 39 | i += 1; 40 | } 41 | bw.close(); 42 | fw.close(); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /epi/ch5/BaseConvert.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Q5.7 - Given an input string and an input base b_1 convert the 3 | * number to the target base b_2 and return it as a string. 4 | * 5 | * b_1 and b_2 are [2, 16] inclusive. A = 10, B = 11, ... 6 | */ 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | 12 | class BaseConvert { 13 | public static String convert(String input, int baseInput, int baseOutput) { 14 | int sum = 0; 15 | for (int i = input.length() - 1, power = 0; i >= 0; i--, power++) { 16 | char c = input.charAt(i); 17 | int multiple = (int)Math.pow(baseInput, power); 18 | if (c - '0' <= 9) 19 | sum += (c - '0') * multiple; 20 | else 21 | sum += (c - 'A' + 10) * multiple; 22 | } 23 | List values = new ArrayList(); 24 | while (sum != 0) 25 | { 26 | int remainder = sum % baseOutput; 27 | sum = sum / baseOutput; 28 | values.add(remainder); 29 | } 30 | StringBuilder output = new StringBuilder(); 31 | for (Integer value : values) { 32 | if (value <= 9) 33 | output.append(new Character((char)(value + '0'))); 34 | else 35 | output.append(new Character((char)(value - 10 + 'A'))); 36 | } 37 | return output.reverse().toString(); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(convert("10110100", 2, 16)); // B4 42 | System.out.println(convert("B4", 16, 2)); // 10110100 43 | } 44 | } -------------------------------------------------------------------------------- /codingforinterviews/emailaddress/doc/local-part-fsm.gv: -------------------------------------------------------------------------------- 1 | digraph local_part_fsm { 2 | rankdir=LR; 3 | size="16,5" 4 | node [fontsize = 35, penwidth = 3]; 5 | edge [fontsize = 35, penwidth = 3, arrowsize = 3]; 6 | node [shape = doublecircle]; ACCEPT; 7 | node [shape = point]; qi; 8 | node [shape = circle]; 9 | qi -> START; 10 | END_COMMENT_AT_END -> ACCEPT [ label = "" ]; 11 | END_COMMENT_AT_END -> IN_COMMENT_AT_END [ label = "LBRACKET" ]; 12 | END_COMMENT_AT_END -> START [ label = "DOT" ]; 13 | END_DQUOTE -> IN_COMMENT_AT_END [ label = "LBRACKET" ]; 14 | END_DQUOTE -> START [ label = "DOT" ]; 15 | END_DQUOTE -> ACCEPT [ label = "" ]; 16 | IN_COMMENT_AT_END -> END_COMMENT_AT_END [ label = "RBRACKET" ]; 17 | IN_COMMENT_AT_END -> IN_COMMENT_AT_END [ label = "COMMENT_CHAR" ]; 18 | IN_COMMENT_AT_START -> IN_COMMENT_AT_START [ label = "COMMENT_CHAR" ]; 19 | IN_COMMENT_AT_START -> START [ label = "RBRACKET" ]; 20 | IN_DQUOTE -> END_DQUOTE [ label = "DQUOTE" ]; 21 | IN_DQUOTE -> IN_DQUOTE [ label = "IN_DQUOTE_CHAR" ]; 22 | OUT_DQUOTE -> ACCEPT [ label = "" ]; 23 | OUT_DQUOTE -> IN_COMMENT_AT_END [ label = "LBRACKET" ]; 24 | OUT_DQUOTE -> OUT_DQUOTE [ label = "OUT_DQUOTE_CHAR" ]; 25 | OUT_DQUOTE -> START [ label = "DOT" ]; 26 | START -> IN_COMMENT_AT_START [ label = "LBRACKET" ]; 27 | START -> IN_DQUOTE [ label = "DQUOTE" ]; 28 | START -> OUT_DQUOTE [ label = "OUT_DQUOTE_CHAR" ]; 29 | } -------------------------------------------------------------------------------- /interview/Comparators.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Comparator; 3 | 4 | 5 | class StringComparators { 6 | public static class StringLengthAscendingComparator implements Comparator { 7 | public int compare(String s1, String s2) { 8 | if (s1.length() < s2.length()) return -1; 9 | else if (s1.length() == s2.length()) return 0; 10 | else return 1; 11 | } 12 | 13 | } 14 | 15 | public static class StringLengthDescendingComparator implements Comparator { 16 | public int compare(String s1, String s2) { 17 | if (s1.length() < s2.length()) return 1; 18 | else if (s1.length() == s2.length()) return 0; 19 | else return -1; 20 | } 21 | } 22 | 23 | public static String[] sortLengthAscending(String[] input) { 24 | String[] result = Arrays.copyOf(input, input.length); 25 | Arrays.sort(result, new StringLengthAscendingComparator()); 26 | return result; 27 | } 28 | 29 | public static String[] sortLengthDescending(String[] input) { 30 | String[] result = Arrays.copyOf(input, input.length); 31 | Arrays.sort(result, new StringLengthDescendingComparator()); 32 | return result; 33 | } 34 | } 35 | 36 | class Comparators { 37 | public static void main(String[] args) { 38 | String[] foo = {"12345", "1234567", "1", "12"}; 39 | System.out.println(Arrays.deepToString(StringComparators.sortLengthAscending(foo))); 40 | System.out.println(Arrays.deepToString(StringComparators.sortLengthDescending(foo))); 41 | } 42 | } -------------------------------------------------------------------------------- /epi/ch12/partition_dictionary_by_anagrams.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env pypy 2 | 3 | # Q12.7: given a dictionary return a data structure that partitions 4 | # the dictionary into subsets of words that are anagrams of one another. 5 | # 6 | # Assign a prime number per character. Products of anagrams are 7 | # identical. Use a dictionary to map particular products to a list 8 | # of anagrams. Relies heavily on Python's transparent support for 9 | # arbitrary precision integer arithmetic. 10 | # 11 | # Book solution: sort the word by character before hashing. More 12 | # elegant! 13 | 14 | import operator 15 | import pprint 16 | import re 17 | 18 | if __name__ == "__main__": 19 | primes = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 'g': 17, 20 | 'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37, 'm': 41, 21 | 'n': 43, 'o': 47, 'p': 53, 'q': 59, 'r': 61, 's': 67, 22 | 't': 71, 'u': 73, 'v': 79, 'w': 83, 'x': 89, 'y': 97, 23 | 'z': 101} 24 | anagrams = {} 25 | with open("/usr/share/dict/words") as f_in: 26 | lines = (line.strip() for line in f_in) 27 | for line in lines: 28 | if re.match("^[a-z]+$", line): 29 | product = reduce(operator.mul, (primes[x] for x in line)) 30 | if product not in anagrams: 31 | anagrams[product] = [] 32 | anagrams[product].append(line) 33 | lists = sorted(anagrams.values()) 34 | 35 | # To debug it only print out anagram lists with at least two 36 | # anagrams 37 | pprint.pprint([x for x in lists if len(x) > 1]) 38 | 39 | #pprint.pprint(lists) 40 | -------------------------------------------------------------------------------- /interview/cracking_all_paths_with_sum.py: -------------------------------------------------------------------------------- 1 | class BinaryTree(object): 2 | def __init__(self, value): 3 | self.value = value 4 | self.left = None 5 | self.right = None 6 | 7 | def __str__(self): 8 | return '{value: %s}' % self.value 9 | 10 | def __repr__(self): 11 | return str(self) 12 | 13 | 14 | def get_all_subpaths(path): 15 | """Return all subpaths. 16 | 17 | e.g. [1, 2, 3] returns 18 | [[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]] 19 | """ 20 | 21 | return_value = [tuple(path)] 22 | if len(path) == 1: 23 | return return_value 24 | for subpath in [tuple(path[1:]), tuple(path[:-1])]: 25 | return_value.extend(get_all_subpaths(subpath)) 26 | return list(set(return_value)) 27 | 28 | 29 | def all_paths_with_sum(tree, value, path=None): 30 | if path is None: 31 | path = [] 32 | path.append(tree) 33 | if tree.left is None and tree.right is None: 34 | for subpath in get_all_subpaths(path): 35 | if sum(node.value for node in subpath) == value: 36 | yield subpath 37 | nodes = [node for node in [tree.left, tree.right] 38 | if node is not None] 39 | for node in nodes: 40 | for subpath in all_paths_with_sum(node, value, path[:]): 41 | yield subpath 42 | 43 | a = BinaryTree(5) 44 | b = BinaryTree(4) 45 | c = BinaryTree(3) 46 | d = BinaryTree(2) 47 | e = BinaryTree(1) 48 | f = BinaryTree(6) 49 | 50 | a.left = b 51 | a.right = c 52 | b.left = d 53 | c.right = e 54 | c.left = f 55 | 56 | print [path for path in all_paths_with_sum(a, 9)] 57 | -------------------------------------------------------------------------------- /cracking/ch09/SearchRotatedArray.java: -------------------------------------------------------------------------------- 1 | class SearchRotatedArray { 2 | public static int find(int[] array, int key) { 3 | int lo = 0; 4 | int hi = array.length - 1; 5 | while (lo <= hi) { 6 | int mid = lo + (hi - lo) / 2; 7 | //System.out.println(String.format("lo: %s, mid: %s, hi: %s", lo, mid, hi)); 8 | if (array[mid] == key) 9 | return mid; 10 | if ((array[mid] < array[0]) && (array[mid] < array[array.length - 1])) { 11 | // in right increasing portion of rotated array 12 | //System.out.println("right increasing portion"); 13 | if ((key > array[mid]) && (key <= array[array.length - 1])) { 14 | lo = mid + 1; 15 | } else { 16 | hi = mid - 1; 17 | } 18 | } else { 19 | // in left increasing portion of rotated array 20 | //System.out.println("left increasing portion"); 21 | if ((key < array[mid]) && (key >= array[0])) { 22 | hi = mid - 1; 23 | } else { 24 | lo = mid + 1; 25 | } 26 | } 27 | } 28 | return -1; 29 | } 30 | 31 | public static void main(String[] args) { 32 | int[] array = {11, 12, 15, 1, 5, 10}; 33 | System.out.println(find(array, 5)); // 4 34 | System.out.println(find(array, 11)); // 0 35 | System.out.println(find(array, 10)); // 5 36 | System.out.println(find(array, 2)); // -1 37 | System.out.println(find(array, 13)); // -1 38 | } 39 | } -------------------------------------------------------------------------------- /epi/ch12/sort_large_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env pypy 2 | 3 | """Sort a large file that does not fit in memory, composed of lines 4 | of varying length. Sort in O(nlogn) but such that memory usage is 5 | capped at a reasonably small level. 6 | """ 7 | 8 | import heapq 9 | import os 10 | 11 | 12 | class HeapElement(object): 13 | def __init__(self, filepath): 14 | self.f_in = open(filepath) 15 | 16 | def __iter__(self): 17 | return self 18 | 19 | def next(self): 20 | line = self.f_in.readline() 21 | if line == '': 22 | raise StopIteration 23 | if not line.endswith('\n'): 24 | line = line + '\n' 25 | return line 26 | 27 | def close(self): 28 | self.f_in.close() 29 | 30 | def __del__(self): 31 | self.close() 32 | 33 | 34 | def sort_file(input_file, output_file): 35 | input_size = os.stat(input_file).st_size 36 | R = max(input_size / (2000 * 1024), 16) 37 | chunk_size = input_size / R 38 | temp_files = [] 39 | with open(input_file) as f_in: 40 | for i in xrange(R): 41 | temp_file = "temp_%05d.txt" % i 42 | with open(temp_file, "w") as f_out: 43 | contents = f_in.read(chunk_size) + f_in.readline() 44 | contents = contents.splitlines() 45 | contents.sort() 46 | f_out.write('\n'.join(contents)) 47 | temp_files.append(HeapElement(temp_file)) 48 | with open(output_file, 'w') as f_out: 49 | f_out.writelines(heapq.merge(*temp_files)) 50 | 51 | 52 | if __name__ == "__main__": 53 | sort_file("large_file.txt", "large_file_sorted.txt") 54 | -------------------------------------------------------------------------------- /interview/ShuffleSongs.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Random; 4 | 5 | class Song implements Comparable { 6 | private String name; 7 | Song(String name) { this.name = name; } 8 | 9 | @Override 10 | public int compareTo(Song o) { 11 | return name.compareTo(o.name); 12 | } 13 | 14 | @Override 15 | public boolean equals(Object o) { 16 | if (this == o) return true; 17 | if (!(o instanceof Song)) return false; 18 | Song song = (Song)o; 19 | return this.name.equals(song.name); 20 | } 21 | 22 | @Override 23 | public int hashCode() { 24 | int result = 17; 25 | result = 31 * result + name.hashCode(); 26 | return result; 27 | } 28 | 29 | @Override 30 | public String toString() { 31 | return String.format("{name=%s}", name); 32 | } 33 | } 34 | 35 | class ShuffleSongs { 36 | static > void shuffle(List array) { 37 | final int n = array.size(); 38 | Random r = new Random(); 39 | for (int i = n - 1; i > 0; i--) { 40 | int j = r.nextInt(i + 1); 41 | T temp = array.get(j); 42 | array.set(j, array.get(i)); 43 | array.set(i, temp); 44 | } 45 | } 46 | 47 | public static void main(String[] args) { 48 | List songs = new ArrayList(); 49 | songs.add(new Song("lalala")); 50 | songs.add(new Song("falala")); 51 | songs.add(new Song("tralala")); 52 | System.out.println(songs); 53 | shuffle(songs); 54 | System.out.println(songs); 55 | } 56 | } -------------------------------------------------------------------------------- /googlecodejam/alien_language/A-small-practice.in: -------------------------------------------------------------------------------- 1 | 10 25 10 2 | nwlrbbmqbh 3 | cdarzowkky 4 | hiddqscdxr 5 | jmowfrxsjy 6 | bldbefsarc 7 | bynecdyggx 8 | xpklorelln 9 | mpapqfwkho 10 | pkmcoqhnwn 11 | kuewhsqmgb 12 | buqcljjivs 13 | wmdkqtbxix 14 | mvtrrbljpt 15 | nsnfwzqfjm 16 | afadrrwsof 17 | sbcnuvqhff 18 | bsaqxwpqca 19 | cehchzvfrk 20 | mlnozjkpqp 21 | xrjxkitzyx 22 | acbhhkicqc 23 | oendtomfgd 24 | wdwfcgpxiq 25 | vkuytdlcgd 26 | ewhtacioho 27 | rdtqkvwcsg 28 | nwlr(nqxb)bm(dgqw)bh 29 | (gu)(umo)(cdq)(bru)(ote)(xyk)(oah)(hwc)(vdm)(xr) 30 | (aknw)(glmw)(jlue)(kruw)(bci)(xbu)(mue)(qemn)(tyab)(hmrd) 31 | (ijklmopqrstuvyzabcefgh)(qrtuvwxyzabcdefghijklmnop)(ijmnopqsuvwxyabcdefgh)(fghijklmopqrstuvxyzbcde)(pqrstuvwxyzbcdefghijkno)(ghijlpqsuvwxyzabcdef)(yzbcdefgijlmnopqrstuvwx)(nopqrstuvwxyzabcdefghijklm)(klmnopqrsuvwxyzabcdefghj)(rstuvwxbcdefgijklmnopq) 32 | (mnopqrstuvwxyzbcefgikl)(efghjkmnopqrstuvwxyzabcd)(tuvwxyzbcdefghijklmnopq)(pqrstuvwxyabcdefghijklmn)(cdefghijklmnopqstvxzab)(klmnoqrstuvwxyabcdeghi)(jlopqrsuvwxyzabdefghi)(cdefghijklmnopqruxzab)(abdefghijklmnpqrstuvwxz)(zabcdfgijklmnoprstuvwxy) 33 | (rtwd)(dgmy)(sdqr)(kzc)(nqyb)(qtv)(qbc)(xijt)(vcil)(bnvx) 34 | (ghjklmnpstuvwyzabcdef)(xyzabdegjklmnopqstuv)(abcdefghiklmnopqrstuwxz)(cdefghijklmnopqrstuvwxyab)(hjmnopqrstuvwxyzabcdefg)(rtvwyzabcdefghijklnop)(yzcdefhjklmnpqrstuvwx)(opqrstvwxyzabcdefghijklm)(qruvwxyzacdefgijlmno)(xyzabcegiklmnopqstuvw) 35 | (almq)(fot)(pqah)(kovd)(ira)(mqr)(mvwx)(svbj)(sao)(zfi) 36 | (opqrsvwxyzabcdefghijklmn)(yzabcdefgijklmnpqrstuvwx)(ijklmopqrstuvwxzabcefgh)(stuvwxyzabcdefhijklmnopq)(mnopqrstuvwxyzabdefghijkl)(ijklmnopqrstuvwxzbcdefh)(stuvwzabcdefgijklmnopq)(efghijklmnopqrsuvwxyacd)(rstuvxyzadefghijklmnopq)(noqrsuwxyzabdfghjlm) 37 | -------------------------------------------------------------------------------- /interview/geeksforgeeks/geeksforgeeks_left_view_of_binary_tree.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a Binary Tree, print left view of it. Left view of a Binary Tree is set 3 | of nodes visible when tree is visited from left side. Left view of following 4 | tree is 12, 10, 25. 5 | 6 | 12 7 | / \ 8 | 10 30 9 | / \ 10 | 25 40 11 | """ 12 | 13 | 14 | class BinaryTree(object): 15 | def __init__(self, key): 16 | self.key = key 17 | self.left = None 18 | self.right = None 19 | 20 | def __str__(self): 21 | return '{key: %s}' % self.key 22 | 23 | def __repr__(self): 24 | return str(self) 25 | 26 | 27 | class Sentinel(object): 28 | def __str__(self): 29 | return '{Sentinel}' 30 | 31 | def __repr__(self): 32 | return str(self) 33 | 34 | 35 | def print_left_view(tree): 36 | queue = [Sentinel(), tree] 37 | level = [] 38 | while len(queue) != 0: 39 | node = queue.pop() # pops queue[-1] 40 | if isinstance(node, Sentinel): 41 | print level[0] 42 | level = [] 43 | if len(queue) == 0: 44 | break 45 | queue.insert(0, Sentinel()) 46 | continue 47 | if node.right is not None: 48 | queue.insert(0, node.right) 49 | if node.left is not None: 50 | queue.insert(0, node.left) 51 | level.insert(0, node) 52 | 53 | a = BinaryTree('a') 54 | b = BinaryTree('b') 55 | c = BinaryTree('c') 56 | d = BinaryTree('d') 57 | e = BinaryTree('e') 58 | f = BinaryTree('f') 59 | 60 | a.left = b 61 | a.right = c 62 | b.left = d 63 | c.left = e 64 | c.right = f 65 | 66 | print_left_view(a) 67 | -------------------------------------------------------------------------------- /interview/topcoder_lcs.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def lcs_recursive_basic(s, t): 5 | if len(s) == 0 or len(t) == 0: 6 | return '' 7 | if s[0] == t[0]: 8 | return s[0] + lcs_recursive_basic(s[1:], t[1:]) 9 | left = lcs_recursive_basic(s[1:], t) 10 | right = lcs_recursive_basic(s, t[1:]) 11 | if len(left) > len(right): 12 | return left 13 | else: 14 | return right 15 | 16 | 17 | def lcs_dp(s, t): 18 | A = [[None] * (len(t) + 1)] * (len(s) + 1) 19 | for i in xrange(len(s), -1, -1): 20 | for j in xrange(len(t), -1, -1): 21 | if i == len(s) or j == len(t): 22 | A[i][j] = '' 23 | elif s[i] == t[j]: 24 | A[i][j] = s[i] + A[i+1][j+1] 25 | else: 26 | left = A[i+1][j] 27 | right = A[i][j+1] 28 | if len(left) > len(right): 29 | A[i][j] = left 30 | else: 31 | A[i][j] = right 32 | return A[0][0] 33 | 34 | 35 | class LCSTestCase(object): 36 | def test1(self): 37 | self.assertEqual(self.lcs('ABCDE', 'AFCGE'), 'ACE') 38 | 39 | def test_empty(self): 40 | self.assertEqual(self.lcs('', ''), '') 41 | 42 | 43 | class LCSRecursiveBasic(unittest.TestCase, LCSTestCase): 44 | def __init__(self, *args, **kwargs): 45 | super(LCSRecursiveBasic, self).__init__(*args, **kwargs) 46 | self.lcs = lcs_recursive_basic 47 | 48 | 49 | class LCSDP(unittest.TestCase, LCSTestCase): 50 | def __init__(self, *args, **kwargs): 51 | super(LCSDP, self).__init__(*args, **kwargs) 52 | self.lcs = lcs_dp 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /spoj/JOHNNY/src/stackoverflow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | ''' 4 | http://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number 5 | 6 | ''' 7 | 8 | import os 9 | import sys 10 | 11 | def stackoverflow(x_list, target): 12 | memo = dict() 13 | result, _ = g(x_list, x_list, target, memo) 14 | return (sum(result), result) 15 | 16 | def g(v, w, S, memo): 17 | subset = [] 18 | id_subset = [] 19 | for i, (x, y) in enumerate(zip(v, w)): 20 | # Check if there is still a solution if we include v[i] 21 | if f(v, i + 1, S - x, memo) > 0: 22 | subset.append(x) 23 | id_subset.append(y) 24 | S -= x 25 | return subset, id_subset 26 | 27 | def f(v, i, S, memo): 28 | if i >= len(v): 29 | return 1 if S == 0 else 0 30 | if (i, S) not in memo: # <-- Check if value has not been calculated. 31 | count = f(v, i + 1, S, memo) 32 | count += f(v, i + 1, S - v[i], memo) 33 | memo[(i, S)] = count # <-- Memoize calculated result. 34 | return memo[(i, S)] # <-- Return memoized value. 35 | 36 | def get_weights(): 37 | number_of_weights = int(sys.stdin.readline().strip()) 38 | weights = [] 39 | for i in xrange(number_of_weights): 40 | weights.append(int(sys.stdin.readline().strip())) 41 | return weights 42 | 43 | def main(): 44 | weights = get_weights() 45 | total_weight = sum(weights) 46 | best_weight = total_weight / 2 47 | subset = stackoverflow(weights, best_weight) 48 | for element in subset: 49 | sys.stdout.write("%s\n" % (weights.index(element), )) 50 | sys.stdout.flush() 51 | 52 | if __name__ == "__main__": 53 | main() 54 | -------------------------------------------------------------------------------- /epi/ch8/TowersOfHanoi.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | 4 | class StackWithName { 5 | private String name; 6 | private Deque data = new ArrayDeque<>(); 7 | StackWithName(String name) { this.name = name; } 8 | public String getName() { return this.name; } 9 | 10 | public void push(T value) { data.push(value); } 11 | public T pop() { return data.pop(); } 12 | public T peek() { return data.peek(); } 13 | } 14 | 15 | class TowersOfHanoi { 16 | public static void execute(int numberOfRings) { 17 | StackWithName fromPole = new StackWithName<>("fromPole"); 18 | StackWithName toPole = new StackWithName<>("toPole"); 19 | StackWithName withPole = new StackWithName<>("withPole"); 20 | for (int i = numberOfRings - 1; i >= 0; i--) 21 | fromPole.push(i); 22 | moveTower(numberOfRings, fromPole, toPole, withPole); 23 | } 24 | 25 | public static void moveTower(int height, StackWithName fromPole, 26 | StackWithName toPole, StackWithName withPole) { 27 | if (height == 0) return; 28 | moveTower(height - 1, fromPole, withPole, toPole); 29 | moveDisk(fromPole, toPole); 30 | moveTower(height - 1, withPole, toPole, fromPole); 31 | } 32 | 33 | public static void moveDisk(StackWithName fromPole, StackWithName toPole) { 34 | System.out.println(String.format("moving disk %s from %s to %s", 35 | fromPole.peek(), fromPole.getName(), toPole.getName())); 36 | toPole.push(fromPole.pop()); 37 | } 38 | 39 | public static void main(String[] args) { 40 | execute(3); 41 | } 42 | } -------------------------------------------------------------------------------- /clrs/07_quicksort/src/Quick.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.Random; 3 | 4 | public class Quick> { 5 | Random generator; 6 | 7 | Quick() { this(new Random()); } 8 | Quick(Random generator) { 9 | this.generator = generator; 10 | } 11 | 12 | static > void sort(List A) { 13 | new Quick().quicksort(A, 0, A.size() - 1); 14 | } 15 | 16 | static > void randomizedSort(List A) { 17 | new Quick().randomizedQuicksort(A, 0, A.size() - 1); 18 | } 19 | 20 | public int partition(List A, int p, int r) { 21 | T x = A.get(r); // pivot value 22 | int i = p - 1; // where we start comparisons to pivot. 23 | for (int j = p; j <= (r - 1); j++) { // from first element to before the pivot 24 | if (A.get(j).compareTo(x) < 0) { // is this smaller than the pivot? 25 | i += 1; 26 | exchange(A, i, j); 27 | } 28 | } 29 | // i+1 is the new pivot 30 | exchange(A, i+1, r); 31 | return (i+1); 32 | } 33 | 34 | public int randomizedPartition(List A, int p, int r) { 35 | int i = generator.nextInt(r-p+1) + p; 36 | exchange(A, r, i); 37 | return partition(A, p, r); 38 | } 39 | 40 | public void randomizedQuicksort(List A, int p, int r) { 41 | if (p < r) { 42 | int q = randomizedPartition(A, p, r); 43 | randomizedQuicksort(A, p, q - 1); 44 | randomizedQuicksort(A, q + 1, r); 45 | } 46 | } 47 | 48 | public void quicksort(List A, int p, int r) { 49 | if (p < r) { 50 | int q = partition(A, p, r); 51 | quicksort(A, p, q-1); 52 | quicksort(A, q+1, r); 53 | } 54 | } 55 | 56 | private void exchange(List A, int i, int j) { 57 | T temp = A.get(i); 58 | A.set(i, A.get(j)); 59 | A.set(j, temp); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /googlecodejam/store_credit/src/A-small-practice.in: -------------------------------------------------------------------------------- 1 | 10 2 | 100 3 | 3 4 | 5 75 25 5 | 200 6 | 7 7 | 150 24 79 50 88 345 3 8 | 8 9 | 8 10 | 2 1 9 4 4 56 90 3 11 | 542 12 | 100 13 | 230 863 916 585 981 404 316 785 88 12 70 435 384 778 887 755 740 337 86 92 325 422 815 650 920 125 277 336 221 847 168 23 677 61 400 136 874 363 394 199 863 997 794 587 124 321 212 957 764 173 314 422 927 783 930 282 306 506 44 926 691 568 68 730 933 737 531 180 414 751 28 546 60 371 493 370 527 387 43 541 13 457 328 227 652 365 430 803 59 858 538 427 583 368 375 173 809 896 370 789 14 | 789 15 | 65 16 | 591 955 829 805 312 83 764 841 12 744 104 773 627 306 731 539 349 811 662 341 465 300 491 423 569 405 508 802 500 747 689 506 129 325 918 606 918 370 623 905 321 670 879 607 140 543 997 530 356 446 444 184 787 199 614 685 778 929 819 612 737 344 471 645 726 17 | 101 18 | 5 19 | 722 600 905 54 47 20 | 35 21 | 51 22 | 210 582 622 337 626 580 994 299 386 274 591 921 733 851 770 300 380 225 223 861 851 525 206 714 985 82 641 270 5 777 899 820 995 397 43 973 191 885 156 9 568 256 659 673 85 26 631 293 151 143 423 23 | 890 24 | 62 25 | 286 461 830 216 539 44 989 749 340 51 505 178 50 305 341 292 415 40 239 950 404 965 29 972 536 922 700 501 730 430 630 293 557 542 598 795 28 344 128 461 368 683 903 744 430 648 290 135 437 336 152 698 570 3 827 901 796 682 391 693 161 145 26 | 163 27 | 90 28 | 22 391 140 874 75 339 439 638 158 519 570 484 607 538 459 758 608 784 26 792 389 418 682 206 232 432 537 492 232 219 3 517 460 271 946 418 741 31 874 840 700 58 686 952 293 848 55 82 623 850 619 380 359 479 48 863 813 797 463 683 22 285 522 60 472 948 234 971 517 494 218 857 261 115 238 290 158 326 795 978 364 116 730 581 174 405 575 315 101 99 29 | 295 30 | 17 31 | 678 227 764 37 956 982 118 212 177 597 519 968 866 121 771 343 561 32 | -------------------------------------------------------------------------------- /interview/MergeSortTest.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | import java.util.Arrays; 4 | 5 | class Merge { 6 | public static > void sort(List array) { 7 | List buffer = new ArrayList(array.size()); 8 | for (int i = 0; i < array.size(); i++) 9 | buffer.add(null); 10 | sortHelper(array, 0, array.size() - 1, buffer); 11 | } 12 | 13 | private static > void sortHelper( 14 | List array, int lo, int hi, List buffer) { 15 | if (lo < hi) { 16 | int mid = lo + (hi - lo) / 2; 17 | sortHelper(array, lo, mid, buffer); 18 | sortHelper(array, mid + 1, hi, buffer); 19 | merge(array, lo, mid, hi, buffer); 20 | } 21 | } 22 | 23 | private static > void merge( 24 | List array, int lo, int mid, int hi, List buffer) { 25 | int i = lo, j = mid + 1; 26 | for (int k = lo; k <= hi; k++) { 27 | if (i > mid) 28 | buffer.set(k, array.get(j++)); 29 | else if (j > hi) 30 | buffer.set(k, array.get(i++)); 31 | else if (array.get(i).compareTo(array.get(j)) == -1) 32 | buffer.set(k, array.get(i++)); 33 | else 34 | buffer.set(k, array.get(j++)); 35 | } 36 | for (int k = lo; k <= hi; k++) { 37 | array.set(k, buffer.get(k)); 38 | } 39 | } 40 | } 41 | 42 | class MergeSortTest { 43 | public static void main(String args[]) { 44 | List array = Arrays.asList(1, 7, 8, 1, 3, 1, 1, 4); 45 | Merge.sort(array); 46 | System.out.println(array); 47 | } 48 | } -------------------------------------------------------------------------------- /cracking/ch05_bit_manipulation/src/ai/cracking/bitmanipulation/ProblemTest.java: -------------------------------------------------------------------------------- 1 | package ai.cracking.bitmanipulation; 2 | 3 | import static org.junit.Assert.*; 4 | import org.junit.Test; 5 | 6 | public class ProblemTest { 7 | 8 | // ------------------------------------------------------------------ 9 | // Problem 1. 10 | // ------------------------------------------------------------------ 11 | @Test 12 | public void testApplySubstring1() { 13 | long N = Long.parseLong("10000000000", 2); 14 | long M = Long.parseLong("10101", 2); 15 | int i = 2; 16 | int j = 6; 17 | int expectedOutput = Integer.parseInt("10001010100", 2); 18 | assertEquals(expectedOutput, Problem1.applySubstring(N, M, i, j)); 19 | } 20 | 21 | @Test 22 | public void testApplySubstring2() { 23 | long N = Long.parseLong("11111111111111111111111111111111", 2); 24 | long M = Long.parseLong("0", 2); 25 | int i = 0; 26 | int j = 31; 27 | int expectedOutput = Integer.parseInt("0", 2); 28 | assertEquals(expectedOutput, Problem1.applySubstring(N, M, i, j)); 29 | } 30 | // ------------------------------------------------------------------ 31 | 32 | // ------------------------------------------------------------------ 33 | // Problem 2. 34 | // ------------------------------------------------------------------ 35 | @Test 36 | public void testPrintBinaryString1() { 37 | double input = 3.25; 38 | String expectedOutput = "11.01"; 39 | assertEquals(expectedOutput, Problem2.printBinaryString(input)); 40 | } 41 | 42 | @Test 43 | public void testPrintBinaryString2() { 44 | double input = 1.1; 45 | String expectedOutput = "ERROR"; 46 | assertEquals(expectedOutput, Problem2.printBinaryString(input)); 47 | } 48 | 49 | // ------------------------------------------------------------------ 50 | 51 | } 52 | -------------------------------------------------------------------------------- /cracking/ch09/Circus.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Comparator; 4 | import java.util.List; 5 | 6 | class Person { 7 | int height; 8 | int weight; 9 | Person(int height, int weight) { 10 | this.height = height; 11 | this.weight = weight; 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return String.format("{height: %s, weight: %s}", height, weight); 17 | } 18 | } 19 | 20 | class CircusComparator implements Comparator { 21 | public int compare(Person o1, Person o2) { 22 | if (o1.height < o2.height && o1.weight < o2.weight) 23 | return -1; 24 | else if (o1.height > o2.height && o1.weight > o2.weight) 25 | return 1; 26 | else 27 | return 0; 28 | } 29 | } 30 | 31 | class Circus { 32 | public static void main(String args[]) { 33 | Person p1 = new Person(65, 100); 34 | Person p2 = new Person(70, 150); 35 | Person p3 = new Person(56, 90); 36 | Person p4 = new Person(75, 190); 37 | Person p5 = new Person(60, 95); 38 | Person p6 = new Person(68, 110); 39 | List people = new ArrayList(); 40 | people.add(p1); people.add(p2); people.add(p3); people.add(p4); 41 | people.add(p5); people.add(p6); 42 | CircusComparator comparator = new CircusComparator(); 43 | Collections.sort(people, comparator); 44 | 45 | int numberOfPeople = 1; 46 | for (int i = 1; i < people.size(); i++) { 47 | if (comparator.compare(people.get(i), people.get(i-1)) <= 0) break; 48 | numberOfPeople++; 49 | } 50 | 51 | System.out.println(people); 52 | System.out.println(numberOfPeople); 53 | } 54 | } -------------------------------------------------------------------------------- /hackerrank/codesprint5/IsFibo.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Scanner; 3 | 4 | class IsFibo { 5 | private static final BigInteger FOUR = new BigInteger("4"); 6 | private static final BigInteger FIVE = new BigInteger("5"); 7 | 8 | public static BigInteger bigIntSqRootFloor(BigInteger x) { 9 | // square roots of 0 and 1 are trivial and 10 | // y == 0 will cause a divide-by-zero exception 11 | if (x == BigInteger.ZERO || x == BigInteger.ONE) { 12 | return x; 13 | } // end if 14 | BigInteger two = BigInteger.valueOf(2L); 15 | BigInteger y; 16 | // starting with y = x / 2 avoids magnitude issues with x squared 17 | for (y = x.divide(two); 18 | y.compareTo(x.divide(y)) > 0; 19 | y = ((x.divide(y)).add(y)).divide(two)); 20 | return y; 21 | } // end bigIntSqRootFloor 22 | 23 | public static boolean isPerfectSquare(BigInteger input) { 24 | BigInteger sqrt = bigIntSqRootFloor(input); 25 | return sqrt.multiply(sqrt).equals(input); 26 | } 27 | 28 | public static boolean isFibonacciNumber(BigInteger input) { 29 | BigInteger portion = input.pow(2).multiply(FIVE); 30 | return (isPerfectSquare(portion.add(FOUR)) || 31 | isPerfectSquare(portion.subtract(FOUR))); 32 | } 33 | 34 | public static void main(String[] args) { 35 | Scanner input = new Scanner(System.in); 36 | input.nextInt(); 37 | while (input.hasNextBigInteger()) { 38 | BigInteger candidate = input.nextBigInteger(); 39 | if (isFibonacciNumber(candidate)) 40 | System.out.println("IsFibo"); 41 | else 42 | System.out.println("IsNotFibo"); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /interview/tree_bfs.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | 4 | @functools.total_ordering 5 | class Node(object): 6 | def __init__(self, value): 7 | self.value = value 8 | self.left = None 9 | self.right = None 10 | 11 | def __lt__(self, other): 12 | return self.value < other.value 13 | 14 | def __eq__(self, other): 15 | if not type(self) is type(other): 16 | return False 17 | return self.value == other.value 18 | 19 | def __str__(self): 20 | return self.value 21 | 22 | def __repr__(self): 23 | return str(self) 24 | 25 | 26 | class Sentinel(object): 27 | def __eq__(self, other): 28 | return type(self) is type(other) 29 | 30 | 31 | def print_levels(root): 32 | sentinel = Sentinel() 33 | queue = [root, sentinel] 34 | level = [] 35 | while True: 36 | current = queue.pop(0) # pops left-most 37 | if current == sentinel: 38 | print ' '.join(str(node) for node in level) 39 | level = [] 40 | if len(queue) == 0: 41 | break 42 | queue.append(sentinel) 43 | continue 44 | level.append(current) 45 | if current.left is not None: 46 | queue.append(current.left) 47 | if current.right is not None: 48 | queue.append(current.right) 49 | 50 | 51 | a = Node('a') 52 | b = Node('b') 53 | c = Node('c') 54 | d = Node('d') 55 | e = Node('e') 56 | a.left = b 57 | a.right = c 58 | c.left = d 59 | c.right = e 60 | 61 | print_levels(a) 62 | 63 | 64 | 65 | def find_number_greater_than(root, value): 66 | if root.value > value: 67 | return root.value 68 | if root.right is None: 69 | return None 70 | return find_number_greater_than(root.right, value) 71 | -------------------------------------------------------------------------------- /interview/Anagrams.java: -------------------------------------------------------------------------------- 1 | /** 2 | * find the sets of words that share the same characters that contain the most 3 | * words in them. 4 | */ 5 | 6 | import java.util.*; 7 | import java.io.*; 8 | import java.nio.file.*; 9 | import java.nio.charset.StandardCharsets; 10 | 11 | class CollectionSizeComparator implements Comparator> { 12 | @Override 13 | public int compare(Collection c1, Collection c2) { 14 | if (c1.size() < c2.size()) return 1; 15 | else if (c1.size() == c2.size()) return 0; 16 | else return -1; 17 | } 18 | } 19 | 20 | class Anagrams { 21 | public static void main(String[] args) throws IOException { 22 | Map> anagrams = new HashMap<>(); 23 | Path path = FileSystems.getDefault().getPath("/usr/share/dict/words"); 24 | try ( 25 | BufferedReader br = Files.newBufferedReader(path, 26 | StandardCharsets.UTF_8); 27 | ) { 28 | String line = null; 29 | while ((line = br.readLine()) != null) { 30 | line = line.toLowerCase(); 31 | char[] temp = line.toCharArray(); 32 | Arrays.sort(temp); 33 | String sorted = new String(temp); 34 | if (!(anagrams.containsKey(sorted))) 35 | anagrams.put(sorted, new LinkedHashSet()); 36 | anagrams.get(sorted).add(line); 37 | } 38 | } 39 | List> sortedAnagrams = 40 | new ArrayList<>(anagrams.values()); 41 | Collections.sort(sortedAnagrams, 42 | new CollectionSizeComparator()); 43 | for (int i = 0; i < 10; i++) 44 | System.out.println(sortedAnagrams.get(i)); 45 | } 46 | } -------------------------------------------------------------------------------- /projecteuler/src/problem7/src/main/scala/Problem7.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem7.main 2 | 3 | import scala.annotation.tailrec 4 | import scala.math 5 | import scala.collection.mutable.ListBuffer 6 | 7 | object Problem7 { 8 | def primeNumbers: Iterator[Int] = { 9 | class Counter(start: Int, step: Int) extends Iterator[Int] { 10 | var count = start - step 11 | val hasNext = true 12 | def next = { count += step; count } 13 | } 14 | 15 | class PrimeNumberIterator extends Iterator[Int] { 16 | def not_divisible(i: Int, xs: ListBuffer[Int]): Boolean = xs.forall(i % _ != 0) 17 | var primes = ListBuffer(2) 18 | val hasNext = true 19 | def next = { 20 | var count = new Counter(start = primes.last + 1, step = 1) 21 | count.find(not_divisible(_, primes)) match { 22 | case Some(i) => { primes += i; i } 23 | case _ => -1 24 | } 25 | } 26 | } 27 | new PrimeNumberIterator 28 | } 29 | 30 | def getElementAtIndex(iterable: Iterator[Int], index: Int): Int = { 31 | @tailrec 32 | def _getElementAtIndex(iterable: Iterator[Int], index: Int, acc: Int): Int = { 33 | if (acc == (index - 1)) iterable.next() 34 | else { iterable.next(); _getElementAtIndex(iterable, index, acc + 1) } 35 | } 36 | _getElementAtIndex(iterable, index, 0) 37 | } 38 | 39 | def getAnswer(index: Int): Int = { 40 | getElementAtIndex(primeNumbers, index - 1) 41 | } 42 | 43 | def main(args: Array[String]) { 44 | val answer = getAnswer(10001) 45 | println("Problem 7 answer: %s".format(answer)) 46 | } 47 | } // object Problem7 48 | 49 | // vim: set ts=4 sw=4 et: 50 | -------------------------------------------------------------------------------- /interview/skiplist.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | class SkipListNode(object): 5 | def __init__(self, value=None, height=32): 6 | self.value = value 7 | self.next = [None for i in xrange(height+1)] 8 | 9 | @property 10 | def height(self): 11 | return len(self.next) - 1 12 | 13 | 14 | class SkipListSortedSet(object): 15 | sentinel = SkipListNode() 16 | 17 | def __init__(self): 18 | self.height = 0 19 | 20 | def find(self, value): 21 | u = self._find_predecessor_node(value) 22 | if u.next[0] is None: 23 | return None 24 | return u.next[0].value 25 | 26 | def add(self, value): 27 | u = self.sentinel 28 | r = self.height 29 | array = [None for i in xrange(self.height+1)] 30 | while r >= 0: 31 | while u.next[r] is not None and value > u.next[r].value: 32 | u = u.next[r] 33 | if u.next[r] is not None and value == u.next[r].value: 34 | return False 35 | array[r] = u 36 | r -= 1 37 | w = SkipListNode(value, self._pick_height()) 38 | while self.height < w.height: 39 | array[self.height] = self.sentinel 40 | self.height += 1 41 | for i in xrange(len(w.next)): 42 | w.next[i] = array[i].next[i] 43 | array[i].next[i] = w 44 | return True 45 | 46 | def _find_predecessor_node(self, value): 47 | u = self.sentinel 48 | r = self.height 49 | while r >= 0: 50 | while u.next[r] is not None and value > u.next[r].value: 51 | u = u.next[r] 52 | r -= 1 53 | return u 54 | 55 | def _pick_height(self): 56 | height = 0 57 | while random.random() <= 0.5: 58 | height += 1 59 | return height 60 | -------------------------------------------------------------------------------- /projecteuler/src/problem4/src/main/scala/Problem4.scala: -------------------------------------------------------------------------------- 1 | package com.euler.problem4.main 2 | 3 | import scala.annotation.tailrec 4 | import scala.math 5 | 6 | object Problem4 { 7 | def isPalindrome(x: Int): Boolean = { 8 | val string = x.toString 9 | string.reverseIterator.sameElements(string.iterator) 10 | } 11 | 12 | /* 13 | def getPairs(minimum: Int, maximum: Int) = { 14 | def _pairs1(i: Int, j: Int, maximum: Int): Stream[(Int, Int)] = { 15 | if (i == maximum && j == maximum) Stream.empty 16 | else if (j == maximum) (i, j) #:: _pairs1(i + 1, 0, maximum) 17 | else (i, j) #:: _pairs1(i, j + 1, maximum) 18 | } 19 | 20 | def _pairs2(minimum: Int, maximum: Int) = { 21 | for (i <- minimum to maximum view; 22 | j <- minimum to maximum view) 23 | yield (i, j) 24 | } 25 | _pairs2(minimum, maximum) 26 | } 27 | */ 28 | 29 | def getPairs(minimum: Int, maximum: Int) = { 30 | for (i <- minimum to maximum view; 31 | j <- minimum to maximum view) 32 | yield (i, j) 33 | } 34 | 35 | def getAnswer(numberOfDigits: Int): Int = { 36 | val maximum = math.pow(10, numberOfDigits).toInt 37 | val minimum = math.pow(10, numberOfDigits - 1).toInt 38 | val products = for { 39 | pair <- getPairs(minimum, maximum) 40 | product = pair match { case (i, j) => i * j } 41 | if isPalindrome(product) 42 | } yield product 43 | products.par.max 44 | } 45 | 46 | def main(args: Array[String]) { 47 | val answer = getAnswer(4) 48 | println("Problem 4 answer: %s".format(answer)) 49 | } 50 | } // object Problem4 51 | 52 | // vim: set ts=4 sw=4 et: 53 | -------------------------------------------------------------------------------- /rosalind/iprb/iprb.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import random 3 | from decimal import Decimal 4 | import numpy as np 5 | 6 | def simulate(k, m, n, iterations): 7 | pool = [] 8 | pool.extend(["k"] * k) 9 | pool.extend(["m"] * m) 10 | pool.extend(["n"] * n) 11 | 12 | probability_lookup = { 13 | ("k", "k"): 1, 14 | ("k", "m"): 1, 15 | ("k", "n"): 1, 16 | ("m", "k"): 1, 17 | ("m", "m"): 0.75, 18 | ("m", "n"): 0.5, 19 | ("n", "k"): 1, 20 | ("n", "m"): 0.5, 21 | ("n", "n"): 0, 22 | } 23 | 24 | number_of_dominants = 0 25 | for i in xrange(iterations): 26 | (a, b) = random.sample(pool, 2) 27 | probability = probability_lookup[(a, b)] 28 | if probability == 1: 29 | number_of_dominants += 1 30 | elif probability == 0: 31 | pass 32 | elif random.random() <= probability: 33 | number_of_dominants += 1 34 | else: 35 | pass 36 | return Decimal(number_of_dominants) / Decimal(iterations) 37 | 38 | def calculate(k, m, n): 39 | counts = np.matrix([[float(k), float(m), float(n)]]) 40 | probs = counts / sum([k, m, n]) 41 | strings = [str(elem) for elem in [k, m, n]] 42 | subcounts_string = "; ".join([" ".join(strings)] * 3) 43 | subcounts = np.matrix(subcounts_string) - np.eye(3) 44 | subprobs = subcounts / (sum([k, m, n]) - 1) 45 | 46 | dominant = np.matrix([[1.0, 1.0, 1.0], 47 | [1.0, 0.75, 0.5], 48 | [1.0, 0.5, 0.0]]) 49 | result1 = (subprobs * dominant).sum(axis=1) 50 | result2 = result1 * probs 51 | import ipdb; ipdb.set_trace() 52 | 53 | if __name__ == "__main__": 54 | # = 0.65067369 55 | print simulate(k=16, m=25, n=29, 56 | iterations=100000000) 57 | #calculate(2, 2, 2) 58 | 59 | 60 | -------------------------------------------------------------------------------- /interview/glassdoor/SortedArrayFindMinimumInserts.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Given a sorted array find the minimum amount of values that are 3 | * needed to be inserted to make a sequence of a given length. ie 4 | * [0, 2, 5, 7, 11] for length 5 5 | */ 6 | 7 | class SortedArrayFindMinimumInserts { 8 | public static int binarySearch(int[] array, int key) { 9 | int lo = 0, hi = array.length - 1, mid; 10 | while (lo <= hi) { 11 | mid = lo + (hi - lo) / 2; 12 | if (array[mid] < key) 13 | lo = mid + 1; 14 | else if (array[mid] > key) 15 | hi = mid - 1; 16 | else 17 | return mid; 18 | } 19 | return lo; 20 | } 21 | 22 | public static int findMinimumInserts(int[] array, int length) { 23 | int minimumInserts = Integer.MAX_VALUE; 24 | String minimumRange = null; 25 | 26 | int minimum = array[0]; 27 | int maximum = array[array.length - 1]; 28 | for (int start = minimum - length + 1, end = start + length; 29 | start <= maximum; start++, end++) { 30 | int startIndex = binarySearch(array, start); 31 | int endIndex = binarySearch(array, end); 32 | int newInserts = length - (endIndex - startIndex); 33 | if (newInserts < minimumInserts) { 34 | minimumInserts = newInserts; 35 | minimumRange = String.format("[%s, %s]", start, end); 36 | } 37 | } 38 | System.out.println(String.format("Minimum inserts: %s, for range: %s", 39 | minimumInserts, minimumRange)); 40 | return minimumInserts; 41 | } 42 | 43 | public static void main(String[] args) { 44 | int[] array = {0, 2, 5, 7, 11}; 45 | System.out.println(findMinimumInserts(array, 5)); 46 | } 47 | } 48 | --------------------------------------------------------------------------------