├── .DS_Store
├── README.md
├── aa_data_structures_workshop
├── .DS_Store
├── level_values.js
├── march_2019
│ ├── .DS_Store
│ ├── dynamic_programming
│ │ └── lecture_notes.js
│ └── trees
│ │ ├── .DS_Store
│ │ ├── 1_lecture_notes.js
│ │ ├── 2_lecture_notes
│ │ ├── max_path_sum.js
│ │ ├── tree_sum.js
│ │ └── trees_2.js
│ │ ├── balanced_bst_notes_reading.md
│ │ ├── binary_search_tree_notes_reading.md
│ │ ├── binary_trees_notes_reading.md
│ │ ├── depth_and_breadth_first_notes_reading.md
│ │ ├── images
│ │ ├── balanced_unbalanced.png
│ │ ├── bsts.png
│ │ ├── good_bad_bst.png
│ │ ├── graph_a.png
│ │ ├── graphs.png
│ │ ├── height.png
│ │ ├── log_heights.png
│ │ └── not_bst.png
│ │ └── inorder_preorder_postorder_reading.md
├── max_path_sum.js
├── tree_sum.js
├── trees_1.js
└── trees_2.js
├── alvin.txt
├── anne.txt
├── c++
├── .DS_Store
├── atoi.cpp
├── binarySearchTree
│ ├── binaryTree.cpp
│ ├── binaryTree.h
│ └── main.cpp
├── bubbleSort.cpp
├── eightQueens.cpp
├── magicIndex.cpp
├── mergeSort.cpp
├── permute.cpp
├── pong
│ ├── main.cpp
│ ├── paddle.cpp
│ ├── paddle.h
│ ├── pong
│ ├── pos.cpp
│ └── pos.h
├── quickSort.cpp
├── rotateGrid.cpp
├── setOfStacks.cpp
├── sortStack.cpp
├── stringCompress.cpp
└── tripleStack
│ ├── .DS_Store
│ ├── main.cpp
│ ├── tripleStack.cpp
│ └── tripleStack.h
├── christine.txt
├── codeJam
├── allYourBase.py
├── coinJam
│ ├── C-large.in
│ ├── C-small-attempt0.in
│ ├── jamCoin.py
│ ├── largeOutput.txt
│ └── smallOutput.txt
├── countingSheep
│ ├── A-large.in
│ ├── A-small-attempt0.in
│ ├── countingSheep.py
│ ├── largeOutput.txt
│ └── smallOutput.txt
├── fileFix
│ └── fileFix.py
├── fractiles
│ ├── D-small-attempt0.in
│ ├── fractiles.py
│ ├── smallOutput.txt
│ ├── test.in
│ └── testOutput.txt
├── pancakeRevenge
│ ├── B-large.in
│ ├── B-small-attempt0.in
│ ├── largeOutput.txt
│ ├── pancakeRevenge.py
│ └── smallOutput.txt
└── reverseWords
│ ├── B-large-practice.in
│ ├── B-small-practice.in
│ ├── largeOutput.txt
│ ├── reverseWords.py
│ └── smallOutput.txt
├── dan.txt
├── foobar
├── binaryBunnies.py
├── boredGame.py
├── breedingLikeRabbits.py
├── directoryListing.py
├── equilibriumIndex.py
├── minglishLesson.py
├── minionsBoredGame.py
├── rustyCalculator.py
├── saveRabbit.py
├── stringCleaning.py
└── whenItRainsItPours.py
├── jj.txt
├── mike.txt
├── python
├── .DS_Store
├── addBinary.py
├── anagram.py
├── arrayLessThan.py
├── arrayPairs.py
├── bestLine.py
├── bst.py
├── buildOrder.py
├── buildTreeFromOrder.py
├── buyTwo.py
├── checkIntersect.py
├── coinChange.py
├── countPaths.py
├── debruijn.py
├── deepestNode.py
├── depthList.py
├── distinctSubstring.py
├── evenOddDiff.py
├── fib.py
├── findCycle.py
├── flipTree.py
├── getPermutations.py
├── graphSearch.py
├── groupAnagrams.py
├── inOrderSucessor.py
├── intersection.py
├── islands.py
├── iterator.py
├── klast.py
├── largestLexicoSubstr.py
├── listSort.py
├── loop.py
├── maxSubarray.py
├── mergeLists.py
├── mergeStep.py
├── minimalTree.py
├── nextMax.py
├── numberSlice.py
├── operations.py
├── orderedLinkedList.py
├── palindrome.py
├── palindromeStr.py
├── partition.py
├── pathSum.py
├── patternMatch.py
├── permutation.py
├── pow2.py
├── pow5.py
├── powerSet.py
├── prime.py
├── primeFactor.py
├── primeSum.py
├── productSeries.py
├── pythagoreanTriplet.py
├── reverseLinkedList.py
├── reverseStr.py
├── reverseVowels.py
├── reverseWords.py
├── runningMedian.py
├── setOfStacks.py
├── shuffleArray.py
├── singleEdit.py
├── sortMatrix.py
├── sortStack.py
├── sortStr.py
├── splitWords.py
├── strCompress.py
├── stripSpace.py
├── subSort.py
├── subsets.py
├── sumOfSquares.py
├── sumSubmatrix.py
├── topologicalSort.py
├── treeSize.py
├── treeToList.py
├── tripleStep.py
├── unpairedInArray.py
└── zeroMatrix.py
└── yansi.txt
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/.DS_Store
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Practice Problems Repository
2 | Solutions to some common algorithms/data-structures practice problems.
3 | Problem difficulty ranges from trivial to "pray no one ever asks this during an interview".
4 | Problems come from Cracking the Coding Interview, GeeksforGeeks, ProjectEuler, Google foobar challenge, etc.
5 |
6 | 
--------------------------------------------------------------------------------
/aa_data_structures_workshop/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/.DS_Store
--------------------------------------------------------------------------------
/aa_data_structures_workshop/level_values.js:
--------------------------------------------------------------------------------
1 | const { BST } = require("./trees_1");
2 |
3 | // Write a function that accepts the root of a tree as an arg.
4 | // The function should return a 2D array representing the values at each level of the tree.
5 |
6 | function level_values(root) {
7 | let queue = [{ node: root, level: 0 }];
8 |
9 | let levels = [];
10 |
11 | while (queue.length > 0) {
12 | let { node, level } = queue.shift();
13 |
14 | if (levels[level] === undefined) {
15 | levels[level] = [ node.val ];
16 | } else {
17 | levels[level].push(node.val);
18 | }
19 |
20 | if (node.left) queue.push({ node: node.left, level: level+1 });
21 | if (node.right) queue.push({ node: node.right, level: level+1 });
22 | }
23 |
24 | return levels;
25 | }
26 |
27 | const tree = new BST();
28 |
29 | tree.insert(10);
30 | tree.insert(5);
31 | tree.insert(15);
32 | tree.insert(3);
33 | tree.insert(7);
34 | tree.insert(17);
35 | tree.insert(16);
36 |
37 | console.log(level_values(tree.root));
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/.DS_Store
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/dynamic_programming/lecture_notes.js:
--------------------------------------------------------------------------------
1 | // // Dynamic Programming is useful WHEN
2 | // // we have a large problem that can be decomposed into smaller
3 | // // subproblems of the same structure
4 | // //
5 | // // SOLVE THE BRUTE FORCE FIRST
6 |
7 | // // Write a function, lucasNumber(n), that takes in a number.
8 | // // The function should return the n-th number of the Lucas Sequence.
9 | // // The 0-th number of the Lucas Sequence is 2.
10 | // // The 1-st number of the Lucas Sequence is 1
11 | // // To generate the next number of the sequence, we add up the previous two numbers.
12 | // //
13 | // // For example, the sequence begins: 2, 1, 3, 4, 7, 11, ...
14 | // //
15 | // // Examples:
16 | // //
17 | // // lucasNumber(0) // => 2
18 | // // lucasNumber(1) // => 1
19 | // // lucasNumber(40) // => 228826127
20 | // // lucasNumber(41) // => 370248451
21 | // // lucasNumber(42) // => 599074578
22 | // //
23 |
24 | // // lucasNumber(5) => 11
25 |
26 | // // Memoization - RECURSIVE DYNAMIC PROGRAMMING
27 | // // 1. add an obj as arg into your func
28 | // // the obj should have the orig func arg as keys and values should be returns
29 | // // 2. add a base case that checks if orig arg is in the memo
30 | // // 3. wherever we return in the recursive case, store that in the memo first
31 |
32 | // // function lucasNumber(n, memo={0: 2, 1 : 1}) {
33 | // // if (n in memo) return memo[n];
34 |
35 | // // memo[n] = lucasNumber(n - 1, memo) + lucasNumber(n - 2, memo);
36 |
37 | // // return memo[n];
38 | // // }
39 |
40 | // // Tabulation - ITERATIVE DP
41 |
42 | // function lucasNumber(n) {
43 | // let table = new Array(n + 1);
44 |
45 | // table[0] = 2;
46 | // table[1] = 1;
47 |
48 | // for (var i = 2; i < table.length; i++) {
49 | // table[i] = table[i - 1] + table[i - 2];
50 | // }
51 |
52 | // return table[n];
53 | // }
54 |
55 | // // function lucasNumber(n, memo = {}) {
56 | // // if (n === 0) return 2;
57 | // // if (n === 1) return 1;
58 |
59 | // // if ((n - 1) in memo) {
60 | // // let lastLucas = memo[(n - 1)];
61 | // // } else {
62 | // // // recurse
63 | // // }
64 |
65 | // // if ((n - 2) in memo) {
66 |
67 | // // }
68 | // // memo[n] = lucasNumber(n - 1, memo) + lucasNumber(n - 2, memo);
69 |
70 | // // return memo[n];
71 | // // }
72 |
73 | // console.log(lucasNumber(5));
74 | // console.log(lucasNumber(0)); // => 2
75 | // console.log(lucasNumber(1)); // => 1
76 | // console.log(lucasNumber(40)); // => 228826127
77 | // console.log(lucasNumber(41)); // => 370248451
78 | // console.log(lucasNumber(42)); // => 599074578
79 | // console.log(lucasNumber(100)); // => 599074578
80 |
81 | // In ruby, arrays and hashes are pass by ref
82 | // In JS, arrays and objs are pass by ref
83 |
84 | // Write a function, minChange(coins, amount), that accepts an array of coin values
85 | // and a target amount as arguments. The method should the minimum number of coins needed
86 | // to make the target amount. A coin value can be used multiple times.
87 | //
88 | // After you pass the first 3 examples, you'll likely need to memoize your code
89 | // in order to pass the 4th example in a decent runtime.
90 | //
91 | // Examples:
92 | //
93 | // minChange([1, 2, 5], 11) // => 3, because 5 + 5 + 1 = 11
94 | // minChange([1, 4, 5], 8) // => 2, because 4 + 4 = 8
95 | // minChange([1, 5, 10, 25], 15) // => 2, because 10 + 5 = 15
96 | // minChange([1, 5, 10, 25], 100) // => 4, because 25 + 25 + 25 + 25 = 100
97 |
98 | // function minChange(coins, amount, memo={}) {
99 | // if (amount in memo) return memo[amount];
100 | // if (amount === 0) return 0;
101 |
102 | // let possibilities = [];
103 | // coins.forEach(coinVal => {
104 | // let remainder = amount - coinVal;
105 | // if (remainder >= 0) {
106 | // possibilities.push(minChange(coins, remainder, memo) + 1);
107 | // }
108 | // });
109 |
110 | // memo[amount] = Math.min(...possibilities);
111 | // return memo[amount];
112 | // }
113 |
114 | // console.log(minChange([1, 2, 5], 11)) // => 3, because 5 + 5 + 1 = 11
115 | // console.log(minChange([1, 4, 5], 8)) // => 2, because 4 + 4 = 8
116 | // console.log(minChange([1, 5, 10, 25], 15)) // => 2, because 10 + 5 = 15
117 | // console.log(minChange([1, 5, 10, 25], 100)) // => 4, because 25 + 25 + 25 + 25 = 100
118 |
119 | // let arr = [
120 | // [1,2],
121 | // [3,4,5]
122 | // ];
123 |
124 | // let cp = arr.map((row) =>row.slice());
125 | // console.log(cp)
126 |
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/.DS_Store
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/1_lecture_notes.js:
--------------------------------------------------------------------------------
1 | // March 5, 2019
2 | class Node {
3 | constructor(val) {
4 | this.val = val
5 | this.left = null;
6 | this.right = null;
7 | }
8 | }
9 |
10 | class BST {
11 | constructor() {
12 | this.root = null;
13 | }
14 |
15 | insert(val, root = this.root) {
16 | // if the tree is empty, then set the abs root to the val
17 | if (this.root === null) {
18 | this.root = new Node(val);
19 | return;
20 | }
21 |
22 | // if the val is less, go left
23 | // otherwise go right
24 | if (val < root.val) {
25 | if (root.left === null) {
26 | // if the left tree is empty, then add it here
27 | root.left = new Node(val);
28 | } else {
29 | // otherwise its nonempty, so travel to the left subtree and insert there
30 | this.insert(val, root.left);
31 | }
32 | } else {
33 | if (root.right === null) {
34 | root.right = new Node(val);
35 | } else {
36 | this.insert(val, root.right);
37 | }
38 | }
39 | }
40 |
41 | inOrderPrint(root = this.root) {
42 | if (root === null) return;
43 |
44 | this.inOrderPrint(root.left);
45 | console.log(root.val);
46 | this.inOrderPrint(root.right);
47 | }
48 |
49 | height(root = this.root) {
50 | if (root === null) return -1;
51 | let leftH = this.height(root.left);
52 | let rightH = this.height(root.right);
53 | return Math.max(leftH, rightH) + 1;
54 | }
55 | }
56 |
57 | const tree = new BST();
58 | tree.insert(10);
59 | tree.insert(5);
60 | tree.insert(15);
61 | tree.insert(3);
62 | tree.insert(7);
63 | tree.insert(13);
64 | tree.insert(17);
65 | tree.insert(11);
66 |
67 | console.log(tree.height());
68 |
69 |
70 |
71 | // tree.insert(10);
72 | // tree.insert(5);
73 | // tree.insert(15);
74 | // tree.insert(3);
75 | // tree.insert(7);
76 | // tree.insert(17);
77 | // tree.insert(17);
78 | // tree.insert(5);
79 |
80 | // tree.inOrderPrint();
81 | // console.log(tree.root);
82 |
83 | // Balanced Tree
84 | // - given the root of a tree
85 | // - the left subtree and right subtree MUST
86 | // differ in height by at most 1
87 | // - AND the left subtree is balanced
88 | // - AND the right subtree is balanced
89 |
90 | // BST
91 | // - given the root of a tree
92 | // - all vals in the left subtree are <
93 | // - all vals in the right subtree are >=
94 | // - AND the left subtree is a BST
95 | // - AND the right subtree is a BST
96 | // - an empty tree is a BST
97 |
98 |
99 |
100 | // Empty tree has height of -1
101 | // tree with only one node, has height of 0
102 | //
103 |
104 | // Why are balanced trees good?
105 | // - the height of a balanced tree is small
106 | // - binary search in the worst case will travel the
107 | // full height of the tree
108 | // - binary search will take O(h), where h = height
109 | // - a balanced tree has height of log(n), where n = # nodes
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/2_lecture_notes/max_path_sum.js:
--------------------------------------------------------------------------------
1 | const { BST } = require("./trees_2");
2 |
3 | // Write a function that accepts the root of a tree as an arg.
4 | // The function should return the maximum sum of a path through the tree.
5 | // For this problem, a path must begin at the root and end at a leaf.
6 |
7 | function maxPathSum(root) {
8 | if (root === null) return -Infinity;
9 | let leftSum = maxPathSum(root.left);
10 | let rightSum = maxPathSum(root.right);
11 | let best = Math.max(leftSum, rightSum)
12 | if (best === -Infinity) {
13 | return root.val;
14 | } else {
15 | return root.val + best;
16 | }
17 | }
18 |
19 | const tree = new BST();
20 |
21 | // tree.insert(-10);
22 | // tree.insert(-5);
23 | // tree.insert(-15);
24 | // tree.insert(-3);
25 | // tree.insert(-7);
26 | // tree.insert(-17);
27 | // tree.insert(-16);
28 |
29 | // tree.insert(-4);
30 | // tree.insert(-5);
31 | // tree.insert(-6);
32 |
33 | console.log(maxPathSum(tree.root));
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/2_lecture_notes/tree_sum.js:
--------------------------------------------------------------------------------
1 | const { BST } = require("./trees_2");
2 |
3 | // Write a function that accepts the root of a tree as an arg.
4 | // The function should return the total sum of all node values in the tree.
5 |
6 | function treeSum(root) {
7 | if (root === null) return 0;
8 | let leftSum = treeSum(root.left);
9 | let rightSum = treeSum(root.right);
10 | return leftSum + root.val + rightSum;
11 | }
12 |
13 | const tree = new BST();
14 |
15 | tree.insert(10);
16 | tree.insert(5);
17 | tree.insert(15);
18 | tree.insert(3);
19 | tree.insert(7);
20 | tree.insert(17);
21 | tree.insert(16);
22 |
23 | console.log(treeSum(tree.root)); // 73
24 |
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/2_lecture_notes/trees_2.js:
--------------------------------------------------------------------------------
1 | class Node {
2 | constructor(val) {
3 | this.val = val;
4 | this.left = null;
5 | this.right = null;
6 | }
7 | }
8 |
9 | class BST {
10 | constructor() {
11 | this.root = null;
12 | }
13 |
14 | insert(val, root = this.root) {
15 | // if the tree is empty, then set the abs root to the val
16 | if (this.root === null) {
17 | this.root = new Node(val);
18 | return;
19 | }
20 |
21 | // if the val is less, go left
22 | // otherwise go right
23 | if (val < root.val) {
24 | if (root.left === null) {
25 | // if the left tree is empty, then add it here
26 | root.left = new Node(val);
27 | } else {
28 | // otherwise its nonempty, so travel to the left subtree and insert there
29 | this.insert(val, root.left);
30 | }
31 | } else {
32 | if (root.right === null) {
33 | root.right = new Node(val);
34 | } else {
35 | this.insert(val, root.right);
36 | }
37 | }
38 | }
39 |
40 | inOrderPrint(root = this.root) {
41 | if (root === null) return;
42 |
43 | this.inOrderPrint(root.left);
44 | console.log(root.val);
45 | this.inOrderPrint(root.right);
46 | }
47 |
48 | height(root = this.root) {
49 | if (root === null) return -1;
50 | let leftH = this.height(root.left);
51 | let rightH = this.height(root.right);
52 | return Math.max(leftH, rightH) + 1;
53 | }
54 |
55 | search(target, root = this.root) {
56 | if (root === null) return null;
57 |
58 | if (target < root.val) {
59 | return this.search(target, root.left);
60 | } else if (target > root.val) {
61 | return this.search(target, root.right);
62 | }
63 |
64 | return root;
65 | }
66 |
67 | // runtime:
68 | // O(n)
69 | dfPrint() {
70 | let stack = [this.root];
71 |
72 | while (stack.length > 0) {
73 | let node = stack.pop();
74 | console.log(node.val);
75 | if (node.right !== null) stack.push(node.right);
76 | if (node.left !== null) stack.push(node.left);
77 | }
78 | }
79 |
80 | // runtime:
81 | // O(n)
82 | bfPrint() {
83 | let queue = [this.root];
84 |
85 | while (queue.length > 0) {
86 | let node = queue.shift();
87 | console.log(node.val);
88 | if (node.left !== null) queue.push(node.left);
89 | if (node.right !== null) queue.push(node.right);
90 | }
91 | }
92 | }
93 |
94 | // const tree = new BST();
95 | // tree.insert(10);
96 | // tree.insert(5);
97 | // tree.insert(15);
98 | // tree.insert(3);
99 | // tree.insert(7);
100 | // tree.insert(13);
101 | // tree.insert(17);
102 | // tree.insert(11);
103 |
104 |
105 | // tree.dfPrint();
106 | // tree.bfPrint();
107 | // tree.inOrderPrint();
108 |
109 | // console.log(tree.search(11)); // => true
110 | // console.log(tree.search(13)); // => true
111 | // console.log(tree.search(9)); // => false
112 |
113 | // WORST CASE B-SEARCH ON BST
114 | // n is the number of nodes
115 | // runtime: O(n)
116 | // when "tree" is really linked list and the val is not found
117 | // BEST CASE
118 | // runtime: O(logn)
119 | // when "tree" is balanced
120 |
121 |
122 | // console.log(tree.height());
123 | // console.log(tree.dfPrint());
124 | // console.log(tree.bfPrint());
125 | // console.log(tree.search(10));
126 |
127 |
128 |
129 | module.exports = { BST };
130 |
131 |
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/balanced_bst_notes_reading.md:
--------------------------------------------------------------------------------
1 | # Searching and Balanced BSTs
2 |
3 | Let's explore the main application of a Binary Search Tree. Since a BST is a sorted data structure, this allows us to conduct the Binary Search algorithm. This algorithm will be similar to the same Binary Search strategy we used on sorted arrays!
4 |
5 | ### Implementing Binary Search on a BST
6 |
7 | Our goal is to implement a `#search` method on our previous `BST` class that will solve the problem:
8 |
9 | ```
10 | Given a binary search tree and a target value, return a boolean indicating whether or not the target is
11 | contained in the tree.
12 | ```
13 |
14 | In other words, our `BST#search` should satisfy the following behavior:
15 |
16 | ```javascript
17 | let tree = new BST();
18 | tree.insert(10);
19 | tree.insert(5);
20 | tree.insert(16);
21 | tree.insert(1);
22 | tree.insert(7);
23 | tree.insert(16);
24 |
25 | tree.search(7); // => true
26 | tree.search(16); // => true
27 | tree.search(14); // => false
28 | ```
29 |
30 | As with many tree problems, this problem lends itself nicely to recursion! Like always, our base case should capture the scenario where the input tree is trivial and we know the answer to the problem without further calculation. If the given tree is empty, then we can be certain that the target is not found in the tree. The logic of our `BST#search` method will be much the same compared to our `binarySearch` function for sorted arrays. Try to interpret the code below and scroll further to the annotated version when you need clarification
31 |
32 | ```javascript
33 | // assuming our BST class from the previous section
34 | class BST {
35 | // ...
36 |
37 | search(val, root=this.root) {
38 | if (!root) return false;
39 |
40 | if (val < root.val) {
41 | return this.search(val, root.left);
42 | } else if (val > root.val){
43 | return this.search(val, root.right);
44 | } else {
45 | return true;
46 | }
47 | }
48 | }
49 | ```
50 |
51 | ```javascript
52 | // assuming our BST class from the previous section
53 | class BST {
54 | // ...
55 |
56 | // commented
57 | search(val, root=this.root) {
58 | // if the tree is empty, then the target val is not in the tree, so return false
59 | if (!root) return false;
60 |
61 | // otherwise the tree is not empty, so...
62 | if (val < root.val) {
63 | // if the target is less than the root,
64 | // then search the left subtree
65 | return this.search(val, root.left);
66 | } else if (val > root.val){
67 | // if the target is greater than the root,
68 | // then search the right subtree
69 | return this.search(val, root.right);
70 | } else {
71 | // otherwise, the target must be equal to the root
72 | // so return true since we found it!
73 | return true;
74 | }
75 | }
76 | }
77 | ```
78 |
79 | ### Height Balance
80 |
81 | Before we analyze the time complexity of `BST#search`, we'll first need to learn about height balance. Recalling what we touched on briefly in our chat on binary trees, **height** is defined as the number of edges between the root and farthest leaf in a tree. Note that height is dictated by the **farthest** leaf (think worst case):
82 |
83 | 
84 |
85 | Following this definition, a tree consisting of a single node has height 0. We consider then an empty tree as having height -1. Height is relevant because not all BSTs are created equal! That is, some BSTs have "good / small" heights, others have "bad / large" heights. Take a look at these two BSTs containing identical values, but very different heights:
86 |
87 | 
88 |
89 | `Tree 1` is preferred over `Tree 2`, because `Tree 1` is **balanced**. Balanced Binary Treess will be the most efficient to perform operations on.
90 |
91 | For a binary tree to be **balanced**:
92 |
93 | + the left and right subtrees must differ in height by at most 1
94 | + AND the left subtree is balanced
95 | + AND the right subtree is balanced
96 |
97 | Notice that **balanced** has a recursive definition. Like you probably guessed, the empty tree is considered balanced. This will be the base case of our definition.
98 |
99 | ### Only the Best Trees Have Logs
100 |
101 | A balanced binary tree is incredible to have because it's height is guaranteed to be **O(log2(n))**, where n is the number of nodes in the tree. Let's take a look at a few examples:
102 |
103 | 
104 |
105 | To make the approximations above, we rounded the result of each log down to the nearest integer. If you are not convinced of how powerful this is, this means that a balanced tree of 1000 nodes will have a height of just 10.
106 |
107 | ### Time Complexity Analysis of Binary Search for BSTs
108 |
109 | Worst case for the algorithm occurs when the target value is not present in the tree. This means that we must traverse a path from root to a leaf, so we must travel the full **height** of the tree in the worst case. However, like we discussed, the height of a tree can vary wildly. We can have a tree with minimal height (a balanced tree like `Tree 1`), or we can have a tree with maximal height (a linked list like `Tree 2`).
110 |
111 | + **O(log(n))** time for a balanced tree:
112 | + **O(n)** time for unbalanced tree:
113 |
114 | ### Space Complexity Analysis of Binary Search for BSTs
115 |
116 | No additional space is needed for the algorithm, so we have constant **O(1)** space.
117 |
118 | To play devil's advocate, what if we count the recursive stack calls as contributing to the space complexity? Some coding challenges in your job hunt may pose this. If that is the case then our recursive implementation above will use:
119 |
120 | + **O(log(n))** space for a balanced tree
121 | + **O(n)** space for unbalanced tree
122 |
123 | To truly get constant space out of Binary Search, we're going to have to avoid recursion. Can you think of how we can write the algorithm iteratively? We'll save this for the upcoming project :).
124 |
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/binary_search_tree_notes_reading.md:
--------------------------------------------------------------------------------
1 | # Binary Search Trees
2 |
3 | Now that we have a solid grasp of **Binary Trees**, let's add another constraint to the data structure. A Binary **Search** Tree (BST) has an additional criteria where:
4 |
5 | + given any node of the tree, the values in the left subtree must all be strictly less than the given node's value.
6 | + and the values in the right subtree must all be greater than or equal to the given node's value
7 |
8 | ### BST Definition
9 |
10 | We can also describe a BST using a recursive definition. A **Binary Tree** is a **Binary Search Tree** if:
11 |
12 | + the left subtree contains values less than the root
13 | + AND the right subtree contains values greater than or equal to the root
14 | + AND the left subtree is a Binary Search Tree
15 | + AND the right subtree is a Binary Search Tree
16 |
17 | It's worth mentioning that the empty tree (a tree with 0 nodes) is indeed a BST (did someone say base case?).
18 |
19 | Here are a few examples of BSTs:
20 |
21 | 
22 |
23 | Take a moment to verify that the above binary trees are BSTs. Note that image 2 has the sane chain structure as a linked list. This will come into play later.
24 |
25 | Below is an example of a binary tree that is **not** a search tree because a left child (35) is greater than it's parent (23):
26 |
27 | 
28 |
29 | ### A BST is a Sorted Data Structure
30 |
31 | So what's the big deal with BSTs? Well, because of the properties of a BST, we can consider the tree as having an order to the values. That means the values are fully sorted! By looking at the three BST examples above, you are probably not convinced of things being sorted. This is because the ordering is encoded by an inorder traversal. Let's recall our previous `inOrderPrint` function:
32 |
33 | ```javascript
34 | function inOrderPrint(root) {
35 | if (!root) return;
36 |
37 | inOrderPrint(root.left);
38 | console.log(root.val);
39 | inOrderPrint(root.right);
40 | }
41 | ```
42 |
43 | If we run `inOrderPrint` on the three BSTs, we will get the following output:
44 |
45 | ```
46 | BST 1: 42
47 | BST 2: 4, 5, 6
48 | BST 3: 1, 5, 7, 10, 16, 16
49 | ```
50 |
51 | For each tree, we printed out values in increasing order! A binary search tree contains sorted data; this will come into play when we perform algorithms on this data structure.
52 |
53 | ### Naive BST Implementation
54 |
55 | Let's implement a `BST` class that will maintain the ordered property through any number of insertions into the tree. We are going to avoid manually creating all nodes and explicitly setting `left`s and `right`s, so we don't have to worry about breaking order. We'll use our classic `TreeNode` as a component of `BST`. In addition, we'll need a proper `BST#insert` method that will conduct legal insertions on the tree. Interpret the code below and scroll further to our annotated version when you need clarification:
56 |
57 | ```javascript
58 | class TreeNode {
59 | constructor(val) {
60 | this.val = val;
61 | this.left = null;
62 | this.right = null;
63 | }
64 | }
65 |
66 | class BST {
67 | constructor() {
68 | this.root = null;
69 | }
70 |
71 | insert(val, root=this.root) {
72 | if(!this.root) {
73 | this.root = new TreeNode(val);
74 | return;
75 | }
76 |
77 | if (val < root.val) {
78 | if (!root.left) {
79 | root.left = new TreeNode(val);
80 | } else {
81 | this.insert(val, root.left);
82 | }
83 | } else {
84 | if (!root.right) {
85 | root.right = new TreeNode(val);
86 | } else {
87 | this.insert(val, root.right);
88 | }
89 | }
90 | }
91 | }
92 | ```
93 |
94 | ```javascript
95 | // commented naive BST class
96 | class BST {
97 | constructor() {
98 | // initialize the tree to be empty
99 | this.root = null;
100 | }
101 |
102 | insert(val, root=this.root) {
103 | // if the tree is currently empty, then create the node as the 'absolute' root
104 | if(!this.root) {
105 | this.root = new TreeNode(val);
106 | return;
107 | }
108 |
109 | // otherwise, the tree is not empty, so...
110 | // if our val to insert is less than the root...
111 | if (val < root.val) {
112 | if (!root.left) { // ...and the left child does not exist,
113 | root.left = new TreeNode(val); // then create the node as the left child
114 | } else { // ...and the left child already exists,
115 | this.insert(val, root.left); // then recursively insert on the left subtree
116 | }
117 |
118 | // if our val to insert is greater than or equal to the root...
119 | } else {
120 | if (!root.right) { // ...and the right child does not exist,
121 | root.right = new TreeNode(val); // then create the node as the right child
122 | } else { // ...and the right child already exists,
123 | this.insert(val, root.right); // then recursively insert on the right subtree
124 | }
125 | }
126 | }
127 | }
128 | ```
129 |
130 | We can call `insert` to build up the `BST` without worrying about breaking the search tree property. Let's build two different trees:
131 |
132 | ```javascript
133 | let tree1 = new BST();
134 | tree1.insert(10);
135 | tree1.insert(5);
136 | tree1.insert(16);
137 | tree1.insert(1);
138 | tree1.insert(7);
139 | tree1.insert(16);
140 |
141 | let tree2 = new BST();
142 | tree2.insert(1);
143 | tree2.insert(5);
144 | tree2.insert(7);
145 | tree2.insert(10);
146 | tree2.insert(16);
147 | tree2.insert(16);
148 | ```
149 |
150 | The insertions above will yield the following trees:
151 |
152 | 
153 |
154 | Are you cringing at `tree2`? You should be. Although we have the same values in both trees, they display drastically different structures because of the insertion order we used. This is why we have been referring to our `BST` implementation as **naive**. Both of these trees are Binary Search Trees, however not all BSTs are created equal. A worst case BST degenerates into a linked list. The "best" BSTs are **height balanced**, we'll explore this concept soon™.
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/binary_trees_notes_reading.md:
--------------------------------------------------------------------------------
1 | # Binary Trees
2 |
3 | Binary Trees are perhaps the most pervasive data structure in computer science. Let's take a moment to go over the basic characteristics of a Binary Tree before we explore algorithms that utilize this structure.
4 |
5 | ### What is a Graph?
6 |
7 | Before we define what a **Tree** is, we must first understand the definition of a **Graph**. A graph is a collection of **nodes** and any **edges** between those nodes. You've likely seen depictions of graphs before, they usual exist as circles (nodes) and arrows (edges) between those circles. Below are few examples of graphs:
8 |
9 | 
10 |
11 | For now, you can ignore the blue coloring. Notice how the graphs above vary greatly in their structure. A graph is indeed a very broad, overarching category. In fact, linked lists and trees are both considered subclasses of graphs. We'll cover algorithms that operate on a general graph structure later, but for now we want to focus on what graphs are trees and what graphs are not. It's worth mentioning that a single node with no edges (image 1) is considered a graph. The empty graph (a graph with 0 nodes and 0 edges, not pictured :)) is also still a graph. This line of thinking will help us later when we design graph algorithms.
12 |
13 | ### What is a Tree?
14 |
15 | A **Tree** is a **Graph** that does not contain any cycles. A cycle is is defined as a path through edges that begins and ends at the same node. This seems straightforward, but the definition becomes a bit muddled as Mathematicians and Computer Scientists use the term "tree" in slightly different ways. Lets break it down:
16 |
17 | + To a Mathematician, graphs 1, 2, 3, and 4 in the above image are trees.
18 | + To a Computer Scientist, only graphs 1 ,2, and 3 are trees.
19 |
20 | Well, at least both camps agree that graph 5 is most certainly not a tree! This is because of the obvious cycle that spans all three nodes. However, why is there disagreement over graph 4? The reason is this: In computer science, we use to the term "tree" to really refer to a "rooted tree." A "rooted tree" is a "tree" where there exists a special node from which every other node is accessible; we call this special node the "root". Think of the root as ultimate ancestor, the single node that all other nodes inherit from. Above we have colored all roots in blue. Like you'd probably suspect, in this course we'll subscribe to the Computer Scientist's interpretation. That is, we won't consider graph 4 a tree because there is no such root we can label.
21 |
22 | You've probably heard the term "root" throughout your software engineering career: root directory, root user, etc.. All of these concepts branch† from the humble tree data structure!
23 |
24 | ### What is a Binary Tree?
25 |
26 | A **Binary Tree** is a **Tree** where nodes have **at most 2 children**. This means graphs 1, 2, and 3 are all Binary Trees. There exist ternary trees (at most 3 children) and n-ary trees (at most n children), but you'll likely encounter binary trees in your job hunt, so we'll focus on them in this course. Based on our final definition for a binary tree, here is some food for thought:
27 |
28 | + an empty graph of 0 nodes and 0 edges is a binary tree
29 | + a graph of 1 node and 0 edges is a binary tree
30 | + a linked list is a binary tree
31 |
32 | Take a moment to use the definitions we explored to verify that each of the three statements above is true. We bring up these three scenarios in particular because they are the simplest types of Binary Trees. We want to eventually build elegant algorithms and these simple scenarios will fuel our design.
33 |
34 | ### Representing a Tree with Node Instances
35 |
36 | Let's explore a common way to represent binary trees using some object oriented design. A tree is a collection of nodes, so let's implement a `TreeNode` class. We'll use properties of `left` and `right` to reference the children of a `TreeNode`. That is, `left` and `right` will reference other `TreeNode`s:
37 |
38 | ```javascript
39 | class TreeNode {
40 | constructor(val) {
41 | this.val = val;
42 | this.left = null;
43 | this.right = null;
44 | }
45 | }
46 | ```
47 |
48 | Constructing a tree is a matter of creating the nodes and setting `left` and `right` however we please. For example:
49 |
50 | ```javascript
51 | let a = new TreeNode('a');
52 | let b = new TreeNode('b');
53 | let c = new TreeNode('c');
54 | let d = new TreeNode('d');
55 | let e = new TreeNode('e');
56 | let f = new TreeNode('f');
57 |
58 | a.left = b;
59 | a.right = c;
60 | b.left = d;
61 | b.right = e;
62 | c.right = f;
63 | ```
64 |
65 | The visual representation of the tree is:
66 |
67 | 
68 |
69 | To simplify our diagrams, we'll omit the arrowheads on the edges. Moving forward you can assume that the top node is the root and the direction of edges points downward. In other words, node A is the Root. Node A can access node B through `a.left`, but Node B cannot access Node A.
70 |
71 | We now have a data structure we can use to explore Binary Tree algorithms! Creating a tree in this way may be tedious and repetitive, however it allows us to decide exactly what nodes are connected and in what direction. This is will be useful as we account for edge cases in our design.
72 |
73 | ### Basic Tree Terminology
74 |
75 | + tree - graph with no cycles
76 | + binary tree - tree where nodes have at most 2 nodes
77 | + root - the ultimate parent, the single node of a tree that can access every other node through edges; by definition the root will not have a parent
78 | + internal node - a node that has children
79 | + leaf - a node that does not have any children
80 | + path - a series of nodes that can be traveled through edges - for example A, B, E is a path through the above tree
81 |
82 | † Pun Intended
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/depth_and_breadth_first_notes_reading.md:
--------------------------------------------------------------------------------
1 | # Depth and Breadth First Traversal
2 |
3 | Let's add two more tree traversal algorithms to our arsenal. **Depth-First** and **Breadth-First** are two classic traversal strategies that differ in the order nodes are hit. In this reading, our candidate tree will be:
4 |
5 | 
6 |
7 | Like we are accustomed to, we can represent the tree programmatically with:
8 |
9 | ```javascript
10 | class TreeNode {
11 | constructor(val) {
12 | this.val = val;
13 | this.left = null;
14 | this.right = null;
15 | }
16 | }
17 |
18 | let a = new TreeNode('a');
19 | let b = new TreeNode('b');
20 | let c = new TreeNode('c');
21 | let d = new TreeNode('d');
22 | let e = new TreeNode('e');
23 | let f = new TreeNode('f');
24 |
25 | a.left = b;
26 | a.right = c;
27 | b.left = d;
28 | b.right = e;
29 | c.right = f;
30 | ```
31 |
32 | ## Depth-First
33 |
34 | To help verbalize Depth-First (DF), we'll be using a few familial terms to describe the relative positions of the nodes. Think of the words you would use if viewing a family tree! Here are some examples:
35 |
36 | + `B` and `C` are siblings
37 | + `D` and `E` are descendants of `B`
38 | + `B`, `C`, `D`, `E`, `F` are all descendants of `A`
39 |
40 | A Depth-First traversal will continually travel deeper into a tree before switching branches. This means that, given a node, we must visit all of it's descendants before visiting it's sibling.
41 |
42 | Performing DF on our tree will hit the nodes in the order: `A, B, D, E, C, F`
43 |
44 | ### Depth-First Implementation
45 |
46 | To travel the nodes of a tree according to Depth-First behavior, we'll utilize a **stack.** Recall from earlier that a stack is LIFO (Last In, First Out). Our strategy is to use an array as a stack. We'll use `push` to add to the top of our stack and `pop` to remove the top. Below is a complete implementation of `depthFirst`. Try to interpret the code below and scroll further to see the annotated version:
47 |
48 | ```javascript
49 | function depthFirst(root) {
50 | let stack = [ root ];
51 | while (stack.length) {
52 | let node = stack.pop();
53 | console.log(node.val);
54 | if (node.right) stack.push(node.right);
55 | if (node.left) stack.push(node.left);
56 | }
57 | }
58 | ```
59 |
60 | ```javascript
61 | function depthFirst(root) {
62 | // initialize the stack with the root node
63 | let stack = [ root ];
64 |
65 | // continue running the algorithm while there are still nodes on the stack
66 | while (stack.length) {
67 |
68 | // pop the top node from the stack
69 | let node = stack.pop();
70 |
71 | // we consider a node visited once we pop it,
72 | // so we should print the node's value now
73 | console.log(node.val);
74 |
75 | // add the node's left and right children, if they exist
76 | if (node.right) stack.push(node.right);
77 | if (node.left) stack.push(node.left);
78 |
79 | // IMPORTANT: do not print out the children yet; they must wait their turn to be popped first
80 | }
81 | }
82 | ```
83 |
84 | You should watch the video lecture that follows this reading for a visual on how a stack inherently gives us DF order. For now, a key idea to take away is that we only consider a node "visited" once we pop it. We do not consider a node "visited" when we push it.
85 |
86 | Because a stack naturally leads to DF order on a tree, we can easily write a recursive version. Why is recursion relevant to DF? Recursion utilizies the call **stack**:
87 |
88 | ```javascript
89 | function depthFirstRecur(root) {
90 | if (!root) return;
91 | console.log(root.val);
92 | depthFirstRecur(root.left);
93 | depthFirstRecur(root.right);
94 | }
95 | ```
96 |
97 | Does this code look familiar? It's identical to the `preOrderPrint` function we wrote previously. That's right, pre-order and depth-first are identical tree node orderings.
98 |
99 | You should study both the iterative and recursive implementations as they will both prove valuable to solving problems.
100 |
101 | ## Breadth-First
102 |
103 | This algorithm has nothing to do with bread. The word "breadth" is the same as "width". To help veribalize Breadth-First (BF) we'll need to understand the simple concept of tree **levels**. With the tree at the top of this reading in mind, we can say the following:
104 |
105 | + level 0 contains `A`
106 | + level 1 contains `B`, `C`
107 | + level 2 contains `D`, `E`, `F`
108 |
109 | A Breadth-First traversal will visit all nodes across a level, before moving to the next level. This means we travel laterally as much as we can before going deeper into the tree.
110 |
111 | Perform BF on our tree will hit the nodes in the order: `A, B, C, D, E, F`
112 |
113 | ### Breadth-First Implementation
114 |
115 | While DF uses a stack, BF will use a **queue**. Recall that a queue is FIFO (First In, First Out). The code is very similar to our iterative DF, except we will use an array as a queue. `shift` will remove the front of the queue and `push` will add to the back of the queue. Interpret the implementation below and scroll further to the annotated version when you need more insight:
116 |
117 | ```javascript
118 | function breadthFirst(root) {
119 | let queue = [ root ];
120 | while (queue.length) {
121 | let node = queue.shift();
122 |
123 | console.log(node.val);
124 |
125 | if (node.left) queue.push(node.left);
126 | if (node.right) queue.push(node.right);
127 | }
128 | }
129 | ```
130 |
131 | ```javascript
132 | function breadthFirst(root) {
133 | // initialize the queue with the root node
134 | let queue = [ root ];
135 |
136 | // continue running the algorithm while there are still nodes on the queue
137 | while (queue.length) {
138 | // remove the front node from the queue
139 | let node = queue.shift();
140 |
141 | // the node we just removed is now "visited", so print it
142 | console.log(node.val);
143 |
144 | // add the left and right children to the back of the queue, if they exist
145 | if (node.left) queue.push(node.left);
146 | if (node.right) queue.push(node.right);
147 |
148 | // IMPORTANT: do not print out the children yet; they must wait their turn to exit the front of the queue first
149 | }
150 | }
151 | ```
152 |
153 | We'll rarely run into a recursive BF implementation (probably never) because recursion uses an underlying call stack, but we really want the opposite of a stack (a queue).
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/balanced_unbalanced.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/balanced_unbalanced.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/bsts.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/bsts.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/good_bad_bst.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/good_bad_bst.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/graph_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/graph_a.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/graphs.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/graphs.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/height.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/height.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/log_heights.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/log_heights.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/images/not_bst.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/aa_data_structures_workshop/march_2019/trees/images/not_bst.png
--------------------------------------------------------------------------------
/aa_data_structures_workshop/march_2019/trees/inorder_preorder_postorder_reading.md:
--------------------------------------------------------------------------------
1 | # Binary Tree Print Order Algorithms
2 |
3 | Now that we have the basic definition of a binary tree, let's begin with three short algorithms that print out the values. The algorithms are structurally the same, however they will differ in what order the values are printed. We'll use the following tree as the input when running these algorithms:
4 |
5 | 
6 |
7 | ## In-Order
8 |
9 | Let's begin with the `inOrderPrint` function. All three of our algorithms will be recursive and have the same base case. As always, our base case should cover the scenario where the input is trivially small enough so that we don't need to perform further calculation. Since our "problem" is to print all values in a tree, what is the simplest tree we can be given? The empty tree! A common mistake when designing recursive tree algorithms is to make the base case about the root being a leaf, instead we'll want the basecase to cover the root being empty:
10 |
11 | ```javascript
12 | function inOrderPrint(root) {
13 | if (root === null) return;
14 | // ...
15 | }
16 | ```
17 |
18 | Note that taking in an entire tree as input is really just a matter of taking in the root node. This is because the root node can access every other node through a path of edges. Our base case says, "if the tree is empty, return since there is nothing to print."
19 |
20 | Here is where the meat of the algorithm comes in. Given the root of a tree, the steps for `inOrderPrint` are:
21 |
22 | ```
23 | - print all nodes in the left subtree
24 | - print root
25 | - print all nodes in the right subtree
26 | ```
27 |
28 | Translating this into code:
29 |
30 | ```javascript
31 | function inOrderPrint(root) {
32 | if (!root) return;
33 |
34 | inOrderPrint(root.left);
35 | console.log(root.val);
36 | inOrderPrint(root.right);
37 | }
38 | ```
39 |
40 | Given our tree, `inOrderPrint` would print the values in the order: `d, b, e, a, c, f`
41 |
42 | In-Order has the pattern of left, self, right. This means:
43 | + a node can only be printed once it's left subtree has been completely printed.
44 | + a node's right subtree can only be printed once the node itself has been printed.
45 |
46 | ## Pre-Order
47 |
48 | Given the root of a tree, the steps for `preOrderPrint` are:
49 |
50 | ```
51 | - print root
52 | - print all nodes in the left subtree
53 | - print all nodes in the right subtree
54 | ```
55 |
56 | Translating this into code:
57 |
58 | ```javascript
59 | function preOrderPrint(root) {
60 | if (!root) return;
61 |
62 | console.log(root.val);
63 | preOrderPrint(root.left);
64 | preOrderPrint(root.right);
65 | }
66 | ```
67 |
68 | Given our tree, `preOrderPrint` would print the values in the order: `a, b, d, e, c, f`
69 |
70 | Pre-Order has the patten of self, left, right. This means:
71 | + a node must be printed before it's children
72 | + a node's left subtree must be printed before it's right subtree
73 |
74 | ## Post-Order
75 |
76 | Given the root of a tree, the steps for `postOrderPrint` are:
77 |
78 | ```
79 | - print all nodes in the left subtree
80 | - print all nodes in the right subtree
81 | - print root
82 | ```
83 |
84 | Translating this into code:
85 |
86 | ```javascript
87 | function postOrderPrint(root) {
88 | if (!root) return;
89 |
90 | preOrderPrint(root.left);
91 | preOrderPrint(root.right);
92 | console.log(root.val);
93 | }
94 | ```
95 |
96 | Given our Tree, `postOrderPrint` would print the values in the order: `d, e, b, f, c, a`
97 |
98 | Post-Order has the pattern of left, right, self. This means:
99 | + a node can only be printed after it's left and right subtrees
100 | + a node's left subtree is printed before it's right subtree
101 |
--------------------------------------------------------------------------------
/aa_data_structures_workshop/max_path_sum.js:
--------------------------------------------------------------------------------
1 | const { BST } = require("./trees_1");
2 |
3 | // Write a function that accepts the root of a tree as an arg.
4 | // The function should return the maximum sum of a path through the tree.
5 | // For this problem, a path must begin at the root and end at a leaf.
6 |
7 | function maxPathSum(root) {
8 | if (!root) return 0;
9 |
10 | let leftMax = maxPathSum(root.left);
11 | let rightMax = maxPathSum(root.right);
12 | return root.val + Math.max(leftMax, rightMax);
13 | }
14 |
15 | const tree = new BST();
16 |
17 | tree.insert(10);
18 | tree.insert(5);
19 | tree.insert(15);
20 | tree.insert(3);
21 | tree.insert(7);
22 | tree.insert(17);
23 | tree.insert(16);
24 |
25 | console.log(maxPathSum(tree.root));
--------------------------------------------------------------------------------
/aa_data_structures_workshop/tree_sum.js:
--------------------------------------------------------------------------------
1 | const { BST } = require("./trees_1");
2 |
3 | // Write a function that accepts the root of a tree as an arg.
4 | // The function should return the total sum of all node values in the tree.
5 |
6 | function treeSum(root) {
7 | if (!root) return 0;
8 |
9 | let leftSum = treeSum(root.left);
10 | let rightSum = treeSum(root.right);
11 |
12 | return leftSum + root.val + rightSum
13 | }
14 |
15 | const tree = new BST();
16 |
17 | tree.insert(10);
18 | tree.insert(5);
19 | tree.insert(15);
20 | tree.insert(3);
21 | tree.insert(7);
22 | tree.insert(17);
23 | tree.insert(16);
24 |
25 | console.log(treeSum(tree.root));
--------------------------------------------------------------------------------
/aa_data_structures_workshop/trees_1.js:
--------------------------------------------------------------------------------
1 | // Tree Keys to Victory :)
2 | // * a tree containing 0 nodes is still a tree, although an empty tree
3 | // * a tree has no cycles
4 | // * a tree contains many (sub)trees, lending itself to recursion
5 | //
6 | // DEFINITIONS:
7 | //
8 | // Graph - a structure containing nodes and edges
9 | // - a node may contain data, an edges connect two nodes
10 | // - visually we use circles as nodes and arrows as edges
11 | // - programmatically we use node instances as nodes and references as edges
12 | //
13 | // Tree - a graph with no cycles
14 | // - having no cycles means that we can designate a root, the root is the "start" point
15 | // - if we allow cycles: who is the parent? who is the child? - This is why we don't allow them.
16 | // - if we have access to the root, then we have access to the full tree,
17 | // b/c there is a path to every node from the root.
18 | // - having a single node is a tree
19 | // - having no nodes is a tree
20 | // - this means that the definition of a tree is recursive
21 | //
22 | // Binary Tree - a tree where every node has 0, 1, or 2 children
23 | //
24 | // Binary Search Tree - a binary tree where the left subtree contains values less than the root,
25 | // the right subtree contains values greater than or eq to root...
26 | // - AND the left subtree is a binary search tree...
27 | // - AND the right subtree is a binary search tree.
28 | // - an empty tree is a binary search tree
29 | // - this means that the definition of a BST is recursive
30 | //
31 | // Balanced Binary Tree - binary tree where the heights of the left and right subtrees differ by at most 1.
32 | // - AND the left subtree is balanced
33 | // - AND the right subtree is balanced
34 | // - an empty tree is balanced binary tree
35 | // - this means that the definition of balanceness is recursive
36 | //
37 | // WRAPPING UP
38 | // - Our implementation of a BST doesn't guarantee it to be balanced after any arbitrary insertions.
39 | //
40 | // - Tree Height Interpretations
41 | // - Alvin consider's an empty binary tree as having height 0,
42 | // so a tree with a single node has height 1.
43 | // - Another valid interpretation is that an empty tree is height -1,
44 | // so a tree with a single node has height 0
45 | //
46 | // HOMEWORK
47 | // - Reimplement your own BST class with the same methods.
48 | // - #insert
49 | // - our insert logic is pretty redundant, can you DRY it up?
50 | // - #print
51 | // - #search
52 | //
53 | // - Then re-reimplement it without recursion.
54 | // - which one do you prefer recursive or iterative?
55 | // Thanks for Attending! -AZ
56 |
57 | class Node {
58 | constructor(val) {
59 | this.val = val;
60 | this.left = null;
61 | this.right = null;
62 | }
63 | }
64 |
65 | class BST {
66 | constructor() {
67 | this.root = null; // an empty tree's root is null.
68 | }
69 |
70 | // inOrderPrint is an inOrderTraversal which is a type of depthFirstTraversal
71 | inOrderPrint(root=this.root) {
72 |
73 | // since we are printing a search tree,
74 | // we know all nodes in the left subtree are less than root,
75 | // and all nodes in the right subtree are greater than root.
76 | if (!root) return;
77 |
78 | // so inOrderPrint the left subtree...
79 | this.inOrderPrint(root.left);
80 | // then the current root...
81 | console.log(root.val);
82 | // and finally the right subtree...
83 | this.inOrderPrint(root.right);
84 | }
85 |
86 | search(val, root=this.root) {
87 | // if the tree is empty,
88 | // then the val is certainly not going to be found
89 | if (!root) return false;
90 |
91 | // if the root contains the value, we successfully found the val!
92 | if (root.val === val) return true;
93 |
94 | // otherwise, the root does not contain the value, so...
95 | if(val < root.val) { // go left if our target val is less
96 | return this.search(val, root.left);
97 | } else { // go right if our target val is greater or eq
98 | return this.search(val, root.right);
99 | }
100 | }
101 |
102 | insert(val, root=this.root) {
103 | // if the tree is empty,
104 | // then simply set this.root to make the initial node
105 | if (!root) {
106 | this.root = new Node(val);
107 | return;
108 | }
109 |
110 | // otherwise the tree is not empty,
111 | // so decide which subtree to insert into based on value of current root
112 |
113 | if (val < root.val) { // go to left subtree
114 | if (root.left) {
115 | // if the left subtree exists,
116 | // so we insert into that subtree
117 | this.insert(val, root.left);
118 | } else {
119 | // else the left subtree does not exist,
120 | // so create the node at that position
121 | root.left = new Node(val);
122 | }
123 | } else { // go to right subtree
124 | if (root.right) {
125 | this.insert(val, root.right);
126 | } else {
127 | root.right = new Node(val);
128 | }
129 | }
130 | }
131 | }
132 |
133 | // let tree = new BST();
134 |
135 | // tree.insert(10);
136 | // tree.insert(5);
137 | // tree.insert(15);
138 | // tree.insert(3);
139 | // tree.insert(7);
140 | // tree.insert(17);
141 |
142 | // tree.inOrderPrint();
143 |
144 | // console.log(tree.search(7));
145 | // console.log(tree.search(1000));
146 |
147 | module.exports = { BST, Node };
--------------------------------------------------------------------------------
/aa_data_structures_workshop/trees_2.js:
--------------------------------------------------------------------------------
1 | const { BST, Node } = require("./trees_1");
2 |
3 | const tree = new BST();
4 |
5 | tree.insert(10);
6 | tree.insert(5);
7 | tree.insert(15);
8 | tree.insert(3);
9 | tree.insert(7);
10 | tree.insert(17);
11 | tree.insert(16);
12 |
13 |
14 | // inOrder, preOrder, and postOrder are all depth first traversals
15 | function inOrderPrint(root) {
16 | if (!root) return;
17 |
18 | inOrderPrint(root.left);
19 | console.log(root.val);
20 | inOrderPrint(root.right);
21 | }
22 |
23 | function preOrderPrint(root) {
24 | if (!root) return;
25 |
26 | console.log(root.val);
27 | preOrderPrint(root.left);
28 | preOrderPrint(root.right);
29 | }
30 |
31 | function postOrderPrint(root) {
32 | if (!root) return;
33 |
34 | postOrderPrint(root.left);
35 | postOrderPrint(root.right);
36 | console.log(root.val);
37 | }
38 |
39 | function depthFirstRecur(root) {
40 | if (!root) return;
41 |
42 | console.log(root.val);
43 | depthFirstRecur(root.left);
44 | depthFirstRecur(root.right);
45 | }
46 |
47 | function depthFirstIter(root) {
48 | let stack = [ root ];
49 |
50 | while (stack.length > 0) {
51 | let node = stack.pop();
52 | console.log(node.val);
53 |
54 | if (node.right) stack.push(node.right)
55 | if (node.left) stack.push(node.left);
56 | }
57 | }
58 |
59 | function breadthFirstIter(root) {
60 | let queue = [root];
61 |
62 | while (queue.length > 0) {
63 | let node = queue.shift();
64 | console.log(node.val);
65 |
66 | if (node.left) queue.push(node.left);
67 | if (node.right) queue.push(node.right)
68 | }
69 | }
70 |
71 |
72 | breadthFirstIter(tree.root)
--------------------------------------------------------------------------------
/alvin.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/alvin.txt
--------------------------------------------------------------------------------
/anne.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/anne.txt
--------------------------------------------------------------------------------
/c++/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/c++/.DS_Store
--------------------------------------------------------------------------------
/c++/atoi.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | int ctoi(char c) {
8 | if(c == '0') return 0;
9 | if(c == '1') return 1;
10 | if(c == '2') return 2;
11 | if(c == '3') return 3;
12 | if(c == '4') return 4;
13 | if(c == '5') return 5;
14 | if(c == '6') return 6;
15 | if(c == '7') return 7;
16 | if(c == '8') return 8;
17 | if(c == '9') return 9;
18 | }
19 |
20 | int myatoi(string s) {
21 | int sum = 0;
22 | for(int i = s.length() - 1; i >= 0; i--) {
23 | int ex = s.length() - 1 - i;
24 | sum += ctoi(s[i]) * pow(10,ex);
25 | }
26 | return sum;
27 | }
28 |
29 | int main() {
30 | cout << myatoi("1776") << endl;
31 | return 0;
32 | }
--------------------------------------------------------------------------------
/c++/binarySearchTree/binaryTree.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | #include "binaryTree.h"
7 |
8 | using namespace std;
9 |
10 | void ins(Node* &node, int data) {
11 | if(node == NULL) {
12 | node = new Node;
13 | node->data = data;
14 | }
15 | else if(data < node->data) {
16 | ins(node->left, data);
17 | }
18 | else if(data >= node->data) {
19 | ins(node->right, data);
20 | }
21 | }
22 |
23 | void BinaryTree::insert(int data) {
24 | ins(root, data);
25 | }
26 |
27 | void pri(Node* node) {
28 | if(node != NULL) {
29 | pri(node->left);
30 | cout << node->data << " ";
31 | pri(node->right);
32 | }
33 | }
34 |
35 | void BinaryTree::print(void) {
36 | pri(root);
37 | cout << endl;
38 | }
39 |
40 | int height(Node* node, int h) {
41 | if(node == NULL) {
42 | return h;
43 | }
44 | else {
45 | int left = height(node->left, h + 1);
46 | int right = height(node->right, h + 1);
47 | if(left == -1 || right == -1) {
48 | return -1;
49 | }
50 | else if(abs(left - right) > 1) {
51 | return -1;
52 | }
53 | else {
54 | return max(left, right);
55 | }
56 | }
57 | }
58 |
59 | bool BinaryTree::isBalanced(void) {
60 | if (height(root, 0) == -1) {
61 | return false;
62 | }
63 | else {
64 | return true;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/c++/binarySearchTree/binaryTree.h:
--------------------------------------------------------------------------------
1 | #ifndef _BINARY_TREE_H_
2 | #define _BINARY_TREE_H_
3 |
4 | struct Node {
5 | int data;
6 | Node* left = NULL;
7 | Node* right = NULL;
8 | };
9 |
10 | class BinaryTree {
11 | private:
12 | Node* root = NULL;
13 | public:
14 | void insert(int data);
15 | void print(void);
16 | bool isBalanced(void);
17 |
18 | };
19 |
20 | #endif
--------------------------------------------------------------------------------
/c++/binarySearchTree/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "binaryTree.h"
4 |
5 | using namespace std;
6 |
7 | int main() {
8 | cout << "Tree Depth Linked List." << endl;
9 | BinaryTree tree;
10 | tree.insert(5);
11 | tree.insert(6);
12 | tree.insert(7);
13 | tree.insert(4);
14 | tree.print();
15 | cout << tree.isBalanced() << endl;
16 | return 0;
17 | }
--------------------------------------------------------------------------------
/c++/bubbleSort.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 |
5 | using namespace std;
6 |
7 | void printVec(vector arr) {
8 | for(int i = 0; i < arr.size(); i++ ) {
9 | cout << arr[i] << " ";
10 | }
11 | cout<< endl;
12 | }
13 |
14 | void bubbleSort(vector arr) {
15 | bool changed = true;
16 | while(changed) {
17 | changed = false;
18 | for(int j = 0; j < arr.size() - 1; j++) {
19 | if(arr[j] > arr[j + 1]) {
20 | int temp = arr[j + 1];
21 | arr[j + 1] = arr[j];
22 | arr[j] = temp;
23 | changed = true;
24 | }
25 | }
26 | }
27 | printVec(arr);
28 | }
29 |
30 | int main() {
31 | cout << "bubble sort" << endl;
32 | vector arr = {6,2,4,3,7,3,12,19,-3,2,1,100,99,20,19};
33 |
34 | bubbleSort(arr);
35 | return 0;
36 | }
--------------------------------------------------------------------------------
/c++/eightQueens.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 | const int NUM_ROWS = 8;
7 | const int NUM_COLS = 8;
8 |
9 | int count = 0;
10 |
11 | bool myBoard[NUM_ROWS][NUM_COLS];
12 |
13 | void printBoard(bool board[NUM_ROWS][NUM_COLS]) {
14 | for(int row = 0; row < NUM_ROWS; row++) {
15 | for(int col = 0; col < NUM_COLS; col++) {
16 | cout << " " << board[row][col] << " ";
17 | }
18 | cout << endl;
19 | }
20 | }
21 |
22 | bool isClear(int row, int col, bool board[NUM_ROWS][NUM_COLS]) {
23 | for(int r = 0; r < NUM_ROWS; r++) {
24 | for(int c = 0; c < NUM_COLS; c++) {
25 | if(r == row && board[r][c]) {
26 | return false;
27 | }
28 | if(c == col && board[r][c]) {
29 | return false;
30 | }
31 | if(abs(row - r) == abs(col - c) && board[r][c]) {
32 | return false;
33 | }
34 | }
35 | }
36 | return true;
37 | }
38 |
39 | void eightQueens(int numQueens, bool board[NUM_ROWS][NUM_COLS]) {
40 | if(numQueens == 8) {
41 | count++;
42 | printBoard(board);
43 | cout << endl;
44 | return;
45 | }
46 | else {
47 | for(int row = numQueens; row < NUM_ROWS; row++) {
48 | for(int col = 0; col < NUM_COLS; col++) {
49 | if(isClear(row, col, board)) {
50 | bool newBoard[NUM_ROWS][NUM_COLS];
51 | for(int i = 0; i < NUM_ROWS; i++) {
52 | for (int j = 0; j < NUM_COLS; j++) {
53 | newBoard[i][j] = board[i][j];
54 | }
55 | }
56 | newBoard[row][col] = true;
57 | eightQueens(numQueens + 1, newBoard);
58 | }
59 | }
60 | }
61 | }
62 | }
63 |
64 | int main() {
65 | eightQueens(0, myBoard);
66 | cout << "Eight Queens 8x8." << endl;
67 | cout << "Number of Possible Configurations: " << count << endl;
68 |
69 | return 0;
70 | }
--------------------------------------------------------------------------------
/c++/magicIndex.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 | bool magicIndex(int index, vector a) {
7 | cout << "magicIndex(" << index << ")" <= a.size()) {
9 | cout << "MAGIC INDEX NOT FOUND." << endl;
10 | return false;
11 | }
12 | else if(a[index] == index) {
13 | cout << "MAGIC INDEX FOUND: " << index << endl;
14 | return true;
15 | }
16 | else if (a[index] > index) {
17 | magicIndex(a[index], a);
18 | }
19 | else {
20 | magicIndex(index + 1, a);
21 | }
22 | }
23 |
24 | int main() {
25 | cout << "magic index" << endl;
26 | vector sortedArr = {-12,-5,5,5,5,5,10,12,16};
27 | magicIndex(0, sortedArr);
28 |
29 | return 0;
30 | }
--------------------------------------------------------------------------------
/c++/mergeSort.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 | void printVec(vector A) {
7 | for(int i = 0; i < A.size(); i++) {
8 | cout << A[i] << " ";
9 | }
10 | cout << endl;
11 | }
12 |
13 | vector merge(vector left, vector right) {
14 | vector result;
15 | int i = 0;
16 | int j = 0;
17 | while(i < left.size() || j < right.size()) {
18 | if(i == left.size()) {
19 | result.push_back(right[j]);
20 | j++;
21 | }
22 | else if(j == right.size()) {
23 | result.push_back(left[i]);
24 | i++;
25 | }
26 | else if(left[i] < right[j]) {
27 | result.push_back(left[i]);
28 | i++;
29 | }
30 | else if(left[i] >= right[j]) {
31 | result.push_back(right[j]);
32 | j++;
33 | }
34 | }
35 | return result;
36 | }
37 |
38 | vector mergeSort(vector A) {
39 | if(A.size() <= 1) {
40 | return A;
41 | }
42 | int mid = A.size() / 2;
43 | vector left;
44 | vector right;
45 | for(int i = 0; i < A.size(); i++) {
46 | if(i < mid) {
47 | left.push_back(A[i]);
48 | }
49 | else {
50 | right.push_back(A[i]);
51 | }
52 | }
53 | left = mergeSort(left);
54 | right = mergeSort(right);
55 | return merge(left, right);
56 | }
57 |
58 | int main() {
59 | cout << "merge sort" << endl;
60 | vector v = {6,2,4,3,7,3,12,19,-3,2,1,100,0,-25,99,20,19};
61 | printVec(mergeSort(v));
62 | return 0;
63 | }
--------------------------------------------------------------------------------
/c++/permute.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 |
7 | void permute(string perm, string orig) {
8 | string noDups = orig;
9 | sort(noDups.begin(), noDups.end());
10 | noDups.erase(std::unique(noDups.begin(), noDups.end()), noDups.end());
11 | if(orig.empty()) {
12 | cout << perm << endl;
13 | }
14 | for(int i = 0; i < noDups.length(); i++) {
15 | string pStr = perm;
16 | string str = orig;
17 | pStr += noDups[i];
18 | str.erase(str.find(noDups[i]), 1);
19 | permute(pStr, str);
20 | }
21 | }
22 |
23 | void permute(string orig) {
24 | permute("", orig);
25 | }
26 |
27 | int main() {
28 | cout << "string permutations" << endl;
29 | permute("abca");
30 | return 0;
31 | }
--------------------------------------------------------------------------------
/c++/pong/main.cpp:
--------------------------------------------------------------------------------
1 | #include "pos.h"
2 | #include "paddle.h"
3 |
4 | #include
5 |
6 | using namespace std;
7 |
8 | int main() {
9 | cout << "hello pong." << endl;
10 | Paddle p(2);
11 | cout << p.getHeight() << endl;
12 | return 0;
13 | }
14 |
--------------------------------------------------------------------------------
/c++/pong/paddle.cpp:
--------------------------------------------------------------------------------
1 | #include "paddle.h"
2 |
3 | #include
4 | #include
5 |
6 | using namespace std;
7 |
8 | Paddle::Paddle() {
9 | this->height = 3;
10 | }
11 |
12 | Paddle::Paddle(int h) {
13 | this->height = abs(h);
14 | }
15 |
16 | int Paddle::getHeight() {
17 | return this->height;
18 | }
19 |
20 | // Pos Paddle::getPos() {
21 | // return this->position;
22 | // }
23 |
24 | // void Paddle::printPos() {
25 | // this->position.printCoords();
26 | // }
27 |
28 | // Pos Paddle::setPos() {
29 | // return
30 | // }
--------------------------------------------------------------------------------
/c++/pong/paddle.h:
--------------------------------------------------------------------------------
1 | #ifndef _PADDLE_H_
2 | #define _PADDLE_H_
3 |
4 | #include "pos.h"
5 |
6 | class Paddle {
7 | private:
8 | int height;
9 | Pos position;
10 | public:
11 | Paddle();
12 | Paddle(int);
13 | int getHeight();
14 | // Pos getPos();
15 | // Pos setPos();
16 | void printPos();
17 | };
18 |
19 | #endif
--------------------------------------------------------------------------------
/c++/pong/pong:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/c++/pong/pong
--------------------------------------------------------------------------------
/c++/pong/pos.cpp:
--------------------------------------------------------------------------------
1 | #include "pos.h"
2 |
3 | #include
4 |
5 | using namespace std;
6 |
7 | Pos::Pos() {
8 | this->x = 0;
9 | this->y = 0;
10 | return;
11 | }
--------------------------------------------------------------------------------
/c++/pong/pos.h:
--------------------------------------------------------------------------------
1 | #ifndef _POS_H_
2 | #define _POS_H_
3 |
4 | class Pos {
5 | private:
6 | int x;
7 | int y;
8 | public:
9 | Pos();
10 | };
11 |
12 |
13 | #endif
--------------------------------------------------------------------------------
/c++/quickSort.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 | void printVec(vector arr) {
7 | for(int i = 0; i < arr.size(); i++ ) {
8 | cout << arr[i] << " ";
9 | }
10 | cout<< endl;
11 | }
12 |
13 | vector quickSort(vector A) {
14 | if(A.size() <= 1) {
15 | return A;
16 | }
17 | int pivot = A.back();
18 | A.pop_back();
19 | vector left;
20 | vector right;
21 | for(int i = 0; i < A.size(); i ++) {
22 | if(A[i] < pivot) {
23 | left.push_back(A[i]);
24 | }
25 | else if(A[i] >= pivot) {
26 | right.push_back(A[i]);
27 | }
28 | }
29 | left = quickSort(left);
30 | right = quickSort(right);
31 | left.push_back(pivot);
32 | left.insert(left.end(), right.begin(), right.end());
33 | return left;
34 | }
35 |
36 | int main() {
37 | cout << "quick sort" << endl;
38 | vector v = {10,12,64,1,-12,3,5,9,7,5,3,0,100,10,99,3};
39 | printVec(v);
40 | printVec(quickSort(v));
41 |
42 | return 0;
43 | }
--------------------------------------------------------------------------------
/c++/rotateGrid.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | using namespace std;
4 |
5 | const int NUM_ROWS = 5;
6 | const int NUM_COLS = 5;
7 |
8 | void printGrid(int grid[NUM_ROWS][NUM_COLS]) {
9 | for(int row = 0; row < NUM_ROWS; row++) {
10 | for(int col = 0; col < NUM_COLS; col++) {
11 | cout << " " << grid[row][col] << " ";
12 | }
13 | cout << endl;
14 | }
15 | }
16 |
17 | void rotateGrid(int grid[NUM_ROWS][NUM_COLS]) {
18 | printGrid(grid);
19 | int rotatedGrid[NUM_ROWS][NUM_COLS];
20 | for(int row = 0; row < NUM_ROWS; row++) {
21 | for(int col = 0; col < NUM_COLS; col++) {
22 | rotatedGrid[col][NUM_ROWS - 1 - row] = grid[row][col];
23 | }
24 | cout << endl;
25 | }
26 | printGrid(rotatedGrid);
27 | }
28 |
29 | int main() {
30 | cout << "Rotate Grid 90 degrees" << endl;
31 | int grid[NUM_ROWS][NUM_COLS] = {{1,2,3,4,5},
32 | {6,7,8,9,10},
33 | {11,12,13,14,15},
34 | {16,17,18,19,20},
35 | {21,22,23,24,25}};
36 | rotateGrid(grid);
37 | return 0;
38 | }
--------------------------------------------------------------------------------
/c++/setOfStacks.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | using namespace std;
6 |
7 | class setOfStacks {
8 | private:
9 | vector*> stacks;
10 | public:
11 | setOfStacks(void);
12 | void push(int item);
13 | int pop(void);
14 | int popStack(int num);
15 | };
16 |
17 | setOfStacks::setOfStacks(void) {
18 | cout << "constructing" << endl;
19 | cout << "new stack" << endl;
20 | stack* s = new stack;
21 | stacks.push_back(s);
22 | }
23 |
24 | void setOfStacks::push(int item) {
25 | stack* s = stacks.back();
26 | if(s->size() < 3) {
27 | s->push(item);
28 | }
29 | else {
30 | cout << "new stack" << endl;
31 | stacks.push_back(new stack);
32 | s = stacks.back();
33 | s->push(item);
34 | }
35 | cout << "push " << item << endl;
36 | }
37 |
38 | int setOfStacks::pop(void) {
39 | stack* s = stacks.back();
40 | int item = s->top();
41 | s->pop();
42 | if(s->empty()) {
43 | cout << "deleting stack" << endl;
44 | delete s;
45 | stacks.pop_back();
46 | }
47 | cout << "pop " << item << endl;
48 | return item;
49 | }
50 |
51 | int setOfStacks::popStack(int num) {
52 | stack* s = stacks[num];
53 | int item = s->top();
54 | s->pop();
55 | if(s->empty()) {
56 | delete s;
57 | stacks.erase(stacks.begin() + num);
58 | }
59 | cout << "targeted pop " << item << endl;
60 | return item;
61 | }
62 |
63 | int main() {
64 | setOfStacks myStacks;
65 | myStacks.push(1);
66 | myStacks.push(2);
67 | myStacks.push(3);
68 | myStacks.push(4);
69 | myStacks.push(5);
70 | myStacks.push(6);
71 | myStacks.push(7);
72 | myStacks.push(8);
73 | myStacks.push(9);
74 | myStacks.popStack(1);
75 | myStacks.popStack(1);
76 | myStacks.popStack(1);
77 | myStacks.pop();
78 | myStacks.pop();
79 | myStacks.pop();
80 | myStacks.pop();
81 | myStacks.pop();
82 | myStacks.pop();
83 | return 0;
84 | }
--------------------------------------------------------------------------------
/c++/sortStack.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | using namespace std;
5 |
6 |
7 | class SortStack {
8 | private:
9 | stack s;
10 | public:
11 | void push(int item);
12 | int pop(void);
13 | };
14 |
15 | void SortStack::push(int item) {
16 | if(!s.empty()) {
17 | stack temp;
18 | while(s.top() < item) {
19 | temp.push(s.top());
20 | s.pop();
21 | if (s.empty()) {
22 | break;
23 | }
24 | }
25 | s.push(item);
26 | while(!temp.empty()) {
27 | s.push(temp.top());
28 | temp.pop();
29 | }
30 | }
31 | else {
32 | s.push(item);
33 | }
34 | }
35 |
36 | int SortStack::pop(void) {
37 | int item = s.top();
38 | cout << "pop " << item << endl;
39 | s.pop();
40 | return item;
41 | }
42 |
43 | int main () {
44 | cout << "hello" << endl;
45 | SortStack myStack;
46 | myStack.push(5);
47 | myStack.push(7);
48 | myStack.push(4);
49 | myStack.push(3);
50 | myStack.push(10);
51 | myStack.push(9);
52 | myStack.push(1);
53 | myStack.push(2);
54 | myStack.push(6);
55 | myStack.push(8);
56 | myStack.pop();
57 | myStack.pop();
58 | myStack.pop();
59 | myStack.pop();
60 | myStack.pop();
61 | myStack.pop();
62 | myStack.pop();
63 | myStack.pop();
64 | myStack.pop();
65 | myStack.pop();
66 |
67 |
68 | }
--------------------------------------------------------------------------------
/c++/stringCompress.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | using namespace std;
4 |
5 | const string shorter = "abbcccddddcccbbabaa";
6 | const string longer = "abcdeef";
7 |
8 |
9 | string stringCompress(string s) {
10 | string compr = "";
11 | int i = 0;
12 | char c = 0;
13 | for(int i = 0; i < s.size();) {
14 | c = s[i];
15 | int counter= 0;
16 | for(i; i < s.size() && s[i] == c; i++) {
17 | counter++;
18 | }
19 | compr += c + to_string(counter);
20 | }
21 | if(compr.size() < s.size()) {
22 | return compr;
23 | }
24 | else {
25 | return s;
26 | }
27 | }
28 |
29 | int main() {
30 | cout << "string compress" << endl;
31 | cout << shorter << endl;
32 | cout << stringCompress(shorter) << endl;
33 | cout << longer << endl;
34 | cout << stringCompress(longer) << endl;
35 |
36 | return 0;
37 | }
--------------------------------------------------------------------------------
/c++/tripleStack/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/c++/tripleStack/.DS_Store
--------------------------------------------------------------------------------
/c++/tripleStack/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "tripleStack.h"
3 |
4 | using namespace std;
5 |
6 | int main () {
7 | cout << "Triple Stack in Array." << endl;
8 | TripleStack stack;
9 | stack.print();
10 | stack.pushA(10);
11 | stack.pushB(20);
12 | stack.pushC(30);
13 | stack.pushA(11);
14 | stack.pushB(21);
15 | stack.pushC(31);
16 | stack.print();
17 | stack.popA();
18 | stack.popB();
19 | stack.popC();
20 | stack.pushA(12);
21 | stack.pushB(22);
22 | stack.pushC(32);
23 | stack.print();
24 | return 0;
25 | }
--------------------------------------------------------------------------------
/c++/tripleStack/tripleStack.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include "tripleStack.h"
3 |
4 | using namespace std;
5 |
6 | void TripleStack::print() {
7 | for(int i = 0; i < 20; i++) {
8 | cout << arr[i] << " ";
9 | }
10 | cout << endl;
11 | }
12 |
13 | void TripleStack::pushA(int item) {
14 | *a = item;
15 | a += 3;
16 | }
17 |
18 | int TripleStack::popA() {
19 | a -= 3;
20 | return *a;
21 | }
22 |
23 | void TripleStack::pushB(int item) {
24 | *b = item;
25 | b += 3;
26 | }
27 |
28 | int TripleStack::popB() {
29 | b -= 3;
30 | return *b;
31 | }
32 |
33 | void TripleStack::pushC(int item) {
34 | *c = item;
35 | c += 3;
36 | }
37 |
38 | int TripleStack::popC() {
39 | c -= 3;
40 | return *c;
41 | }
--------------------------------------------------------------------------------
/c++/tripleStack/tripleStack.h:
--------------------------------------------------------------------------------
1 | #ifndef _TRIPLESTACK_H_INCLUDED_
2 | #define _TRIPLESTACK_H_INCLUDED_
3 |
4 | class TripleStack {
5 | private:
6 | int arr[20];
7 | int* a = &arr[0];
8 | int* b = &arr[1];
9 | int* c = &arr[2];
10 | public:
11 | void print();
12 | void pushA(int item);
13 | void pushB(int item);
14 | void pushC(int item);
15 | int popA();
16 | int popB();
17 | int popC();
18 |
19 | };
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | #endif
--------------------------------------------------------------------------------
/christine.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/christine.txt
--------------------------------------------------------------------------------
/codeJam/allYourBase.py:
--------------------------------------------------------------------------------
1 | from collections import OrderedDict
2 |
3 | def allBase(s):
4 | symbols = list(OrderedDict.fromkeys(s))
5 | base = len(symbols)
6 | values = [i for i in range(0, base)]
7 | values[0], values[1] = values[1], values[0]
8 | d = dict(zip(symbols, values))
9 | ans = [str(d[c]) for c in s]
10 | ans = ''.join(ans)
11 | return int(ans, base)
12 |
13 | print allBase('11001001')
14 | print allBase('cats')
15 | print allBase('zig')
--------------------------------------------------------------------------------
/codeJam/coinJam/C-large.in:
--------------------------------------------------------------------------------
1 | 1
2 | 32 500
3 |
--------------------------------------------------------------------------------
/codeJam/coinJam/C-small-attempt0.in:
--------------------------------------------------------------------------------
1 | 1
2 | 16 50
3 |
--------------------------------------------------------------------------------
/codeJam/coinJam/jamCoin.py:
--------------------------------------------------------------------------------
1 | import math
2 | import sys
3 |
4 | def jamCoin(inp):
5 | n = int(inp[0])
6 | j = int(inp[1])
7 | coins = getCoins(n)
8 | validCoins = {}
9 | for coin in coins:
10 | divisors = []
11 | for base in range(2, 11):
12 | num = int(coin, base)
13 | div = getDivisor(num)
14 | if div is not None:
15 | divisors.append(str(div))
16 | else:
17 | break
18 | if len(divisors) == 9:
19 | validCoins[str(coin)] = divisors
20 | if len(validCoins) == j:
21 | return validCoins
22 |
23 | def formatSol(validCoins):
24 | ans = ""
25 | for c in validCoins.keys():
26 | ans += c + ' '
27 | ans += ' '.join(validCoins[c]) + '\n'
28 | return ans
29 |
30 |
31 | def getCoins(n):
32 | bits = '0' + str(n - 2) + 'b'
33 | return ['1' + format(i, bits) + '1' for i in range(0, 2**(n - 2))]
34 |
35 | def getDivisor(n):
36 | if n == 2 or n == 3:
37 | return None
38 | if n % 2 == 0:
39 | return 2
40 | h = int(math.ceil(math.sqrt(n)))
41 | for i in range(2, h):
42 | if n % i == 0:
43 | return i
44 | return None
45 |
46 | with open(sys.argv[2]) as inf:
47 | lines = inf.readlines()
48 | lines = [l.strip('\n') for l in lines]
49 | lines = [l.split(' ') for l in lines]
50 |
51 | outName = sys.argv[1] + "Output.txt"
52 | ouf = open(outName, 'w')
53 | for i in range(1, int(lines[0][0]) + 1):
54 | ouf.write("Case" + " #" + str(i) + ":\n" + formatSol(jamCoin(tuple(lines[i]))))
--------------------------------------------------------------------------------
/codeJam/coinJam/largeOutput.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/codeJam/coinJam/largeOutput.txt
--------------------------------------------------------------------------------
/codeJam/coinJam/smallOutput.txt:
--------------------------------------------------------------------------------
1 | Case #1:
2 | 1000000001011101 17 2 3 2 1297 2 11 2 3
3 | 1000000000101011 3 7 13 3 5 43 3 73 7
4 | 1000000001101101 3 2 3 2 7 2 3 2 3
5 | 1000000001110011 3 2 3 2 7 2 3 2 3
6 | 1000000010011001 7 1667 179 13 5 11 23 7 311
7 | 1000000001010111 5 2 3 2 37 2 5 2 3
8 | 1000000001100111 3 2 3 2 7 2 3 2 3
9 | 1000000001100011 23 19 11 105491 5 47 11117 1787 127
10 | 1000000010110011 47 2 3 2 11 2 204311 2 3
11 | 1000000010010111 3 2 3 2 7 2 3 2 3
12 | 1000000001101011 5 2 3 2 37 2 5 2 3
13 | 1000000010010001 3 2 5 2 7 2 3 2 7
14 | 1000000000011011 5 1567 15559 6197 5 5 1031 7 83
15 | 1000000000111101 3 2 3 2 7 2 3 2 3
16 | 1000000010101001 3 5 13 3 5 43 3 73 7
17 | 1000000000010011 3 2 5 2 7 2 3 2 7
18 | 1000000010000011 167 2 11 2 58427 2 23 2 839
19 | 1000000000110101 23 17 11 23 5 299699 43 239 59
20 | 1000000000000101 13 11 3 4751 173 3 53 109 3
21 | 1000000001001111 3 2 3 2 7 2 3 2 3
22 | 1000000000110001 3 2 5 2 7 2 3 2 11
23 | 1000000001011001 11 5 281 101 5 67 5 13 19
24 | 1000000000000001 3 2 5 2 7 2 3 2 7
25 | 1000000010000101 3 2 5 2 7 2 3 2 11
26 | 1000000010100111 5 2 3 2 37 2 5 2 3
27 | 1000000001111011 31 557 7 19 23 1129 7 5441 241
28 | 1000000010100011 3 1259 421 3 5 8893 3 67 17
29 | 1000000010011011 11 2 3 2 13 2 47 2 3
30 | 1000000010001001 5 2 7 2 1933 2 29 2 157
31 | 1000000001010101 3 7 13 3 5 17 3 53 7
32 | 1000000001110101 5 2 3 2 37 2 5 2 3
33 | 1000000000100101 3 2 5 2 7 2 3 2 7
34 | 1000000001111111 3 2 5 2 7 2 3 2 7
35 | 1000000001100001 3 2 5 2 7 2 3 2 11
36 | 1000000010011101 3 2 3 2 7 2 3 2 3
37 | 1000000001000011 3 2 5 2 7 2 3 2 11
38 | 1000000010110101 3 2 3 2 7 2 3 2 3
39 | 1000000000101111 5 2 3 2 37 2 5 2 3
40 | 1000000000011111 3 2 3 2 7 2 3 2 3
41 | 1000000000111011 17 2 3 2 73 2 17 2 3
42 | 1000000000001001 73 5 3 19 19 3 5 19 3
43 | 1000000000011001 3 2 5 2 7 2 3 2 11
44 | 1000000000001101 3 2 5 2 7 2 3 2 11
45 | 1000000000110111 3 2 3 2 7 2 3 2 3
46 | 1000000000000111 3 2 5 2 7 2 3 2 11
47 | 1000000001111101 7 19 43 17 55987 23 7 7 31
48 | 1000000001011011 3 2 3 2 7 2 3 2 3
49 | 1000000001001001 3 2 5 2 7 2 3 2 7
50 | 1000000001111001 3 2 3 2 7 2 3 2 3
51 | 1000000001011111 59 113 7 157 19 1399 7 43 107
52 |
--------------------------------------------------------------------------------
/codeJam/countingSheep/A-large.in:
--------------------------------------------------------------------------------
1 | 100
2 | 0
3 | 1
4 | 2
5 | 11
6 | 1692
7 | 163444
8 | 206929
9 | 459923
10 | 691520
11 | 40
12 | 999993
13 | 612112
14 | 908502
15 | 241453
16 | 926904
17 | 567583
18 | 718525
19 | 994798
20 | 999992
21 | 930033
22 | 25
23 | 1250
24 | 9
25 | 91633
26 | 200917
27 | 5
28 | 7
29 | 4
30 | 999999
31 | 591085
32 | 769864
33 | 71189
34 | 166
35 | 476216
36 | 933652
37 | 609465
38 | 859561
39 | 151411
40 | 58908
41 | 842361
42 | 12500
43 | 323139
44 | 999991
45 | 125
46 | 936133
47 | 51830
48 | 482657
49 | 20
50 | 116539
51 | 34
52 | 864874
53 | 832128
54 | 999995
55 | 369944
56 | 999996
57 | 984828
58 | 8
59 | 316091
60 | 125000
61 | 963821
62 | 3
63 | 900468
64 | 124
65 | 938493
66 | 479210
67 | 594362
68 | 943739
69 | 109175
70 | 210398
71 | 558587
72 | 61739
73 | 1000000
74 | 442303
75 | 838365
76 | 404663
77 | 139873
78 | 999994
79 | 622115
80 | 6665
81 | 200
82 | 434677
83 | 794175
84 | 959320
85 | 446431
86 | 270963
87 | 249267
88 | 328146
89 | 438600
90 | 685319
91 | 790765
92 | 999997
93 | 382063
94 | 521535
95 | 570226
96 | 555254
97 | 365801
98 | 406629
99 | 10
100 | 999998
101 | 6
102 |
--------------------------------------------------------------------------------
/codeJam/countingSheep/A-small-attempt0.in:
--------------------------------------------------------------------------------
1 | 100
2 | 0
3 | 1
4 | 2
5 | 11
6 | 96
7 | 57
8 | 4
9 | 123
10 | 7
11 | 86
12 | 36
13 | 107
14 | 152
15 | 184
16 | 173
17 | 44
18 | 29
19 | 45
20 | 14
21 | 154
22 | 37
23 | 5
24 | 195
25 | 26
26 | 105
27 | 141
28 | 180
29 | 175
30 | 178
31 | 122
32 | 115
33 | 9
34 | 140
35 | 25
36 | 167
37 | 110
38 | 199
39 | 6
40 | 71
41 | 177
42 | 8
43 | 31
44 | 3
45 | 194
46 | 133
47 | 73
48 | 103
49 | 190
50 | 198
51 | 124
52 | 104
53 | 200
54 | 109
55 | 52
56 | 34
57 | 20
58 | 174
59 | 17
60 | 66
61 | 166
62 | 38
63 | 155
64 | 142
65 | 10
66 | 50
67 | 160
68 | 145
69 | 35
70 | 55
71 | 111
72 | 137
73 | 89
74 | 90
75 | 23
76 | 164
77 | 188
78 | 91
79 | 132
80 | 125
81 | 40
82 | 172
83 | 60
84 | 121
85 | 42
86 | 181
87 | 129
88 | 147
89 | 92
90 | 144
91 | 67
92 | 16
93 | 101
94 | 130
95 | 128
96 | 135
97 | 117
98 | 146
99 | 187
100 | 162
101 | 76
102 |
--------------------------------------------------------------------------------
/codeJam/countingSheep/countingSheep.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | def countSheep(n):
4 | if n == 0:
5 | return 'INSOMNIA'
6 | seen = set()
7 | i = 1
8 | while len(seen) < 10:
9 | num = str(i * n)
10 | seen.update([char for char in num])
11 | i += 1
12 | if len(seen) == 10:
13 | return int(num)
14 |
15 | with open(sys.argv[2]) as inf:
16 | lines = inf.readlines()
17 | lines = [l.strip('\n') for l in lines]
18 |
19 | outName = sys.argv[1] + "Output.txt"
20 | ouf = open(outName, 'w')
21 | for i in range(1, int(lines[0]) + 1):
22 | ouf.write("Case" + " #" + str(i) + ": " + str(countSheep(int(lines[i]))) + "\n")
--------------------------------------------------------------------------------
/codeJam/countingSheep/largeOutput.txt:
--------------------------------------------------------------------------------
1 | Case #1: INSOMNIA
2 | Case #2: 10
3 | Case #3: 90
4 | Case #4: 110
5 | Case #5: 5076
6 | Case #6: 653776
7 | Case #7: 620787
8 | Case #8: 4139307
9 | Case #9: 2074560
10 | Case #10: 920
11 | Case #11: 9999930
12 | Case #12: 4896896
13 | Case #13: 3634008
14 | Case #14: 724359
15 | Case #15: 2780712
16 | Case #16: 1702749
17 | Case #17: 3592625
18 | Case #18: 4973990
19 | Case #19: 5999952
20 | Case #20: 4650165
21 | Case #21: 900
22 | Case #22: 90000
23 | Case #23: 90
24 | Case #24: 733064
25 | Case #25: 602751
26 | Case #26: 90
27 | Case #27: 70
28 | Case #28: 92
29 | Case #29: 9999990
30 | Case #30: 2364340
31 | Case #31: 2309592
32 | Case #32: 640701
33 | Case #33: 5478
34 | Case #34: 1904864
35 | Case #35: 1867304
36 | Case #36: 2437860
37 | Case #37: 4297805
38 | Case #38: 908466
39 | Case #39: 235632
40 | Case #40: 3369444
41 | Case #41: 900000
42 | Case #42: 2908251
43 | Case #43: 9999910
44 | Case #44: 9000
45 | Case #45: 3744532
46 | Case #46: 207320
47 | Case #47: 1930628
48 | Case #48: 900
49 | Case #49: 349617
50 | Case #50: 918
51 | Case #51: 4324370
52 | Case #52: 4992768
53 | Case #53: 6999965
54 | Case #54: 2589608
55 | Case #55: 5999976
56 | Case #56: 6893796
57 | Case #57: 96
58 | Case #58: 1580455
59 | Case #59: 9000000
60 | Case #60: 4819105
61 | Case #61: 30
62 | Case #62: 4502340
63 | Case #63: 2356
64 | Case #64: 5630958
65 | Case #65: 1437630
66 | Case #66: 1783086
67 | Case #67: 6606173
68 | Case #68: 436700
69 | Case #69: 841592
70 | Case #70: 3910109
71 | Case #71: 308695
72 | Case #72: 9000000
73 | Case #73: 2211515
74 | Case #74: 3353460
75 | Case #75: 2427978
76 | Case #76: 1398730
77 | Case #77: 5999964
78 | Case #78: 3732690
79 | Case #79: 73315
80 | Case #80: 9000
81 | Case #81: 2173385
82 | Case #82: 3176700
83 | Case #83: 2877960
84 | Case #84: 3125017
85 | Case #85: 812889
86 | Case #86: 747801
87 | Case #87: 1640730
88 | Case #88: 2193000
89 | Case #89: 2741276
90 | Case #90: 4744590
91 | Case #91: 9999970
92 | Case #92: 1528252
93 | Case #93: 3129210
94 | Case #94: 2851130
95 | Case #95: 4997286
96 | Case #96: 1097403
97 | Case #97: 1219887
98 | Case #98: 90
99 | Case #99: 7999984
100 | Case #100: 90
101 |
--------------------------------------------------------------------------------
/codeJam/countingSheep/smallOutput.txt:
--------------------------------------------------------------------------------
1 | Case #1: INSOMNIA
2 | Case #2: 10
3 | Case #3: 90
4 | Case #4: 110
5 | Case #5: 576
6 | Case #6: 570
7 | Case #7: 92
8 | Case #8: 1107
9 | Case #9: 70
10 | Case #10: 946
11 | Case #11: 396
12 | Case #12: 749
13 | Case #13: 912
14 | Case #14: 920
15 | Case #15: 1038
16 | Case #16: 396
17 | Case #17: 203
18 | Case #18: 360
19 | Case #19: 238
20 | Case #20: 924
21 | Case #21: 370
22 | Case #22: 90
23 | Case #23: 2145
24 | Case #24: 390
25 | Case #25: 945
26 | Case #26: 987
27 | Case #27: 900
28 | Case #28: 2625
29 | Case #29: 890
30 | Case #30: 976
31 | Case #31: 805
32 | Case #32: 90
33 | Case #33: 2380
34 | Case #34: 900
35 | Case #35: 1169
36 | Case #36: 990
37 | Case #37: 1990
38 | Case #38: 90
39 | Case #39: 710
40 | Case #40: 1239
41 | Case #41: 96
42 | Case #42: 310
43 | Case #43: 30
44 | Case #44: 970
45 | Case #45: 1064
46 | Case #46: 730
47 | Case #47: 721
48 | Case #48: 1520
49 | Case #49: 990
50 | Case #50: 2356
51 | Case #51: 936
52 | Case #52: 9000
53 | Case #53: 545
54 | Case #54: 936
55 | Case #55: 918
56 | Case #56: 900
57 | Case #57: 870
58 | Case #58: 119
59 | Case #59: 726
60 | Case #60: 5478
61 | Case #61: 190
62 | Case #62: 1085
63 | Case #63: 1136
64 | Case #64: 90
65 | Case #65: 900
66 | Case #66: 2560
67 | Case #67: 1160
68 | Case #68: 560
69 | Case #69: 495
70 | Case #70: 1110
71 | Case #71: 1096
72 | Case #72: 801
73 | Case #73: 450
74 | Case #74: 207
75 | Case #75: 1476
76 | Case #76: 940
77 | Case #77: 910
78 | Case #78: 792
79 | Case #79: 9000
80 | Case #80: 920
81 | Case #81: 1892
82 | Case #82: 900
83 | Case #83: 968
84 | Case #84: 378
85 | Case #85: 905
86 | Case #86: 903
87 | Case #87: 1176
88 | Case #88: 552
89 | Case #89: 1296
90 | Case #90: 469
91 | Case #91: 256
92 | Case #92: 909
93 | Case #93: 1040
94 | Case #94: 896
95 | Case #95: 945
96 | Case #96: 819
97 | Case #97: 730
98 | Case #98: 1309
99 | Case #99: 1458
100 | Case #100: 912
101 |
--------------------------------------------------------------------------------
/codeJam/fileFix/fileFix.py:
--------------------------------------------------------------------------------
1 | # O(n^2 * l) runtime, where l is the length of the longest path
2 | def countMakes(existing, new):
3 | if not existing:
4 | existing = {''}
5 | existing = {path + '/' for path in existing}
6 | new = {path + '/' for path in new}
7 | count = 0
8 | for newDir in new:
9 | diffs = [matchDir(newDir, newDir) - matchDir(newDir, d) for d in existing]
10 | count += min(diffs)
11 | existing.add(newDir)
12 | return count
13 |
14 | def matchDir(a, b):
15 | if len(a) < len(b):
16 | length = len(a)
17 | else:
18 | length = len(b)
19 | count = 0
20 | for i in range(1, length):
21 | if a[i] != b[i]:
22 | break
23 | if a[i] == '/':
24 | count += 1
25 | return count
26 |
27 | # O(n) runtime, where n is the the number total dirs given as input (not paths)
28 | # or O(nl) where l is the length max length of dir names
29 | def countMakesFast(existing, new):
30 | dirs = {}
31 | count = 0
32 | for e in existing:
33 | addDir(dirs, e)
34 | for n in new:
35 | count += addDir(dirs, n)
36 | return count
37 |
38 | def addDir(dirs, new):
39 | new = new.split('/')
40 | new = new[1:]
41 | count = 0
42 | for nDir in new:
43 | if nDir in dirs:
44 | dirs = dirs[nDir]
45 | else:
46 | dirs[nDir] = {}
47 | dirs = dirs[nDir]
48 | count += 1
49 | return count
50 |
51 | e = {'/a'}
52 | n = {'/a/b', '/a/c', '/b/b'}
53 | print countMakesFast(e, n)
54 | e = {}
55 | n = {'/home/gcj/finals', '/home/gcj/quals'}
56 | print countMakesFast(e, n)
57 |
58 |
59 |
--------------------------------------------------------------------------------
/codeJam/fractiles/D-small-attempt0.in:
--------------------------------------------------------------------------------
1 | 100
2 | 2 3 2
3 | 1 1 1
4 | 2 1 2
5 | 3 2 3
6 | 65 5 65
7 | 28 10 28
8 | 19 12 19
9 | 100 9 100
10 | 7 11 7
11 | 86 7 86
12 | 3 3 3
13 | 1 18 1
14 | 100 3 100
15 | 67 2 67
16 | 80 8 80
17 | 100 2 100
18 | 20 8 20
19 | 20 6 20
20 | 79 5 79
21 | 4 20 4
22 | 2 4 2
23 | 4 2 4
24 | 12 1 12
25 | 60 10 60
26 | 67 1 67
27 | 1 27 1
28 | 4 3 4
29 | 66 2 66
30 | 81 9 81
31 | 4 18 4
32 | 4 4 4
33 | 3 37 3
34 | 1 92 1
35 | 78 7 78
36 | 100 4 100
37 | 76 1 76
38 | 1 3 1
39 | 53 2 53
40 | 90 6 90
41 | 61 7 61
42 | 97 3 97
43 | 22 8 22
44 | 4 1 4
45 | 14 7 14
46 | 2 15 2
47 | 87 2 87
48 | 39 4 39
49 | 10 18 10
50 | 11 7 11
51 | 2 2 2
52 | 17 2 17
53 | 6 10 6
54 | 21 8 21
55 | 60 3 60
56 | 75 1 75
57 | 12 16 12
58 | 57 1 57
59 | 10 4 10
60 | 60 1 60
61 | 100 1 100
62 | 54 7 54
63 | 39 8 39
64 | 2 56 2
65 | 10 5 10
66 | 58 6 58
67 | 1 11 1
68 | 9 13 9
69 | 55 8 55
70 | 43 3 43
71 | 70 5 70
72 | 75 5 75
73 | 71 4 71
74 | 31 11 31
75 | 92 1 92
76 | 70 8 70
77 | 36 5 36
78 | 4 29 4
79 | 3 11 3
80 | 1 100 1
81 | 23 12 23
82 | 1 46 1
83 | 1 2 1
84 | 16 1 16
85 | 12 2 12
86 | 4 11 4
87 | 4 13 4
88 | 46 8 46
89 | 46 7 46
90 | 21 9 21
91 | 1 4 1
92 | 2 22 2
93 | 2 59 2
94 | 50 5 50
95 | 25 12 25
96 | 31 10 31
97 | 3 4 3
98 | 3 1 3
99 | 1 9 1
100 | 35 4 35
101 | 48 4 48
102 |
--------------------------------------------------------------------------------
/codeJam/fractiles/fractiles.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import itertools
3 |
4 | def findGold(inp):
5 | k = int(inp[0])
6 | c = int(inp[1])
7 | s = int(inp[2])
8 | origins = list(itertools.product('LG', repeat = k))
9 | fractals = [buildFractal(''.join(f), c) for f in origins]
10 | result = choosePos(fractals, s, -1, [])
11 | if result is None:
12 | return 'IMPOSSIBLE'
13 | else:
14 | result = [str(i + 1) for i in result]
15 | return ' '.join(result)
16 |
17 | def choosePos(fractals, s, last, ans):
18 | if s == 0:
19 | return None
20 | l = len(fractals[0])
21 | positions = {}
22 | for i in range(last + 1, l):
23 | if i in ans:
24 | continue
25 | newFractals = [f for f in fractals if f[i] != 'G']
26 | positions[i] = newFractals
27 | if len(newFractals) < 2:
28 | ans.append(i)
29 | return ans
30 | i = getSmallestKey(positions)
31 | ans.append(i)
32 | result = choosePos(positions[i], s - 1, i, ans)
33 | if result is not None:
34 | return result
35 | return None
36 |
37 | def getSmallestKey(d):
38 | smallestK = -1
39 | smallest = -1
40 | for k in d.keys():
41 | if smallest == -1:
42 | smallestK = k
43 | smallest = len(d[k])
44 | elif len(d[k]) < smallest:
45 | smallestK = k
46 | smallest = len(d[k])
47 | return smallestK
48 |
49 | def buildFractal(frac, c):
50 | k = len(frac)
51 | ans = frac
52 | for i in range(1, c):
53 | newAns = ""
54 | for char in ans:
55 | if char == 'L':
56 | newAns += frac
57 | else:
58 | newAns += ''.join(['G' for _ in range(0, k)])
59 | ans = newAns
60 | return ans
61 |
62 | print findGold((65,5,65))
63 |
64 | # with open(sys.argv[2]) as inf:
65 | # lines = inf.readlines()
66 | # lines = [l.strip('\n') for l in lines]
67 | # lines = [l.split(' ') for l in lines]
68 |
69 | # outName = sys.argv[1] + "Output.txt"
70 | # ouf = open(outName, 'w')
71 | # for i in range(1, int(lines[0][0]) + 1):
72 | # ouf.write("Case" + " #" + str(i) + ": " + findGold(tuple(lines[i])) + '\n')
--------------------------------------------------------------------------------
/codeJam/fractiles/smallOutput.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/codeJam/fractiles/smallOutput.txt
--------------------------------------------------------------------------------
/codeJam/fractiles/test.in:
--------------------------------------------------------------------------------
1 | 5
2 | 2 3 2
3 | 1 1 1
4 | 2 1 1
5 | 2 1 2
6 | 3 2 3
--------------------------------------------------------------------------------
/codeJam/fractiles/testOutput.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/codeJam/fractiles/testOutput.txt
--------------------------------------------------------------------------------
/codeJam/pancakeRevenge/B-large.in:
--------------------------------------------------------------------------------
1 | 100
2 | -
3 | -+
4 | +-
5 | +++
6 | --+-
7 | +++-+--++---+---+++-+---+-++---+--++----+-+------+--+--++--++-+--+-++-+++---+++---+--+--++---++-+++-
8 | +--------------------------------------------------------------------------------------------------+
9 | +--+---+++++-+--------++-----+--+-+-----+++-+--+----+---++++++-+-+-+---++++--++--+--+---+----+-----+
10 | -+-
11 | ++++++--+-+---+-++-+-----+-+-++++---++-+++---+-+-++-+---++--+++-+++++-+++--++-+-+--+--++-++-+++-----
12 | ---+++++----+++-+-+-++++++----++++---++--+-++++-+---+--+-++++---+---++++--++--++-++++--------+-+-+--
13 | --+-++--++++-+-+--++++--+-+++-++-++++++++-+----+-+--+----+++--++--+++-++++--++---+----++++-+++-++--+
14 | ++---+++-++----+-+-++++-+-----++-+--+++-+++++-+-+-----++--++---+++----+---+-++----+++-+++-++-+-+-+--
15 | -+++--+++++------+++--++-----++---+----++--+-
16 | +--------+
17 | ++++--++++--+-+++---+-+---+---+--++++--++-++------++++---++-+++--++--++----+----++---+-+-+----++++-+
18 | ++-+-+---+-+-++-+++-++++-++++-+---+--+--+-++-+-+-+-++-+-+----++++-++++--+-+----+----++++--+-+--+----
19 | --++-----+-----+-----+---++--++++-+--++--+++++-++++-+++--+--+++-------++-+++--++-+---
20 | ----+-++-+-+--------+---+-+++-+-----++--++--+---+--+-+-++--++-+--+++--+-++--+-+-+-+++++++---+--++---
21 | ++-+++---+-+--++--------+-++---++-----++-+-+--++-++-++--++--+++--+-+++---+++-----++-+++---++--++-+--
22 | +-+-+-+-+-
23 | ---
24 | +--+--+---++--++-++-+-++++++++-+---++-+++++----++--+-++--+-++-+--+---+-+--
25 | --+-+-+++--+-++-+-+++-+++-++-+-+---------+----++-++-++-++-+--++++-+---+----+--+++--+-++-+--+--+--+--
26 | -+-+++-----++----++-++++--++--+++--++---+--+-------+--++-++--+-++
27 | -+--+++++-++---+-++-++-+-+---+--+-+++---++---++----++--++--+----+---+-+----+--++---+++-------+-+++++
28 | ----+--+++-++++---+--+++++--+--++-+------+-++-++-+-++-----+--------+++++-++-++---+++-+--+-+-++++---+
29 | -++-+++++++----+---+++++-----+---++++--+-----++++++-++++++----+------++--+--++-+--------------+-+++-
30 | ++-+---+++++--++-++-++++-++--+-+--+-++-+-+++-+++++++-+++-+--+++-+++-----++-+----+++-----+--+-+--++++
31 | -++++++++-
32 | +--+-+++++++-++-----+-+--+---+-+++------+++---+-++-+-++-+++++-+---+-++-+++--++-++++---+++----++-++-+
33 | -++
34 | -++++--+-++++-++--++--+-+++-+-+--++++-+----+++++--+++-+-++++++
35 | ---+-+--+-++--+-++++-+-++-+++-+-+-+--+-++---+-+---+-+-------++++---+-+-++++++---++-++---++++++-+-++-
36 | ---++++-+-+-+-+++-+---+-------+++----+--++++---++--+--+++-+--++++--+++-
37 | +++++-++--+--+---+---+-+--+++-++-+--+---+-+----++++-+-++++--+-++++-++++--+----+--++------++++-+++-+-
38 | --++++-+++++----++-+++-+-----++++--+--+++----+-++-++++-+----++-+++--+----+++-+-++++-+++-++-++---+++-
39 | +-+
40 | --+-++-+---++--+--++++--++----+--++++-+-+++-+---++---++---+
41 | ---+++--++-+----+---+-++++++++----++-++--++-++-+++-+--++---+----+-++++--+++-+++-++---++--+---+++---+
42 | --+
43 | +++++--++++-+---+--+-+++-----++--------+--+-+-++-+++----++-++-+----+-+-+
44 | +--++-+-+-+++--+-++++++-+--+-+-+-+---+-+++++--+-+-+---++-+-+-+-+-+++-+--++-+-+-+-+-+---+-+-+-++++---
45 | +---+++++--++-+-++-+++-+-+-+-+++----++++++-+++++-+-+-----+-+--+++--++-+
46 | +++++-++++++-+++-++++++-+-+-+-+-+++-+-+-+++----+-+-++++--++++---++-++-++++++--+----+-+++++---+-++-++
47 | --------------------------------------------------
48 | +++-+-++--+++++----++--++-+-++-++-----+-++++++-+-+++-+--+---+-+-++-+----++--++-+--
49 | -----+---+------+-+-+---++--++-++-++-+++--+--+++-+++-++-+---+-+---+-----+-+--++---+-+---+--+----++-+
50 | +++++-+-+--+
51 | -+-+-+-+-+
52 | --+-+-++--+--+---+-+++++-++-+++-+--+--+++---+-++++-+---+---++-+-------+++--++--+---++++++-+++-----++
53 | -++--+++-+
54 | -++-+-++--++----+---+-++---+-++--+---++
55 | +--
56 | ++-----+--++-++------++-+----+---+--+----+-++---++++-+---+-++----+++++++-+++++----+-+-++-+-++++----+
57 | --+++---++-++++--+-++-+++-+++--+++----+-++--+++--+++-+---++--+--++-+--+-++----+---+++--++--+++-----+
58 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
59 | -+---++-++-----+-+++--+---++++---+-+-+++--+-+-++----+--+-+-++++-+-+--+--++++------+++++-+++-++--+-+-
60 | -++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
61 | +---+----++++--+-+-+--+---+-++-++--+---+--++----++-++-+----++++--+-
62 | -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
63 | ++++--+++-+++-++-+-+---++-+++-+-++-+---++--+-++++++-+--+++-+-+-+---+-++++--+-+--+++--++------+-+-+-+
64 | --+-+---+-+----++-+-+-+-+-+--++------+----++-+-----+------++--+----
65 | +-+++----++--++-++-+++-+-+--------++-++--+--+---+-+---++--++++---+-----+-++---+--++--+-+-+++-++--+-+
66 | -+++++-++-+--+---+--++++++-+---++-++----++-++-++-+------++-+-+-++++-++--+++-++-+-+---+-+--+---+++++-
67 | ---+---+-+--++-++-++-+++-+---+-++++-++--++++--++++++---+++++++---+-+++-+-+-+---+-+--+-+++++---+++-+-
68 | -+-+++--++++-+---++--+++-+-+-++++++-+++-
69 | -----+--+-+-+-----+--+--++---+-++-++-+-+--+---+++-+++--+--+-++-+++++---+++-+++-+-+---+-+-++---+-+++-
70 | ++--+-+-+-+-++-++-++-+-++--++++-+--+--+--++++----++-----+-++++---+-++++-+-++++--+--+-+++-+++-+++-+++
71 | ++
72 | -----
73 | --+----+-++-+++-++------++++++--++++--+-+-+++++++-----++-+-+-++-+-++++-+-+--+++----++-++-++++++++---
74 | +++--++++-++---++++-+-++---+-+-+---+-+-+---+-----+--+--+--------++-+++++---+--++-+-++--++-+++-+-+-++
75 | -+--+--+++++++++---+-++++++-++----++-----+-+-+--+-++-+-+-++----++-+-+-++--+-++---+--++---+--++-++-+-
76 | --+----++--+-++++----+--+--++--+-++----++++++--+++-+--+-+--++-++-----++-++-++--+-++-----+--++-++-+++
77 | ++-+-++----+---+-++---++--+--+-+++-+++++-----+-+++-------+--+++--+-+-+-----++++++-+---+--+-++-+-+-+-
78 | +++-+-----+---++----+-+++--+-+++-++---++---+--+---+-++-+--+----+++++-+-++-++---+----+-+------+++--+-
79 | ++-+--+-+-++----++------+---++--
80 | +
81 | ++++-++++------+++++-+++-+-+-+-+-+----+--++--+++--++----+--+-+++--+--++-+-++++----
82 | +-+--++-++-++---+++--+--+-+++++-++++--+-++---+++-+--+++--++-+-+++++----+---+--+-++--+++-+++-+-+++---
83 | ++++++++++++++++++++++++++++++++++++++++++++++++++
84 | --+---+-++++-+--+---+++++++++----++++-+----+--++-+----++---++++----++-+--++--+----+--+++---+-+++++++
85 | +-+----+----+++--------++-+-+-+-++++-+-++-+-+++-+-++-----+-++-+-++++++-+-+++--+++--++-+-++---
86 | +-++++----++--+---+-+---+--+--++-+-++++++++++++--++++-+--+--+++--++---++--++-++-++++++++-++--+-++---
87 | ---+++--++++--++------+-++-+----++----+++++-++++-+-+++-+++--+-+-++-+++++-++-+--+---+-++-+--+------+-
88 | +-+--+---+--+--+--++-+-+-++------+---++-++++-+--+---++-+++-++---++---+-+--++-++++++-----+----+-+----
89 | ++-
90 | --+---+++-++--++--++-+++-+-+---++--+++-++-++++++-+++++-+-+---+-+---+++-+++--++-+--
91 | ---+-+---+-+---+-+---++-----++-++-+--++---+++-+-+--++++++-+++--+--+-+-+-+-+-+-+++----+---++++++++---
92 | --+-++-+-+------+---++-+--+--+--++-++-----++--++--+--+++----+----++-+++--++-+---++++++++++++-+-+--++
93 | ---++-+-++-+-++--++-+---+--+++++-+-+++-++++-+--+----+++-++-++++---+++-++++-+-+++-+-++---++-++-+----+
94 | +-++++--+-+++-++--+--++-+--++-+--+-+++---+++-+---+-++++++--+-+--+++++-+-+++-+-++----+++-+++-------+-
95 | ---+++-----++----+-++-+-+---+-+-+-++++-+----++----------++-++++-+---+-+-++++--+-----+++-+++++--+----
96 | ++-+-+++-+--+--++--+++++-+++--++++--+----+++---+--+-++--++-+-+------+---+-+-++++++-+-+-+++-+++-++---
97 | --
98 | ++-+------+++--+---+----+-+-+++-+--+-++++-+-+-----+-++-++-+++-++---+---++-++-+--+--++---+-++-++++-++
99 | +-+-++++--+-+--+-++++-+--++-+++--++++--+-++-+++++---+++-++----+-+--+---+-+--++-+-+-+++--++++--+-+---
100 | ---++-+-----+-----+-+---+--+++-----++--+-++++--+++++---++-+-+---+-+-+-+--++----++-+++-+-+++++-+---++
101 | +++++
102 |
--------------------------------------------------------------------------------
/codeJam/pancakeRevenge/B-small-attempt0.in:
--------------------------------------------------------------------------------
1 | 100
2 | -
3 | -+
4 | +-
5 | +++
6 | --+-
7 | +-+---+-++
8 | +++-+--+--
9 | ++-+-+-+--
10 | +-++-+-+--
11 | -+-+-+-+-+
12 | ++--+
13 | +---+-
14 | +--+--++++
15 | -+---+-++-
16 | --++
17 | ------+-++
18 | -+++-+++-+
19 | -++-
20 | -+++++-
21 | +----+-+--
22 | +-+
23 | ++-----++-
24 | +---++-+++
25 | ++-
26 | +-+-+----+
27 | +++++
28 | -+--+
29 | +--
30 | -+--+--+--
31 | +++---+-+
32 | +++++-
33 | --+
34 | -+++++-+++
35 | +--+
36 | ----
37 | -+-+++++-
38 | -++--+-++-
39 | -++++++++-
40 | -++-++--+-
41 | -+++
42 | +-+-++----
43 | -+-++--+--
44 | ++-+-++-++
45 | +++++---++
46 | +-+-
47 | +----+-+-+
48 | ---+
49 | -+-++++---
50 | +--+-++---
51 | +
52 | ++
53 | ++---+-+-+
54 | ---++++-++
55 | +--+-+--+-
56 | --+--++-+-
57 | +--------+
58 | +-++++-+--
59 | +-++
60 | +----+-+++
61 | ++---+-
62 | ++++
63 | +-+---++++
64 | +--+-+-+--
65 | +++-
66 | ++--
67 | ++--+-++++
68 | -++++
69 | --+---
70 | -+--
71 | --
72 | +-+-++++++
73 | -+++++++-+
74 | +++-++
75 | +---++++++
76 | +----+++-
77 | -----
78 | -+---+++-+
79 | ---+-+-+++
80 | -+-
81 | +-++----+-
82 | +--+-+--++
83 | -+-+
84 | ++++--+--+
85 | ---
86 | ++-+
87 | -++-+-
88 | ---++-+++-
89 | -++
90 | +-+-++-+-+
91 | ++----+-++
92 | +---+++--+
93 | ++-----
94 | +---++
95 | +-+++--+--
96 | +---
97 | -------+++
98 | +-+-+-+-+-
99 | --+---+---
100 | -+-++----+
101 | --++++-+++
102 |
--------------------------------------------------------------------------------
/codeJam/pancakeRevenge/largeOutput.txt:
--------------------------------------------------------------------------------
1 | Case #1: 1
2 | Case #2: 1
3 | Case #3: 2
4 | Case #4: 0
5 | Case #5: 3
6 | Case #6: 52
7 | Case #7: 2
8 | Case #8: 44
9 | Case #9: 3
10 | Case #10: 52
11 | Case #11: 43
12 | Case #12: 47
13 | Case #13: 50
14 | Case #14: 17
15 | Case #15: 2
16 | Case #16: 44
17 | Case #17: 58
18 | Case #18: 35
19 | Case #19: 53
20 | Case #20: 48
21 | Case #21: 10
22 | Case #22: 1
23 | Case #23: 40
24 | Case #24: 57
25 | Case #25: 29
26 | Case #26: 47
27 | Case #27: 45
28 | Case #28: 33
29 | Case #29: 48
30 | Case #30: 3
31 | Case #31: 48
32 | Case #32: 1
33 | Case #33: 29
34 | Case #34: 55
35 | Case #35: 33
36 | Case #36: 50
37 | Case #37: 45
38 | Case #38: 2
39 | Case #39: 29
40 | Case #40: 45
41 | Case #41: 1
42 | Case #42: 34
43 | Case #43: 68
44 | Case #44: 36
45 | Case #45: 48
46 | Case #46: 1
47 | Case #47: 44
48 | Case #48: 53
49 | Case #49: 6
50 | Case #50: 9
51 | Case #51: 47
52 | Case #52: 5
53 | Case #53: 21
54 | Case #54: 2
55 | Case #55: 44
56 | Case #56: 47
57 | Case #57: 100
58 | Case #58: 53
59 | Case #59: 3
60 | Case #60: 36
61 | Case #61: 99
62 | Case #62: 56
63 | Case #63: 35
64 | Case #64: 52
65 | Case #65: 53
66 | Case #66: 51
67 | Case #67: 21
68 | Case #68: 57
69 | Case #69: 54
70 | Case #70: 0
71 | Case #71: 1
72 | Case #72: 45
73 | Case #73: 52
74 | Case #74: 55
75 | Case #75: 49
76 | Case #76: 52
77 | Case #77: 50
78 | Case #78: 16
79 | Case #79: 0
80 | Case #80: 40
81 | Case #81: 52
82 | Case #82: 0
83 | Case #83: 41
84 | Case #84: 50
85 | Case #85: 46
86 | Case #86: 49
87 | Case #87: 52
88 | Case #88: 2
89 | Case #89: 43
90 | Case #90: 53
91 | Case #91: 47
92 | Case #92: 53
93 | Case #93: 52
94 | Case #94: 45
95 | Case #95: 52
96 | Case #96: 1
97 | Case #97: 54
98 | Case #98: 56
99 | Case #99: 49
100 | Case #100: 0
101 |
--------------------------------------------------------------------------------
/codeJam/pancakeRevenge/pancakeRevenge.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | def countFlips(s):
4 | up = ''.join(['+' for i in range(0, len(s))])
5 | down = ''.join(['-' for i in range(0, len(s))])
6 | count = 0
7 | while not (s == up or s == down):
8 | if s == up:
9 | return count
10 | if s == down:
11 | return count + 1
12 | s = flip(s)
13 | count += 1
14 | if s == up:
15 | return count
16 | else:
17 | return count + 1
18 |
19 | def flip(s):
20 | for i in range(0, len(s) - 1):
21 | if s[i] != s[i + 1]:
22 | if s[0] == '-':
23 | return ''.join(['+' for _ in range(0, i + 1)]) + s[i + 1:]
24 | else:
25 | return ''.join(['-' for _ in range(0, i + 1)]) + s[i + 1:]
26 |
27 | with open(sys.argv[2]) as inf:
28 | lines = inf.readlines()
29 | lines = [l.strip('\n') for l in lines]
30 |
31 | outName = sys.argv[1] + "Output.txt"
32 | ouf = open(outName, 'w')
33 | for i in range(1, int(lines[0]) + 1):
34 | ouf.write("Case" + " #" + str(i) + ": " + str(countFlips(lines[i])) + "\n")
--------------------------------------------------------------------------------
/codeJam/pancakeRevenge/smallOutput.txt:
--------------------------------------------------------------------------------
1 | Case #1: 1
2 | Case #2: 1
3 | Case #3: 2
4 | Case #4: 0
5 | Case #5: 3
6 | Case #6: 6
7 | Case #7: 6
8 | Case #8: 8
9 | Case #9: 8
10 | Case #10: 9
11 | Case #11: 2
12 | Case #12: 4
13 | Case #13: 4
14 | Case #14: 7
15 | Case #15: 1
16 | Case #16: 3
17 | Case #17: 5
18 | Case #18: 3
19 | Case #19: 3
20 | Case #20: 6
21 | Case #21: 2
22 | Case #22: 4
23 | Case #23: 4
24 | Case #24: 2
25 | Case #25: 6
26 | Case #26: 0
27 | Case #27: 3
28 | Case #28: 2
29 | Case #29: 7
30 | Case #30: 4
31 | Case #31: 2
32 | Case #32: 1
33 | Case #33: 3
34 | Case #34: 2
35 | Case #35: 1
36 | Case #36: 5
37 | Case #37: 7
38 | Case #38: 3
39 | Case #39: 7
40 | Case #40: 1
41 | Case #41: 6
42 | Case #42: 7
43 | Case #43: 6
44 | Case #44: 2
45 | Case #45: 4
46 | Case #46: 6
47 | Case #47: 1
48 | Case #48: 5
49 | Case #49: 6
50 | Case #50: 0
51 | Case #51: 0
52 | Case #52: 6
53 | Case #53: 3
54 | Case #54: 8
55 | Case #55: 7
56 | Case #56: 2
57 | Case #57: 6
58 | Case #58: 2
59 | Case #59: 4
60 | Case #60: 4
61 | Case #61: 0
62 | Case #62: 4
63 | Case #63: 8
64 | Case #64: 2
65 | Case #65: 2
66 | Case #66: 4
67 | Case #67: 1
68 | Case #68: 3
69 | Case #69: 3
70 | Case #70: 1
71 | Case #71: 4
72 | Case #72: 3
73 | Case #73: 2
74 | Case #74: 2
75 | Case #75: 4
76 | Case #76: 1
77 | Case #77: 5
78 | Case #78: 5
79 | Case #79: 3
80 | Case #80: 6
81 | Case #81: 6
82 | Case #82: 3
83 | Case #83: 4
84 | Case #84: 1
85 | Case #85: 2
86 | Case #86: 5
87 | Case #87: 5
88 | Case #88: 1
89 | Case #89: 8
90 | Case #90: 4
91 | Case #91: 4
92 | Case #92: 2
93 | Case #93: 2
94 | Case #94: 6
95 | Case #95: 2
96 | Case #96: 1
97 | Case #97: 10
98 | Case #98: 5
99 | Case #99: 5
100 | Case #100: 3
101 |
--------------------------------------------------------------------------------
/codeJam/reverseWords/B-large-practice.in:
--------------------------------------------------------------------------------
1 | 100
2 | this is a test
3 | foobar
4 | all your base
5 | class per pony along only like less pony write alpha item all pony base base bar this snow five item alpha than entry than way this this like
6 | snow a less item along only done this long base base way words foo too base too a class this class done would too bar base than like set five base only too the way set than entry with item this the set way entry class alpha pony foo cola base too foo like pony word five only chars chars foo set this done way item long snow way way chars word write all snow long this pony all pony foo this write cola base alpha bar words five than snow chars too bar the only
7 | the with alpha with less foo words would way base a base a entry all word write set this this less words this base words base entry long too would along item alpha only too foo too word chars this chars entry class set cola foo class this too only way like only cola only item snow foo long
8 | like cola than word base along alpha words chars would words would chars entry all words like way chars alpha item this snow way long too too pony words per a all less cola alpha five a this pony item word bar long only per done entry way all done the entry five the entry too foo bar class a this would word only along like pony base this pony done this bar way the along only class base too alpha along done
9 | write long this chars done less cola way per cola the only a would this five like less only the write all class a word snow item like word chars pony alpha would item chars too alpha set per item with chars with only set long than word way set class bar way like snow set too like too set five five snow bar foo entry cola base this a word pony a item per would entry snow pony chars entry cola all this long item along the snow only bar set entry per cola than foo pony the too like only words along less word per words per set
10 | way cola done less class a pony class the entry with with entry too item like too snow chars
11 | than way cola chars way item cola words word chars chars per a write snow than alpha cola than done less word class too the only done per words with class chars like pony a foo pony than entry way this pony way base way than set snow would write way foo write snow too like alpha the set write entry only would write snow only way entry less base would this bar pony five chars entry pony way than word per item set with class done per five long only words a all five only entry bar per class like a entry bar only item class like the with less than cola with bar word foo entry all entry all long would along this only word too write foo item pony too long done chars
12 | than per entry than bar than along alpha a class way foo class item a pony per words
13 | done with foo five class words word long item the class entry done than too chars bar a only too base this class long long long entry foo five per item five item bar this entry item long per write less along write like snow this chars pony cola five word the base this done too would words this five than way foo all item per chars chars than a write like alpha long like per would base like with entry done than pony chars per all long cola item a would bar less along a words entry done done the foo this like five pony too with cola cola all the entry than set snow less only would class cola words this five alpha class a five entry entry word base long done this long would than all along the bar pony item per along all only base alpha only a than way
14 | would a five set alpha bar chars words along would too way item a along cola less entry less word less five five done all along a way way snow five snow word pony chars too pony this entry than words set item snow along long along chars five snow five word way chars the along way write than entry snow than write a base class cola the way all would all all a way per words cola less only write class class set way long too like along would with a with item five pony foo set only foo only class per only words with class too set snow a words class too set with long done write per
15 | too word way class less alpha long bar with class base all only entry per way class done the pony pony with this five pony way class foo item alpha only this like chars all write chars done base alpha all this set entry word too chars chars all along set the with item too word five five base long would a would item like along per
16 | done cola this along too cola five along way words chars long word entry snow write words less foo per with foo alpha words way only set would only item would snow a only a with word less chars chars a the base item item less foo like words per a snow word write a like base the five would would foo the write base the per words write words alpha done done with
17 | chars only this the cola entry would pony word with long a word alpha done words per entry snow pony would set five this item cola words per than write a way bar foo item set foo snow five along than bar way pony than pony with cola words write words all set item alpha too long than chars this write chars the all less bar the less than snow a bar set only way entry too words five
18 | this too pony the a would this class foo class class set too class words per item like done item class done snow alpha only set set done class done words entry would five a write along five a per along would item per long base word done base like all class words set done than pony pony only this less all way done item would a all alpha too done would the long a with cola less this entry item words with foo five like write bar words pony long pony five way
19 | alpha pony along would bar bar long the less cola less set only per a pony all word way than less pony set base write done a words pony bar with class only word this this set pony like the foo bar snow word chars write set class chars all less
20 | cola done with class bar item too way set with only a word item too set set a only five too chars long snow entry less a words done foo only item foo word alpha would word class set all all foo pony only all a too entry only foo class done a done only long along only chars five pony bar base five per too a class cola with less pony write done than base base words along too only per
21 | less only all write than cola cola done item with this would word too the only along per class pony class alpha only this entry snow the snow would item done five than set too
22 | per all words per long alpha per way a would bar way item only bar this word only this than like too cola bar alpha less word than per way less pony than along like long
23 | five only snow foo a word way chars chars pony foo bar
24 | like set like cola the with word five foo done item with item set write per too way foo write class only set write along item pony alpha done snow like snow long chars entry less all per snow would cola way along the bar base set words word chars pony per class set than cola a long than only five
25 | the entry like like long less a done along cola write long item snow long less long all alpha the along way long pony word alpha set class way a words done than less snow a bar the the like set like class way a alpha less with write this snow this way way class cola base cola like set with less alpha all would write five this would bar with a class this pony base chars like only all write snow would way class words per than five would done foo along too done word snow along would entry foo per with entry cola with item cola like class entry the like this foo all cola foo only way way would with entry write snow snow than per less alpha like words foo cola write than write snow long only a less too the like alpha per words item write set way set less
26 | long five with the all way write entry all cola a
27 | this this per chars like alpha only along would alpha base long bar than word entry class along the along this chars with set way too a way alpha snow than way than long bar a base this foo bar word with than class five write than would this the base a foo all
28 | than less foo the less all only would snow five snow five all long five all words than bar than with chars alpha set a alpha this alpha too this chars alpha class class set class along way way foo the less done write a five along only write the the than chars alpha set cola this with like long would class than long base along chars five item entry write
29 | base words bar only per alpha item word base less less five would would than this along snow base words write this less alpha foo with foo like along a write write base along this five class words long bar this bar all only less class along base alpha entry like bar too chars only too with less this snow less less item way with class entry item snow entry snow word per item all than foo pony write word item base
30 | with entry too all words long bar class write along long class
31 | alpha too bar snow too than cola base would set long alpha would write the bar done with done done snow all words way class set all per entry chars set word only done less foo along all too only only class than item way word less snow class than along all alpha only this too way only like word all long all word done this class foo foo class base bar along way bar less chars foo base all too item per done way class words alpha word foo with this per this set set entry the a than item
32 | the would would word the class less write way item would long five only
33 | write like done base long the way with too alpha with less per way less class cola with a item would foo all words entry alpha words class word five alpha base with all words entry snow would words class long per along per entry foo way along cola way like write snow a alpha cola per words base item only with less only long write like than five per alpha long too item way done word words all words base than entry done write words alpha only word than along cola write with foo cola pony all way would class like pony would five than alpha long cola pony all class along entry the chars only done word class all only entry done bar done cola all alpha would pony snow way with class per would with pony five bar
34 | base would alpha foo bar base than long base chars class item word set pony the write base cola like this snow too set five this long bar write a chars done foo long five
35 | item foo cola with long class words this write set
36 | than cola chars cola done done bar alpha done set write base long all words entry alpha alpha word less like like like per snow entry chars word less like all five per words word along this word all set five write per per with entry cola per done bar word done class long this item long the too with way entry item like only cola word chars with a bar too with pony with would word too cola too like a the would pony write foo per write than item the this per like like than five set set
37 | entry way write along all the five bar with along only snow like word cola a way done five a the chars per set than long entry five class snow than per words per only only the write than words item a words like along along word with set than foo snow would done this class snow along done bar bar foo words alpha set write less way cola snow foo set base along with write foo only way snow five cola write bar
38 | way way alpha item foo foo
39 | way with with snow along a a snow pony too base along set like pony alpha only entry with alpha class class alpha way item snow words way would this five write item this bar done pony word words a chars way a way only words less item like snow foo write with done this item write base all cola way pony base would the foo chars five cola pony too words
40 | entry only alpha
41 | the pony class too word would all the too set cola than this foo alpha with way would words this alpha pony done class class foo way this would base item way word write base than class snow cola cola foo snow base a too set word long five write done a a along alpha would pony would chars way less only cola cola words less words five write
42 | word base word this item with item done chars base foo words the item per words words alpha per base class too alpha too the entry too entry like per alpha
43 | the five a pony per foo entry long snow a all foo all only write would this the item item this the alpha like snow the all like only long too too words the base bar long class foo long per set a than this entry the foo snow than chars all way long set all long less class done along than cola item pony done set less bar this than set
44 | foo write base word snow all per base this set entry than entry bar would foo less than only cola bar would base like five with bar item words class like pony base class item with base this would word done class than too like per long only write snow write item way pony base only five way long per the the with base this the five set way set too class this pony a snow per word alpha base foo with way chars pony this too way write word the way with with a cola foo class pony write five done bar chars like write less set way five word than too this a done per bar pony too set class write this pony all five bar words would way too would class less pony along than item than
45 | long long this cola five write way than only item words less only all less five less per all way with bar per word entry along entry pony alpha words write would alpha long a with per than class this long write the five only snow bar five like five the less a long too only would this word entry write five five five set way alpha word chars bar long than bar write word foo five chars set done five set too like less long would words entry all pony too less all pony done write words word way done words snow too less alpha alpha word class along snow pony per
46 | snow five foo class done alpha bar foo like alpha done class class would class would bar with per pony along a chars done bar write too class along entry alpha pony way bar the per five word set class this five pony this with five word less than a the snow done alpha item too item class less five like long foo write like only five cola set class pony like cola class alpha per per only would base entry along five item bar entry item class word chars chars would word foo less like with only too this cola done like too foo chars long
47 | a too per per would per set set with than snow words long too too item all per too set the class a a a base too only snow this along way foo write along five chars words entry set five word the pony only chars chars five
48 | than would base the with chars pony would along write class cola pony would per foo bar per class the all snow the write word per than set words along class snow entry cola the words item this entry per class all write way foo words long set cola
49 | base all along a per base pony foo way class along five too all pony five than all per set set pony chars would chars per less than than item long alpha five per words base than pony item this per per a long word bar bar alpha done write chars chars a snow foo a the item alpha word long the would than entry set set pony way less write words than this this five snow with this words five the chars only pony five long than a write only entry base way class
50 | word than class cola item this snow done way this foo long the word like per word base alpha long set like would words word bar cola base per
51 | base than with too set bar with long like item bar like class long than alpha along five item write per per bar long words less done cola way cola this bar set all less too set entry base entry done snow all base pony chars entry like than too write only too pony the all than long done chars only less bar all base foo entry all chars would less with pony foo less a than all alpha bar word this base a done set set like the words like entry less with all foo alpha like would set less snow
52 | item entry per foo five like word the bar too write words only entry pony only item set item write the per entry pony write done write pony five too entry would cola would set a like chars class foo only bar write cola this all a way this entry pony foo per than with word only base five snow write foo words like a would along pony like item snow set bar set five way pony base with bar a set foo than entry bar bar bar alpha bar write would set entry pony snow five foo
53 | would write like long class foo base way like than like than word done alpha per item along less the pony done cola class too foo a the all the entry way chars than foo words word per done snow only bar five foo item words foo too word word per a item way less foo item less foo words less set pony too alpha too entry this this too way the item base bar set way five would long than snow word words the foo a less only long all cola chars this item than base set class snow long the alpha five
54 | base would foo alpha write set along done only write the all five along words the all entry set foo cola class item snow chars write pony per entry words chars write than foo set words pony alpha long pony chars less cola word five words bar the this set all a snow class way bar five only base cola all than
55 | class a all words done way all along class than words pony bar word less snow a bar the the too done too too item foo cola per words long class alpha foo per like set per base would long would pony five would write five foo set way the foo only the bar entry long all a item bar like like chars write pony way with too word class cola set foo write base done
56 | alpha alpha than with less bar than chars bar long snow write item the chars way with per snow foo write less less all too than all per would would too snow the would per cola done foo pony snow entry long long this along all write would
57 | class class set cola this pony cola long way like along pony set bar alpha pony foo only five
58 | chars along way pony this would the way less chars long than along only chars all with too done snow foo all five pony than with foo long word the chars pony with way snow foo like less class chars write like bar snow this a alpha all set would base a class with write alpha with all item less cola with cola snow than along chars a this along write the snow a
59 | chars this a with cola five done along five alpha words this chars class write would long chars cola only way set pony like entry per per than less per chars class chars foo along foo with less this cola the alpha the the way would write like per per way way snow write this this all pony pony item done entry bar this cola per than word alpha the with per chars than bar long write this than words word a set way this chars per five along foo this foo the like would a write this a class item pony a foo snow too all like than long pony only than words cola way too a pony the
60 | per this item way base the too alpha word pony five alpha way class too along pony would words per entry done way a like long word with a base a all too only a class five cola way all item item with cola all class item five a per done long five all like the write way chars chars bar class item a per pony way bar than item bar chars along with foo like bar pony all set per five too would base long the this alpha than only cola along pony pony cola the too five item per like the entry way with
61 | words too write set pony entry long write along foo done this words all a a long with too cola than pony only the only all five class than this the chars base class alpha this set this word set all class five less less a per words words all than alpha write chars snow too class words the a than class along too along base write entry write pony less cola alpha less the per all
62 | words like cola like set a along base per class class entry a done set base bar five all set foo five this done along long cola word a words this write with too item alpha would with word set write along alpha foo per only cola this only only entry entry set the long entry foo word pony like base foo than item only write this pony snow class would write all this along along cola write less per words entry all too words item done five the long entry less item word per words words per chars a class snow all per set long entry this too a alpha only chars bar write this less item entry the chars item would pony entry only per long base long entry chars item with along too only only item chars word this item pony chars
63 | alpha set cola all entry pony with less alpha pony item set would chars alpha class per pony all foo class too chars than a item done too way only this alpha along item bar than cola like all than a item class like word alpha pony a words this snow a set all foo than set class entry words bar class bar too class done than class entry per item only than class per item per foo would pony too too the words done chars words too set long would item five with five a like per along words this than only this entry cola
64 | per only bar bar words a alpha cola too cola five
65 | class the class entry chars cola per all words item entry bar entry than done entry than with five words would bar along write foo only per long way entry only alpha pony five foo foo set would a this than bar the too done too this done all set way with this the would foo entry done would way along like way bar chars long chars item with foo bar bar word the per class all than alpha write the per word alpha bar class the base five done along long along item like cola five only way bar a foo done per done pony class too class foo class word would foo foo class than the base
66 | done entry this word would snow this cola along alpha write five too with set with long class the class the write entry foo like long this a write only entry write base foo set write a too done this way chars per pony entry way write done pony pony snow foo way way item a item class would long only cola a five entry along entry snow along like alpha done than way bar
67 | class less the the word a the entry cola entry done would words word cola item with long pony done word cola less word cola chars the set entry all item this class all the snow with five class a done long word chars entry
68 | would write the alpha than too along foo the write this this word less bar would base the alpha item than way cola like pony entry than snow base chars this a long class pony alpha way base pony chars way base too cola cola pony this foo cola way entry the long set too the all a would this all foo along less class pony entry cola only like base class word foo entry words snow five cola less along the chars less pony pony bar foo foo item the the way foo with this only done pony along set item entry would done set only only entry way class base five along words done per words words like this write like than the all
69 | the class like bar the word than
70 | pony the snow done word words word word cola this less way a chars the set alpha only chars class item word alpha alpha like five only done write would cola bar base word words cola with this snow pony too bar would words cola a pony snow would along bar done item per cola item set set alpha less way a write this write write done with entry way like set along item words like would along entry like long entry would foo way a along way word all too per long would too would words less item five this class would write chars bar long than snow cola write with than all cola a long like done chars per alpha class per a five cola base snow set
71 | snow would snow long only class five item alpha chars less than cola like less a long chars too this word class too word five way set less base all set way per chars done with all than alpha with too the would only along done with set this alpha a class set cola a all item word along way alpha the alpha word pony done per class set long with like than snow only foo per along write class class pony cola foo chars pony a cola chars bar done base class entry like too with less write alpha done set done this done five entry along base cola base this bar words done word item the too less with
72 | class set word item five pony pony this along would base with long less would per foo five set with alpha bar base long the bar too with chars bar all too entry bar pony like like cola per only words less with entry item done along long alpha alpha words foo words set bar set chars entry write per than way only entry item cola word alpha done set chars set snow than write base done along would long class alpha bar all done only write chars chars cola per item class chars entry snow like than too set pony would chars
73 | long less all too base done snow chars per pony along along entry less the than chars five along bar the chars with write done words chars chars chars words per less the snow this than this per per this way than like entry along than entry item chars done all with with foo snow item per a only along words too a way all would a cola five alpha word only done way too the too chars with than than foo set alpha
74 | alpha per chars write less less along way entry all pony less with way than like this item bar entry alpha all the cola this write alpha the the way too would class only snow less item alpha done with entry too the chars foo five the would way set class done set entry five all foo this five this bar item a per write less a a word too set base with per item snow five per long pony alpha cola way words foo set word word would pony chars with base base only set way base word would like this alpha cola pony than five entry bar pony bar too along set like snow per
75 | words only words bar too write only five all
76 | base along alpha alpha foo a the than way cola snow bar along like the snow write this words than class than set bar words along base with item along per word with words a foo done the item this less with this like long like set like snow cola words than all snow along foo cola way would a alpha way a long cola done done chars the class set pony alpha the all like along long cola only bar a item pony done would
77 | only snow word base pony write way set cola with cola this chars set entry base pony all class base along chars write than entry cola than along base way word bar word all base with word alpha than bar words words a only base bar word word class with word would too like along foo item along only cola like than done along the less way snow too only like class with class this five item too item write the only way five with item foo than along set alpha too set way with foo than a word only set cola along base all along per pony
78 | per cola a less way word write write chars pony five too along like set item done all than pony pony along along snow than all bar bar snow item word a pony word cola pony bar would along class word only the base entry the all along write cola way per five than base like entry alpha long done entry all done snow foo chars five along
79 | like cola done foo than per item per words alpha all than too foo foo cola snow would snow cola long along than item would entry long entry done write word a class this base snow the chars five done along alpha along chars with a long only snow too like only item the too
80 | less like along write than entry this done chars foo done alpha bar like base this with long along foo set like done entry write way word per less base would entry like write done a only write bar all foo too base write would class pony only less less entry less write entry per like per base too would foo long way entry way alpha along pony snow would too a entry foo than with the too with the the a base base only chars set bar write entry cola way base five words chars less snow write a way word would with snow only the the foo chars
81 | per pony class this base along the item than too foo cola only pony all a words done done a with the snow less only alpha snow way bar only words five write less set base per with than base words done this this item item less way long five entry less like entry too five set done too way a like way word
82 | foo only bar item pony less word five words too this the bar way less base per cola bar set less this all set foo way class word the this write item along cola alpha with all item a pony base entry snow too pony like words way alpha the snow long only done cola pony class like class pony only foo snow five
83 | all entry five set pony the done set chars than than set word like this word base the done chars bar set with class word along alpha with with per pony with would class a less class cola this a entry with like only foo per like words chars class item long long all
84 | item way done alpha a chars words this than like like cola words only less less done word this like set long way this foo less than item a five pony all all would set
85 | along write entry class way class only foo write less foo too would item less long than foo with cola cola class per words all entry per would base bar with per set base write snow the along snow base too with chars than write too words only too than along cola words done word less alpha word than this than along less way would snow would all all item set done foo pony this entry way
86 | class done bar foo pony set with foo the a too base with entry five than done write chars like per base class five done write
87 | way bar words write base pony the this long per word entry like like words base with way like would along like bar write word cola entry a class along this chars done all a along like per this a only the write cola entry than words way snow chars base alpha pony the entry base too a too class all all pony long with bar the snow a like a write cola set long a less than five bar write along would too all base pony per base with this too write
88 | cola set long foo bar item only words alpha done set like item write way write along way bar class chars entry way set pony word with entry base like less entry along class too words cola entry pony five done pony done bar base alpha done set five class like
89 | per pony a snow than per alpha the words all five all alpha pony snow item along like less per done class along base words entry only foo too way with word too entry per way five base bar would way way all along all word less done set along long words per
90 | pony write item words alpha class all would with class words base less all only too only five long set class the write chars entry all alpha long too bar cola would set way foo too too way too the the entry foo all set base alpha snow done item word all the only entry foo foo all less base bar way than like along word way only alpha foo this set along along with this long alpha words like set cola this would the class cola the write long set words five than like five done a foo all class all all chars only base long long base word item with per done too snow than entry write done like would
91 | class this five bar snow bar than way along less the foo bar entry with snow less only write too the would chars cola foo word entry done word per long all along words way snow chars all all per cola done chars would like words the like chars along five entry with snow words along bar alpha alpha base long the less alpha entry alpha snow this like class long entry alpha snow less word
92 | along bar cola class entry word entry set class pony would would like the done per would than item along word only along pony chars would less snow cola way base the pony word word pony bar way too the the like way chars write bar with only too write base words pony only along
93 | base a pony along snow bar this chars all all word set than set like the way five five this class would foo item would too only five five base entry words way less write all with too write the the word pony foo all less less per this than base snow done foo long words entry long base word class pony per snow five a than five
94 | done like than pony set too long cola than all done a set write word word entry item a would chars alpha foo long a along item class all item bar set cola alpha pony all along word this only item word entry way per than cola the with chars cola class alpha with per this a word snow word alpha five this too long words pony word entry all done less foo set foo alpha only only word word words class way write would per all only all done too five only would words done entry bar than than snow five a would word this would than class class too set long set with foo long five item done words this this foo this way
95 | alpha cola than a foo item write chars alpha alpha done write base too done way all snow like base done this long write set entry item foo foo than the too only with a this too item than per class less per long words with long five item done this write words alpha long all class cola less pony all base class all only would entry like class like class per cola like with five class item pony cola snow base class foo done entry base this long per a set too cola like way write than alpha chars pony long like pony with word done all long than too pony foo along along less only a less base five a like alpha all all pony would set all write would done the done base like chars a all too pony only this with a than word than done long the word base
96 | snow way words like the pony chars item long item set per words base like foo words only would base write snow entry item than base class cola snow with would would set class chars long less with too less item words item long less than would pony way way too words snow long item less only write only with per too way a long alpha per pony pony would word than way foo done foo set all five class only would only class cola along write alpha item word five long like write entry set only bar all word like less all cola base set pony long alpha per with alpha bar too less per item pony entry the less entry cola snow chars snow like item pony foo write like all less a only set per the item write chars base set words long write words base write five would per way only base per
97 | set all long foo
98 | would entry like alpha like word entry pony write bar than item per item foo snow cola the along chars the snow along pony set too like this a along per only along write bar alpha the would this this would snow item way long words like cola five less only like with a chars cola alpha foo a class base done done long item item entry words alpha this base bar would write write base with write with along only words words too a pony way than class would base all set a done like alpha set words bar set class base a long word entry word like way word item pony words per only along foo item only words less
99 | snow would with less per all this done long this foo a less per long the like snow the bar pony set write alpha words done way alpha way words the item a this words
100 | too alpha the only would class bar foo would write snow all five bar item too a done entry a only like class long set foo than this along the write less foo word snow way
101 | entry too a the item less snow base less bar chars only a only the would than pony this a only than than this words long than than cola five word per with snow set less all too the too the would only item less alpha base
102 |
--------------------------------------------------------------------------------
/codeJam/reverseWords/B-small-practice.in:
--------------------------------------------------------------------------------
1 | 5
2 | this is a test
3 | foobar
4 | all your base
5 | class
6 | pony along
7 |
--------------------------------------------------------------------------------
/codeJam/reverseWords/reverseWords.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | def reverseWords(s):
4 | words = s.split(' ')
5 | words = words[::-1]
6 | return ' '.join(words)
7 |
8 | with open(sys.argv[2]) as inf:
9 | lines = inf.readlines()
10 | lines = [l.strip('\n') for l in lines]
11 |
12 | outName = sys.argv[1] + "Output.txt"
13 | ouf = open(outName, 'w')
14 | for i in range(1, int(lines[0]) + 1):
15 | ouf.write("Case" + " #" + str(i) + ": " + reverseWords(lines[i]) + "\n")
--------------------------------------------------------------------------------
/codeJam/reverseWords/smallOutput.txt:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/dan.txt:
--------------------------------------------------------------------------------
1 | korean bbq
--------------------------------------------------------------------------------
/foobar/binaryBunnies.py:
--------------------------------------------------------------------------------
1 | from math import factorial
2 |
3 | class Node():
4 | def __init__(self, data):
5 | self.data = data
6 | self.left = None
7 | self.right = None
8 |
9 | class Tree():
10 | def __init__(self):
11 | self.root = None
12 |
13 | def insert(self, node, n):
14 | if self.root is None:
15 | self.root = Node(n)
16 | return
17 | if n < node.data:
18 | if node.right is None:
19 | node.right = Node(n)
20 | else:
21 | self.insert(node.right, n)
22 | elif n > node.data:
23 | if node.left is None:
24 | node.left = Node(n)
25 | else:
26 | self.insert(node.left, n)
27 |
28 | def buildTree(self, l):
29 | while l:
30 | self.insert(self.root, l.pop(0))
31 |
32 | def countBuilds(root):
33 | if root is None:
34 | return 1
35 | return weave(size(root.left), size(root.right)) * countBuilds(root.left) * countBuilds(root.right)
36 |
37 | def size(root):
38 | if root is None:
39 | return 0
40 | return 1 + size(root.left) + size(root.right)
41 |
42 | def weave(a, b):
43 | return factorial(a + b) / (factorial(b) * factorial(a))
44 |
45 | def answer(seq):
46 | tree = Tree()
47 | tree.buildTree(seq[:])
48 | return str(countBuilds(tree.root))
--------------------------------------------------------------------------------
/foobar/boredGame.py:
--------------------------------------------------------------------------------
1 | def move(t, n, pos, lastPos, count):
2 | if (n - pos) > t:
3 | return
4 | if lastPos == n and pos != n:
5 | return
6 | if pos < 1 or pos > n:
7 | return
8 | if t == 0 and pos == n:
9 | count[0] += 1
10 | return
11 | elif t == 0:
12 | return
13 | move(t - 1, n, pos - 1, pos, count)
14 | move(t - 1, n, pos + 1, pos, count)
15 | move(t - 1, n, pos, pos, count)
16 |
17 | def count(t, n):
18 | count = [0]
19 | move(t, n, 1, 1, count)
20 | return count[0]
21 |
22 | def bruteAnswer(t, n):
23 | count = [0]
24 | move(t, n, 1, 1, count)
25 | return count[0] % 123454321
26 |
27 | def answer(t, n):
28 | currMoves = [0 for _ in range(0, n)]
29 | currMoves[n - 1] = 1
30 | lastMoves = [0 for _ in range(0, n)]
31 | for i in range(0, t):
32 | currMoves, lastMoves = lastMoves, currMoves
33 | for j in range(0, n):
34 | currMoves[j] = lastMoves[j]
35 | if j == n - 1:
36 | continue
37 | if j > 0:
38 | currMoves[j] += lastMoves[j - 1]
39 | currMoves[j] += lastMoves[j + 1]
40 | currMoves[j] %= 123454321
41 | return currMoves[0]
42 |
43 | print bruteAnswer(15,12)
44 | print answer(15,12)
45 |
--------------------------------------------------------------------------------
/foobar/breedingLikeRabbits.py:
--------------------------------------------------------------------------------
1 | def zombit(n, cache):
2 | if n not in cache:
3 | h = n / 2
4 | if h * 2 == n:
5 | cache[n] = zombit(h, cache) + zombit(h + 1, cache) + h
6 | else:
7 | cache[n] = zombit(h - 1, cache) + zombit(h, cache) + 1
8 | return cache[n]
9 |
10 | def searchEven(low, high, target, cache):
11 | if low >= high:
12 | return "None"
13 | mid = (low + high) / 2
14 | if mid % 2 == 1:
15 | mid += 1
16 | result = zombit(mid, cache)
17 | if result == target:
18 | return str(mid)
19 | elif result < target:
20 | return searchEven(mid + 1, high, target, cache)
21 | else:
22 | return searchEven(low, mid - 1, target, cache)
23 |
24 | def searchOdd(low, high, target, cache):
25 | if low >= high:
26 | return "None"
27 | mid = (low + high) / 2
28 | if mid % 2 == 0:
29 | mid += 1
30 | result = zombit(mid, cache)
31 | if result == target:
32 | return str(mid)
33 | elif result < target:
34 | return searchOdd(mid + 1, high, target, cache)
35 | else:
36 | return searchOdd(low, mid - 1, target, cache)
37 |
38 | def answer(str_S):
39 | s = int(str_S)
40 | cache = {0: 1, 1: 1, 2: 2}
41 | oddAns = searchOdd(0, s, s, cache)
42 | if oddAns != "None":
43 | return oddAns
44 | else:
45 | return searchEven(0, s, s, cache)
--------------------------------------------------------------------------------
/foobar/directoryListing.py:
--------------------------------------------------------------------------------
1 | def solution(S):
2 | a = S.splitlines()
3 | images = []
4 | for i in range(0, len(a)):
5 | if not "." in a[i]:
6 | lvl = len(a[i]) - len(a[i].lstrip(' '))
7 | for j in range(i + 1, len(a)):
8 | if lvl >= (len(a[j]) - len(a[j].lstrip(' '))):
9 | i = j
10 | break
11 | if lvl == (len(a[j]) - len(a[j].lstrip(' ')) - 1):
12 | if (".jpeg" in a[j]) or (".png" in a[j]) or (".gif" in a[j]):
13 | images.append(i)
14 | total = 0
15 | for i in range(0, len(a)):
16 | if (".jpeg" in a[i]) or (".png" in a[i]) or (".gif" in a[i]):
17 | if len(a[i]) == len(a[i].lstrip(' ')):
18 | total += 1
19 | break
20 | for k in images:
21 | total += findPathLen(a, k)
22 | return total
23 |
24 | def findPathLen(a, k):
25 | lastlvl = len(a[k]) - len(a[k].lstrip(' '))
26 | path = '/' + a[k]
27 | for i in range(k - 1, -1, -1):
28 | if not "." in a[i]:
29 | if lastlvl - 1 == (len(a[i]) - len(a[i].lstrip(' '))):
30 | path += '/' + a[i]
31 | return len(path.replace(' ', ''))
32 |
33 | s = """dir1
34 | me.jpeg
35 | you.gif
36 | dir11
37 | dir12
38 | picture.jpeg
39 | dir121
40 | file1.txt
41 | dir2
42 | file2.gif"""
43 |
44 | print solution(s)
--------------------------------------------------------------------------------
/foobar/equilibriumIndex.py:
--------------------------------------------------------------------------------
1 | def solution2(A):
2 | for i in range(0, len(A)):
3 | if sum(A[0:i]) == sum(A[i + 1: len(A)]):
4 | return i
5 | return -1
6 |
7 | def solution(A):
8 | left = 0
9 | right = sum(A[1:len(A)])
10 | i = 0
11 | while i < len(A):
12 | if left == right:
13 | return i
14 | if i == len(A) - 1:
15 | break
16 | left = left + A[i]
17 | right = right - A[i + 1]
18 | i += 1
19 | return -1
20 |
21 | a = [-5, 7, 3, -8]
22 |
23 | print solution2(a)
24 | print solution(a)
25 |
--------------------------------------------------------------------------------
/foobar/minglishLesson.py:
--------------------------------------------------------------------------------
1 | def answer(words):
2 | graph = makeGraph(words)
3 | start = getStartNodes(graph)
4 | sort = []
5 | visited = []
6 |
7 | def visit(node):
8 | if node not in visited:
9 | visited.append(node)
10 | if node in graph:
11 | for neighbor in graph[node]:
12 | visit(neighbor)
13 | sort.append(node)
14 |
15 | for node in start:
16 | visit(node)
17 | ans = ''.join(sort[::-1])
18 | return ans
19 |
20 | def getEdge(a, b):
21 | length = min(len(a), len(b))
22 | for i in range(length):
23 | if a[i] != b[i]:
24 | return a[i], b[i]
25 |
26 | def getStartNodes(graph):
27 | e = set()
28 | for edges in graph.values():
29 | e.update(edges)
30 | sNodes = set(n for n in graph if n not in e)
31 | return sNodes
32 |
33 | def makeGraph(words):
34 | graph = {}
35 | for i in range(len(words) - 1):
36 | edge = getEdge(words[i], words[i + 1])
37 | if edge is not None:
38 | if edge[0] in graph:
39 | graph[edge[0]].append(edge[1])
40 | else:
41 | graph[edge[0]] = [edge[1]]
42 | return graph
43 |
44 |
45 |
46 |
47 | print answer(["ba", "ab", "cb"])
--------------------------------------------------------------------------------
/foobar/minionsBoredGame.py:
--------------------------------------------------------------------------------
1 | cache = {
2 | (1, 2): 1,
3 | (3, 2): 3
4 | }
5 |
6 | def numberWays(t, n, cache):
7 | if (t, n) in cache:
8 | return cache[(t, n)]
9 |
10 | def bruteForce(t, n):
11 |
12 |
13 | def move(t, n, pos, moves):
14 | if pos < 1:
15 | return
16 | if pos > n:
17 | return
18 |
19 |
20 |
--------------------------------------------------------------------------------
/foobar/rustyCalculator.py:
--------------------------------------------------------------------------------
1 |
2 | def answer(str):
3 | ans=''
4 | stack = []
5 | for char in str:
6 | if char == '+':
7 | while stack and stack[len(stack)-1] == '*':
8 | ans += stack.pop()
9 | stack.append(char)
10 | elif char == '*':
11 | stack.append(char)
12 | else:
13 | ans += char
14 | while stack:
15 | ans += stack.pop()
16 | return ans
--------------------------------------------------------------------------------
/foobar/saveRabbit.py:
--------------------------------------------------------------------------------
1 | inf = float("inf")
2 |
3 | def answer(food, grid):
4 | memo = [[inf for col in row] for row in grid]
5 | ans = []
6 | traverse(food, grid, 0, 0, memo, ans)
7 | if ans:
8 | return min(ans)
9 | else:
10 | return -1
11 |
12 |
13 | def traverse(food, grid, row, col, memo, ans):
14 | currFood = food - grid[row][col]
15 | if currFood < 0:
16 | return
17 | if currFood < memo[row][col]:
18 | memo[row][col] = currFood
19 | else:
20 | return
21 | if row == len(grid) - 1 and col == len(grid[0]) - 1:
22 | ans.append(currFood)
23 | return
24 | if row < (len(grid) - 1):
25 | traverse(currFood, grid, row + 1, col, memo, ans)
26 | if col < (len(grid[0]) - 1):
27 | traverse(currFood, grid, row, col + 1, memo, ans)
28 |
29 | food1 = 7
30 | grid1 = [[0, 2, 5], [1, 1, 3], [2, 1, 1]]
31 |
32 | food2 = 12
33 | grid2 = [[0, 2, 5], [1, 1, 3], [2, 1, 1]]
34 |
35 |
36 | print answer(food2, grid2)
--------------------------------------------------------------------------------
/foobar/stringCleaning.py:
--------------------------------------------------------------------------------
1 | def answer(chunk, word):
2 | strings = []
3 | explored = []
4 | rmWord(chunk, word, strings, explored)
5 | strings.sort()
6 | return strings[0]
7 |
8 | def rmWord(chunk, word, strings, explored):
9 | positions = [i for i in range(len(chunk)) if chunk.startswith(word, i)]
10 | if not positions:
11 | strings.append(chunk)
12 | for i in positions:
13 | newChunk = chunk[:i] + chunk[i + len(word):]
14 | if newChunk not in explored:
15 | explored.append(newChunk);
16 | rmWord(newChunk, word, strings, explored)
17 |
18 |
19 | print answer("lololololo", "lol")
20 | print answer("goodgooogoogfogoood", "goo")
--------------------------------------------------------------------------------
/foobar/whenItRainsItPours.py:
--------------------------------------------------------------------------------
1 | def answer(heights):
2 | totalWater = 0
3 | i = 0
4 | while i < len(heights) - 1:
5 | lMax = i
6 | # (height, index)
7 | rMax = (0, -1)
8 | if heights[i] > 1:
9 | for j in range(i + 1, len(heights)):
10 | if heights[j] >= heights[lMax]:
11 | rMax = (heights[j], j)
12 | i = j - 1
13 | break
14 | elif heights[j] >= rMax[0]:
15 | rMax = (heights[j], j)
16 | i = j - 1
17 | totalWater += getVolume(heights, lMax, rMax[1])
18 | i += 1
19 | return totalWater
20 |
21 | def getVolume(heights, i, j):
22 | displacement = 0
23 | for height in heights[i + 1:j]:
24 | displacement += height
25 | volume = min([heights[i], heights[j]]) * (j - i - 1)
26 | return volume - displacement
--------------------------------------------------------------------------------
/jj.txt:
--------------------------------------------------------------------------------
1 | JJ is the best
2 |
--------------------------------------------------------------------------------
/mike.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/mike.txt
--------------------------------------------------------------------------------
/python/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/python/.DS_Store
--------------------------------------------------------------------------------
/python/addBinary.py:
--------------------------------------------------------------------------------
1 | def addBinary(a, b):
2 | a10 = int(a, 2)
3 | b10 = int(b, 2)
4 | ans = bin(a10 + b10)
5 | ans = ans[2:]
6 | return ans
7 |
8 | print addBinary('111', '10')
--------------------------------------------------------------------------------
/python/anagram.py:
--------------------------------------------------------------------------------
1 | from collections import Counter
2 | from copy import deepcopy
3 |
4 | def containsAnagram(a, b):
5 | lista = list(a)
6 | for i in range(0, len(b) - len(a) + 1):
7 | chars = lista[:]
8 | for j in range(i, i + len(a)):
9 | if b[j] in chars:
10 | chars.remove(b[j])
11 | if not chars:
12 | return True
13 | else:
14 | break
15 | return False
16 |
17 | def containsAnagram2(a, b):
18 | counta = Counter(a)
19 | substrings = [b[i:i+len(a)] for i in range(0, len(b) - len(a) + 1)]
20 | return any(Counter(subStr) == counta for subStr in substrings)
21 |
22 | print containsAnagram('npe','pencilcase')
23 | print containsAnagram2('npe','pencilcase')
24 | print containsAnagram('case','pencilcase')
25 | print containsAnagram2('case','pencilcase')
26 | print containsAnagram('esca','pencilcase')
27 | print containsAnagram2('esca','pencilcase')
28 | print containsAnagram('abcdef','abczdefabc')
29 | print containsAnagram2('abcdef','abczdefabc')
30 | print containsAnagram('abcdef','abczdefhij')
31 | print containsAnagram2('abcdef','abczdefhij')
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/python/arrayLessThan.py:
--------------------------------------------------------------------------------
1 | # O(nlogn) time, O(n) space
2 |
3 | def arrayLess(n):
4 | s = sorted(n)
5 | s = s[::-1]
6 | last = None
7 | ans = {}
8 | for i in range(0, len(s)):
9 | if s[i] != last:
10 | ans[s[i]] = len(s[:i])
11 | last = s[i]
12 | return [ans[c] for c in n]
13 |
14 | print arrayLess([9,2,5,1,6,7,3,2])
15 |
--------------------------------------------------------------------------------
/python/arrayPairs.py:
--------------------------------------------------------------------------------
1 | import random
2 | from time import time
3 |
4 | def arrayPairs(a, x):
5 | pairs = set()
6 | numMap = {}
7 | for i in range(0, len(a)):
8 | if a[i] in numMap:
9 | numMap[a[i]].append(i)
10 | else:
11 | numMap[a[i]] = [i]
12 | for i in range(0, len(a)):
13 | c = x - a[i]
14 | if c in numMap:
15 | for j in numMap[c]:
16 | if i != j:
17 | if (i, j) not in pairs and (j, i) not in pairs:
18 | pairs.add((i, j))
19 | return pairs
20 |
21 | def arrayPairsBrute(a, x):
22 | pairs = set()
23 | for i in range(0, len(a)):
24 | for j in range(0, len(a)):
25 | if a[i] + a[j] == x and i != j:
26 | if (i, j) not in pairs and (j, i) not in pairs:
27 | pairs.add((i, j))
28 | return pairs
29 |
30 | a = [random.randrange(-10, 10) for i in range(0, 10001)]
31 | print 'finished initializing array...'
32 |
33 | start1 = time()
34 | arrayPairs(a, 3)
35 | end1 = time()
36 | print 'fast: ', end1 - start1
37 |
38 | start2 = time()
39 | arrayPairsBrute(a, 3)
40 | end2 = time()
41 | print 'slow: ', end2 - start2
42 |
43 |
--------------------------------------------------------------------------------
/python/bestLine.py:
--------------------------------------------------------------------------------
1 | from __future__ import division
2 |
3 | # O(n^2) time, calculates line for every pair of points
4 | # beware of floating point comparison, representing slope as rational fraction would be best.
5 | def bestLine(points):
6 | # lines represented by pair (slope, y-intercept)
7 | # or (None, x-intercept) if slope undefined in case of vertical line
8 | lines = {}
9 | pairs = getPairs(points)
10 | for pair in pairs:
11 | l = getLine(pair[0], pair[1])
12 | if l in lines:
13 | if pair[0] not in lines[l]:
14 | lines[l].add(pair[0])
15 | if pair[1] not in lines[l]:
16 | lines[l].add(pair[1])
17 | else:
18 | lines[l] = {pair[0], pair[1]}
19 | return max([len(val) for val in lines.values()])
20 |
21 | def getSlope(s, t):
22 | if s[0] - t[0] == 0:
23 | return None
24 | else:
25 | return (s[1] - t[1]) / (s[0] - t[0])
26 |
27 | def getYIntercept(s, m):
28 | if m is None:
29 | return s[0]
30 | else:
31 | return (m * (-s[0])) + s[1]
32 |
33 | def getLine(s, t):
34 | m = getSlope(s, t)
35 | b = getYIntercept(s, m)
36 | return (m, b)
37 |
38 | def getPairs(inputSet):
39 | pairs = []
40 | done = set()
41 | for s in inputSet:
42 | for t in inputSet - {s}:
43 | if (s, t) not in done:
44 | pairs.append((s, t))
45 | done.add((s, t))
46 | done.add((t, s))
47 | return pairs
48 |
49 | p = {(-1,-1), (0,0), (1,1), (4, 4) ,(1,4), (1,6), (1, 20), (1,-20)}
50 | print bestLine(p)
--------------------------------------------------------------------------------
/python/bst.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data):
3 | self.data = data
4 | self.left = None
5 | self.right = None
6 |
7 | class BST:
8 | def __init__(self):
9 | self.root = None
10 |
11 | def insert(self, data):
12 | if self.root is None:
13 | self.root = Node(data)
14 | else:
15 | self._insert(self.root, data)
16 |
17 | def _insert(self, root, data):
18 | if data < root.data:
19 | if root.left is not None:
20 | self._insert(root.left, data)
21 | else:
22 | root.left = Node(data)
23 | else:
24 | if root.right is not None:
25 | self._insert(root.right, data)
26 | else:
27 | root.right = Node(data)
28 |
29 |
30 | def printTree(self):
31 | self._printTree(self.root)
32 |
33 | def _printTree(self, root):
34 | if root is None:
35 | return
36 | else:
37 | self._printTree(root.left)
38 | print root.data
39 | self._printTree(root.right)
40 |
41 |
42 | tree = BST()
43 | tree.insert(50)
44 | tree.insert(25)
45 | tree.insert(20)
46 | tree.insert(30)
47 | tree.insert(75)
48 | tree.insert(70)
49 | tree.insert(-10)
50 | tree.insert(60)
51 | tree.insert(60)
52 | tree.insert(23)
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/python/buildOrder.py:
--------------------------------------------------------------------------------
1 | def buildOrder(projects, deps):
2 | ins = {p:set() for p in projects}
3 | outs = {p:set() for p in projects}
4 | for d in deps:
5 | ins[d[0]].add(d[1])
6 | outs[d[1]].add(d[0])
7 | order = topSort(outs, ins)
8 | return order
9 |
10 | # O(V + E) time complexity O(V) space
11 | def topSort(outs, ins):
12 | order = []
13 | ready = [n for n in ins.keys() if not ins[n]]
14 | while ready:
15 | n = ready.pop()
16 | order.append(n)
17 | for m in outs[n]:
18 | ins[m] -= {n}
19 | if not ins[m]:
20 | ready.append(m)
21 | if len(order) == len(outs):
22 | return order
23 | else:
24 | return -1
25 |
26 | p1 = ['a', 'b', 'c', 'd', 'e', 'f']
27 | d1 = [('d','a'),('b','f'),('d','b'),('a','f'),('c','d')]
28 | print buildOrder(p1, d1)
29 |
30 | p2 = [1,2,3]
31 | d2 = [(1,2), (2,3), (3,1)]
32 | print buildOrder(p2, d2)
--------------------------------------------------------------------------------
/python/buildTreeFromOrder.py:
--------------------------------------------------------------------------------
1 | from collections import Counter
2 |
3 | class Node:
4 | def __init__(self):
5 | self.data = None
6 | self.left = None
7 | self.right = None
8 |
9 | def splitSeq(s, k):
10 | kcount = Counter(k)
11 | for i in range(len(k), len(s) + 1):
12 | if Counter(s[:i]) == kcount:
13 | return s[:i], s[i:]
14 |
15 | # O(n) runtime
16 | def buildTree(inorder, preorder, node):
17 | node.data = preorder[0]
18 | i = inorder.index(preorder[0])
19 | lInorder = inorder[:i]
20 | rInorder = inorder[i+1:]
21 | lPreorder, rPreorder = splitSeq(preorder[1:], lInorder)
22 | if lInorder:
23 | node.left = Node()
24 | buildTree(lInorder, lPreorder, node.left)
25 | if rInorder:
26 | node.right = Node()
27 | buildTree(rInorder, rPreorder, node.right)
28 |
29 | def printTree(root):
30 | if root is None:
31 | return
32 | else:
33 | printTree(root.left)
34 | print root.data
35 | printTree(root.right)
36 |
37 | print "balanced tree: "
38 | inorder = [3, 5, 7 , 10, 13, 15, 17]
39 | preorder = [10, 5 , 3, 7, 15, 13, 17]
40 | root = Node()
41 | buildTree(inorder, preorder, root)
42 | printTree(root)
43 |
44 | print "unbalanced tree input: "
45 | inorder = [5, 10, 13, 15, 16, 17]
46 | preorder = [10, 5, 15, 13, 17, 16]
47 | root = Node()
48 | buildTree(inorder, preorder, root)
49 | printTree(root)
--------------------------------------------------------------------------------
/python/buyTwo.py:
--------------------------------------------------------------------------------
1 | def buyTwoSlow(cost, items):
2 | for i in range(0, len(items) - 1):
3 | for j in range(0, len(items)):
4 | if items[i] + items[j] == cost:
5 | return i, j
6 |
7 | def buyTwoFast(cost, items):
8 | index = {items[i]:i for i in range(0, len(items))}
9 | for i in range(0, len(items)):
10 | if cost - items[i] in index:
11 | return i, index[cost - items[i]]
12 |
13 | print buyTwoSlow(100, [32, 75,10, 25,28])
14 | print buyTwoFast(100, [32, 75,10, 25,28])
15 |
--------------------------------------------------------------------------------
/python/checkIntersect.py:
--------------------------------------------------------------------------------
1 | # [a,b) and [c,d)
2 | def checkIntersect(a, b, c, d):
3 | if (c >= a and c < b) or (d - 1 >= a and d - 1 < b) or (a >= c and a < d) or (b - 1 >= c and b - 1 < d):
4 | return True
5 | else:
6 | return False
7 |
8 | print checkIntersect(5,7,10,12)
--------------------------------------------------------------------------------
/python/coinChange.py:
--------------------------------------------------------------------------------
1 | # ALVIN ZABLAN
2 | # Professor Saad
3 | # CSCI 395
4 | # Homework 1
5 | # Problem 1 part d
6 | # run with 'python coinChange.py'
7 |
8 | def value(a, c):
9 | s = 0
10 | for i in range(1, a[0] + 1):
11 | s += a[i] * c[i]
12 | return s
13 |
14 | def count(a):
15 | s = 0
16 | for i in range(1, a[0] + 1):
17 | s += a[i]
18 | return s
19 |
20 | def skip(a,c,d,M):
21 | if a[0] == d:
22 | a = [0, '-', '-', '-']
23 | else:
24 | a[0] += 1
25 | a[a[0]] = 0
26 |
27 | def next(a, c, d, m):
28 | if a[0] < d:
29 | a[0] += 1
30 | a[a[0]] = 0
31 | else:
32 | if a[a[0]] < m / c[a[0]]:
33 | a[a[0]] += 1
34 | else:
35 | while a[a[0]] == m / c[a[0]]:
36 | a[a[0]] = '-'
37 | a[0] -= 1
38 | if a[0] == 0:
39 | return
40 | a[a[0]] += 1
41 |
42 | def search(a, c, d, m):
43 | best = m
44 | checked = 0
45 | while a[0] > 0:
46 | checked += 1
47 | if value(a, c) or count(a) > best:
48 | skip(a,c,d,m)
49 | if a[0] == d:
50 | if value(a,c) == m and count(a) < best:
51 | best = count(a)
52 | besta = a[:]
53 | next(a, c, d, m)
54 | print "num checked:", checked
55 | return besta
56 |
57 | def slowSearch(a, c, d, m):
58 | best = m
59 | checked = 0
60 | while a[0] > 0:
61 | checked += 1
62 | if a[0] == d:
63 | if value(a,c) == m and count(a) < best:
64 | best = count(a)
65 | besta = a[:]
66 | next(a, c, d, m)
67 | print "num checked:", checked
68 | return besta
69 |
70 | coins = [None, 25, 15, 1]
71 | numCoins = 3
72 |
73 | arr = [1, 0, 0 ,0]
74 | print search(arr, coins, numCoins, 687)
75 |
76 | arr = [1, 0, 0 ,0]
77 | print slowSearch(arr, coins, numCoins, 687)
78 |
79 |
--------------------------------------------------------------------------------
/python/countPaths.py:
--------------------------------------------------------------------------------
1 | def countPaths(a):
2 | ways = {(0, 0): 1}
3 | return countPath(len(a) - 1, len(a[0]) - 1, a, ways)
4 |
5 | def countPath(i, j, a, ways):
6 | if i < 0 or j < 0:
7 | return 0
8 | if a[i][j] == 0:
9 | return 0
10 | if (i, j) in ways:
11 | return ways[(i, j)]
12 | count = countPath(i - 1, j, a, ways) + countPath(i, j - 1, a, ways)
13 | ways[(i, j)] = count
14 | return count
15 |
16 | a = [
17 | [1,1,1,1,1,1,1,1,1,1,1,1],
18 | [1,0,1,1,1,1,1,1,0,1,1,1],
19 | [1,0,0,1,1,1,1,1,0,0,1,1],
20 | [1,0,1,1,1,1,1,1,1,0,1,1],
21 | [1,1,1,1,1,1,1,1,1,0,0,1],
22 | [1,1,1,0,0,0,1,1,1,1,1,1],
23 | [1,1,1,0,0,1,1,1,1,1,1,1],
24 | [1,1,1,1,1,1,1,1,1,1,1,1],
25 | [1,1,1,1,1,1,1,0,0,0,0,1],
26 | [1,1,1,1,0,1,1,1,1,1,0,1],
27 | [1,1,1,1,0,1,1,1,1,1,0,1],
28 | [1,1,1,1,0,1,1,1,1,1,1,1],
29 | [1,1,1,1,1,1,1,1,1,1,1,1],
30 | [1,1,1,1,1,1,1,0,1,1,1,1],
31 | [1,1,1,1,1,1,1,1,1,1,1,1],
32 | [1,1,1,1,1,1,1,1,1,1,1,1],
33 | [1,1,1,1,1,1,1,1,1,1,1,1],
34 | ]
35 |
36 | print countPaths(a)
37 |
38 |
--------------------------------------------------------------------------------
/python/debruijn.py:
--------------------------------------------------------------------------------
1 | from itertools import product
2 | from copy import deepcopy
3 |
4 | def debruijn(k, n):
5 | if isinstance(k, int):
6 | chars = [str(i) for i in range(0, k)]
7 | elif isinstance(k, str):
8 | chars = [c for c in k]
9 | k = len(k)
10 | length = k ** n
11 | print length
12 | tups = list(product(chars, repeat=n))
13 | strs = set(''.join(e) for e in tups)
14 | remaining = deepcopy(strs)
15 | ans = [];
16 | db(strs, remaining, "", length, ans)
17 | return ans
18 |
19 | def db(strs, remainingStrs, seq, length, ans):
20 | if len(seq) == length:
21 | if isDb(strs, seq):
22 | ans.append(seq)
23 | else:
24 | return
25 | for s in remainingStrs:
26 | if len(seq) == 0:
27 | newSeq = seq + s
28 | newStrs = deepcopy(remainingStrs)
29 | newStrs.remove(s)
30 | db(strs, newStrs, newSeq, length, ans)
31 | elif squish(seq, s):
32 | newSeq = seq + s[-1]
33 | newStrs = deepcopy(remainingStrs)
34 | newStrs.remove(s)
35 | db(strs, newStrs, newSeq, length, ans)
36 |
37 | def squish(str1, str2):
38 | if len(str1) == 0:
39 | return True
40 | elif str1[len(str1) - len(str2) + 1:] == str2[:len(str2) - 1]:
41 | return True
42 | else:
43 | return False
44 |
45 | def isDb(strs, seq):
46 | circleSeq = seq + seq
47 | for s in strs:
48 | if s not in circleSeq:
49 | return False
50 | return True
51 |
52 | x = debruijn(2, 3)
53 |
54 |
55 |
--------------------------------------------------------------------------------
/python/deepestNode.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data):
3 | self.data = data
4 | self.left = None
5 | self.right = None
6 |
7 | def findDeepest(root):
8 | deepest = [-1, None]
9 | traverse(root, 0, deepest)
10 | print 'node:', deepest[1].data
11 | print 'depth:', deepest[0]
12 | return deepest
13 |
14 | def traverse(root, depth, deepest):
15 | if root is None:
16 | return
17 | if depth > deepest[0]:
18 | deepest[0] = depth
19 | deepest[1] = root
20 | traverse(root.left, depth + 1, deepest)
21 | traverse(root.right, depth + 1, deepest)
22 |
23 | one = Node(1)
24 | two = Node(2)
25 | three = Node(3)
26 | four = Node(4)
27 | five = Node(5)
28 | six = Node(6)
29 | seven = Node(7)
30 |
31 | one.left = two
32 | one.right = three
33 | three.left = four
34 | four.right = five
35 | four.left = six
36 | six.right = seven
37 |
38 | findDeepest(one)
--------------------------------------------------------------------------------
/python/depthList.py:
--------------------------------------------------------------------------------
1 | # working with tree class such as bst.py
2 |
3 | class Lnode:
4 | def __init__(self, data):
5 | self.data = data
6 | self.next = None
7 |
8 | def printList(head):
9 | if head is None:
10 | print
11 | return
12 | print '->',
13 | print head.data,
14 | printList(head.next)
15 |
16 | def depthList(root):
17 | n = [root]
18 | l = []
19 | while n:
20 | l.append(Lnode(n[0].data))
21 | last = l[-1]
22 | for i in range(1, len(n)):
23 | last.next = Lnode(n[i].data)
24 | last = last.next
25 | m = len(n)
26 | for i in range(0, m):
27 | node = n.pop(0)
28 | if node.left is not None:
29 | n.append(node.left)
30 | if node.right is not None:
31 | n.append(node.right)
32 | for head in l:
33 | printList(head)
34 |
--------------------------------------------------------------------------------
/python/distinctSubstring.py:
--------------------------------------------------------------------------------
1 | def getDistinct(s):
2 | longest = s[0]
3 | i = 0
4 | latestPos = {s[0]: 0}
5 | for j in range(1, len(s)):
6 | if s[j] in latestPos:
7 | if latestPos[s[j]] >= i:
8 | i = latestPos[s[j]] + 1
9 | latestPos[s[j]] = j
10 | if len(s[i:j + 1]) > len(longest):
11 | longest = s[i:j + 1]
12 | return longest
13 |
14 | # O(n) time compexity
15 |
16 | print getDistinct('aaaaaaaaaa')
17 | print getDistinct('aaabbaaaaa')
18 | print getDistinct('banana')
19 | print getDistinct('alvin')
20 | print getDistinct('geeksforgeeks')
--------------------------------------------------------------------------------
/python/evenOddDiff.py:
--------------------------------------------------------------------------------
1 | # for tree, return (sum of values at odd levels) - (sum of values at even levels)
2 |
3 | def evenOddDiff(root):
4 | s = [0]
5 | evenOdd(root, 0, s)
6 | return s[0]
7 |
8 | def evenOdd(root, depth, s):
9 | if root is None:
10 | return
11 | if depth % 2 == 0:
12 | s[0] -= root.data
13 | else:
14 | s[0] += root.data
15 | evenOdd(root.left, depth + 1, s)
16 | evenOdd(root.right, depth + 1, s)
--------------------------------------------------------------------------------
/python/fib.py:
--------------------------------------------------------------------------------
1 | def fib(x):
2 | if x == 1 or x == 2:
3 | return 1
4 | else:
5 | return fib(x - 1) + fib(x - 2)
6 |
7 | def fibCount(x):
8 | last2 = 0
9 | last1 = 1
10 | print 'fib 1 = 1'
11 | for i in range(2, x + 1):
12 | f = last1 + last2
13 | print 'fib ' + str(i) + ' =',
14 | print f
15 | last2 = last1
16 | last1 = f
17 |
18 | print fib(3)
19 | print fib(4)
20 | print fib(5)
21 | print fib(6)
22 | print fib(7)
23 | print fib(8)
24 |
25 | fibCount(8)
26 |
27 |
--------------------------------------------------------------------------------
/python/findCycle.py:
--------------------------------------------------------------------------------
1 | # O(v+e) time, O(v) space
2 |
3 | def findCycle(n, g, thisVisited, visited):
4 | if n in thisVisited:
5 | return True
6 | if n in visited:
7 | return
8 | newVisited = set(thisVisited)
9 | newVisited.add(n)
10 | for node in g[n]:
11 | if findCycle(node, g, newVisited, visited):
12 | return True
13 | visited.add(n)
14 | return False
15 |
16 | def containsCycle(g):
17 | visited = set()
18 | for v in g:
19 | if findCycle(v, g, set(), visited):
20 | return True
21 | return False
22 |
23 | g = {1:[2], 2:[3], 3:[4, 5], 4:[5, 6], 5:[], 6:[], 7:[7]}
24 | print containsCycle(g)
25 |
--------------------------------------------------------------------------------
/python/flipTree.py:
--------------------------------------------------------------------------------
1 | def flipTree(root):
2 | if root is None:
3 | return
4 | flipTree(root.left)
5 | flipTree(root.right)
6 | root.left, root.right = root.right, root.left
--------------------------------------------------------------------------------
/python/getPermutations.py:
--------------------------------------------------------------------------------
1 | def getPerms(stri):
2 | chars = list(stri)
3 | perms = []
4 | getPerms_(chars, perms, "")
5 | return perms
6 |
7 | def getPerms_(chars, perms, s):
8 | if len(chars) == 0:
9 | perms.append(s)
10 | else:
11 | charSet = set(chars)
12 | for c in charSet:
13 | newChars = chars[:]
14 | newChars.remove(c)
15 | newS = s + c
16 | getPerms_(newChars, perms, newS)
17 |
18 | print getPerms("aaa")
19 | print getPerms("abc")
20 | print getPerms("abca")
21 | print getPerms("bottle")
22 |
--------------------------------------------------------------------------------
/python/graphSearch.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data, neighbors):
3 | self.visited = False
4 | self.data = data
5 | self.neighbors = neighbors
6 |
7 | def bfs(root):
8 | queue = []
9 | root.visited = True
10 | queue.append(root)
11 | while queue:
12 | node = queue.pop(0)
13 | print node.data
14 | for n in node.neighbors:
15 | if not n.visited:
16 | n.visited = True
17 | queue.append(n)
18 |
19 | def dfs(root):
20 | root.visited = True;
21 | print root.data
22 | for n in root.neighbors:
23 | if not n.visited:
24 | n.visited = True
25 | dfs(n)
26 |
27 | one = Node(1,[])
28 | two = Node(2,[])
29 | three = Node(3,[])
30 | four = Node(4,[])
31 | five = Node(5,[])
32 | six = Node(6,[])
33 | seven = Node(7,[])
34 | eight = Node(8,[])
35 |
36 | one.neighbors = [two, three]
37 | three.neighbors = [four, two]
38 | two.neighbors = [six, one]
39 | eight.neighbors = [seven, six]
40 |
41 | def isPath(a, b):
42 | aq = [a]
43 | bq = [b]
44 | avisited = {a}
45 | bvisited = {b}
46 | while aq or bq:
47 | bfsStep(aq, avisited)
48 | bfsStep(bq, bvisited)
49 | if avisited.intersection(bvisited):
50 | return True
51 | return False
52 |
53 | def bfsStep(q, visited):
54 | print 'step'
55 | size = len(q)
56 | for i in range(size):
57 | node = q.pop(0)
58 | for n in node.neighbors:
59 | if n not in visited:
60 | print n.data
61 | visited.add(n)
62 | q.append(n)
63 |
64 | print isPath(one, eight)
65 |
66 |
--------------------------------------------------------------------------------
/python/groupAnagrams.py:
--------------------------------------------------------------------------------
1 | def sortAnagrams(words):
2 | sortChars = {}
3 | for w in words:
4 | wsorted = ''.join(sorted(w))
5 | if wsorted in sortChars:
6 | sortChars[wsorted].append(w)
7 | else:
8 | sortChars[wsorted] = [w]
9 | ans = []
10 | for l in sortChars.values():
11 | ans.extend(l)
12 | return ans
13 |
14 | w = ['alvin', 'tac', 'cat', 'nivla', 'cat', 'vinal', 'dog', 'god', 'supocto','taco', 'octopus', 'computer']
15 | print sortAnagrams(w)
--------------------------------------------------------------------------------
/python/inOrderSucessor.py:
--------------------------------------------------------------------------------
1 | class Node():
2 | def __init__(self, data):
3 | self.data = data
4 | self.left = None
5 | self.right = None
6 | self.parent = None
7 |
8 | def inOrderSuccessor(node):
9 | if node.right is None:
10 | if node.parent.data > node.data:
11 | return node.parent.data
12 | elif node.parent.parent.data > node.data:
13 | return node.parent.parent.data
14 | else:
15 | return 'LAST NODE, NO SUCCESSOR'
16 | elif node.right is not None:
17 | curr = node.right
18 | while curr.left is not None:
19 | curr = curr.left
20 | return curr.data
21 |
22 | ten = Node(10)
23 | five = Node(5)
24 | eight = Node(8)
25 | eight.parent = five
26 | five.right = eight
27 | fifteen = Node(15)
28 | twelve = Node(12)
29 | eighteen = Node(18)
30 | thirteen = Node(13)
31 | thirteen.parent = twelve
32 | twelve.right = thirteen
33 | twelve.parent = fifteen
34 | eighteen.parent = fifteen
35 | fifteen.left = twelve
36 | fifteen.right = eighteen
37 | five.parent = ten
38 | fifteen.parent = ten
39 | ten.left = five
40 | ten.right = fifteen
41 |
42 | print inOrderSuccessor(twelve)
--------------------------------------------------------------------------------
/python/intersection.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data, next):
3 | self.data = data
4 | self.next = next
5 |
6 | class LinkedList:
7 | def __init__(self):
8 | self.head = None
9 |
10 | def insert(self, data):
11 | nextNode = self.head
12 | self.head = Node(data, nextNode)
13 |
14 | def insertNode(self, node):
15 | nextNode = self.head
16 | self.head = node
17 |
18 | def delete(self, data):
19 | if self.head.data == data:
20 | self.head = self.head.next
21 | curr = self.head
22 | while curr is not None:
23 | if curr.data == data:
24 | prev.next = curr.next
25 | break
26 | prev = curr
27 | curr = curr.next
28 |
29 | def getHead(self):
30 | return self.head
31 |
32 | def printList(self):
33 | curr = self.head
34 | while curr is not None:
35 | print curr.data,
36 | curr = curr.next
37 | print
38 |
39 | # return intersecting node
40 | # or return false if no intersection
41 | def getIntersection(list1, list2):
42 | a = list1.getHead()
43 | ids = set()
44 | while a is not None:
45 | ids.add(id(a))
46 | a = a.next
47 | b = list2.getHead()
48 | while b is not None:
49 | if id(b) in ids:
50 | return b
51 | b = b.next
52 | return false
53 |
54 |
55 | a = LinkedList()
56 | a.insert(1)
57 | a.insert(2)
58 | a.insert(3)
59 | a.insert(4)
60 | a.insert(5)
61 | print "list a:"
62 | a.printList()
63 | print "list b:"
64 | b = LinkedList()
65 | b.insertNode(a.getHead())
66 | b.insert(6)
67 | b.insert(7)
68 | b.insert(8)
69 | b.insert(9)
70 | b.insert(10)
71 | b.printList()
72 | intersectNode = getIntersection(a,b)
73 | print "intersection:"
74 | print intersectNode.data
75 |
--------------------------------------------------------------------------------
/python/islands.py:
--------------------------------------------------------------------------------
1 | from itertools import product
2 |
3 | def numIslands(g):
4 | visited = set()
5 | islands = 0
6 | for r in range(len(g)):
7 | for c in range(len(g[0])):
8 | if (r,c) not in visited and g[r][c]:
9 | visited.add((r,c))
10 | bfs(g, r, c, visited)
11 | islands += 1
12 | return islands
13 |
14 | def dfs(g, r, c, visited):
15 | neighbors = getNeighbors(g, r, c)
16 | neighbors -= visited
17 | visited |= neighbors
18 | for row, col in neighbors:
19 | dfs(g, row, col, visited)
20 |
21 | def bfs(g, r, c, visited):
22 | q = []
23 | q.append((r, c))
24 | while q:
25 | row, col = q.pop(0)
26 | neighbors = getNeighbors(g, row, col)
27 | neighbors -= visited
28 | visited |= neighbors
29 | q.extend(neighbors)
30 |
31 | def getNeighbors(g, r, c):
32 | offsets = list(product([-1, 0, 1], repeat=2))
33 | return {(r + y, c + x) for (y, x) in offsets if isValid(g, r + y, c + x)}
34 |
35 | def isValid(g, r, c):
36 | if r < 0 or c < 0:
37 | return False
38 | if r >= len(g) or c >= len(g[0]):
39 | return False
40 | if g[r][c]:
41 | return True
42 | else:
43 | return False
44 |
45 | g = [[1,0,0,1],
46 | [1,1,0,0],
47 | [1,0,0,1],
48 | [1,1,1,1]]
49 |
50 | print numIslands(g)
--------------------------------------------------------------------------------
/python/iterator.py:
--------------------------------------------------------------------------------
1 | class Iterator:
2 | def __init__(self, iterable):
3 | self.iterable = iterable
4 | self.i = 0
5 |
6 | def next(self):
7 | if self.i >= len(self.iterable):
8 | raise StopIteration
9 | item = self.iterable[self.i]
10 | self.i += 1
11 | return item
12 |
13 | l = [0,2,4,6,8,10]
14 | it = Iterator(l)
15 |
16 | # will raise exception
17 | print it.next()
18 | print it.next()
19 | print it.next()
20 | print it.next()
21 | print it.next()
22 | print it.next()
23 | print it.next()
24 | print it.next()
25 | print it.next()
--------------------------------------------------------------------------------
/python/klast.py:
--------------------------------------------------------------------------------
1 | def klast(k, root):
2 | ans = []
3 | _klast(k, root, ans)
4 | if ans:
5 | return ans[0]
6 | else:
7 | return None
8 |
9 | def _klast(k, root, ans):
10 | if root.next is None:
11 | num = 1
12 | else:
13 | num = _klast(k, root.next, ans) + 1
14 | if num == k:
15 | ans.append(root)
16 | return num
--------------------------------------------------------------------------------
/python/largestLexicoSubstr.py:
--------------------------------------------------------------------------------
1 | def lexicoSubstr(s):
2 | for i in range(1, len(s)):
3 | if s[i] > s[0]:
4 | return s[i:]
5 |
6 | a = 'catinthehat'
7 | b = "huntercollege"
8 | c = "xwvza"
9 | d = "ddanger"
10 | print lexicoSubstr(a)
11 | print lexicoSubstr(b)
12 | print lexicoSubstr(c)
13 | print lexicoSubstr(d)
--------------------------------------------------------------------------------
/python/listSort.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data):
3 | self.data = data
4 | self.next = None
5 |
6 | def printL(head):
7 | if head is None:
8 | return
9 | else:
10 | print head.data
11 | printL(head.next)
12 |
13 | def sortList(head):
14 | print 'sorting'
15 | l = []
16 | l.append(head)
17 | curr = head
18 | while curr.next is not None:
19 | curr = curr.next
20 | l.append(curr)
21 | sortedL = mergeSort(l)
22 | for i in range(0, len(sortedL) - 1):
23 | sortedL[i].next = sortedL[i + 1]
24 | sortedL[-1].next = None
25 |
26 | def mergeSort(l):
27 | if len(l) == 1:
28 | return l
29 | mid = len(l) / 2
30 | left = mergeSort(l[:mid])
31 | right = mergeSort(l[mid:])
32 | return merge(left, right)
33 |
34 | def merge(a, b):
35 | result = []
36 | while a or b:
37 | if a and not b:
38 | result.append(a.pop(0))
39 | elif b and not a:
40 | result.append(b.pop(0))
41 | elif a[0].data < b[0].data:
42 | result.append(a.pop(0))
43 | else:
44 | result.append(b.pop(0))
45 | return result
46 |
47 | fifty = Node(50)
48 | fortyFive = Node(45)
49 | seventyTwo = Node(72)
50 | seventyFive = Node(75)
51 | negativeTen = Node(-10)
52 | negativeNine = Node(-9)
53 | four = Node(4)
54 | five = Node(5)
55 |
56 | fifty.next = fortyFive
57 | fortyFive.next = seventyTwo
58 | seventyTwo.next = seventyFive
59 | seventyFive.next = negativeTen
60 | negativeTen.next = negativeNine
61 | negativeNine.next = four
62 | four.next = five;
63 |
64 | printL(fifty)
65 | sortList(fifty)
66 | printL(negativeTen)
67 |
68 |
69 |
--------------------------------------------------------------------------------
/python/loop.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data, next):
3 | self.data = data
4 | self.next = next
5 |
6 |
7 | class LinkedList:
8 | def __init__(self):
9 | self.head = None
10 |
11 | def insert(self, data):
12 | nextNode = self.head
13 | self.head = Node(data, nextNode)
14 |
15 | def getNode(self, index):
16 | curr = self.head
17 | for _ in range(0,index):
18 | curr = curr.next
19 | return curr
20 |
21 | def append(self, node):
22 | curr = self.head
23 | while curr.next is not None:
24 | curr = curr.next
25 | curr.next = node
26 |
27 | def loopCheck(self):
28 | curr = self.head
29 | ids = set()
30 | while True:
31 | nodeId = id(curr)
32 | if nodeId in ids:
33 | break
34 | ids.add(nodeId)
35 | curr = curr.next
36 | return curr
37 |
38 |
39 | l = LinkedList()
40 | l.insert(1)
41 | l.insert(2)
42 | l.insert(3)
43 | l.insert(4)
44 | l.insert(5)
45 | l.insert(6)
46 | l.insert(7)
47 | node = l.getNode(4)
48 | l.append(node)
49 | loopingNode = l.loopCheck()
50 | print loopingNode.data
--------------------------------------------------------------------------------
/python/maxSubarray.py:
--------------------------------------------------------------------------------
1 | def maxSubarraySum(l):
2 | maximum = 0
3 | thisMax = 0
4 | for v in l:
5 | thisMax = max(0, thisMax + v)
6 | maximum = max(maximum, thisMax)
7 | return maximum
8 |
9 | l = [10, 25, 5, 5]
10 | k = [10, -15, 5 , 6]
11 |
12 | print maxSubarraySum(l)
13 | print maxSubarraySum(k)
14 |
--------------------------------------------------------------------------------
/python/mergeLists.py:
--------------------------------------------------------------------------------
1 | def mergeLists(lists):
2 | result = []
3 | for l in lists:
4 | result = merge(l, result)
5 | return result
6 |
7 | def merge(alist, blist):
8 | ans = []
9 | a = alist[:]
10 | b = blist[:]
11 | while a or b:
12 | if a and not b:
13 | ans.append(a.pop(0))
14 | elif b and not a:
15 | ans.append(b.pop(0))
16 | elif a < b:
17 | ans.append(a.pop(0))
18 | else:
19 | ans.append(b.pop(0))
20 | return ans
21 |
22 | a = [1,2,3,4,5,6,7,8,9,10]
23 | b = [2,4,6,8,10]
24 | c = [5,10,15]
25 | d = [3]
26 | e = [7,21,28]
27 | f = [9,9,9]
28 | lists = [a,b,c,d,e,f]
29 | print mergeLists(lists)
30 |
31 |
32 |
--------------------------------------------------------------------------------
/python/mergeStep.py:
--------------------------------------------------------------------------------
1 | def merge(a, b):
2 | ans = []
3 | while a or b:
4 | if a and not b:
5 | ans.append(a.pop(0))
6 | elif b and not a:
7 | ans.append(b.pop(0))
8 | elif a < b:
9 | ans.append(a.pop(0))
10 | else:
11 | ans.append(b.pop(0))
12 | return ans
13 |
14 | a = [5, 10, 15, 20, 25, 50, 75, 100, 101]
15 | b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 27, 81, 90, 99, 101, 103, 300]
16 | print merge(a, b)
--------------------------------------------------------------------------------
/python/minimalTree.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | class Node:
4 | def __init__(self):
5 | self.data = None
6 | self.left = None
7 | self.right = None
8 |
9 | def minimal(a):
10 | root = Node()
11 | _minimal(a, root)
12 | printOrder(root)
13 |
14 | def _minimal(a, root):
15 | mid = int(math.floor(len(a) / 2.0))
16 | root.data = a[mid]
17 | lefta = a[:mid]
18 | righta = a[mid + 1:]
19 | if lefta:
20 | root.left = Node()
21 | _minimal(lefta, root.left)
22 | if righta:
23 | root.right = Node()
24 | _minimal(righta, root.right)
25 |
26 | def printOrder(root):
27 | if root is None:
28 | return
29 | printOrder(root.left)
30 | print root.data
31 | printOrder(root.right)
32 |
33 | a = [1,2,3,4,5,6,7,8,9,10,11,12,13]
34 | minimal(a)
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/python/nextMax.py:
--------------------------------------------------------------------------------
1 | def nextMax(arr):
2 | if len(arr) < 2:
3 | return "error"
4 | largest = float("-inf")
5 | nextLargest = float("-inf")
6 | for i in arr:
7 | if i > largest:
8 | nextLargest = largest
9 | largest = i
10 | elif i > nextLargest:
11 | nextLargest = i
12 | return nextLargest
13 |
14 |
15 | a = [10,4,6]
16 | print nextMax(a)
--------------------------------------------------------------------------------
/python/numberSlice.py:
--------------------------------------------------------------------------------
1 | def solution(X):
2 | xstr = str(X)
3 | indices = []
4 | for i in range(0, len(xstr) - 1):
5 | if xstr[i] == xstr[i + 1]:
6 | indices.append(i)
7 | nums = [int(xstr[:i] + xstr[i + 1:]) for i in indices]
8 | return max(nums)
9 |
10 | print solution(2839339001112)
11 |
--------------------------------------------------------------------------------
/python/operations.py:
--------------------------------------------------------------------------------
1 | # operations using onling the addition (+) operator
2 |
3 | def abs(a):
4 | if a < 0:
5 | return negate(a)
6 | else:
7 | return a
8 |
9 | def negate(a):
10 | if a < 0:
11 | increment = 1
12 | elif a > 0:
13 | increment = -1
14 | else:
15 | return 0
16 | s = 0
17 | if a > 0:
18 | for i in range(0, a):
19 | s += increment
20 | else:
21 | for i in range(0, a, -1):
22 | s += increment
23 | return s
24 |
25 | def subtract(a, b):
26 | return a + negate(b)
27 |
28 | def multiply(a, b):
29 | s = 0
30 | for i in range(0, abs(b)):
31 | s += abs(a)
32 | if (a < 0) ^ (b < 0):
33 | s = negate(s)
34 | return s
35 |
36 | def divide(a, b):
37 | s = abs(a)
38 | i = 0
39 | while s > 0:
40 | s = subtract(s, abs(b))
41 | i += 1
42 | if (a < 0) ^ (b < 0):
43 | i = negate(i)
44 | return i
45 |
46 | print divide(81, -9)
--------------------------------------------------------------------------------
/python/orderedLinkedList.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data, next):
3 | self.data = data
4 | self.next = next
5 |
6 | class LinkedList:
7 | def __init__(self):
8 | self.head = Node(None, None)
9 | self.size = 0
10 |
11 | def insert(self, data):
12 | curr = self.head
13 | while True:
14 | if curr.next is None:
15 | curr.next = Node(data, None)
16 | self.size += 1
17 | return
18 | elif curr.next.data > data:
19 | curr.next = Node(data, curr.next)
20 | self.size += 1
21 | return
22 | curr = curr.next
23 |
24 | def delete(self, data):
25 | prev = self.head
26 | curr = self.head.next
27 | while True:
28 | if curr.data == data:
29 | prev.next = curr.next
30 | self.size -= 1
31 | return
32 | elif curr.next is None:
33 | return
34 | prev = curr
35 | curr = curr.next
36 |
37 | def printSize(self):
38 | print "Size:",self.size
39 |
40 | def printAll(self):
41 | curr = self.head.next
42 | while True:
43 | if curr is None:
44 | print
45 | return
46 | print curr.data,
47 | curr = curr.next
48 |
49 | l = LinkedList()
50 | l.insert(30)
51 | l.insert(32)
52 | l.insert(0)
53 | l.insert(30)
54 | l.insert(29)
55 | l.insert(15)
56 | l.insert(22)
57 | l.insert(-2)
58 | l.insert(-2)
59 | l.insert(0)
60 | l.insert(-1)
61 | l.insert(102)
62 | l.delete(0)
63 | l.delete(102)
64 | l.delete(-2)
65 | l.printAll()
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/python/palindrome.py:
--------------------------------------------------------------------------------
1 |
2 | class Node:
3 | def __init__(self, data, next):
4 | self.data = data
5 | self.next = next
6 |
7 | class LinkedList:
8 | def __init__(self):
9 | self.head = None
10 | self.size = 0
11 |
12 | def insert(self, data):
13 | if self.size == 0:
14 | self.head = Node(data, None)
15 | self.size += 1
16 | else:
17 | nextNode = self.head
18 | self.head = Node(data, nextNode)
19 | self.size += 1
20 |
21 | def getItem(self, index):
22 | curr = self.head
23 | for i in range(0, index):
24 | curr = curr.next
25 | return curr.data
26 |
27 | def getSize(self):
28 | return self.size
29 |
30 | def printAll(self):
31 | curr = self.head
32 | while True:
33 | if curr is None:
34 | print
35 | return
36 | print curr.data,
37 | curr = curr.next
38 |
39 | def getHead(self):
40 | return self.head
41 |
42 | def isPalindrome(linkedList):
43 | stack = []
44 | length = linkedList.getSize()
45 | stackSize = length / 2
46 | for i in range(0, stackSize):
47 | stack.append(linkedList.getItem(i))
48 | if length % 2 == 1:
49 | stackSize += 1
50 | for j in range(stackSize, length):
51 | s = stack.pop()
52 | if s != linkedList.getItem(j):
53 | return False
54 | return True
55 |
56 |
57 | def getSize(head):
58 | curr = head
59 | size = 1
60 | while curr.next is not None:
61 | size += 1
62 | curr = curr.next
63 | return size
64 |
65 | def isPalindrome2(head):
66 | curr = head
67 | stack = []
68 | length = getSize(head)
69 | stackSize = length / 2
70 | for i in range(0, stackSize):
71 | stack.append(curr.data)
72 | curr = curr.next
73 | if length % 2 == 1:
74 | curr = curr.next
75 | while curr is not None:
76 | s = stack.pop()
77 | if s != curr.data:
78 | return False
79 | curr = curr.next
80 | return True
81 |
82 |
83 | l = LinkedList()
84 | l.insert(4)
85 | l.insert(3)
86 | l.insert(2)
87 | l.insert(1)
88 | l.insert(100)
89 | l.insert(1)
90 | l.insert(2)
91 | l.insert(3)
92 | l.insert(4)
93 | l.printAll()
94 | head = l.getHead()
95 | print "length = ", getSize(head)
96 | print "isPalindrome = ", isPalindrome2(head)
--------------------------------------------------------------------------------
/python/palindromeStr.py:
--------------------------------------------------------------------------------
1 | def palindrome(string):
2 | mid = len(string) / 2
3 | for i in range(0, mid):
4 | if string[i] != string[-(i + 1)]:
5 | return False
6 | return True
7 |
8 | print palindrome("abcdef")
9 | print palindrome("abdef")
10 | print palindrome("lool")
11 | print palindrome("locol")
12 |
13 |
14 |
--------------------------------------------------------------------------------
/python/partition.py:
--------------------------------------------------------------------------------
1 | class Node:
2 | def __init__(self, data, next):
3 | self.data = data
4 | self.next = next
5 |
6 | class LinkedList:
7 | def __init__(self):
8 | self.head = None
9 |
10 | def insert(self, data):
11 | nextNode = self.head
12 | self.head = Node(data, nextNode)
13 |
14 | def append(self, node):
15 | curr = self.head
16 | while curr.next is not None:
17 | curr = curr.next
18 | curr.next = node
19 |
20 | def printList(self):
21 | curr = self.head
22 | while curr is not None:
23 | print curr.data,
24 | curr = curr.next
25 | print
26 | def getHead(self):
27 | return self.head
28 |
29 | def partition(head, item):
30 | less = LinkedList()
31 | more = LinkedList()
32 | curr = head
33 | while curr is not None:
34 | if curr.data < item:
35 | less.insert(curr.data)
36 | else:
37 | more.insert(curr.data)
38 | curr = curr.next
39 | more.insert(item)
40 | moreHead = more.getHead()
41 | less.append(moreHead)
42 | less.printList()
43 |
44 |
45 | l = LinkedList()
46 | l.insert(7)
47 | l.insert(1)
48 | l.insert(3)
49 | l.insert(10)
50 | l.insert(2)
51 | l.insert(6)
52 | l.insert(5)
53 | l.insert(4)
54 | l.insert(1)
55 | l.insert(9)
56 | l.printList()
57 | partition(l.getHead(), 5)
58 |
59 |
60 |
--------------------------------------------------------------------------------
/python/pathSum.py:
--------------------------------------------------------------------------------
1 | # BRUTE FORCE SOLUTION O(N^2) TIME:
2 | # def pathSum(root, n, target, count):
3 | # if n == target:
4 | # count[0] += 1
5 | # if root.left is not None:
6 | # pathSum(root.left, n + root.left.data, target, count)
7 | # if root.right is not None:
8 | # pathSum(root.right, n + root.right.data, target, count)
9 |
10 | # def countPath(root, target, count):
11 | # if root is None:
12 | # return
13 | # else:
14 | # pathSum(root, root.data, target, count)
15 | # countPath(root.left, target, count)
16 | # countPath(root.right, target, count)
17 |
18 | # def countPathSum(root, target):
19 | # count = [0]
20 | # countPath(root, target, count)
21 | # return count[0]
22 |
23 | def countPathSum(root, target):
24 | count = [0]
25 | sums = {}
26 | countPath(root, target, sums, count)
27 | return count[0]
28 |
29 | def pathSum(root, target, sums, count):
30 | if root.data == target:
31 | count[0] += 1
32 | if root.left is None and root.right is None:
33 | sums[id(root)] = [root.data]
34 | return
35 | if id(root) not in sums:
36 | sums[id(root)] = [root.data]
37 | if root.left is not None:
38 | for s in sums[id(root.left)]:
39 | thisSum = root.data + s
40 | sums[id(root)].append(thisSum)
41 | if thisSum == target:
42 | count[0] += 1
43 | if root.right is not None:
44 | for s in sums[id(root.right)]:
45 | thisSum = root.data + s
46 | sums[id(root)].append(thisSum)
47 | if thisSum == target:
48 | count[0] += 1
49 |
50 | def countPath(root, target, sums, count):
51 | if root is None:
52 | return
53 | countPath(root.left, target, sums, count)
54 | countPath(root.right, target, sums, count)
55 | pathSum(root, target, sums, count)
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/python/patternMatch.py:
--------------------------------------------------------------------------------
1 | # pattern match, wildcards: '.' = 1 char, '?' = 1 or 0 chars
2 |
3 | def patternMatch(p, s):
4 | j = 0
5 | for i in range(0, len(p)):
6 | if p[i] == '?':
7 | if patternMatch(p[i+1:], s[j:]):
8 | return True
9 | if j == len(s):
10 | return False
11 | if p[i] == '?' or p[i] == '.' or p[i] == s[j]:
12 | j += 1
13 | else:
14 | return False
15 | if len(p) == len(s):
16 | return True
17 | else:
18 | return False
19 |
20 | print patternMatch('?????al?????in??', 'alvin')
21 | print patternMatch('alvin?zablan', 'alvin zablan')
22 | print patternMatch('alvin?zablan', 'alvinzablan')
23 | print patternMatch('al?in', 'alvin')
24 | print patternMatch('al.in', 'alvin')
25 | print patternMatch('al.in.', 'alvin')
26 | print patternMatch('al', 'alvin')
27 | print patternMatch('alvin?', 'al')
--------------------------------------------------------------------------------
/python/permutation.py:
--------------------------------------------------------------------------------
1 | def permutation(a, b):
2 | asort = sorted(a)
3 | bsort = sorted(b)
4 | if asort == bsort:
5 | return True
6 | else:
7 | return False
8 |
9 | def permutation2(a, b):
10 | charList = list(a)
11 | for char in b:
12 | if char in charList:
13 | charList.remove(char)
14 | else:
15 | return False
16 | if charList:
17 | return False
18 | else:
19 | return True
20 |
21 | def permutation3(a, b):
22 | charDict = dict()
23 | if len(a) != len(b):
24 | return False
25 | for char in a:
26 | if char in charDict:
27 | charDict[char] += 1
28 | else:
29 | charDict[char] = 1
30 | for char in b:
31 | if char in charDict:
32 | if charDict[char] == 0:
33 | return False;
34 | charDict[char] -= 1
35 | else:
36 | return False
37 | return True
38 |
39 |
--------------------------------------------------------------------------------
/python/pow2.py:
--------------------------------------------------------------------------------
1 | def isPow2(n):
2 | p = n.bit_length()
3 | m = 1
4 | m = m << p - 1
5 | if m == n:
6 | return True
7 | else:
8 | return False
9 |
10 | def isPow2_(n):
11 | if n == 0:
12 | return False
13 | if (n & (n - 1)) == 0:
14 | return True
15 | else:
16 | return False
17 |
18 | print isPow2(1024)
19 | print isPow2_(1024)
20 |
--------------------------------------------------------------------------------
/python/pow5.py:
--------------------------------------------------------------------------------
1 | def pow5(n):
2 | for i in range(1, n):
3 | if 5**i == n:
4 | return True
5 | elif 5**i > n:
6 | return False
7 |
--------------------------------------------------------------------------------
/python/powerSet.py:
--------------------------------------------------------------------------------
1 | def powerSet(l):
2 | ans = []
3 | pSet(l, [], 0, ans)
4 | return ans
5 |
6 | def pSet(l, a, n, ans):
7 | if n == len(l):
8 | ans.append(a)
9 | else:
10 | y = a[:]
11 | y.append(l[n])
12 | pSet(l, y, n + 1, ans)
13 | pSet(l, a[:], n + 1, ans)
14 |
15 | print powerSet([1,2,3,4,5])
--------------------------------------------------------------------------------
/python/prime.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def isPrime(n):
4 | if n == 2 or n == 3:
5 | return True
6 | if n % 2 == 0:
7 | return False
8 | h = int(math.ceil(math.sqrt(n)))
9 | for i in range(2, h):
10 | if n % i == 0:
11 | return False
12 | return True
13 |
14 | def prime(n):
15 | pCount = 0
16 | i = 2
17 | while True:
18 | if isPrime(i):
19 | pCount += 1
20 | if pCount == n:
21 | return i
22 | i += 1
23 |
24 | print prime(10001)
--------------------------------------------------------------------------------
/python/primeFactor.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def is_prime(n):
4 | if n == 2 or n == 3: return True
5 | if n < 2 or n%2 == 0: return False
6 | if n < 9: return True
7 | if n % 3 == 0: return False
8 | r = int(n**0.5)
9 | f = 5
10 | while f <= r:
11 | if n%f == 0: return False
12 | if n%(f+2) == 0: return False
13 | f +=6
14 | return True
15 |
16 | def largestPrimeFactor(n):
17 | for i in range(1, int(n / 2)):
18 | if n % i == 0:
19 | p = n / i
20 | if is_prime(p):
21 | return p
22 |
23 | print largestPrimeFactor(13195)
24 |
--------------------------------------------------------------------------------
/python/primeSum.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def isPrime(n):
4 | if n == 2:
5 | return True
6 | if n % 2 == 0:
7 | return False
8 | for i in range(2, int(math.sqrt(n)) + 1):
9 | if n % i == 0:
10 | return False
11 | return True
12 |
13 | def sumPrimes(n):
14 | s = 0
15 | for i in range(2, n):
16 | if isPrime(i):
17 | s += i
18 | return s
19 |
20 | print sumPrimes(2000000)
--------------------------------------------------------------------------------
/python/productSeries.py:
--------------------------------------------------------------------------------
1 | num = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
2 |
3 | def largestSeriesProduct(num, n):
4 | largest = -1
5 | for i in range(0, len(num) - n + 1):
6 | s = 1
7 | for j in range(i, i + n):
8 | s = s * int(num[j])
9 | if s > largest:
10 | largest = s
11 | return largest
12 |
13 | print largestSeriesProduct(num, 13)
14 |
--------------------------------------------------------------------------------
/python/pythagoreanTriplet.py:
--------------------------------------------------------------------------------
1 | import time
2 | import math
3 |
4 | def pythagoreanTriplet(n):
5 | for a in range(1, n):
6 | for b in range(a, n):
7 | c = math.sqrt(a**2 + b**2)
8 | if a + b + c == n:
9 | return a * b * c
10 | return -1
11 |
12 | start = time.clock()
13 | print pythagoreanTriplet(1000)
14 | end = time.clock()
15 | print end - start
--------------------------------------------------------------------------------
/python/reverseLinkedList.py:
--------------------------------------------------------------------------------
1 | # for linked list with dummy head
2 | # l is list class
3 |
4 | def reverse(l, last, root):
5 | if root is None:
6 | l.head.next = last
7 | return
8 | next = root.next
9 | root.next = last
10 | reverse(l, root, next)
11 |
12 | # call with reverse(l, None, l.head.next)
--------------------------------------------------------------------------------
/python/reverseStr.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def reverse(string):
4 | s = list(string)
5 | mid = len(s) / 2
6 | for i in range(0, mid):
7 | s[i], s[-(i + 1)] = s[-(i + 1)], s[i]
8 | return ''.join(s)
9 |
10 | print reverse("abcdef")
11 | print reverse("abcde")
12 |
13 |
14 |
--------------------------------------------------------------------------------
/python/reverseVowels.py:
--------------------------------------------------------------------------------
1 | def reverseVowels(string):
2 | vowels = {'a', 'e', 'i', 'o', 'u'}
3 | stack = []
4 | for c in string:
5 | if c in vowels:
6 | stack.append(c)
7 | reverse = list(string)
8 | for i in range(0, len(reverse)):
9 | if reverse[i] in vowels:
10 | reverse[i] = stack.pop()
11 | return ''.join(reverse)
12 |
13 | print reverseVowels("abcdefghi")
14 |
--------------------------------------------------------------------------------
/python/reverseWords.py:
--------------------------------------------------------------------------------
1 | def reverseWords(s):
2 | words = s.split()
3 | words = words[::-1]
4 | return ' '.join(words)
5 |
6 | print reverseWords('hi i am alvin zablan')
--------------------------------------------------------------------------------
/python/runningMedian.py:
--------------------------------------------------------------------------------
1 | from heapq import heappush
2 | from heapq import heappop
3 | from heapq import heappushpop
4 |
5 | class median:
6 | def __init__(self):
7 | self.less = []
8 | self.more = []
9 |
10 | def add(self, n):
11 | if not self.less and not self.more:
12 | heappush(self.less, -n)
13 | return
14 | if n > -self.less[0]:
15 | heappush(self.more, n)
16 | else:
17 | heappush(self.less, -n)
18 | if (len(self.less) - len(self.more)) > 1:
19 | heappush(self.more, -heappop(self.less))
20 | elif (len(self.more) - len(self.less)) > 1:
21 | heappush(self.less, -heappop(self.more))
22 |
23 |
24 | def getMed(self):
25 | if len(self.less) == len(self.more):
26 | return (self.more[0] + -(self.less[0])) / 2.0
27 | elif len(self.less) > len(self.more):
28 | return -(self.less[0])
29 | elif len(self.more) > len(self.less):
30 | return self.more[0]
31 |
32 | m = median()
33 | m.add(10)
34 | print m.getMed()
35 | m.add(9)
36 | print m.getMed()
37 | m.add(11)
38 | print m.getMed()
39 | m.add(50)
40 | print m.getMed()
41 | m.add(7)
42 | print m.getMed()
43 | m.add(100)
44 | print m.getMed()
45 | m.add(101)
46 | print m.getMed()
47 |
48 |
--------------------------------------------------------------------------------
/python/setOfStacks.py:
--------------------------------------------------------------------------------
1 | class SetOfStacks:
2 | def __init__(self):
3 | self.stacks = []
4 | self.stacks.append([])
5 |
6 | def push(self, item):
7 | if len(self.stacks[-1]) < 3:
8 | self.stacks[-1].append(item)
9 | else:
10 | print "adding new stack"
11 | self.stacks.append([])
12 | self.stacks[-1].append(item)
13 | def pop(self):
14 | item = self.stacks[-1].pop()
15 | if len(self.stacks[-1]) == 0:
16 | print "removing stack"
17 | self.stacks.pop()
18 | return item
19 |
20 |
21 | stacks = SetOfStacks()
22 | stacks.push(1)
23 | stacks.push(2)
24 | stacks.push(3)
25 | stacks.push(4)
26 | stacks.push(5)
27 | stacks.push(6)
28 | stacks.push(7)
29 | stacks.push(8)
30 |
31 | print stacks.pop()
32 | print stacks.pop()
33 | print stacks.pop()
34 | print stacks.pop()
35 | print stacks.pop()
36 | print stacks.pop()
37 | print stacks.pop()
38 |
39 |
--------------------------------------------------------------------------------
/python/shuffleArray.py:
--------------------------------------------------------------------------------
1 | from random import randrange
2 |
3 | # O(n) time, O(n) space
4 | def shuffle(a):
5 | values = a[:]
6 | ans = []
7 | while len(ans) != len(values):
8 | k = randrange(0, len(values) - len(ans))
9 | ans.append(mark(values, k))
10 | return ans
11 |
12 | def mark(a, k):
13 | count = -1
14 | for i in range(0, len(a)):
15 | if a[i] is None:
16 | continue
17 | else:
18 | count += 1
19 | if count == k:
20 | ans = a[i]
21 | a[i] = None
22 | return ans
23 |
24 | a = [0,1,2,3,4,5,6,7,8,9]
25 | print shuffle(a)
26 |
--------------------------------------------------------------------------------
/python/singleEdit.py:
--------------------------------------------------------------------------------
1 | # O(n) runtime, O(1) space
2 |
3 | def singleEdit(a, b):
4 | if singleSwap(a, b) or singleInsert(a, b):
5 | return True
6 | else:
7 | return False
8 |
9 | def singleSwap(a, b):
10 | if len(a) != len(b):
11 | return False
12 | edit = 0
13 | for i in range(0, len(a)):
14 | if a[i] != b[i]:
15 | edit += 1
16 | if edit > 1:
17 | return False
18 | return True
19 |
20 | def singleInsert(a, b):
21 | if len(a) == len(b):
22 | return False
23 | elif abs(len(a) - len(b)) > 1:
24 | return False
25 | if len(a) < len(b):
26 | a, b = b, a
27 | edit = 0
28 | for i in range(0, len(b)):
29 | if a[i] != b[i]:
30 | a = a[:i] + a[i + 1:]
31 | edit += 1
32 | if edit > 1:
33 | return False
34 | return True
35 |
36 | print singleEdit('pale', 'ple')
37 | print singleEdit('pales', 'pale')
38 | print singleEdit('pale', 'bale')
39 | print singleEdit('pale', 'pale')
40 | print singleEdit('pale', 'bake')
41 |
42 |
43 |
--------------------------------------------------------------------------------
/python/sortMatrix.py:
--------------------------------------------------------------------------------
1 | from heapq import heappush, heappop
2 | from time import time
3 |
4 | # matrix such that an element is >= the element to the right
5 | # and the element below
6 |
7 | # O(nk*lognk) runtime
8 | def sortMatrixSlow(m):
9 | if len(m) < len(m[0]):
10 | return mergeLists()
11 | else:
12 | newMatrix = []
13 | for i in range(0, len(m[0])):
14 | newL = []
15 | for l in m:
16 | newL.append(l[i])
17 | newMatrix.append(newL)
18 | return mergeLists(newMatrix)
19 |
20 | def mergeLists(lists):
21 | lists = lists[:]
22 | result = []
23 | for l in lists:
24 | result = merge(l, result)
25 | return result[::-1]
26 |
27 | def merge(alist, blist):
28 | ans = []
29 | a = alist[:]
30 | b = blist[:]
31 | while a or b:
32 | if a and not b:
33 | ans.append(a.pop(0))
34 | elif b and not a:
35 | ans.append(b.pop(0))
36 | elif a > b:
37 | ans.append(a.pop(0))
38 | else:
39 | ans.append(b.pop(0))
40 | return ans
41 |
42 | # for k by n matrix O(kn*log(k)) runtime if k < n
43 | def sortMatrixFast(m):
44 | if len(m) < len(m[0]):
45 | return mergeListsQ()
46 | else:
47 | newMatrix = []
48 | for i in range(0, len(m[0])):
49 | newL = []
50 | for l in m:
51 | newL.append(l[i])
52 | newMatrix.append(newL)
53 | return mergeListsQ(newMatrix)
54 |
55 | def mergeListsQ(lists):
56 | lists = lists[:]
57 | h = []
58 | for i in range(0, len(lists)):
59 | pair = (lists[i].pop(), i)
60 | heappush(h, pair)
61 | ans = []
62 | while h:
63 | value, i = heappop(h)
64 | ans.append(value)
65 | if lists[i]:
66 | pair = (lists[i].pop(), i)
67 | heappush(h, pair)
68 | return ans
69 |
70 |
71 | m = [
72 | [100, 90, 80, 70, 68, 50],
73 | [92, 90, 77, 59, 55, 33],
74 | [69, 68, 71, 56, 54, 33],
75 | [64, 30, 29, 29, 22, 16],
76 | [27, 24, 22, 21, 13, 11],
77 | [23, 21, 18, 16, 11, 10]
78 | ]
79 |
80 | print sortMatrixFast(m)
81 |
--------------------------------------------------------------------------------
/python/sortStack.py:
--------------------------------------------------------------------------------
1 | class SortStack:
2 | def __init__(self):
3 | self.s = []
4 |
5 | def push(self, item):
6 | temp = []
7 | if len(self.s) == 0:
8 | self.s.append(item)
9 | return
10 | else:
11 | while self.s[-1] < item:
12 | temp.append(self.s.pop());
13 | if len(self.s) == 0:
14 | break;
15 | self.s.append(item)
16 | while len(temp):
17 | self.s.append(temp.pop())
18 |
19 | def pop(self):
20 | item = self.s.pop()
21 | print "pop ", item
22 |
23 | myStack = SortStack()
24 | myStack.push(14)
25 | myStack.push(17)
26 | myStack.push(20)
27 | myStack.push(15)
28 | myStack.push(3)
29 | myStack.push(2)
30 | myStack.push(16)
31 | myStack.push(17)
32 | myStack.push(25)
33 | myStack.push(19)
34 | myStack.pop()
35 | myStack.pop()
36 | myStack.pop()
37 | myStack.pop()
38 | myStack.pop()
39 | myStack.pop()
40 | myStack.pop()
41 | myStack.pop()
42 | myStack.pop()
43 | myStack.pop()
--------------------------------------------------------------------------------
/python/sortStr.py:
--------------------------------------------------------------------------------
1 | def merge(s1, s2, key):
2 | ans = []
3 | while s1 or s2:
4 | if s1 and not s2:
5 | ans.append(s1.pop(0))
6 | elif s2 and not s1:
7 | ans.append(s2.pop(0))
8 | elif s1 and s2:
9 | if key[s1[0]] < key[s2[0]]:
10 | ans.append(s1.pop(0))
11 | else:
12 | ans.append(s2.pop(0))
13 | return ans
14 |
15 | def mergeSort(s, key):
16 | if len(s) == 1:
17 | return s
18 | mid = len(s) / 2
19 | left = mergeSort(s[:mid], key)
20 | right = mergeSort(s[mid:], key)
21 | return merge(left, right, key)
22 |
23 |
24 | def sort(str1, str2):
25 | order = {l : i for i, l in enumerate(str2)}
26 | for l in str1:
27 | if l not in order:
28 | order[l] = len(str2)
29 | ans = mergeSort(list(str1), order)
30 | return ''.join(ans)
31 |
32 | print sort("hello", "loade")
33 | print sort("terrible", "brelt")
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/python/splitWords.py:
--------------------------------------------------------------------------------
1 | def splitWords(s, d, m):
2 | if s in d:
3 | return s
4 | elif s in m.keys():
5 | return m[s]
6 | else:
7 | for i in range(len(s)):
8 | prefix = s[:i]
9 | suffix = s[i:]
10 | if prefix in d:
11 | remainder = splitWords(suffix, d, m)
12 | if remainder is not None:
13 | split = prefix + ' ' + remainder
14 | m[s] = split
15 | return split
16 | m[s] = None
17 | return None
18 |
19 | s = 'peanutbutter'
20 | d = {'pea', 'nut', 'but' ,'butt', 'butter', 'utter'}
21 | memo = {}
22 | print splitWords(s, d, memo)
23 |
24 | s = 'aaaaaaaaaab'
25 | d = {'a','aa','aaa','aaaa', 'aaaaa', 'aaaaaa', 'aaaaaaa', 'aaaaaaaa', 'aaaaaaaaa'}
26 | memo = {}
27 | print splitWords(s, d, memo)
--------------------------------------------------------------------------------
/python/strCompress.py:
--------------------------------------------------------------------------------
1 | def strCompress(s):
2 | freq = {}
3 | for char in s:
4 | if char not in freq:
5 | freq[char] = 1
6 | else:
7 | freq[char] += 1
8 | ans = ''
9 | for k in freq.keys():
10 | ans += str(k)
11 | ans += str(freq[k])
12 | return ans
13 |
14 | print strCompress('alvinzablanisacomputersciencemajorpythonisthebestlanguageever')
--------------------------------------------------------------------------------
/python/stripSpace.py:
--------------------------------------------------------------------------------
1 | def stripSpace(s):
2 | words = s.split()
3 | return ' '.join(words)
4 |
5 |
6 | def stripSpace2(s):
7 | words = []
8 | word = []
9 | for i in range(len(s)):
10 | if s[i] is not ' ':
11 | word.append(s[i])
12 | elif word:
13 | words.append(''.join(word))
14 | word = []
15 | if word:
16 | words.append(''.join(word))
17 | return ' '.join(words)
18 |
19 | print stripSpace2('hi i am alvin ')
20 |
--------------------------------------------------------------------------------
/python/subSort.py:
--------------------------------------------------------------------------------
1 | def subSortSlow(a):
2 | asorted = sorted(a)
3 | for i in range(0, len(a)):
4 | if a[i] != asorted[i]:
5 | left = i
6 | break
7 | for j in range(len(a) - 1, -1, -1):
8 | if a[j] != asorted[j]:
9 | right = j
10 | break
11 | return (left, right)
12 | # O(nlogn)
13 |
14 | def subSort(a):
15 | for i in range(0, len(a) - 1):
16 | if a[i] > a[i + 1]:
17 | left = i
18 | break
19 | for j in range(len(a) - 1, 0, -1):
20 | if a[j] < a[j - 1]:
21 | right = j
22 | break
23 | minL = min(a[left:right + 1])
24 | maxR = max(a[left:right + 1])
25 | for i in range(left - 1, -1, -1):
26 | if a[i] < minL:
27 | left = i + 1
28 | break
29 | for j in range(right + 1, len(a)):
30 | if a[j] > maxR:
31 | right = j - 1
32 | break
33 | return (left, right)
34 | # O(n)
35 |
36 |
37 | a = [6,1,2,3,4,5,7,8,9]
38 | print subSort(a)
39 | print subSortBrute(a)
--------------------------------------------------------------------------------
/python/subsets.py:
--------------------------------------------------------------------------------
1 |
2 | def subsetPrint(l):
3 | myList = []
4 | for (ele, val) in l:
5 | if val == True:
6 | myList.append(ele)
7 | print myList
8 |
9 | def getSubsets(l, index):
10 | if len(l) == index:
11 | subsetPrint(l)
12 | else:
13 | e = l[index]
14 | eTrue = (e, True)
15 | eFalse = (e, False)
16 | list1 = l[:]
17 | list2 = l[:]
18 | list1[index] = eTrue
19 | list2[index] = eFalse
20 | getSubsets(list1, index + 1)
21 | getSubsets(list2, index + 1)
22 |
23 |
24 | myList = [1,2,3,4,5]
25 | list2 = ['a','b','c']
26 | getSubsets(list2, 0)
--------------------------------------------------------------------------------
/python/sumOfSquares.py:
--------------------------------------------------------------------------------
1 | from time import time
2 |
3 | def getSquares(n):
4 | ans = []
5 | i = 1
6 | while i**2 <= n:
7 | ans.append(i**2)
8 | i += 1
9 | return ans[::-1]
10 |
11 | def getShortestSqSumBrute(n):
12 | best = [[1 for i in range(0, n)]]
13 | squares = getSquares(n)
14 | findSumBrute(n, [], squares, best)
15 | return best[0]
16 |
17 | def findSumBrute(n, ans, squares, best):
18 | if n < 0:
19 | return
20 | # if len(ans) >= len(best[0]):
21 | # return
22 | if n == 0 and len(ans) < len(best[0]):
23 | best[0] = ans
24 | return
25 | for s in squares:
26 | newAns = ans[:]
27 | newAns.append(s)
28 | findSumBrute(n - s, newAns, squares, best)
29 | # brute force, O(n^2), O(1) space
30 |
31 | def getShortestSqSum(n):
32 | sumsDict = {0: [], 1: [1]}
33 | squares = getSquares(n)
34 | return findSum(n, sumsDict, squares)
35 |
36 | def findSum(n, sums, squares):
37 | if n in sums:
38 | return sums[n]
39 | best = [1 for i in range(0, n)]
40 | for s in squares:
41 | if s > n:
42 | continue
43 | ans = [s]
44 | ans.extend(findSum(n - s, sums, squares))
45 | if len(ans) < len(best):
46 | best = ans
47 | sums[n] = best
48 | return best
49 | # dynamic programming, O(n) time, O(n) space
50 |
51 | for i in range(0, 50):
52 | print i, "==============================================="
53 | start = time()
54 | getShortestSqSum(i)
55 | end = time()
56 | print 'dynamic programming: ', end - start
57 | start = time()
58 | getShortestSqSumBrute(i)
59 | end = time()
60 | print 'brute force: ', end - start
61 |
--------------------------------------------------------------------------------
/python/sumSubmatrix.py:
--------------------------------------------------------------------------------
1 | import numpy
2 |
3 | def sumSubmatrix(m, left, right, bottom, top):
4 | subSum = 0
5 | for i in range(top, bottom + 1):
6 | for j in range(left, right + 1):
7 | subSum += m[i][j]
8 | return subSum
9 |
10 | m = numpy.random.random_integers(1, 9, (9, 9))
11 | print m
12 | print sumSubmatrix(m, 6, 8, 1, 0)
13 |
14 |
--------------------------------------------------------------------------------
/python/topologicalSort.py:
--------------------------------------------------------------------------------
1 | def topSort(outs, ins):
2 | order = []
3 | ready = [n for n in ins.keys() if not ins[n]]
4 | while ready:
5 | n = ready.pop()
6 | order.append(n)
7 | for m in outs[n]:
8 | ins[m] -= {n}
9 | if not ins[m]:
10 | ready.append(m)
11 | return order
12 |
13 | outs = {
14 | 1:{3},
15 | 2:{3,7},
16 | 3:{4,6},
17 | 4:{5,6},
18 | 6:{5},
19 | 5:{7},
20 | 7:{8},
21 | 8:{}
22 | }
23 |
24 | ins = {
25 | 1:{},
26 | 2:{},
27 | 3:{1,2},
28 | 4:{3},
29 | 6:{3,4},
30 | 5:{4,6},
31 | 7:{2,5},
32 | 8:{7}
33 | }
34 |
35 | print topSort(outs, ins)
--------------------------------------------------------------------------------
/python/treeSize.py:
--------------------------------------------------------------------------------
1 | def countSize(root):
2 | if root is None:
3 | return 0
4 | return countSize(root.left) + countSize(root.right) + 1
5 |
6 | def countInRange(root, minVal, maxVal):
7 | if root is None:
8 | return 0
9 | if root.data >= minVal and root.data <= maxVal:
10 | thisNode = 1
11 | else:
12 | thisNode = 0
13 | return countInRange(root.left, minVal, maxVal) + countInRange(root.right, minVal, maxVal) + thisNode
--------------------------------------------------------------------------------
/python/treeToList.py:
--------------------------------------------------------------------------------
1 | # last should be a list containing a dummy node to begin list O(1) space
2 |
3 | def inOrderList(root, last):
4 | if root is None:
5 | return
6 | inOrderList(root.left, last)
7 | last[0].right = root
8 | root.left = last[0]
9 | last[0] = root
10 | inOrderList(root.right, last)
11 |
12 | def printL(root):
13 | if root is None:
14 | return
15 | print root.data
16 | printL(root.right)
--------------------------------------------------------------------------------
/python/tripleStep.py:
--------------------------------------------------------------------------------
1 |
2 | def tripleStep(n, results, x=0, y=0, z=0):
3 | remainder = n - (x + 2*y + 3*z)
4 | if remainder == 0:
5 | results.append((x,y,z))
6 | return
7 | if remainder >= 3:
8 | tripleStep(n,results,x,y,z+1)
9 | if remainder >= 2:
10 | tripleStep(n,results,x,y+1,z)
11 | tripleStep(n,results,x+1,y,z)
12 |
13 | def countTripleStep(n):
14 | results = []
15 | tripleStep(n,results)
16 | print len(results)
17 |
18 |
19 | def countWays(n):
20 | if n < 0:
21 | return 0
22 | elif n == 0:
23 | return 1
24 | else:
25 | return countWays(n-1) + countWays(n-2) + countWays(n-3)
26 |
27 | countTripleStep(6)
28 | print countWays(6)
--------------------------------------------------------------------------------
/python/unpairedInArray.py:
--------------------------------------------------------------------------------
1 | def findUnpairedElement(a):
2 | unpaired = a[0]
3 | for item in a[1:]:
4 | unpaired ^= item
5 | return unpaired
6 |
7 | l = [1,7,1,3,4,5,5,4,3]
8 | print findUnpairedElement(l)
--------------------------------------------------------------------------------
/python/zeroMatrix.py:
--------------------------------------------------------------------------------
1 | import numpy
2 |
3 | # O(nm) time, O(1) space
4 | def zeroMatrix(m):
5 | print m
6 | zeroFirstRow, zeroFirstCol = findZeros(m)
7 | for r in range(1, len(m)):
8 | if m[r][0] == -1:
9 | zeroRow(r, m)
10 | for c in range(1, len(m[0])):
11 | if m[0][c] == -1:
12 | zeroCol(c, m)
13 | if zeroFirstRow:
14 | zeroRow(0, m)
15 | if zeroFirstCol:
16 | zeroCol(0, m)
17 | print m
18 |
19 | def findZeros(m):
20 | zeroRow = False
21 | zeroCol = False
22 | for r in range(0, len(m)):
23 | if m[r][0] == 0:
24 | zeroCol = True
25 | break
26 | for c in range(0, len(m[0])):
27 | if m[0][c] == 0:
28 | zeroRow = True
29 | break
30 | for row in range(0, len(m)):
31 | for col in range(0, len(m[0])):
32 | if m[row][col] == 0:
33 | m[0][col] = -1
34 | m[row][0] = -1
35 | return zeroRow, zeroCol
36 |
37 | def zeroRow(row, m):
38 | for i in range(0, len(m[0])):
39 | m[row][i] = 0
40 |
41 | def zeroCol(col, m):
42 | for i in range(0, len(m)):
43 | m[i][col] = 0;
44 |
45 | m = numpy.random.random_integers(1,9, (9,9))
46 | m[0][1] = 0
47 | m[3][7] = 0
48 | m[3][0] = 0
49 | m[8][8] = 0
50 | m[5][1] = 0
51 | zeroMatrix(m)
--------------------------------------------------------------------------------
/yansi.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alvin-the-programmer/Practice/6ef2f68980ca40c76ff162f980e8972d94618498/yansi.txt
--------------------------------------------------------------------------------