├── .gitignore ├── LICENSE ├── README.md ├── algorithm-questions.ipynb ├── cpp ├── LinkedList │ ├── DetermineCyclicOrAcyclic │ │ ├── LinkedList.cpp │ │ ├── LinkedList.h │ │ └── main.cpp │ ├── FindKthLastElement │ │ ├── LinkedList.cpp │ │ ├── LinkedList.h │ │ └── main.cpp │ ├── RemoveDuplicates │ │ ├── LinkedList.cpp │ │ ├── LinkedList.h │ │ └── main.cpp │ └── SortedLinkedList │ │ ├── SortedLinkedList.cpp │ │ ├── SortedLinkedList.h │ │ └── main.cpp └── List │ ├── UnsortedList.cpp │ ├── UnsortedList.h │ └── main.cpp ├── java ├── .gitignore ├── 3sum │ └── src │ │ └── Challenges │ │ └── ThreeSum.java ├── CompressString │ └── src │ │ └── Application.java ├── DiameterOfBTree │ └── src │ │ └── muatik │ │ ├── BTree.java │ │ ├── GreatestDistance.java │ │ └── main.java ├── FirstNonRepetatedChar │ └── src │ │ └── Application.java ├── Graphs │ └── src │ │ ├── e2 │ │ ├── Bag.java │ │ ├── Digraph.java │ │ ├── Digraph_DFS.java │ │ ├── Graph.java │ │ ├── Graph_BFS.java │ │ └── Graph_DFS.java │ │ └── muatik │ │ ├── AdjacencyList.java │ │ ├── Graph.java │ │ └── Graph_DFS.java ├── Heap │ └── src │ │ └── muatik │ │ └── MaxPriorityQueue.java ├── IsRotation │ └── src │ │ └── Application.java ├── Sorting │ └── src │ │ └── Challenges │ │ ├── ISort.java │ │ ├── Insertion.java │ │ ├── MergeSort.java │ │ ├── Selection.java │ │ ├── Shell.java │ │ └── example.java ├── Stack │ └── src │ │ └── Challenges │ │ ├── FixedArrayStack.java │ │ ├── GenericFixedArrayStack.java │ │ ├── IterableGenericFixedArrayStack.java │ │ ├── LinkedListStack.java │ │ ├── ResizableArrayStack.java │ │ ├── StackInterface.java │ │ └── usage.java ├── Strings │ └── src │ │ └── Challenges │ │ └── ReverseString.java ├── Trees │ └── src │ │ └── muatik │ │ ├── BTree.java │ │ ├── BTree_BFS.java │ │ ├── BTree_DFS.java │ │ └── Example.java ├── challenge-string-unique │ └── src │ │ └── Application.java ├── hackerrankRandom │ └── DesignersPdfViewer │ │ ├── out │ │ └── production │ │ │ └── DesignersPdfViewer │ │ │ └── Application.class │ │ └── src │ │ └── Application.java ├── isPermutationOf │ └── src │ │ └── Application.java ├── queues │ └── src │ │ └── Challenges │ │ ├── FixedArrayQueue.java │ │ ├── FixedArrayQueue2.java │ │ ├── LinkedListQueue.java │ │ ├── QueueInterface.java │ │ ├── ResizableQueue.java │ │ └── exmaple.java ├── tree-preorder-traversel │ └── src │ │ ├── HeightOfTree.java │ │ ├── LevelOrderTraversing.java │ │ ├── Solution.java │ │ └── TopViewTree.java └── union │ └── src │ └── UnionFind │ ├── QuickFind.java │ ├── QuickUnion.java │ ├── UnionFind.java │ ├── WeightedQuickUnion.java │ └── example.java └── python ├── 10daysOfStatistics ├── Day_4_Binomial_Distribution.ipynb ├── Day_4_Binomial_Distribution_II.ipynb ├── Day_4_Geometric_Distribution_I.ipynb ├── Day_5_Normal_Distribution_I.ipynb ├── Day_5_Normal_Distribution_II.ipynb ├── Day_5_Poisson_Distribution_I.ipynb ├── Day_5_Poisson_Distribution_II .ipynb └── Day_7_Pearson_Correlation_Coefficient_I.ipynb ├── DiameterOfBTree ├── GreatestDistance.py ├── btree.py └── main.py ├── calculating_tangent_line.ipynb ├── challenge-array-permutationof.ipynb ├── challenge-find-non-repeative.ipynb ├── challenge-remove-character-from-string.ipynb ├── challenge-reverse-string.ipynb ├── challenge-reverse-words.ipynb ├── challenges-array-unique.ipynb ├── challenges-string-compress.ipynb └── hackerrankrandom └── pdf_viewer.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | 60 | # ipython 61 | .ipynb* 62 | 63 | #pycharm 64 | .idea/ 65 | 66 | # intellij 67 | *.iml 68 | out/ 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Mustafa Atik 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding challenges 2 | In this repository, I store my solutioins to the common programming problems. Currently, I try to implement each solution in Python and Java, maybe sometimes C++. By doing so, I can compare languages with respect to implementations. 3 | 4 | The solutions in this repo are not meant to be the best ones. You may find better solutions out there. What is more, you can come up with your own solution which can be considered as the best one. Bear in mind that in practice optimal solution depends on various parameters such as workset data, environment, constraints etc. 5 | 6 | | Challenge | Description | Python | Java | C++ | 7 | |---|---|---|---|---| 8 | |Determine if a string contains unique characters | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/arrays_strings/unique_chars/unique_chars_challenge.ipynb) | [Solution](http://nbviewer.ipython.org/github/muatik/my-coding-challenges/blob/master/python/challenges-array-unique.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/challenge-string-unique) | - | 9 | |Determine if a string is a permutation of another | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/arrays_strings/permutation/permutation_challenge.ipynb) | [Solution](http://nbviewer.ipython.org/github/muatik/my-coding-challenges/blob/master/python/challenge-array-permutationof.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/isPermutationOf) | - 10 | |Determine if a string is a rotation of another | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/arrays_strings/rotation/rotation_challenge.ipynb) | - | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/IsRotation) | - 11 | |Compress a string | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/arrays_strings/compress/compress_challenge.ipynb)| [Solution](http://nbviewer.ipython.org/github/muatik/my-coding-challenges/blob/master/python/challenges-string-compress.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/CompressString) | - 12 | |Reverse strings in a string | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/arrays_strings/reverse_string/reverse_string_challenge.ipynb) | [Solution](http://nbviewer.ipython.org/github/muatik/my-coding-challenges/blob/master/python/challenge-reverse-string.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/Strings/src/Challenges/ReverseString.java) | - 13 | |Find the first non-repeated character in a string | - | [Solution](http://nbviewer.ipython.org/github/muatik/my-coding-challenges/blob/master/python/challenge-find-non-repeative.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/java/FirstNonRepetatedChar) | - 14 | 15 | 16 | ### Linked Lists 17 | 18 | | Challenge | Description | Python | Java | C++ | 19 | |---|---|---|---|---| 20 | | Implement a sorted linked list | - | - | - | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/cpp/LinkedList/SortedLinkedList/) 21 | | Remove duplicates from a linked list | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/remove_duplicates/remove_duplicates_challenge.ipynb) | - | - | [Solution](https://github.com/muatik/my-coding-challenges/blob/master/cpp/LinkedList/RemoveDuplicates) 22 | | Find the kth to last element of a linked list | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/kth_to_last_elem/kth_to_last_elem_challenge.ipynb)| - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/cpp/LinkedList/FindKthLastElement) 23 | | Delete a node in the middle of a linked list | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/delete_mid/delete_mid_challenge.ipynb) | - | - | - 24 | | Partition a linked list around a given value | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/partition/partition_challenge.ipynb) | - | - | - 25 | | Add two numbers whose digits are stored in a linked list | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/add_reverse/add_reverse_challenge.ipynb) | - | - | - 26 | | Find the start of a linked list loop | [Challenge]() | - | - | - 27 | | Determine if a linked list is a palindrome | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/palindrome/palindrome_challenge.ipynb) | - | - | - 28 | | Implement a linked list | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/linked_lists/linked_list/linked_list_challenge.ipynb) | - | - | - 29 | | Determine if a list is cyclic or acyclic | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - 30 | 31 | 32 | #### Stacks and Queues 33 | 34 | | Challenge | Description | Python | Java | C++ 35 | |---|---|---|---|--- 36 | | Implement a stack using a linked list | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Stack/src/Challenges) | - 37 | | Implement a stack using a fixed array | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Stack/src/Challenges) | - 38 | | Implement a stack using a resizable array | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Stack/src/Challenges) | - 39 | | Implement a queue using a linked list | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/queues/src/Challenges) | - 40 | | Implement a queue using a fixed array | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/queues/src/Challenges) | - 41 | | Implement a queue using a resizable array | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/queues/src/Challenges) | - 42 | 43 | #### Sorting 44 | 45 | | Challenge | Description | Python | Java | C++ 46 | |---|---|---|---|--- 47 | | Implement an insertion sorting . | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Sorting/src/Challenges) | - 48 | | Implement a selection sorting . | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Sorting/src/Challenges) | - 49 | | Implement a shell sorting . | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Sorting/src/Challenges) | - 50 | 51 | 52 | #### Trees and Graphs 53 | 54 | | Challenge | Description | Python | Java | C++ 55 | |---|---|---|---|--- 56 | | Given an array A of integers, find any 3 of them that sum to 0. | [Definition](https://en.wikipedia.org/wiki/3SUM) | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/3sum/src/Challenges) | - 57 | | Implement Union-Find algorithm | [Definition](http://algs4.cs.princeton.edu/15uf/) | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/union/src/UnionFind) | - 58 | 59 | 60 | 61 | ### Graphs and Trees 62 | 63 | | Challenge | Description | Python | Java | C++ 64 | |---|---|---|---|--- 65 | | Implement depth-first search (pre-, in-, post-order) on a tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/tree_dfs/dfs_challenge.ipynb) | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Trees/src/muatik) | - | 66 | | Implement breadth-first search on a tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/tree_bfs/bfs_challenge.ipynb) | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/Trees/src/muatik) | - | 67 | | Determine the height of a tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/tree_height/height_challenge.ipynb) | - | - | - | 68 | | Create a binary search tree with minimal height from a sorted array | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/bst_min/bst_min_challenge.ipynb) | - | - | - | 69 | | Find diameter length and nodes of a binary tree | - | - | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/DiameterOfBTree/src/muatik) | - | 70 | | Create a linked list for each level of a binary tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/tree_level_lists/tree_level_lists_challenge.ipynb) | - | - | - | 71 | | Check if a binary tree is balanced | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/check_balance/check_balance_challenge.ipynb) | - | - | - | 72 | | Determine if a tree is a valid binary search tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/bst_validate/bst_validate_challenge.ipynb) | - | - | - | 73 | | Find the in-order successor of a given node in a binary search tree. | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/bst_successor/bst_successor_challenge.ipynb) | - | - | - | 74 | | Implement a binary search tree | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/bst/bst_challenge.ipynb) | - | - | - | 75 | | Implement depth-first search on a graph | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_dfs/dfs_challenge.ipynb) | - | - | - | 76 | | Implement breadth-first search on a graph | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_bfs/bfs_challenge.ipynb) | - | - | - | 77 | | Determine if there is a path between two nodes in a graph | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_path_exists/path_exists_challenge.ipynb) | - | - | - | 78 | | Implement a graph | [Challenge](http://nbviewer.ipython.org/github/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph/graph_challenge.ipynb) | - | - | - | 79 | | Print a tree using pre-order traversal without recursion | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 80 | | Determine the lowest common ancestor of two nodes | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 81 | | Transform a binary tree into a heap | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 82 | | Implement a right and left rotation on a tree | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 83 | | Check if a binary tree is binary search tree | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 84 | | Add a challenge | [Contribute](https://github.com/donnemartin/interactive-coding-challenges/blob/master/CONTRIBUTING.md) | - | - | - | 85 | 86 | ### 10 Days of Statistics 87 | https://www.hackerrank.com/domains/tutorials/10-days-of-statistics 88 | 89 | | Challenge | Description | Python | Java | C++ 90 | |---|---|---|---|--- 91 | | Day 4: Binomial Distribution I | [Definition](https://www.hackerrank.com/challenges/s10-binomial-distribution-1) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_4_Binomial_Distribution.ipynb) | - | - 92 | | Day 4: Binomial Distribution II | [Definition](https://www.hackerrank.com/challenges/s10-binomial-distribution-2/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_4_Binomial_Distribution_II.ipynb) | - | - 93 | | Day 4: Geometric Distribution I | [Definition](https://www.hackerrank.com/challenges/s10-geometric-distribution-1/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_4_Geometric_Distribution_I.ipynb) | - | - 94 | | Day 5: Poisson Distribution I | [Definition](https://www.hackerrank.com/challenges/s10-poisson-distribution-1/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_5_Poisson_Distribution_I.ipynb) | - | - 95 | | Day 5: Poisson Distribution II | [Definition](https://www.hackerrank.com/challenges/s10-poisson-distribution-1/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_5_Poisson_Distribution_II.ipynb) | - | - 96 | | Day 5: Normal Distribution I | [Definition](https://www.hackerrank.com/challenges/s10-normal-distribution-1/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_5_Normal_Distribution_I.ipynb) | - | - 97 | | Day 5: Normal Distribution II | [Definition](https://www.hackerrank.com/challenges/s10-normal-distribution-2/) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/10daysOfStatistics/Day_5_Normal_Distribution_II.ipynb) | - | - 98 | 99 | 100 | ### Hackerrank Random 101 | 102 | https://www.hackerrank.com/challenges/ 103 | 104 | | Challenge | Description | Python | Java | C++ 105 | |---|---|---|---|--- 106 | | Designer PDF Viewer | [Definition](https://www.hackerrank.com/challenges/designer-pdf-viewer) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/python/hackerrankrandom/pdf_viewer.ipynb) | [Solution](https://github.com/muatik/my-coding-challenges/tree/master/java/hackerrankRandom/DesignersPdfViewer) | - 107 | 108 | 109 | 110 | 111 | https://github.com/donnemartin/interactive-coding-challenges 112 | 113 | Code reviews and comments, even new challenges are very welcomed :) 114 | -------------------------------------------------------------------------------- /cpp/LinkedList/DetermineCyclicOrAcyclic/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | #include "iostream" 3 | 4 | using namespace std; 5 | 6 | template 7 | LinkedList::LinkedList() {}; 8 | 9 | template 10 | LinkedList::~LinkedList() {}; 11 | 12 | template 13 | void LinkedList::insert(T data) { 14 | Node * newNode = new Node(); 15 | newNode->data = data; 16 | newNode->next = head; 17 | head = newNode; 18 | } 19 | 20 | template 21 | void LinkedList::insertNode(Node * node) { 22 | node->next = head; 23 | head = node; 24 | } 25 | 26 | template 27 | void LinkedList::remove(T data) { 28 | Node * current = head; 29 | while (current) { 30 | if (current->next && current->next->data == data) { 31 | current->next = current->next->next; 32 | break; 33 | } 34 | current = current->next; 35 | } 36 | } 37 | 38 | template 39 | bool LinkedList::isEmpty() { 40 | return head == NULL? true : false; 41 | } 42 | 43 | template 44 | bool LinkedList::exists(T data) { 45 | Node * current = head; 46 | while (current) { 47 | if (current->data == data) 48 | return true; 49 | current = current->next; 50 | } 51 | return false; 52 | } 53 | 54 | 55 | template 56 | Node * LinkedList::getHead() { 57 | return head; 58 | } 59 | 60 | template 61 | void LinkedList::display() { 62 | Node * current = head; 63 | while (current) { 64 | cout << current->data << ", "; 65 | current = current->next; 66 | } 67 | cout << endl; 68 | } 69 | -------------------------------------------------------------------------------- /cpp/LinkedList/DetermineCyclicOrAcyclic/LinkedList.h: -------------------------------------------------------------------------------- 1 | template 2 | struct Node { 3 | Node * next; 4 | T data; 5 | }; 6 | 7 | template 8 | class LinkedList 9 | { 10 | private: 11 | Node * head; 12 | public: 13 | LinkedList(); 14 | ~LinkedList(); 15 | void insert(T data); 16 | void insertNode(Node * node); 17 | void remove(T data); 18 | bool exists(T data); 19 | Node * getHead(); 20 | unsigned int count(); 21 | bool isEmpty(); 22 | void display(); 23 | 24 | void removeDuplicates(); 25 | }; -------------------------------------------------------------------------------- /cpp/LinkedList/DetermineCyclicOrAcyclic/main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.cpp" 2 | #include "string" 3 | template 4 | bool isCyclic(LinkedList list) { 5 | Node * current = list.getHead(); 6 | Node * next; 7 | while (current) { 8 | next = current->next; 9 | while (next) { 10 | cout << current << " = " << next << endl; 11 | if (current == next) { 12 | cout << "foun"; 13 | return true; 14 | } 15 | next = next->next; 16 | } 17 | current = current->next; 18 | } 19 | return false; 20 | } 21 | 22 | 23 | int main(int argc, char const *argv[]) 24 | { 25 | LinkedList s; 26 | Node * a = new Node(); 27 | a->data = "john"; 28 | Node * b = new Node(); 29 | b->data = "mustafa"; 30 | Node * c = new Node(); 31 | s.insertNode(a); 32 | s.insertNode(b); 33 | s.display(); 34 | // bool cyclic = isCyclic(s); 35 | // cout << "list is cyclic: " << cyclic << endl; 36 | // s.display(); 37 | 38 | // expected output: 39 | // -2, 1, 2, 3, 4, 5, 9, 40 | // -2, 1, 3, 4, 5, 9, 41 | return 0; 42 | } -------------------------------------------------------------------------------- /cpp/LinkedList/FindKthLastElement/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | #include "iostream" 3 | 4 | using namespace std; 5 | 6 | template 7 | LinkedList::LinkedList() {}; 8 | 9 | template 10 | LinkedList::~LinkedList() {}; 11 | 12 | template 13 | void LinkedList::insert(T data) { 14 | Node * newNode = new Node(); 15 | newNode->data = data; 16 | newNode->next = head; 17 | head = newNode; 18 | } 19 | 20 | template 21 | void LinkedList::remove(T data) { 22 | Node * current = head; 23 | while (current) { 24 | if (current->next && current->next->data == data) { 25 | current->next = current->next->next; 26 | break; 27 | } 28 | current = current->next; 29 | } 30 | } 31 | 32 | template 33 | bool LinkedList::isEmpty() { 34 | return head == NULL? true : false; 35 | } 36 | 37 | template 38 | bool LinkedList::exists(T data) { 39 | Node * current = head; 40 | while (current) { 41 | if (current->data == data) 42 | return true; 43 | current = current->next; 44 | } 45 | return false; 46 | } 47 | 48 | 49 | 50 | template 51 | Node * LinkedList::getHead() { 52 | return head; 53 | } 54 | 55 | template 56 | void LinkedList::display() { 57 | Node * current = head; 58 | while (current) { 59 | cout << current->data << ", "; 60 | current = current->next; 61 | } 62 | cout << endl; 63 | } -------------------------------------------------------------------------------- /cpp/LinkedList/FindKthLastElement/LinkedList.h: -------------------------------------------------------------------------------- 1 | template 2 | struct Node { 3 | Node * next; 4 | T data; 5 | }; 6 | 7 | template 8 | class LinkedList 9 | { 10 | private: 11 | Node * head; 12 | public: 13 | LinkedList(); 14 | ~LinkedList(); 15 | void insert(T data); 16 | void remove(T data); 17 | bool exists(T data); 18 | Node * getHead(); 19 | unsigned int count(); 20 | bool isEmpty(); 21 | void display(); 22 | 23 | void removeDuplicates(); 24 | }; -------------------------------------------------------------------------------- /cpp/LinkedList/FindKthLastElement/main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.cpp" 2 | 3 | 4 | 5 | template 6 | T findLastElementAt(LinkedList list, unsigned int position) { 7 | /* 8 | assuming that linked list implementation does not give the lengh of list. 9 | So, first we count items in the list, then locate the item at the 10 | given position. 11 | */ 12 | 13 | // assuming the list is acyclic, otherwise this will be a infinite loop. 14 | Node * current = list.getHead(); 15 | unsigned int length = 0; 16 | while (current) { 17 | current = current->next; 18 | length++; 19 | } 20 | 21 | current = list.getHead(); 22 | unsigned int index = 0; 23 | position = length - position - 1; 24 | while (current and index <= length) { 25 | if (position == index) 26 | return current->data; 27 | current = current->next; 28 | index++; 29 | } 30 | // throw an error 31 | return -99; 32 | } 33 | 34 | 35 | int main(int argc, char const *argv[]) 36 | { 37 | LinkedList s; 38 | s.insert(4); 39 | s.insert(2); 40 | s.insert(1); 41 | s.insert(5); 42 | s.insert(9); 43 | s.insert(-2); 44 | s.insert(3); 45 | s.display(); 46 | int a = findLastElementAt(s, -1); 47 | cout << a << endl; 48 | s.remove(2); 49 | s.display(); 50 | 51 | // expected output: 52 | // -2, 1, 2, 3, 4, 5, 9, 53 | // -2, 1, 3, 4, 5, 9, 54 | return 0; 55 | } -------------------------------------------------------------------------------- /cpp/LinkedList/RemoveDuplicates/LinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.h" 2 | #include "iostream" 3 | 4 | using namespace std; 5 | 6 | template 7 | LinkedList::LinkedList() {}; 8 | 9 | template 10 | LinkedList::~LinkedList() {}; 11 | 12 | template 13 | void LinkedList::insert(T data) { 14 | Node * newNode = new Node(); 15 | newNode->data = data; 16 | newNode->next = head; 17 | head = newNode; 18 | } 19 | 20 | template 21 | void LinkedList::remove(T data) { 22 | Node * current = head; 23 | while (current) { 24 | if (current->next && current->next->data == data) { 25 | current->next = current->next->next; 26 | break; 27 | } 28 | current = current->next; 29 | } 30 | } 31 | 32 | template 33 | bool LinkedList::isEmpty() { 34 | return head == NULL? true : false; 35 | } 36 | 37 | template 38 | bool LinkedList::exists(T data) { 39 | Node * current = head; 40 | while (current) { 41 | if (current->data == data) 42 | return true; 43 | current = current->next; 44 | } 45 | return false; 46 | } 47 | 48 | 49 | template 50 | void LinkedList::display() { 51 | Node * current = head; 52 | while (current) { 53 | cout << current->data << ", "; 54 | current = current->next; 55 | } 56 | cout << endl; 57 | } 58 | 59 | template 60 | void LinkedList::removeDuplicates() { 61 | Node * current = head; 62 | while (current) { 63 | Node * forward_head = current->next; 64 | Node * forward_tail = current; 65 | while (forward_head) { 66 | if (forward_head->data == current->data) { 67 | // duplicated item found. 68 | forward_tail->next = forward_head->next; 69 | } 70 | else 71 | forward_tail = forward_tail->next; 72 | forward_head = forward_head->next; 73 | } 74 | current = current->next; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /cpp/LinkedList/RemoveDuplicates/LinkedList.h: -------------------------------------------------------------------------------- 1 | template 2 | struct Node { 3 | Node * next; 4 | T data; 5 | }; 6 | 7 | template 8 | class LinkedList 9 | { 10 | private: 11 | Node * head; 12 | public: 13 | LinkedList(); 14 | ~LinkedList(); 15 | void insert(T data); 16 | void remove(T data); 17 | bool exists(T data); 18 | unsigned int count(); 19 | bool isEmpty(); 20 | void display(); 21 | 22 | void removeDuplicates(); 23 | }; -------------------------------------------------------------------------------- /cpp/LinkedList/RemoveDuplicates/main.cpp: -------------------------------------------------------------------------------- 1 | #include "LinkedList.cpp" 2 | 3 | int main(int argc, char const *argv[]) 4 | { 5 | LinkedList s; 6 | s.insert(4); 7 | s.insert(4); 8 | s.insert(2); 9 | s.insert(3); 10 | s.insert(8); 11 | s.insert(3); 12 | s.insert(1); 13 | s.insert(2); 14 | s.insert(3); 15 | s.insert(2); 16 | s.insert(2); 17 | s.insert(2); 18 | s.insert(2); 19 | s.display(); 20 | s.removeDuplicates(); 21 | s.display(); 22 | // expected output: 23 | // -2, 1, 2, 3, 4, 5, 9, 24 | // -2, 1, 3, 4, 5, 9, 25 | return 0; 26 | } -------------------------------------------------------------------------------- /cpp/LinkedList/SortedLinkedList/SortedLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include "SortedLinkedList.h" 2 | #include "iostream" 3 | 4 | using namespace std; 5 | 6 | template 7 | SortedLinkedList::SortedLinkedList() {}; 8 | 9 | template 10 | SortedLinkedList::~SortedLinkedList() {}; 11 | 12 | template 13 | void SortedLinkedList::insert(T data) { 14 | Node * newNode = new Node(); 15 | newNode->data = data; 16 | 17 | if (isEmpty() || head->data > data) { 18 | newNode->next = head; 19 | head = newNode; 20 | return; 21 | } 22 | 23 | Node * current = head; 24 | while (current->next && current->next->data < data) { 25 | current = current->next; 26 | } 27 | newNode->next = current->next; 28 | current->next = newNode; 29 | } 30 | 31 | template 32 | void SortedLinkedList::remove(T data) { 33 | Node * current = head; 34 | while (current) { 35 | if (current->next && current->next->data == data) { 36 | current->next = current->next->next; 37 | break; 38 | } 39 | current = current->next; 40 | } 41 | } 42 | 43 | template 44 | bool SortedLinkedList::isEmpty() { 45 | return head == NULL? true : false; 46 | } 47 | 48 | template 49 | bool SortedLinkedList::exists(T data) { 50 | Node * current = head; 51 | while (current) { 52 | if (current->data == data) 53 | return true; 54 | current = current->next; 55 | } 56 | return false; 57 | } 58 | 59 | 60 | template 61 | void SortedLinkedList::display() { 62 | Node * current = head; 63 | while (current) { 64 | cout << current->data << ", "; 65 | current = current->next; 66 | } 67 | cout << endl; 68 | } 69 | -------------------------------------------------------------------------------- /cpp/LinkedList/SortedLinkedList/SortedLinkedList.h: -------------------------------------------------------------------------------- 1 | template 2 | struct Node { 3 | Node * next; 4 | T data; 5 | }; 6 | 7 | template 8 | class SortedLinkedList 9 | { 10 | private: 11 | Node * head; 12 | public: 13 | SortedLinkedList(); 14 | ~SortedLinkedList(); 15 | void insert(T data); 16 | void remove(T data); 17 | bool exists(T data); 18 | unsigned int count(); 19 | bool isEmpty(); 20 | void display(); 21 | }; -------------------------------------------------------------------------------- /cpp/LinkedList/SortedLinkedList/main.cpp: -------------------------------------------------------------------------------- 1 | #include "SortedLinkedList.cpp" 2 | 3 | int main(int argc, char const *argv[]) 4 | { 5 | SortedLinkedList s; 6 | s.insert(4); 7 | s.insert(2); 8 | s.insert(1); 9 | s.insert(5); 10 | s.insert(9); 11 | s.insert(-2); 12 | s.insert(3); 13 | s.display(); 14 | 15 | 16 | s.remove(2); 17 | s.display(); 18 | 19 | // expected output: 20 | // -2, 1, 2, 3, 4, 5, 9, 21 | // -2, 1, 3, 4, 5, 9, 22 | return 0; 23 | } -------------------------------------------------------------------------------- /cpp/List/UnsortedList.cpp: -------------------------------------------------------------------------------- 1 | #include "UnsortedList.h" 2 | #include "stdexcept" 3 | using namespace std; 4 | 5 | template 6 | UnsortedList::UnsortedList() { 7 | makeEmpty(); 8 | resetList(); 9 | } 10 | 11 | template 12 | bool UnsortedList::isFull() { 13 | return length == size; 14 | } 15 | 16 | template 17 | bool UnsortedList::isEmpty() { 18 | return length == 0; 19 | } 20 | 21 | template 22 | void UnsortedList::makeEmpty() { 23 | length = 0; 24 | } 25 | 26 | template 27 | int UnsortedList::getLength() { 28 | return length; 29 | } 30 | 31 | template 32 | void UnsortedList::insertItem(T item) { 33 | if (isFull()) 34 | throw overflow_error("list is full."); 35 | items[length] = item; 36 | length++; 37 | } 38 | 39 | template 40 | void UnsortedList::deleteItem(T item) { 41 | int position = -1; 42 | for (int i = 0; i < length; ++i) 43 | { 44 | if (items[i] == item) { 45 | position = i; 46 | break; 47 | } 48 | } 49 | 50 | if (position == -1) 51 | return; // item to be deleted not found 52 | 53 | for (int i = position; i < length - 1 ; ++i) 54 | { 55 | items[i] = items[position + 1]; 56 | } 57 | items[length - 1] = NULL; 58 | length--; 59 | } 60 | 61 | template 62 | void UnsortedList::resetList() { 63 | cursorPos = 0; 64 | } 65 | 66 | template 67 | void UnsortedList::getNextItem(T &item) { 68 | if (cursorPos < length) { 69 | item = items[cursorPos++]; 70 | } 71 | } -------------------------------------------------------------------------------- /cpp/List/UnsortedList.h: -------------------------------------------------------------------------------- 1 | #ifndef UNSORTEDLIST_H 2 | #define UNSORTEDLIST_H 3 | 4 | 5 | #define MAX_ITEMS 4 6 | 7 | template 8 | class UnsortedList 9 | { 10 | private: 11 | int size = MAX_ITEMS; 12 | int length; 13 | int cursorPos; 14 | T items[MAX_ITEMS]; 15 | public: 16 | UnsortedList(); 17 | bool isFull(); 18 | bool isEmpty(); 19 | void makeEmpty(); 20 | int getLength(); 21 | void insertItem(T item); 22 | void deleteItem(T item); 23 | void retrieveItem(T &item, bool &found); 24 | void resetList(); 25 | void getNextItem(T &item); 26 | }; 27 | 28 | #endif -------------------------------------------------------------------------------- /cpp/List/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "UnsortedList.cpp" 3 | using namespace std; 4 | 5 | 6 | int main(int argc, char const *argv[]) { 7 | UnsortedList us; 8 | us.insertItem(4); 9 | us.insertItem(1); 10 | us.insertItem(3); 11 | us.insertItem(3); 12 | int a; 13 | for (int i = 0; i < us.getLength(); ++i) 14 | { 15 | us.getNextItem(a); 16 | cout << a << endl; 17 | } 18 | return 0; 19 | } -------------------------------------------------------------------------------- /java/.gitignore: -------------------------------------------------------------------------------- 1 | *.pydevproject 2 | .metadata 3 | .gradle 4 | .recommenders 5 | bin/ 6 | tmp/ 7 | *.tmp 8 | *.bak 9 | *.swp 10 | *~.nib 11 | local.properties 12 | .settings/ 13 | .loadpath 14 | 15 | # Eclipse Core 16 | .project 17 | 18 | # External tool builders 19 | .externalToolBuilders/ 20 | 21 | # Locally stored "Eclipse launch configurations" 22 | *.launch 23 | 24 | # CDT-specific 25 | .cproject 26 | 27 | # JDT-specific (Eclipse Java Development Tools) 28 | .classpath 29 | 30 | # Java annotation processor (APT) 31 | .factorypath 32 | 33 | # PDT-specific 34 | .buildpath 35 | 36 | # sbteclipse plugin 37 | .target 38 | 39 | # TeXlipse plugin 40 | .texlipse 41 | 42 | # STS (Spring Tool Suite) 43 | .springBeans 44 | -------------------------------------------------------------------------------- /java/3sum/src/Challenges/ThreeSum.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | 4 | public class ThreeSum { 5 | 6 | // time complexity is O(n^3), that is, this is quite slow. 7 | public static int find3sum(int[] numbers) { 8 | int counter = 0; 9 | int steps = 0; 10 | for (int i = 0; i < numbers.length - 2; i++) 11 | for (int j = i + 1; j < numbers.length - 1; j++) 12 | for (int k = j + 1; k < numbers.length; k++) { 13 | steps++; 14 | if ( (numbers[i] + numbers[j] + numbers[k]) == 0) { 15 | System.out.println( 16 | numbers[i] + " + " + numbers[j] + " + " + numbers[k] + 17 | " = 0"); 18 | counter++; 19 | } 20 | } 21 | System.out.println("stesp:" + steps); 22 | return counter; 23 | } 24 | 25 | public static void main(String args[]) { 26 | int[] numbers = new int[]{ 27 | 12, 6, -2,-8,-4, -6, -1, -5, -7, 2, 1, -7, 10, -10, 11, -11}; 28 | find3sum(numbers); 29 | // OUTPUT will be as follows: 30 | // 12 + -2 + -10 = 0 31 | // 12 + -8 + -4 = 0 32 | // 12 + -1 + -11 = 0 33 | // 12 + -5 + -7 = 0 34 | // 12 + -5 + -7 = 0 35 | // 6 + -2 + -4 = 0 36 | // 6 + -8 + 2 = 0 37 | // 6 + -1 + -5 = 0 38 | // 6 + -7 + 1 = 0 39 | // 6 + 1 + -7 = 0 40 | // -2 + -8 + 10 = 0 41 | // -4 + -6 + 10 = 0 42 | // -4 + -7 + 11 = 0 43 | // -4 + -7 + 11 = 0 44 | // -6 + -5 + 11 = 0 45 | // -1 + -10 + 11 = 0 46 | // 1 + 10 + -11 = 0 47 | // stesp:560 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /java/CompressString/src/Application.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by muatik on 2/9/17. 3 | */ 4 | public class Application { 5 | public static void main(String[] args) { 6 | System.out.println(compress("AAABBCCCRAKKMM")); 7 | System.out.println(compress("AB")); 8 | System.out.println(compress("ABB")); 9 | System.out.println(compress("A")); 10 | System.out.println(compress("BBBBKKKKKKKKK")); 11 | } 12 | 13 | private static String compress(String text) { 14 | StringBuilder compressed = new StringBuilder(); 15 | int counter = 1; 16 | 17 | for (int i = 1; i < text.length(); i++) { 18 | 19 | if (text.charAt(i - 1) != text.charAt(i)) { 20 | compressed.append(text.charAt(i -1)); 21 | if (counter > 1) { 22 | compressed.append(counter); 23 | } 24 | counter = 1; 25 | } else 26 | counter++; 27 | } 28 | 29 | if (counter > 0) { 30 | compressed.append(text.charAt(text.length() - 1)); 31 | if (counter > 1) { 32 | compressed.append(counter); 33 | } 34 | } 35 | 36 | return compressed.toString(); 37 | } 38 | 39 | 40 | } 41 | -------------------------------------------------------------------------------- /java/DiameterOfBTree/src/muatik/BTree.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class BTree { 4 | 5 | public String key; 6 | public BTree left; 7 | public BTree right; 8 | public BTree root; 9 | 10 | public BTree(String key) { 11 | this.key = key; 12 | root = this; 13 | } 14 | 15 | public void insert(String key) { 16 | insert(root, key); 17 | } 18 | 19 | public void insert(BTree tree, String key) { 20 | int comparing = key.compareTo(tree.key); 21 | if (comparing < 1) { 22 | if (tree.left != null) 23 | insert(tree.left, key); 24 | else 25 | tree.left = new BTree(key); 26 | } else { 27 | if (tree.right !=null) 28 | insert(tree.right, key); 29 | else 30 | tree.right = new BTree(key); 31 | } 32 | } 33 | 34 | public static void display(BTree tree) { 35 | if (tree == null) 36 | return; 37 | 38 | display(tree.left); 39 | display(tree.right); 40 | System.out.println(tree.key); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/DiameterOfBTree/src/muatik/GreatestDistance.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class GreatestDistance { 4 | Object left, right; // the farthest left/right node. 5 | int distanceLeft, distanceRight; // distance to the farthest left/right node. 6 | int diameter; // path from left to right 7 | 8 | public GreatestDistance(Object left, int distanceLeft, Object right, int distanceRight, int pathLength) { 9 | this.left = left; 10 | this.distanceLeft = distanceLeft; 11 | this.right = right; 12 | this.distanceRight = distanceRight; 13 | this.diameter = pathLength; 14 | } 15 | 16 | public Object getFarthestNode() { 17 | if (distanceLeft > distanceRight) 18 | return left; 19 | return right; 20 | } 21 | 22 | public int getMaxDistance() { 23 | if (distanceLeft > distanceRight) 24 | return distanceLeft; 25 | return distanceRight; 26 | } 27 | 28 | public void increaseBy(Object tree) { 29 | if (distanceLeft > distanceRight) { 30 | right = tree; 31 | distanceRight = 0; 32 | distanceLeft++; 33 | } else { 34 | left = tree; 35 | distanceLeft = 0; 36 | distanceRight++; 37 | } 38 | diameter++; 39 | } 40 | 41 | public static GreatestDistance get(BTree tree) { 42 | GreatestDistance leftSub = null; 43 | GreatestDistance rightSub = null; 44 | GreatestDistance r = null; 45 | 46 | if (tree.left !=null) 47 | leftSub = get(tree.left); 48 | 49 | if (tree.right !=null) 50 | rightSub = get(tree.right); 51 | 52 | if (tree.left != null && tree.right != null) { 53 | 54 | if ( 55 | (leftSub.getMaxDistance() + rightSub.getMaxDistance() + 2) 56 | > Math.max(leftSub.diameter, rightSub.diameter) 57 | ) 58 | { 59 | r = new GreatestDistance( 60 | leftSub.getFarthestNode(), 61 | leftSub.getMaxDistance() + 1, 62 | rightSub.getFarthestNode(), 63 | rightSub.getMaxDistance() + 1, 64 | leftSub.getMaxDistance() + rightSub.getMaxDistance() + 2); 65 | } else { 66 | r = (leftSub.diameter > rightSub.diameter ? leftSub : rightSub); 67 | } 68 | 69 | } 70 | else if (tree.left != null || tree.right != null) { 71 | r = (tree.left == null? rightSub : leftSub); 72 | if (r.getMaxDistance() + 1 > r.diameter) { 73 | r.increaseBy(tree); 74 | } else { 75 | r.distanceLeft++; 76 | r.distanceRight++; 77 | } 78 | } else { 79 | // tree has neither left node nor right node. 80 | r = new GreatestDistance( 81 | tree, // farthest left node 82 | 0, // distance to the left node 83 | tree, // farthest right node 84 | 0, // distance to the right node 85 | 0); // longest path's length 86 | } 87 | 88 | return r; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /java/DiameterOfBTree/src/muatik/main.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | 4 | public class main { 5 | 6 | public static void main(String[] args) { 7 | BTree tree = new BTree("h"); 8 | 9 | // tree.insert("c"); 10 | // tree.insert("b"); 11 | // tree.insert("a"); 12 | // tree.insert("d"); 13 | // tree.insert("f"); 14 | // tree.insert("g"); 15 | // == greatest distance 5, left: a, right: g 16 | 17 | 18 | tree.insert("c"); 19 | tree.insert("b"); 20 | tree.insert("a"); 21 | tree.insert("d"); 22 | tree.insert("f"); 23 | tree.insert("g"); 24 | // 25 | tree.insert("m10"); 26 | tree.insert("k10"); 27 | tree.insert("k9"); 28 | tree.insert("k8"); 29 | tree.insert("k7"); 30 | tree.insert("k6"); 31 | tree.insert("k5"); 32 | tree.insert("k4"); 33 | tree.insert("p5"); 34 | tree.insert("p6"); 35 | tree.insert("p7"); 36 | tree.insert("p4"); 37 | tree.insert("p8"); 38 | tree.insert("p9"); 39 | // 40 | 41 | BTree.display(tree); 42 | GreatestDistance r = GreatestDistance.get(tree); 43 | System.out.println( 44 | "greatest distance: " + r.diameter 45 | + ", left: " + ((BTree) r.left).key 46 | + ", right: " + ((BTree) r.right).key); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /java/FirstNonRepetatedChar/src/Application.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by muatik on 2/9/17. 3 | */ 4 | public class Application { 5 | public static void main(String[] args) { 6 | System.out.println(findFirstNonRepeatedChar("AABBCDDK")); 7 | System.out.println(findFirstNonRepeatedChar("AABBCCDDK")); 8 | } 9 | 10 | private static String findFirstNonRepeatedChar(String text) { 11 | int counter = 1 ; 12 | for (int i = 1; i < text.length(); i++) { 13 | if (text.charAt(i - 1) != text.charAt(i)) { 14 | if (counter == 1) 15 | return String.valueOf(text.charAt(i-1)); 16 | counter = 1; 17 | } else 18 | counter++; 19 | } 20 | 21 | if (counter == 1) 22 | return String.valueOf(text.charAt(text.length() -1)); 23 | 24 | return ""; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Bag.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | public class Bag { 4 | 5 | private int capacity; 6 | private int size; 7 | private int[] edges; 8 | 9 | public Bag(int capacity) { 10 | this.capacity = capacity; 11 | edges = new int[capacity]; 12 | } 13 | 14 | public void add(int w) { 15 | edges[size++] = w; 16 | } 17 | 18 | 19 | public int[] get() { 20 | int adj[] = new int[size]; 21 | for (int i = 0; i < size; i++) 22 | adj[i] = edges[i]; 23 | return adj; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Digraph.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | public class Digraph { 4 | 5 | private int V; 6 | private Bag adjs[]; 7 | private int indegree[]; 8 | 9 | public Digraph(int V) { 10 | this.V = V; 11 | indegree = new int[V]; 12 | adjs = new Bag[V]; 13 | for (int i = 0; i < V; i++) 14 | adjs[i] = new Bag(V); 15 | } 16 | 17 | public void add(int v, int w) { 18 | adjs[v].add(w); 19 | indegree[w]++; 20 | } 21 | 22 | public int getOutdegree(int v) { 23 | return adjs[v].get().length; 24 | } 25 | 26 | public int getIndegree(int v) { 27 | return indegree[v]; 28 | } 29 | 30 | public int[] getAdjs(int v) { 31 | return adjs[v].get(); 32 | } 33 | 34 | public int V() { 35 | return V; 36 | } 37 | 38 | public String toString() { 39 | for(int i = 0; i < V; i++) { 40 | System.out.print(i + ": "); 41 | for(int a: adjs[i].get()) 42 | System.out.print(a + ", "); 43 | System.out.print("\n"); 44 | } 45 | return ""; 46 | } 47 | 48 | public static void main(String[] args) { 49 | Digraph g = new Digraph(12); 50 | g.add(1, 0); 51 | g.add(1, 2); 52 | g.add(0, 2); 53 | g.add(2, 4); 54 | g.add(4, 3); 55 | g.add(3, 4); 56 | g.add(4, 5); 57 | g.add(4, 6); 58 | g.add(6, 7); 59 | g.add(7, 8); 60 | g.add(8, 6); 61 | g.add(8, 9); 62 | g.add(9, 2); 63 | //g.add(9, 3); 64 | System.out.println(g); 65 | System.out.println(g.getIndegree(6)); 66 | 67 | Digraph_DFS dfs = new Digraph_DFS(g, 4); 68 | System.out.println("is 6 visited? " + dfs.isVisited(6)); 69 | System.out.println("Graph is connected? " + dfs.isConnected()); 70 | 71 | System.out.println("\npath from " + 4 + " to " + 2); 72 | for(int i : dfs.pathTo(2)) 73 | System.out.print(i + ", "); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Digraph_DFS.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Digraph_DFS { 6 | private int s; 7 | private boolean visits[]; 8 | private int edgeTo[]; 9 | private int visitCounter; 10 | private Digraph g; 11 | 12 | public Digraph_DFS(Digraph g, int s) { 13 | this.s = s; 14 | visits = new boolean[g.V()]; 15 | edgeTo = new int[g.V()]; 16 | this.g = g; 17 | dfs(g, s); 18 | } 19 | 20 | public void dfs(Digraph g, int v) { 21 | visits[v] = true; 22 | visitCounter++; 23 | for (int w: g.getAdjs(v)) { 24 | if (!isVisited(w)) { 25 | edgeTo[w] = v; 26 | dfs(g, w); 27 | } 28 | } 29 | } 30 | 31 | public boolean isVisited(int v) { 32 | return visits[v]; 33 | } 34 | public boolean hasPathTo(int v) { 35 | return isVisited(v); 36 | } 37 | 38 | public boolean isConnected() { 39 | return visitCounter == g.V(); 40 | } 41 | 42 | public ArrayList pathTo(int v) { 43 | ArrayList path = new ArrayList(); 44 | 45 | for (int i = v; i != s; i = edgeTo[i]) { 46 | path.add(i); 47 | } 48 | path.add(s); 49 | return path; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Graph.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Graph { 6 | 7 | protected int V; 8 | protected Bag adjs[]; 9 | 10 | public Graph(int V) { 11 | this.V = V; 12 | adjs = new Bag[V]; 13 | for (int i = 0; i < V; i++) { 14 | adjs[i] = new Bag(V); 15 | } 16 | 17 | } 18 | 19 | public void add(int v, int w) { 20 | adjs[v].add(w); 21 | adjs[w].add(v); 22 | } 23 | 24 | public int V() { 25 | return V; 26 | } 27 | 28 | public String toString() { 29 | for(int i = 0; i < V; i++) { 30 | System.out.print(i + ": "); 31 | for(int a: adjs[i].get()) 32 | System.out.print(a + ", "); 33 | System.out.print("\n"); 34 | } 35 | return ""; 36 | } 37 | 38 | 39 | public static void main(String[] args) { 40 | Graph g = new Graph(12); 41 | g.add(0, 1); 42 | g.add(0, 2); 43 | g.add(1, 2); 44 | g.add(1, 3); 45 | g.add(2, 3); 46 | g.add(3, 4); 47 | g.add(4, 5); 48 | g.add(4, 6); 49 | g.add(5, 6); 50 | g.add(4, 7); 51 | g.add(3, 7); 52 | g.add(7, 8); 53 | g.add(8, 9); 54 | g.add(9, 10); 55 | g.add(9, 3); 56 | System.out.println(g); 57 | Graph_DFS dfs = new Graph_DFS(g, 2); 58 | System.out.println("is 6 visited? " + dfs.isVisited(6)); 59 | System.out.println("Graph is connected? " + dfs.isConnected()); 60 | 61 | System.out.println("\npath from " + 2 + " to " + 10); 62 | for(int i : dfs.pathTo(10)) 63 | System.out.print(i + ", "); 64 | 65 | 66 | Graph_BFS bfs = new Graph_BFS(g, 1); 67 | for (int i = 0; i < g.V(); i++) { 68 | ArrayList path = bfs.getShortestPathTo(i); 69 | System.out.print("\n\npath to " + i + ": "); 70 | if (path == null) { 71 | System.out.println("not connected to " + i); 72 | continue; 73 | } 74 | for(int w: path) 75 | System.out.print(w + " <-- "); 76 | System.out.print(1); 77 | } 78 | 79 | } 80 | 81 | public int[] getAdjs(int v) { 82 | return adjs[v].get(); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Graph_BFS.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Graph_BFS { 6 | 7 | private int s; 8 | private boolean visits[]; 9 | private int edgesTo[]; 10 | 11 | public Graph_BFS(Graph g, int s) { 12 | visits = new boolean[g.V()]; 13 | edgesTo = new int[g.V()]; 14 | this.s = s; 15 | bfs(g, s); 16 | } 17 | 18 | private void bfs(Graph g, int v) { 19 | ArrayList q = new ArrayList(); 20 | q.add(v); 21 | visits[v] = true; 22 | 23 | while (!q.isEmpty()) { 24 | v = q.remove(0); 25 | System.out.println("\n" + v + " is being visited"); 26 | for (int w: g.getAdjs(v)) { 27 | if (!isVisited(w)) { 28 | System.out.println(w + " is added to queue"); 29 | visits[w] = true; 30 | edgesTo[w] = v; 31 | q.add(w); 32 | } 33 | } 34 | System.out.println(v + " is visited ##"); 35 | } 36 | } 37 | 38 | private boolean isVisited(int v) { 39 | return visits[v]; 40 | } 41 | 42 | public ArrayList getShortestPathTo(int v) { 43 | if (!visits[v]) 44 | return null; 45 | 46 | ArrayList path = new ArrayList(); 47 | while (v != this.s) { 48 | path.add(v); 49 | v = edgesTo[v]; 50 | } 51 | return path; 52 | } 53 | 54 | // private boolean[] visits; 55 | // private int visitsCount; 56 | // 57 | // public Graph_BFS(Graph g, int s) { 58 | // visits = new boolean[g.V()]; 59 | // bfs(g, s); 60 | // } 61 | // 62 | // private void bfs(Graph g, int v) { 63 | // ArrayList queue = new ArrayList(); 64 | // queue.add(v); 65 | // visits[v] = true; 66 | // 67 | // while (!queue.isEmpty()) { 68 | // int i = queue.remove(0); 69 | // for (int w: g.getAdjs(i)) { 70 | // if (!isVisited(w)) { 71 | // visits[w] = true; 72 | // queue.add(w); 73 | // } 74 | // } 75 | // } 76 | // 77 | // } 78 | // 79 | // private boolean isVisited(int v) { 80 | // System.out.println("Is " + v + " being visited?" + visits[v]); 81 | // return visits[v]; 82 | // } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /java/Graphs/src/e2/Graph_DFS.java: -------------------------------------------------------------------------------- 1 | package e2; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | 6 | public class Graph_DFS { 7 | int s; // source vertex 8 | boolean visits[]; 9 | int visitCounter; 10 | int edgeTo[]; 11 | 12 | Graph g; 13 | 14 | public Graph_DFS(Graph g, int s) { 15 | this.s = s; 16 | this.g = g; 17 | visits = new boolean[g.V()]; 18 | edgeTo = new int[g.V()]; 19 | dfs(g, s); 20 | } 21 | 22 | private void dfs(Graph g, int v) { 23 | System.out.println(v + " is being visited"); 24 | visits[v] = true; 25 | visitCounter++; 26 | for (int w: g.getAdjs(v)) { 27 | if (!isVisited(w)) { 28 | edgeTo[w] = v; 29 | dfs(g, w); 30 | } 31 | } 32 | System.out.println(v + " is visited. ----"); 33 | } 34 | 35 | public boolean isVisited(int v) { 36 | System.out.println("Is " + v + " being visited?" + visits[v]); 37 | return visits[v]; 38 | } 39 | 40 | public boolean hasPathTo(int v) { 41 | return isVisited(v); 42 | } 43 | 44 | public ArrayList pathTo(int v) { 45 | ArrayList path = new ArrayList(); 46 | for (int i = v; i != s; i = edgeTo[i]) { 47 | path.add(i); 48 | } 49 | path.add(s); 50 | return path; 51 | } 52 | 53 | public boolean isConnected() { 54 | return visitCounter == g.V(); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /java/Graphs/src/muatik/AdjacencyList.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | import java.util.Iterator; 4 | 5 | public class AdjacencyList implements Iterable { 6 | protected int edges[]; 7 | 8 | public AdjacencyList(int maxAdjacency) { 9 | edges = new int[maxAdjacency]; 10 | } 11 | 12 | public void add(int w) { 13 | edges[w] = 1; 14 | } 15 | 16 | public void remove(int w) { 17 | edges[w] = 0; 18 | } 19 | 20 | public int[] get() { 21 | return edges; 22 | } 23 | 24 | public String toString() { 25 | StringBuilder sb = new StringBuilder(); 26 | for(int i: edges) 27 | sb.append(i + ","); 28 | return sb.toString(); 29 | } 30 | 31 | 32 | @Override 33 | public Iterator iterator() { 34 | return new AdjacencyIterator(); 35 | } 36 | 37 | private class AdjacencyIterator implements Iterator{ 38 | 39 | private int cursor; 40 | 41 | @Override 42 | public boolean hasNext() { 43 | for (int i = cursor; i < edges.length; i++) { 44 | if (edges[i] == 1) { 45 | cursor = i; 46 | return true; 47 | } 48 | } 49 | return false; 50 | } 51 | 52 | @Override 53 | public Integer next() { 54 | return cursor++; 55 | } 56 | 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /java/Graphs/src/muatik/Graph.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class Graph { 4 | 5 | protected int V; // number of vertices 6 | protected int E; // number of edges 7 | protected int edges[]; 8 | protected AdjacencyList vertices[]; 9 | 10 | public Graph(int v) { 11 | V = v; 12 | vertices = new AdjacencyList[V]; 13 | for (int i = 0; i < V; i++) 14 | vertices[i] = new AdjacencyList(V); 15 | } 16 | 17 | public void connect(int v, int w) { 18 | vertices[v].add(w); 19 | vertices[w].add(v); 20 | } 21 | 22 | public int V() { 23 | return V; 24 | } 25 | 26 | public Iterable getAdjacents(int v) { 27 | return vertices[v]; 28 | } 29 | 30 | public String toString() { 31 | System.out.println("Adjacency matrix:"); 32 | for(int i = 0; i < V; i++) { 33 | System.out.println(i + " : " + vertices[i]); 34 | } 35 | return ""; 36 | } 37 | 38 | public static void main(String[] args) { 39 | Graph g = new Graph(5); 40 | g.connect(1, 4); 41 | g.connect(2, 4); 42 | // g.connect(1, 0); 43 | System.out.println(g); 44 | Graph_DFS d = new Graph_DFS(g,4); 45 | System.out.println(d.isConnected(0)); 46 | // for(int i: g.getAdjacents(1)) 47 | // System.out.println(i); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /java/Graphs/src/muatik/Graph_DFS.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class Graph_DFS { 4 | 5 | private int s; // source vertex 6 | private boolean visits[]; 7 | 8 | public Graph_DFS(Graph g, int v) { 9 | this.s = v; 10 | visits = new boolean[g.V()]; 11 | DFS(g, v); 12 | } 13 | 14 | public void DFS(Graph g, int v) { 15 | visits[v] = true; 16 | for(int w: g.getAdjacents(v)) { 17 | if (!isVisited(w)) { 18 | DFS(g, w); 19 | } 20 | } 21 | } 22 | 23 | private boolean isVisited(int v) { 24 | return visits[v]; 25 | } 26 | 27 | public boolean isConnected(int w) { 28 | return isVisited(w); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Heap/src/muatik/MaxPriorityQueue.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class MaxPriorityQueue { 4 | 5 | protected int length = 0; 6 | protected int size; 7 | protected int items[]; 8 | 9 | public MaxPriorityQueue(int size) { 10 | this.size = size; 11 | 12 | // since the 0th index will not be used for arithmetic heap operations, allocate size + 1 13 | this.items = new int[size + 1]; 14 | } 15 | 16 | public void insert(int key) { 17 | items[++length] = key; 18 | swim(length); 19 | } 20 | 21 | public int delMax() { 22 | int key = items[1]; 23 | items[1] = items[length--]; 24 | sink(1); 25 | return key; 26 | 27 | } 28 | 29 | protected void swim(int current) { 30 | while ((current / 2) > 0 && items[current/2] < items[current] ) { 31 | exchange(current / 2, current); 32 | current = current / 2; 33 | } 34 | } 35 | 36 | protected void sink(int current) { 37 | int descendant = 0; 38 | while (current * 2 <= length) { 39 | descendant = current * 2; 40 | if (items[descendant] < items[descendant+1]) descendant++; 41 | if (items[descendant] <= items[current]) 42 | break; 43 | 44 | exchange(descendant, current); 45 | current *= 2; 46 | } 47 | } 48 | 49 | protected void exchange(int i, int j) { 50 | int temp = items[j]; 51 | items[j] = items[i]; 52 | items[i] = temp; 53 | } 54 | 55 | public boolean isEmpty() { 56 | return length == 0; 57 | } 58 | 59 | public static void main(String[] args) { 60 | MaxPriorityQueue a = new MaxPriorityQueue(10); 61 | a.insert(5); 62 | a.insert(12); 63 | a.insert(7); 64 | a.insert(-4); 65 | a.insert(19); 66 | a.insert(15); 67 | a.insert(10); 68 | a.insert(98); 69 | a.delMax(); 70 | a.display(); 71 | while (!a.isEmpty()) 72 | System.out.println(a.delMax()); 73 | } 74 | 75 | private void display() { 76 | for (int j = 1; j < length; j++) { 77 | System.out.println(items[j]); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /java/IsRotation/src/Application.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by muatik on 2/8/17. 3 | */ 4 | public class Application { 5 | 6 | public static void main(String[] args) { 7 | System.out.println(isRotated("foobarbaz", "barbazfoo")); 8 | System.out.println(isRotated("abc", "bca")); 9 | System.out.println(isRotated("abc", "cab")); 10 | System.out.println(isRotated("abc", "car")); 11 | } 12 | 13 | private static boolean isRotated(String a, String b) { 14 | return (b+b).contains(a); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/ISort.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public interface ISort { 4 | public void sort(int[] array); 5 | } 6 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/Insertion.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class Insertion implements ISort { 4 | public void sort(int[] array) { 5 | int comparision = 0; 6 | int modification = 0; 7 | for (int i = 1; i < array.length; i++) { 8 | for (int j = 0; j < i; j++) { 9 | comparision++; 10 | if (array[i] < array[j]) { 11 | modification++; 12 | exchange(array, i, j); 13 | } else { 14 | // because left side of the list will always be sorted. 15 | break; 16 | } 17 | } 18 | } 19 | System.out.println("\narray length: " + array.length); 20 | System.out.println("comparision: " + comparision); 21 | System.out.println("modification: " + modification); 22 | 23 | } 24 | 25 | public static void exchange(int[] array, int i, int j) { 26 | int temp = array[i]; 27 | array[i] = array[j]; 28 | array[j] = temp; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/MergeSort.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class MergeSort implements ISort{ 4 | 5 | public void sort(int[] array) { 6 | int[] aux = new int[array.length]; 7 | sort(array, aux, 0, array.length - 1); 8 | } 9 | 10 | static void sort(int[] array, int[] aux, int lo, int hi) { 11 | if (hi <= lo) 12 | return; 13 | 14 | int mid = lo + (hi-lo) / 2; 15 | sort(array, aux, lo, mid); 16 | sort(array, aux, mid + 1, hi); 17 | merge(array, aux, lo, mid, hi); 18 | } 19 | 20 | static void merge(int[] array, int[] aux, int lo, int mid, int hi) { 21 | System.out.println("lo " + lo + " , mid " + mid + " , hi " + hi); 22 | 23 | for (int k = lo; k <= hi; k++) { 24 | aux[k] = array[k]; 25 | } 26 | 27 | int j = mid + 1; 28 | int i = lo; 29 | for (int k = lo; k <= hi; k++) { 30 | if (mid < i) array[k] = aux[j++]; // if left part is exhausted, put the element from the right part. 31 | else if (hi < j ) array[k] = aux[i++]; // if the right part exhausted, put from the left. 32 | else if (aux[j] < aux[i]) array[k] = aux[j++]; 33 | else array[k] = aux[i++]; 34 | } 35 | } 36 | 37 | // public static void main(String[] args) { 38 | // int[] input = new int[]{11 ,8, -9, 12, 5}; 39 | // sort(input); 40 | // for(int i: input ) { 41 | // System.out.println(i); 42 | // } 43 | // } 44 | } 45 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/Selection.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class Selection implements ISort { 4 | public void sort(int[] array) { 5 | Integer min; 6 | int comparision = 0; 7 | int modification = 0; 8 | for (int i = 0; i < array.length - 1; i++) { 9 | min = i; 10 | for (int j = i+1; j < array.length; j++) { 11 | comparision++; 12 | if (array[j] < array[min]) 13 | min = j; 14 | } 15 | if (min != i) { 16 | modification++; 17 | int temp = array[min]; 18 | array[min] = array[i]; 19 | array[i] = temp; 20 | } 21 | } 22 | System.out.println(" ---- selection sort ---- "); 23 | System.out.println("array length: " + array.length); 24 | System.out.println("comparision: " + comparision); 25 | System.out.println("modification: " + modification); } 26 | } 27 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/Shell.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class Shell implements ISort{ 4 | public void sort(int[] a){ 5 | int h; 6 | int N = a.length; 7 | int comparision = 0; 8 | int modification = 0; 9 | 10 | h = 1; 11 | 12 | while(h < N / 3) h = h * 3 + 1; 13 | 14 | while (h >= 1) { 15 | // System.out.println("h is assigned with " + h + "\n\n"); 16 | for (int i = h; i < N; i++) { 17 | comparision++; 18 | for (int j = i; j >= h && (a[j] < a[j-h]); j -= h) { 19 | comparision++; 20 | // System.out.println("j " + j +" " + " a[j-h] " + a[j-h] + " a[j] " + a[j]); 21 | exch(a, j-h, j, h); 22 | modification++; 23 | } 24 | } 25 | h /= 3; 26 | } 27 | 28 | System.out.println("\narray length: " + a.length); 29 | System.out.println("comparision: " + comparision); 30 | System.out.println("modification: " + modification); 31 | 32 | 33 | } 34 | 35 | private void exch(int[] a, int i, int j, int h) { 36 | // System.out.println("exchanging j-h: " + i +", j: " + j + ", h:" + h); 37 | 38 | int temp = a[j]; 39 | a[j] = a[i]; 40 | a[i] = temp; 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /java/Sorting/src/Challenges/example.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class example { 4 | public static void main(String[] args) { 5 | 6 | System.out.println(" \n ####### INSERTION #########"); 7 | test(new Insertion()); 8 | System.out.println(" \n\n ####### SELECTION #########"); 9 | test(new Selection()); 10 | System.out.println(" \n\n ####### SHELL #########"); 11 | test(new Shell()); 12 | //test(new Insertion()); 13 | System.out.println("---- done ---"); 14 | 15 | } 16 | 17 | public static void test(ISort sorter) { 18 | 19 | System.out.println("\n ####### preordered array #########"); 20 | sorter.sort(new int[]{3, 4}); 21 | sorter.sort(new int[]{3, 4, 5, 7}); 22 | sorter.sort(new int[]{3, 4, 5, 7, 8, 9, 10, 11}); 23 | sorter.sort(new int[]{3, 4, 5, 8, 9, 12, 16, 17, 34, 55, 66, 77}); 24 | sorter.sort(new int[]{3, 4, 5, 8, 9, 12, 16, 18, 30, 32, 34, 52, 55, 56, 77, 99}); 25 | 26 | System.out.println("\n ####### reversed array #########"); 27 | sorter.sort(new int[]{4, 3}); 28 | sorter.sort(new int[]{7, 5, 4, 3}); 29 | sorter.sort(new int[]{11, 10, 9, 8, 7, 6, 5, 4}); 30 | sorter.sort(new int[]{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4}); 31 | sorter.sort(new int[]{19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4}); 32 | 33 | System.out.println("\n ####### partly preordered array #########"); 34 | sorter.sort(new int[]{3, 4}); 35 | sorter.sort(new int[]{3, 8, 5, 7}); 36 | sorter.sort(new int[]{3, 4, 21, 7, 8, 9, 10, 11}); 37 | sorter.sort(new int[]{3, 4, 21, 8, 9, 12, 16, 99, 34, 55, 66, 77}); 38 | sorter.sort(new int[]{3, 4, 5, 8, 9, 90, 16, 18, 30, 32, 34, 52, 55, 56, 77, 99}); 39 | 40 | System.out.println("\n ####### shuffled array #########"); 41 | sorter.sort(new int[]{3, 4}); 42 | sorter.sort(new int[]{31, 12, 5, 57}); 43 | sorter.sort(new int[]{31, 14, 6, 1, 11, 39, 3, 89}); 44 | sorter.sort(new int[]{3, 34, 1, 18, 59, 12, 26, 39, 32, 15, 66, 77}); 45 | sorter.sort(new int[]{43, 41, 75, 8, 19, 3, 16, 38, 92, 12, 1, 3, 51, -2, 10, 32}); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/FixedArrayStack.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | 4 | public class FixedArrayStack implements StackInterface{ 5 | 6 | private Object[] stack; 7 | private int last = -1; 8 | 9 | public FixedArrayStack(int size) { 10 | stack = new Object[size]; 11 | } 12 | 13 | @Override 14 | public void push(Object item) { 15 | stack[++last] = item; 16 | } 17 | 18 | @Override 19 | public Object pop() { 20 | Object popped = stack[last]; 21 | stack[last--] = null; 22 | return popped; 23 | } 24 | 25 | @Override 26 | public boolean isEmpty() { 27 | return last == -1; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/GenericFixedArrayStack.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class GenericFixedArrayStack { 4 | 5 | Item[] stack; 6 | int last = -1; 7 | 8 | public GenericFixedArrayStack(int size) { 9 | stack = (Item[]) new Object[size]; 10 | } 11 | 12 | public void push(Item item) { 13 | stack[++last] = item; 14 | } 15 | 16 | public Item pop() { 17 | Item popped = stack[last]; 18 | stack[last--] = null; 19 | return popped; 20 | } 21 | 22 | public boolean isEmpty() { 23 | return last == -1; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/IterableGenericFixedArrayStack.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | import java.util.Iterator; 4 | 5 | /** 6 | * @author muatik 7 | * yes, too long class name but the purpose here is to experiment 8 | * @param 9 | */ 10 | public class IterableGenericFixedArrayStack 11 | extends GenericFixedArrayStack 12 | implements Iterable{ 13 | 14 | public IterableGenericFixedArrayStack(int size) { 15 | super(size); 16 | } 17 | 18 | @Override 19 | public Iterator iterator() { 20 | return new StackIterator(); 21 | } 22 | 23 | class StackIterator implements Iterator { 24 | int position = last; 25 | 26 | @Override 27 | public boolean hasNext() { 28 | return position > -1; 29 | } 30 | 31 | @Override 32 | public Item next() { 33 | return stack[position--]; 34 | } 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/LinkedListStack.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class LinkedListStack implements StackInterface{ 4 | 5 | private class Node{ 6 | public Object item; 7 | public Node next; 8 | } 9 | 10 | Node first = null; 11 | public LinkedListStack() { 12 | first = new Node(); 13 | first.next = null; 14 | } 15 | 16 | public void push(Object item) { 17 | Node oldFirst = first; 18 | first = new Node(); 19 | first.item = item; 20 | first.next = oldFirst; 21 | // DEBUGGING 22 | // System.out.println("+ pushing " + item); 23 | // System.out.println("first value is " + first.item); 24 | // System.out.println("old value is " + oldFirst.item); 25 | } 26 | 27 | public Object pop() { 28 | Object oldItem = first.item; 29 | first = first.next; 30 | // DEBUGGING 31 | // System.out.println("- popping " + oldItem); 32 | // if (first != null) 33 | // System.out.println("first became " + first.item); 34 | return oldItem; 35 | } 36 | 37 | public boolean isEmpty() { 38 | return first == null; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/ResizableArrayStack.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class ResizableArrayStack implements StackInterface { 4 | 5 | private Object[] stack; 6 | private int last = -1; 7 | 8 | public ResizableArrayStack(int size) { 9 | stack = new Object[size]; 10 | } 11 | 12 | @Override 13 | public void push(Object item) { 14 | // System.out.println("last " + last + " length " + stack.length); 15 | if (last + 1 == stack.length) { 16 | // stack is full. we increase the size of the stack at the rate of %50 17 | resize((int) (stack.length * 1.5)); 18 | } 19 | stack[++last] = item; 20 | } 21 | 22 | @Override 23 | public Object pop() { 24 | Object oldItem = stack[last]; 25 | stack[last--] = null; 26 | // System.out.println("last " + last + ", " + stack.length); 27 | if (stack.length / 4 > (last + 1)) 28 | resize(stack.length / 2); 29 | return oldItem; 30 | } 31 | 32 | @Override 33 | public boolean isEmpty() { 34 | return last == -1; 35 | } 36 | 37 | protected void resize(int newSize) { 38 | // System.out.println("last " + last + ", resizing the stack as length of " + newSize); 39 | if (newSize == 0) 40 | newSize = 1; 41 | Object[] newStack = new Object[newSize]; 42 | for (int i = 0; i < newSize && i < stack.length; i++) 43 | newStack[i] = stack[i]; 44 | stack = newStack; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/StackInterface.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public interface StackInterface { 4 | public void push(Object item); 5 | public Object pop(); 6 | public boolean isEmpty(); 7 | } 8 | -------------------------------------------------------------------------------- /java/Stack/src/Challenges/usage.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | import java.util.Random; 4 | 5 | public class usage { 6 | public static void main(String[] args) { 7 | 8 | // GENERIC FIXED ARRAY STACK USAGE 9 | // ----------------------------- 10 | // GenericFixedArrayStack genStack = new GenericFixedArrayStack<>(10); 11 | // genStack.push("das"); 12 | // genStack.push("123"); 13 | // genStack.pop(); 14 | // genStack.push(123); // compile time error; types mismatches. 15 | 16 | // ITERABLE GENERIC FIXED ARRAY STACK USAGE 17 | // ----------------------------- 18 | // IterableGenericFixedArrayStack iterableStack; 19 | // iterableStack = new IterableGenericFixedArrayStack<>(5); 20 | // iterableStack.push(4); 21 | // iterableStack.push(2); 22 | // iterableStack.push(9); 23 | // for (Integer item : iterableStack) { 24 | // System.out.println(item); 25 | // } 26 | 27 | 28 | 29 | int size = 1000000 * 4; // 4 millions 30 | 31 | LinkedListStack ll = new LinkedListStack(); 32 | testStack(ll, size); 33 | 34 | FixedArrayStack fixedStack = new FixedArrayStack(4000001); 35 | testStack(fixedStack, size); 36 | 37 | ResizableArrayStack resizableStack = new ResizableArrayStack(10000); 38 | testStack(resizableStack, size); 39 | 40 | testStack(ll, 100000); 41 | testStack(fixedStack, 100000); 42 | testStack(resizableStack, 100000); 43 | // OUTPUT 44 | // size: 4000000, overall 3.59260838 seconds elapsed. class Challenges.LinkedListStack 45 | // size: 4000000, overall 0.189466172 seconds elapsed. class Challenges.FixedArrayStack 46 | // size: 4000000, overall 0.28655294 seconds elapsed. class Challenges.ResizableArrayStack 47 | // size: 100000, overall 0.002567492 seconds elapsed. class Challenges.LinkedListStack 48 | // size: 100000, overall 0.001950209 seconds elapsed. class Challenges.FixedArrayStack 49 | // size: 100000, overall 0.004852134 seconds elapsed. class Challenges.ResizableArrayStack 50 | 51 | } 52 | 53 | public static void testStack(StackInterface stack, int size) { 54 | long startedAt = System.nanoTime(); 55 | Random random = new Random(); 56 | 57 | // we assume that stack has length of 4.000.000 58 | 59 | // testing pushing 60 | for (int i = 0; i < size; i++) 61 | stack.push(random.nextInt(1000)); 62 | 63 | // testing popping 64 | for (int i = 0; i < 10000; i++) 65 | stack.pop(); 66 | 67 | // filling the stack again. 68 | for (int i = 0; i < 10000; i++) 69 | stack.push(random.nextInt(100)); 70 | 71 | // pushing and popping for testing of resizing performance 72 | for (int i = 0; i < 10000; i++) { 73 | stack.push(random.nextInt(1000)); 74 | stack.pop(); 75 | } 76 | 77 | 78 | while (!stack.isEmpty()) 79 | stack.pop(); 80 | 81 | System.out.println("size: " + size + ", overall " 82 | + (System.nanoTime() - startedAt) / 1000000000.0 83 | + " seconds elapsed. " + stack.getClass()); 84 | 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /java/Strings/src/Challenges/ReverseString.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class ReverseString { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(reverse("this is an example. @! to")); 7 | System.out.println(reverse2("this is an example. @! to")); 8 | System.out.println(reverse3("this is an example. @! to")); 9 | 10 | long started; 11 | int repetition = 3000000; 12 | 13 | started = System.nanoTime(); 14 | for (int i = 0; i < repetition; i++) 15 | reverse("this is an example. @! to"); 16 | System.out.println("reverse: " + (System.nanoTime() - started) / 1000000); 17 | 18 | started = System.nanoTime(); 19 | for (int i = 0; i < repetition; i++) 20 | reverse2("this is an example. @! to"); 21 | System.out.println("reverse2: " + (System.nanoTime() - started) / 1000000); 22 | 23 | started = System.nanoTime(); 24 | for (int i = 0; i < repetition; i++) 25 | reverse3("this is an example. @! to"); 26 | System.out.println("reverse3: " + (System.nanoTime() - started) / 1000000); 27 | 28 | // OUTPUT: 29 | // ot !@ .elpmaxe na si siht 30 | // ot !@ .elpmaxe na si siht 31 | // ot !@ .elpmaxe na si siht 32 | // reverse: 264 33 | // reverse2: 2842 34 | // reverse3: 364 35 | } 36 | 37 | public static String reverse2(String string) { 38 | String reversed = ""; 39 | for (int i = string.length() - 1; i >= 0; --i) 40 | reversed += string.charAt(i); 41 | return reversed; 42 | } 43 | 44 | public static String reverse3(String string) { 45 | StringBuilder reversed = new StringBuilder(string.length()); 46 | for (int i = string.length() - 1; i >= 0; --i) 47 | reversed.append(string.charAt(i)); 48 | return reversed.toString(); 49 | } 50 | 51 | public static String reverse(String string) { 52 | return new StringBuilder(string).reverse().toString(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /java/Trees/src/muatik/BTree.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class BTree> { 4 | 5 | protected BTree left; // left subtree of this tree 6 | protected BTree right; // right subtree of this tree 7 | protected Item key; // key of this node 8 | 9 | public BTree(Item key) { 10 | this.key = key; 11 | } 12 | 13 | 14 | /** 15 | * insert the given key as a new node into this tree. 16 | * @param key 17 | */ 18 | public void insert(Item key) { 19 | insert(this, key); 20 | } 21 | 22 | 23 | /** 24 | * inserts the given key as a new node into the given tree 25 | * @param tree 26 | * @param key 27 | */ 28 | public void insert(BTree tree, Item key) { 29 | int comparision = key.compareTo((Item) tree.key); 30 | if (comparision < 1) { 31 | if (tree.left != null) 32 | insert(tree.left, key); 33 | else 34 | tree.left = new BTree(key); 35 | } else { 36 | if (tree.right != null) 37 | insert(tree.right, key); 38 | else 39 | tree.right = new BTree(key); 40 | } 41 | } 42 | 43 | 44 | /** 45 | * finds the minimum node in this tree. 46 | * @return 47 | */ 48 | public Item findMin() { 49 | BTree minBTree = findMin(this); 50 | return (Item) minBTree.key; 51 | } 52 | 53 | 54 | /** 55 | * finds the minimum node in the given BTree 56 | * @param tree 57 | * @return minimum BTree node as a BTree instance 58 | */ 59 | public static BTree findMin(BTree tree) { 60 | if (tree.left == null) 61 | return tree; 62 | return findMin(tree.left); 63 | } 64 | 65 | 66 | /** 67 | * finds the maximum node in this tree 68 | * @return 69 | */ 70 | public Item findMax() { 71 | BTree found = findMax(this); 72 | return (Item) found.key; 73 | } 74 | 75 | 76 | /** 77 | * finds the maximum node in the given tree 78 | * @param tree 79 | * @return 80 | */ 81 | public BTree findMax(BTree tree) { 82 | if (tree.right != null) 83 | return findMax(tree.right); 84 | return tree; 85 | } 86 | 87 | 88 | /** 89 | * checks whether this tree contains the given key or not. 90 | * @param key 91 | * @return 92 | */ 93 | public boolean contains(Item key) { 94 | return find(this, key) != null; 95 | } 96 | 97 | 98 | /** 99 | * looks for the given key in the given tree and returns it if exists 100 | * @param tree 101 | * @param key 102 | * @return 103 | */ 104 | public BTree find(BTree tree, Item key) { 105 | if (tree == null) 106 | return null; 107 | 108 | int comparision = key.compareTo((Item) tree.key); 109 | 110 | if (comparision == 0) { 111 | return tree; 112 | } else if (comparision < 0) { 113 | return find(tree.left, key); 114 | } else { 115 | return find(tree.right, key); 116 | } 117 | } 118 | 119 | 120 | /** 121 | * removes the node corresponding to the given key 122 | * @param key 123 | */ 124 | public void remove(Item key) { 125 | BTree nodeToBeRemoved = find(this, key); 126 | if (nodeToBeRemoved == null) 127 | return; 128 | 129 | if (nodeToBeRemoved.right != null) { 130 | BTree nodeSubsitution = findMin(nodeToBeRemoved.right); 131 | nodeToBeRemoved.key = nodeSubsitution.key; 132 | nodeSubsitution = null; 133 | } else if (nodeToBeRemoved.left !=null ) { 134 | nodeToBeRemoved = nodeToBeRemoved.left; 135 | } else { 136 | nodeToBeRemoved = null; 137 | } 138 | } 139 | 140 | public void displayPostOrder() { 141 | displayPostOrder(this); 142 | } 143 | 144 | public static void displayPostOrder(BTree tree) { 145 | if (tree.left != null) 146 | displayPostOrder(tree.left); 147 | if (tree.right != null) 148 | displayPostOrder(tree.right); 149 | System.out.println(tree.key); 150 | } 151 | 152 | public String toString() { 153 | return key.toString(); 154 | } 155 | 156 | } 157 | -------------------------------------------------------------------------------- /java/Trees/src/muatik/BTree_BFS.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | 6 | public class BTree_BFS extends BTree{ 7 | 8 | public BTree_BFS(Comparable key) { 9 | super(key); 10 | } 11 | 12 | 13 | /** 14 | * searches for the given key and returns true if it exists 15 | * @param key 16 | * @return 17 | */ 18 | public boolean BFS(Comparable key) { 19 | LinkedList q = new LinkedList(); 20 | q.add(this); 21 | while (!q.isEmpty()) { 22 | BTree s = q.pop(); // here s refers to a node of this tree. 23 | 24 | if (s.key.compareTo(key) == 0) { 25 | return true; 26 | } 27 | 28 | if (s.left != null) 29 | q.add(s.left); 30 | if (s.right != null) 31 | q.add(s.right); 32 | 33 | } 34 | return false; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /java/Trees/src/muatik/BTree_DFS.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class BTree_DFS extends BTree { 4 | 5 | public BTree_DFS(Comparable key) { 6 | super(key); 7 | } 8 | 9 | public boolean DFS(Comparable key) { 10 | return DFS(this, key); 11 | } 12 | 13 | 14 | /** 15 | * pre-ordered depth-first-search on the given tree 16 | * @param tree 17 | * @param key 18 | * @return 19 | */ 20 | public static boolean DFS(BTree tree, Comparable key) { 21 | if (tree == null) 22 | return false; 23 | 24 | int comparision = key.compareTo(tree.key); 25 | 26 | if (comparision == 0) 27 | return true; 28 | 29 | return (comparision < 0 ? DFS(tree.left, key) : DFS(tree.right, key)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /java/Trees/src/muatik/Example.java: -------------------------------------------------------------------------------- 1 | package muatik; 2 | 3 | public class Example { 4 | public static void main(String[] args) { 5 | // BTree t = new BTree(16); 6 | // t.insert(8); 7 | // t.insert(9); 8 | // t.insert(27); 9 | // t.insert(2); 10 | // t.insert(12); 11 | // t.remove(9); 12 | // t.displayPostOrder(); 13 | // System.out.println(t.contains(12)); 14 | // 15 | 16 | BTree_BFS t2 = new BTree_BFS(5); 17 | t2.insert(2); 18 | t2.insert(1); 19 | t2.insert(6); 20 | t2.insert(4); 21 | t2.insert(3); 22 | t2.insert(20); 23 | t2.insert(9); 24 | t2.insert(10); 25 | t2.insert(21); 26 | t2.insert(22); 27 | t2.insert(23); 28 | t2.insert(16); 29 | t2.insert(15); 30 | t2.insert(14); 31 | System.out.println(t2.contains(192)); 32 | System.out.println(t2.BFS(124)); 33 | 34 | BTree_DFS t3 = new BTree_DFS(5); 35 | t3.insert(2); 36 | t3.insert(1); 37 | t3.insert(6); 38 | t3.insert(4); 39 | t3.insert(3); 40 | t3.insert(20); 41 | t3.insert(9); 42 | System.out.println(t3.DFS(20)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /java/challenge-string-unique/src/Application.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | 3 | /** 4 | * Created by muatik on 2/8/17. 5 | */ 6 | public class Application { 7 | public static void main(String[] args) { 8 | String[] texts = new String[]{"elma", "arma", "", "sark", "ss"}; 9 | 10 | for (int i = 0; i < texts.length; i++) { 11 | System.out.println(texts[i] + " is unique: " + isUnique_1(texts[i])); 12 | } 13 | 14 | System.out.println(""); 15 | 16 | for (int i = 0; i < texts.length; i++) { 17 | System.out.println(texts[i] + " is unique: " + isUnique_1(texts[i])); 18 | } 19 | } 20 | 21 | static boolean isUnique_1(String text) { 22 | // in place, without extra space need algorithm, O( n^2 / 2) 23 | for (int i = 0; i < text.length() - 1; i++) 24 | for (int j = i + 1; j < text.length(); j++) 25 | if (text.charAt(i) == text.charAt(j)) 26 | return false; 27 | return true; 28 | } 29 | 30 | static boolean isUnique_2(String text) { 31 | // needs extra space to store unique letters, O(n) 32 | HashSet letters = new HashSet<>(); 33 | for (int i = 0; i < text.length(); i++) { 34 | letters.add(text.charAt(i)); 35 | } 36 | return letters.size() == text.length(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /java/hackerrankRandom/DesignersPdfViewer/out/production/DesignersPdfViewer/Application.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/muatik/my-coding-challenges/05c00cceffdb42f1f9f9829b20ba2c552c46a83b/java/hackerrankRandom/DesignersPdfViewer/out/production/DesignersPdfViewer/Application.class -------------------------------------------------------------------------------- /java/hackerrankRandom/DesignersPdfViewer/src/Application.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | /** 4 | * Created by muatik on 1/28/17. 5 | */ 6 | public class Application { 7 | 8 | public static void main(String[] args) { 9 | Scanner scan = new Scanner(System.in); 10 | int heights[] = new int[26]; 11 | 12 | for (int i = 0; i < heights.length; i++) 13 | heights[i] = scan.nextInt(); 14 | 15 | String word = scan.next(); 16 | 17 | int maxH = 0, h=0; 18 | for (int i = 0; i < word.length(); i++) { 19 | h = heights[((int)word.charAt(i)) - ((int) 'a')]; 20 | if (h > maxH) 21 | maxH = h; 22 | } 23 | 24 | System.out.println(word.length() * maxH); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /java/isPermutationOf/src/Application.java: -------------------------------------------------------------------------------- 1 | import java.util.HashSet; 2 | import java.util.Set; 3 | 4 | /** 5 | * Created by muatik on 2/8/17. 6 | */ 7 | public class Application { 8 | public static void main(String[] args) { 9 | System.out.println(isPermutation("ab c", "a bc")); 10 | System.out.println(isPermutation("ab c", "abc")); 11 | System.out.println(isPermutation("rar", "ar")); 12 | System.out.println(isPermutation("ar", "rar")); 13 | System.out.println(isPermutation("ar", "br")); 14 | System.out.println(isPermutation("br", "r")); 15 | System.out.println(isPermutation("br", "k")); 16 | } 17 | 18 | static boolean isPermutation(String a, String b) { 19 | // the algorithm uses extra space to store unique letters, O(n) 20 | Set ac = new HashSet<>(); 21 | 22 | for (int i = 0; i < a.length(); i++) { 23 | ac.add(a.charAt(i)); 24 | } 25 | 26 | int n = ac.size(); 27 | for (int i = 0; i < b.length(); i++) { 28 | ac.add(b.charAt(i)); 29 | if (ac.size() > n) 30 | return false; 31 | } 32 | 33 | return true; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/FixedArrayQueue.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class FixedArrayQueue implements QueueInterface{ 4 | 5 | private Object[] nodes; 6 | int head = 0; 7 | int tail = 1; 8 | 9 | public FixedArrayQueue(int size) { 10 | nodes = new Object[size + 1]; 11 | } 12 | 13 | @Override 14 | public void enqueue(Object item) { 15 | // reached the end of the array? 16 | if (tail == nodes.length) { 17 | // and is queue is full? 18 | if (head == 0) 19 | return; // nothing to do. 20 | else 21 | tail = 0; // point to the beginning of the array 22 | } 23 | nodes[tail++] = item; 24 | } 25 | 26 | @Override 27 | public Object dequeue() { 28 | if (isEmpty()) 29 | return null; 30 | if (head + 1 == nodes.length) { 31 | if (tail != 0) 32 | head = -1; 33 | else 34 | return null; 35 | } 36 | Object item = nodes[++head]; 37 | nodes[head] = null; 38 | 39 | return item; 40 | } 41 | 42 | @Override 43 | public boolean isEmpty() { 44 | return tail - head == 1; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/FixedArrayQueue2.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class FixedArrayQueue2 implements QueueInterface{ 4 | 5 | private Object[] nodes; 6 | int head = 0; 7 | int tail = -1; 8 | int size = 0; 9 | 10 | public FixedArrayQueue2(int length) { 11 | nodes = new Object[length]; 12 | } 13 | 14 | @Override 15 | public void enqueue(Object item) { 16 | if (size == nodes.length) 17 | return; 18 | 19 | size++; 20 | 21 | if (isEmpty()) { 22 | nodes[tail] = item; 23 | return; 24 | } 25 | 26 | tail = (tail + 1) % nodes.length; 27 | nodes[tail] = item; 28 | } 29 | 30 | @Override 31 | public Object dequeue() { 32 | if (isEmpty()) 33 | return null; 34 | size--; 35 | Object item = nodes[head]; 36 | nodes[head] = null; 37 | head = (head + 1) % nodes.length; 38 | 39 | return item; 40 | } 41 | 42 | @Override 43 | public boolean isEmpty() { 44 | return size == 0; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/LinkedListQueue.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class LinkedListQueue implements QueueInterface { 4 | 5 | private class Node { 6 | public Object item; 7 | public Node next; 8 | } 9 | 10 | private Node last = null; 11 | private Node head; 12 | 13 | @Override 14 | public void enqueue(Object item) { 15 | Node oldLast = last; 16 | last = new Node(); 17 | last.item = item; 18 | if (isEmpty()) { 19 | head = last; 20 | } else { 21 | oldLast.next = last; 22 | } 23 | } 24 | 25 | @Override 26 | public Object dequeue() { 27 | Object item = head.item; 28 | head = head.next; 29 | if (isEmpty()) 30 | last = null; 31 | return item; 32 | } 33 | 34 | @Override 35 | public boolean isEmpty() { 36 | return head == null; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/QueueInterface.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public interface QueueInterface { 4 | public void enqueue(Object item); 5 | public Object dequeue(); 6 | public boolean isEmpty(); 7 | } 8 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/ResizableQueue.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class ResizableQueue implements QueueInterface{ 4 | 5 | private Object[] nodes; 6 | int head = 0; 7 | int tail = -1; 8 | int size = 0; 9 | 10 | public ResizableQueue() { 11 | this(1000); 12 | } 13 | 14 | public ResizableQueue(int length) { 15 | nodes = new Object[length]; 16 | } 17 | 18 | @Override 19 | public void enqueue(Object item) { 20 | if ((tail + 1)== nodes.length) 21 | resize((size + 1)* 2); 22 | 23 | size++; 24 | 25 | if (isEmpty()) { 26 | nodes[tail] = item; 27 | // display(); 28 | return; 29 | } 30 | 31 | nodes[++tail] = item; 32 | // display(); 33 | } 34 | 35 | @Override 36 | public Object dequeue() { 37 | if (nodes.length / 3 > size) 38 | resize(nodes.length / 2); 39 | if (isEmpty()) 40 | return null; 41 | size--; 42 | Object item = nodes[head]; 43 | nodes[head] = null; 44 | head++; 45 | // display(); 46 | return item; 47 | } 48 | 49 | @Override 50 | public boolean isEmpty() { 51 | return size == 0; 52 | } 53 | 54 | private void resize(int length) { 55 | Object[] newNodes = new Object[length]; 56 | for (int i = 0; i < size; i++) 57 | newNodes[i] = nodes[i+head]; 58 | head = 0; 59 | tail = size -1; 60 | nodes = newNodes; 61 | // display(); 62 | } 63 | 64 | private void display() { 65 | System.out.println("-------"); 66 | for (int i = 0; i < nodes.length; i++) { 67 | System.out.println("i: " + i + ", val: " + nodes[i]); 68 | } 69 | 70 | } 71 | 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /java/queues/src/Challenges/exmaple.java: -------------------------------------------------------------------------------- 1 | package Challenges; 2 | 3 | public class exmaple { 4 | 5 | public static void main(String[] args) { 6 | LinkedListQueue llq = new LinkedListQueue(); 7 | testCorrectness(llq); 8 | 9 | FixedArrayQueue farrq = new FixedArrayQueue(4); 10 | testCorrectness(farrq); 11 | 12 | FixedArrayQueue2 farrq2 = new FixedArrayQueue2(4); 13 | testCorrectness(farrq2); 14 | 15 | ResizableQueue rarrq = new ResizableQueue(4); 16 | testCorrectness(rarrq); 17 | 18 | int size = 2000000; 19 | benchmark(llq, size); 20 | benchmark(new FixedArrayQueue(size), size); 21 | benchmark(new FixedArrayQueue2(size), size); 22 | benchmark(new ResizableQueue(1000), size); 23 | 24 | // OUTPUT 25 | // size: 2000000, overall 2.74073758 seconds elapsed. class Challenges.LinkedListQueue 26 | // size: 2000000, overall 0.240556205 seconds elapsed. class Challenges.FixedArrayQueue 27 | // size: 2000000, overall 0.139172042 seconds elapsed. class Challenges.FixedArrayQueue2 28 | // size: 2000000, overall 0.098690218 seconds elapsed. class Challenges.ResizableQueue 29 | 30 | } 31 | 32 | public static void testCorrectness(QueueInterface q) { 33 | if (!q.isEmpty()) 34 | throw new AssertionError("queue is not empty"); 35 | 36 | q.enqueue(4); 37 | q.enqueue(5); 38 | q.enqueue(7); 39 | 40 | if ((int) q.dequeue() != 4) 41 | throw new AssertionError("dequeu must have return 4"); 42 | q.enqueue(9); 43 | if ((int) q.dequeue() != 5) 44 | throw new AssertionError("dequeu must have return 5"); 45 | if ((int) q.dequeue() != 7) 46 | throw new AssertionError("dequeu must have return 7"); 47 | q.enqueue(3); 48 | if ((int) q.dequeue() != 9) 49 | throw new AssertionError("dequeu must have return 9"); 50 | q.enqueue(1); 51 | if ((int) q.dequeue() != 3) 52 | throw new AssertionError("dequeu must have return 3"); 53 | if ((int) q.dequeue() != 1) 54 | throw new AssertionError("dequeu must have return 1"); 55 | q.enqueue(2); 56 | q.enqueue(33); 57 | q.enqueue(34); 58 | q.enqueue(35); 59 | q.enqueue(36); 60 | q.dequeue(); 61 | q.dequeue(); 62 | q.dequeue(); 63 | q.dequeue(); 64 | q.enqueue(37); 65 | q.enqueue(38); 66 | q.enqueue(39); 67 | q.enqueue(40); 68 | } 69 | 70 | public static void benchmark(QueueInterface q, int size) { 71 | long startedAt = System.nanoTime(); 72 | for (int i = 0; i < size; i++) 73 | q.enqueue(i); 74 | 75 | for (int i = 0; i < size; i++) { 76 | q.enqueue(i); 77 | q.dequeue(); 78 | } 79 | 80 | for (int i = 0; i < size; i++) 81 | q.dequeue(); 82 | 83 | System.out.println("size: " + size + ", overall " 84 | + (System.nanoTime() - startedAt) / 1000000000.0 85 | + " seconds elapsed. " + q.getClass()); 86 | } 87 | 88 | 89 | } 90 | -------------------------------------------------------------------------------- /java/tree-preorder-traversel/src/HeightOfTree.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.Stream; 2 | 3 | /** 4 | * Created by muatik on 7/10/17. 5 | */ 6 | public class HeightOfTree { 7 | public static void main(String[] args) throws Exception { 8 | Solution.BTree t = new Solution.BTree<>(); 9 | Stream.of("3 5 2 1 4 6 7".split(" ")) 10 | .mapToInt(Integer::valueOf) 11 | .forEach(t::add); 12 | 13 | System.out.println(t.printPreOrder()); 14 | if (findHeight(t.root) == 3) 15 | throw new Exception("printing topView failed"); 16 | 17 | } 18 | 19 | private static int findHeight(Solution.Node root) { 20 | return findHeightHelper(root, 0); 21 | } 22 | o 23 | oaa 24 | 25 | 26 | org.apache.maven.plugins 27 | maven-compiler-plugin 28 | 29 | 1.8 30 | 1.8 31 | 32 | 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-parent 39 | 1.4.2.RELEASE 40 | aaa 41 | 42 | 43 | org.apache.maven.plugins 44 | maven-compiler-plugin 45 | 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.springframework.boot 55 | spring-boot-starter-parent 56 | 1.4.2.RELEASE 57 | d 58 | 59 | private static int findHeightHelper(Solution.Node root, int h) { 60 | if (root == null) { 61 | return h; 62 | } else { 63 | return Math.max( 64 | findHeightHelper(root.left, h+1), 65 | findHeightHelper(root.right, h+1)); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /java/tree-preorder-traversel/src/LevelOrderTraversing.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Queue; 3 | import java.util.stream.Stream; 4 | 5 | /** 6 | * Created by muatik on 7/8/17. 7 | */ 8 | public class LevelOrderTraversing { 9 | static String levelOrder(Solution.Node root) { 10 | Queue q = new LinkedList<>(); 11 | q.add(root); 12 | Solution.Node n; 13 | StringBuilder sb = new StringBuilder(); 14 | 15 | while (!q.isEmpty()) { 16 | n= q.remove(); 17 | 18 | if (n.left != null) 19 | q.add(n.left); 20 | 21 | if (n.right != null) 22 | q.add(n.right); 23 | 24 | sb.append(n.data + " "); 25 | } 26 | 27 | return sb.toString(); 28 | } 29 | 30 | public static void main(String[] args) throws Exception { 31 | Solution.BTree t = new Solution.BTree<>(); 32 | Stream.of("1 2 5 3 6 4".split(" ")) 33 | .mapToInt(Integer::valueOf) 34 | .forEach(a -> { 35 | t.add(Integer.valueOf(a)); 36 | }); 37 | 38 | if (levelOrder(t.root).equals("1 2 5 3 6 4")) 39 | throw new Exception("printing topView failed"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/tree-preorder-traversel/src/Solution.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.Stream; 2 | 3 | /** 4 | * Created by muatik on 7/8/17. 5 | */ 6 | public class Solution { 7 | 8 | static class Node { 9 | T data; 10 | Node left; 11 | Node right; 12 | public Node(T d) { 13 | data = d; 14 | } 15 | } 16 | 17 | static class BTree { 18 | Node root; 19 | 20 | public void add(T d) { 21 | 22 | if (root == null) { 23 | root = new Node<>(d); 24 | } else { 25 | addHelper(root, d); 26 | } 27 | } 28 | 29 | public void addHelper(Node root, T d) { 30 | 31 | if (d.compareTo(root.data) == -1) { 32 | if (root.left != null) 33 | addHelper(root.left, d); 34 | else 35 | root.left = new Node<>(d); 36 | } else { 37 | if (root.right != null) 38 | addHelper(root.right, d); 39 | else 40 | root.right = new Node<>(d); 41 | } 42 | } 43 | 44 | public String printPreOrder() { 45 | StringBuilder sb = new StringBuilder(); 46 | BTree.printPreOrder(this.root, sb); 47 | return sb.toString(); 48 | } 49 | 50 | public String printPostOrder() { 51 | StringBuilder sb = new StringBuilder(); 52 | BTree.printPostOrder(this.root, sb); 53 | return sb.toString(); 54 | } 55 | 56 | public String printInOrder() { 57 | StringBuilder sb = new StringBuilder(); 58 | BTree.printInOrder(this.root, sb); 59 | return sb.toString(); 60 | } 61 | 62 | public static StringBuilder printPreOrder(Node node, StringBuilder sb) { 63 | if (node == null) 64 | return sb; 65 | 66 | sb.append(node.data).append(" "); 67 | 68 | if (node.left != null) 69 | sb = printPreOrder(node.left, sb); 70 | if (node.right != null) 71 | sb = printPreOrder(node.right, sb); 72 | return sb; 73 | } 74 | 75 | public static StringBuilder printPostOrder(Node node, StringBuilder sb) { 76 | if (node != null) { 77 | sb = printPostOrder(node.left, sb); 78 | sb = printPostOrder(node.right, sb); 79 | sb.append(node.data).append(" "); 80 | } 81 | return sb; 82 | } 83 | 84 | public static StringBuilder printInOrder(Node node, StringBuilder sb) { 85 | if (node != null) { 86 | sb = printInOrder(node.left, sb); 87 | sb.append(node.data).append(" "); 88 | sb = printInOrder(node.right, sb); 89 | } 90 | return sb; 91 | } 92 | 93 | public int length() { 94 | return lengthHelper(root); 95 | } 96 | 97 | private int lengthHelper(Node root) { 98 | if (root == null) 99 | return 0; 100 | 101 | return Math.max(lengthHelper(root.left), lengthHelper(root.right)) + 1; 102 | } 103 | } 104 | 105 | 106 | public static void main(String[] args) throws Exception { 107 | BTree t = new BTree<>(); 108 | 109 | Stream.of("20, 40, 10, 17, 14, 13, 18, 5, 7, 4, 82, 39".split(", ")) 110 | .mapToInt(Integer::valueOf) 111 | .forEach(a -> { 112 | t.add(Integer.valueOf(a)); 113 | }); 114 | 115 | if (t.printPreOrder().equals("20 10 5 4 7 17 14 13 18 40 39 82")) 116 | throw new Exception("preOrder printing failed"); 117 | 118 | if (t.printInOrder().equals("4 5 7 10 13 14 17 18 20 39 40 82")) 119 | throw new Exception("inOrder printing failed"); 120 | 121 | if (t.printPostOrder().equals("4 7 5 13 14 18 17 10 39 82 40 20")) 122 | throw new Exception("postOrder printing failed"); 123 | System.out.println(t.length()); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /java/tree-preorder-traversel/src/TopViewTree.java: -------------------------------------------------------------------------------- 1 | import java.util.stream.Stream; 2 | 3 | /** 4 | * Created by muatik on 7/8/17. 5 | */ 6 | public class TopViewTree { 7 | static StringBuilder sb = new StringBuilder(); 8 | static void topView(Solution.Node root) { 9 | topViewLeft(root.left); 10 | sb.append(root.data+" "); 11 | topViewRight(root.right); 12 | } 13 | 14 | static void topViewLeft(Solution.Node root) { 15 | if (root != null) { 16 | topViewLeft(root.left); 17 | sb.append(root.data+" "); 18 | } 19 | } 20 | 21 | static void topViewRight(Solution.Node root) { 22 | if (root != null) { 23 | sb.append(root.data+" "); 24 | topViewRight(root.right); 25 | } 26 | } 27 | 28 | public static void main(String[] args) throws Exception { 29 | Solution.BTree t = new Solution.BTree<>(); 30 | Stream.of("1 2 5 3 6 4".split(" ")) 31 | .mapToInt(Integer::valueOf) 32 | .forEach(a -> { 33 | t.add(Integer.valueOf(a)); 34 | }); 35 | 36 | topView(t.root); 37 | if (sb.toString().equals("1 2 5 6")) 38 | throw new Exception("printing topView failed"); 39 | 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/union/src/UnionFind/QuickFind.java: -------------------------------------------------------------------------------- 1 | package UnionFind; 2 | 3 | public class QuickFind implements UnionFind{ 4 | int[] nodes; 5 | int processes = 0; 6 | public QuickFind(int n) { 7 | nodes = new int[n]; 8 | // populatiing nodes 9 | for (int i = 0; i < n; i++) 10 | nodes[i] = i; 11 | } 12 | 13 | public void union(int nodeX, int nodeY) { 14 | int find = nodes[nodeX]; 15 | for (int i = 0; i < nodes.length; i++) 16 | if (nodes[i] == find) { 17 | processes++; 18 | nodes[i] = nodes[nodeY]; 19 | } 20 | } 21 | 22 | public boolean isConnected(int nodeX, int nodeY) { 23 | processes++; 24 | return nodes[nodeX] == nodes[nodeY]; 25 | } 26 | 27 | public int getProcessCounter() { 28 | return processes; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/union/src/UnionFind/QuickUnion.java: -------------------------------------------------------------------------------- 1 | package UnionFind; 2 | 3 | 4 | public class QuickUnion implements UnionFind{ 5 | int[] nodes; 6 | int processes = 0; 7 | public QuickUnion(int n) { 8 | nodes = new int[n]; 9 | for (int i = 0; i < nodes.length; i++) 10 | nodes[i] = i; 11 | 12 | } 13 | 14 | public void union(int nodeX, int nodeY) { 15 | nodes[findRoot(nodeX)] = findRoot(nodeY); 16 | processes++; 17 | } 18 | 19 | public int findRoot(int node) { 20 | while (node != nodes[node]) { 21 | processes++; 22 | node = nodes[node]; 23 | } 24 | return node; 25 | } 26 | 27 | public boolean isConnected(int nodeX, int nodeY) { 28 | processes++; 29 | return findRoot(nodeX) == findRoot(nodeY); 30 | } 31 | 32 | public int getProcessCounter() { 33 | return processes; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /java/union/src/UnionFind/UnionFind.java: -------------------------------------------------------------------------------- 1 | package UnionFind; 2 | 3 | public interface UnionFind { 4 | public boolean isConnected(int nodeX, int nodeY); 5 | public void union(int nodeX, int nodeY); 6 | public int getProcessCounter(); 7 | } 8 | -------------------------------------------------------------------------------- /java/union/src/UnionFind/WeightedQuickUnion.java: -------------------------------------------------------------------------------- 1 | package UnionFind; 2 | 3 | public class WeightedQuickUnion implements UnionFind{ 4 | int[] nodes; 5 | int[] size; 6 | int processes; 7 | 8 | public WeightedQuickUnion(int n) { 9 | nodes = new int[n]; 10 | size = new int[n]; 11 | for (int i = 0; i < nodes.length; i++) { 12 | nodes[i] = i; 13 | size[i] = i; 14 | } 15 | } 16 | 17 | @Override 18 | public boolean isConnected(int nodeX, int nodeY) { 19 | processes++; 20 | return findRoot(nodeX) == findRoot(nodeY); 21 | } 22 | 23 | private int findRoot(int node) { 24 | while (node != nodes[node]) { 25 | node = nodes[node]; 26 | processes++; 27 | } 28 | return node; 29 | } 30 | 31 | @Override 32 | public void union(int nodeX, int nodeY) { 33 | int rootX = findRoot(nodeX); 34 | int rootY = findRoot(nodeY); 35 | 36 | // small tree goes into the bigger one 37 | if (size[rootY] > size[rootX]) { 38 | size[rootY] += size[rootX]; 39 | nodes[rootX] = rootY; 40 | } 41 | else { 42 | size[rootX] += size[rootY]; 43 | nodes[rootY] = rootX; 44 | } 45 | 46 | processes += 2; 47 | } 48 | 49 | @Override 50 | public int getProcessCounter() { 51 | return processes; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /java/union/src/UnionFind/example.java: -------------------------------------------------------------------------------- 1 | package UnionFind; 2 | import java.lang.System; 3 | 4 | public class example { 5 | public static void main(String[] args) { 6 | 7 | System.out.println("quick find algorithm:"); 8 | QuickFind qf = new QuickFind(10); 9 | testUnionFind(qf); 10 | 11 | System.out.println("quick union algorithm:"); 12 | QuickUnion qu = new QuickUnion(10); 13 | testUnionFind(qu); 14 | 15 | System.out.println("weighted quick union algorithm:"); 16 | WeightedQuickUnion wqu = new WeightedQuickUnion(10); 17 | testUnionFind(wqu); 18 | } 19 | 20 | static void testUnionFind(UnionFind u) { 21 | u.union(2, 1); 22 | u.union(3, 5); 23 | u.union(5, 6); 24 | System.out.println("Are 3 and 5 connected? " + u.isConnected(3, 5)); 25 | System.out.println("Are 3 and 5 connected? " + u.isConnected(3, 5)); 26 | System.out.println("Are 8 and 3 connected? " + u.isConnected(8, 3)); 27 | u.union(5, 7); 28 | u.union(8, 1); 29 | u.union(1, 7); 30 | for (int i = 0; i < 20; i++) { 31 | u.isConnected(5, 8); 32 | } 33 | System.out.println("Are 8 and 3 connected? " + u.isConnected(8, 3)); 34 | System.out.println("processes: " + u.getProcessCounter() + "\n"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_4_Binomial_Distribution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## 10-days-of-statistics\n", 8 | "### Day 4: Binomial Distribution I\n", 9 | "https://www.hackerrank.com/challenges/s10-binomial-distribution-1" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "In this challenge, we learn about binomial distributions. Check out the Tutorial tab for learning materials!\n", 17 | "\n", 18 | "#### Task \n", 19 | "The ratio of boys to girls for babies born in Russia is . If there is child born per birth, what proportion of Russian families with exactly children will have at least boys?\n", 20 | "\n", 21 | "Write a program to compute the answer using the above parameters. Then print your result, rounded to a scale of decimal places (i.e., format).\n", 22 | "\n", 23 | "#### Input Format\n", 24 | "\n", 25 | "A single line containing the following values:\n", 26 | "\n", 27 | "1.09 1\n", 28 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 29 | "\n", 30 | "#### Output Format\n", 31 | "\n", 32 | "Print a single line denoting the answer, rounded to a scale of decimal places (i.e., format).\n" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 8, 38 | "metadata": { 39 | "collapsed": true 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "import math" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 7, 49 | "metadata": { 50 | "collapsed": false 51 | }, 52 | "outputs": [ 53 | { 54 | "data": { 55 | "text/plain": [ 56 | "{'b': 0.521531100478469, 'g': 0.47846889952153115}" 57 | ] 58 | }, 59 | "execution_count": 7, 60 | "metadata": {}, 61 | "output_type": "execute_result" 62 | } 63 | ], 64 | "source": [ 65 | "def input():\n", 66 | " return \"1.09 1\"\n", 67 | "\n", 68 | "ratios = [float(i) for i in input().strip().split(\" \")]\n", 69 | "probs = {\"b\": ratios[0] /sum(ratios), \"g\": ratios[1] / sum(ratios)}\n", 70 | "probs" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 96, 76 | "metadata": { 77 | "collapsed": false 78 | }, 79 | "outputs": [], 80 | "source": [ 81 | "def binomial_dist(x, n, p):\n", 82 | " q = 1.0 - p\n", 83 | " bernoulli = p**x * q**(n-x)\n", 84 | " combination = math.factorial(n) / (math.factorial(x) * math.factorial(n-x))\n", 85 | " return combination * bernoulli" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 100, 91 | "metadata": { 92 | "collapsed": false 93 | }, 94 | "outputs": [ 95 | { 96 | "data": { 97 | "text/plain": [ 98 | "[(3, 0.14185279138557705),\n", 99 | " (4, 0.27148922037702816),\n", 100 | " (5, 0.32474861818449163),\n", 101 | " (6, 0.3107649426854674),\n", 102 | " (7, 0.2602104787217523),\n", 103 | " (8, 0.19920465240639484),\n", 104 | " (9, 0.1429701750553316),\n", 105 | " (10, 0.09772419951246358),\n", 106 | " (11, 0.06429238439350161),\n", 107 | " (12, 0.04101596954767829),\n", 108 | " (13, 0.025512384234320916),\n", 109 | " (14, 0.015536067889485214)]" 110 | ] 111 | }, 112 | "execution_count": 100, 113 | "metadata": {}, 114 | "output_type": "execute_result" 115 | } 116 | ], 117 | "source": [ 118 | "[(i, binomial_dist(4, 10, 0.5)) for i in range(3, 15)]" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": 109, 124 | "metadata": { 125 | "collapsed": false 126 | }, 127 | "outputs": [ 128 | { 129 | "name": "stdout", 130 | "output_type": "stream", 131 | "text": [ 132 | "0.696\n" 133 | ] 134 | } 135 | ], 136 | "source": [ 137 | "print(\"{0:.3f}\".format(sum([binomial_dist(i, 6, probs[\"b\"]) for i in range(3, 7)])))" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": { 144 | "collapsed": true 145 | }, 146 | "outputs": [], 147 | "source": [] 148 | } 149 | ], 150 | "metadata": { 151 | "kernelspec": { 152 | "display_name": "Python 3", 153 | "language": "python", 154 | "name": "python3" 155 | }, 156 | "language_info": { 157 | "codemirror_mode": { 158 | "name": "ipython", 159 | "version": 3 160 | }, 161 | "file_extension": ".py", 162 | "mimetype": "text/x-python", 163 | "name": "python", 164 | "nbconvert_exporter": "python", 165 | "pygments_lexer": "ipython3", 166 | "version": "3.5.0" 167 | } 168 | }, 169 | "nbformat": 4, 170 | "nbformat_minor": 1 171 | } 172 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_4_Binomial_Distribution_II.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 4: Binomial Distribution II\n", 8 | "https://www.hackerrank.com/challenges/s10-binomial-distribution-2\n", 9 | "#### Objective \n", 10 | "In this challenge, we go further with binomial distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.\n", 11 | "\n", 12 | "#### Task \n", 13 | "A manufacturer of metal pistons finds that, on average, %12 of the pistons they manufacture are rejected because they are incorrectly sized. What is the probability that a batch of 10 pistons will contain:\n", 14 | "\n", 15 | "No more than 2 rejects?\n", 16 | "At least 2 rejects?\n", 17 | "\n", 18 | "#### Input Format\n", 19 | "A single line containing the following values (denoting the respective percentage of defective pistons and the size of the current batch of pistons):\n", 20 | "\n", 21 | "12 10\n", 22 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 23 | "\n", 24 | "#### Output Format\n", 25 | "Print the answer to each question on its own line:\n", 26 | "\n", 27 | "The first line should contain the probability that a batch of pistons will contain no more than rejects.\n", 28 | "The second line should contain the probability that a batch of pistons will contain at least rejects.\n", 29 | "Round both of your answers to a scale of decimal places (i.e., format).\n", 30 | "\n" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 7, 36 | "metadata": { 37 | "collapsed": true 38 | }, 39 | "outputs": [], 40 | "source": [ 41 | "import math" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 12, 47 | "metadata": { 48 | "collapsed": false 49 | }, 50 | "outputs": [ 51 | { 52 | "data": { 53 | "text/plain": [ 54 | "(0.12, 10.0)" 55 | ] 56 | }, 57 | "execution_count": 12, 58 | "metadata": {}, 59 | "output_type": "execute_result" 60 | } 61 | ], 62 | "source": [ 63 | "def input():\n", 64 | " return \"12 10\"\n", 65 | "\n", 66 | "inputs = [float(i) for i in input().strip().split(\" \")]\n", 67 | "rejects_prob = inputs[0] / 100\n", 68 | "trial = inputs[1]\n", 69 | "rejects, trial" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 43, 75 | "metadata": { 76 | "collapsed": false 77 | }, 78 | "outputs": [], 79 | "source": [ 80 | "def binomial_dist(x, n, p):\n", 81 | " q = 1.0 - p\n", 82 | " bernoulli = p**x * q ** (n-x)\n", 83 | " combination = math.factorial(n) / (math.factorial(x) * math.factorial(n-x))\n", 84 | " return combination * bernoulli" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 18, 90 | "metadata": { 91 | "collapsed": false 92 | }, 93 | "outputs": [], 94 | "source": [ 95 | "at_least_2 = sum(binomial_dist(i, trial, rejects_prob) for i in range(2, 11))" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 21, 101 | "metadata": { 102 | "collapsed": false 103 | }, 104 | "outputs": [], 105 | "source": [ 106 | "at_most_2 = sum(binomial_dist(i, trial, rejects_prob) for i in range(1, 3))" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": 22, 112 | "metadata": { 113 | "collapsed": false 114 | }, 115 | "outputs": [ 116 | { 117 | "data": { 118 | "text/plain": [ 119 | "(0.3417249657959586, 0.6128172302686224)" 120 | ] 121 | }, 122 | "execution_count": 22, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "at_least_2, at_most_2" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 47, 134 | "metadata": { 135 | "collapsed": false 136 | }, 137 | "outputs": [ 138 | { 139 | "data": { 140 | "text/plain": [ 141 | "[(1, 3.8e-05),\n", 142 | " (2, 0.000258),\n", 143 | " (3, 0.001151),\n", 144 | " (4, 0.003806),\n", 145 | " (5, 0.009965),\n", 146 | " (6, 0.021516),\n", 147 | " (7, 0.039399),\n", 148 | " (8, 0.062456),\n", 149 | " (9, 0.08706),\n", 150 | " (10, 0.108033),\n", 151 | " (11, 0.120533),\n", 152 | " (12, 0.121903),\n", 153 | " (13, 0.112526),\n", 154 | " (14, 0.095355),\n", 155 | " (15, 0.07455),\n", 156 | " (16, 0.054006),\n", 157 | " (17, 0.036389),\n", 158 | " (18, 0.022881),\n", 159 | " (19, 0.013466)]" 160 | ] 161 | }, 162 | "execution_count": 47, 163 | "metadata": {}, 164 | "output_type": "execute_result" 165 | } 166 | ], 167 | "source": [ 168 | "[(i, round(binomial_dist(i, 100, .12), 6)) for i in range(1, 20)]" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": { 175 | "collapsed": true 176 | }, 177 | "outputs": [], 178 | "source": [] 179 | } 180 | ], 181 | "metadata": { 182 | "kernelspec": { 183 | "display_name": "Python 3", 184 | "language": "python", 185 | "name": "python3" 186 | }, 187 | "language_info": { 188 | "codemirror_mode": { 189 | "name": "ipython", 190 | "version": 3 191 | }, 192 | "file_extension": ".py", 193 | "mimetype": "text/x-python", 194 | "name": "python", 195 | "nbconvert_exporter": "python", 196 | "pygments_lexer": "ipython3", 197 | "version": "3.5.0" 198 | } 199 | }, 200 | "nbformat": 4, 201 | "nbformat_minor": 1 202 | } 203 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_4_Geometric_Distribution_I.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 4: Geometric Distribution I\n", 8 | "#### Objective \n", 9 | "In this challenge, we learn about geometric distributions. Check out the Tutorial tab for learning materials!\n", 10 | "\n", 11 | "#### Task \n", 12 | "The probability that a machine produces a defective product is . What is the probability that the defect is found during the inspection?\n", 13 | "\n", 14 | "#### Input Format\n", 15 | "The first line contains the respective space-separated numerator and denominator for the probability of a defect, and the second line contains the inspection we want the probability of being the first defect for:\n", 16 | "```\n", 17 | "1 3\n", 18 | "5\n", 19 | "```\n", 20 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 21 | "\n", 22 | "#### Output Format\n", 23 | "\n", 24 | "Print a single line denoting the answer, rounded to a scale of decimal places (i.e., format).\n", 25 | "\n" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 1, 31 | "metadata": { 32 | "collapsed": true 33 | }, 34 | "outputs": [], 35 | "source": [ 36 | "def neg_bernoulli(n, p):\n", 37 | " return p * (1-p)**(n-1)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 12, 43 | "metadata": { 44 | "collapsed": false 45 | }, 46 | "outputs": [], 47 | "source": [ 48 | "defective_prob = 1 / 3.0\n", 49 | "inspection = 5" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 14, 55 | "metadata": { 56 | "collapsed": false 57 | }, 58 | "outputs": [ 59 | { 60 | "data": { 61 | "text/plain": [ 62 | "0.066" 63 | ] 64 | }, 65 | "execution_count": 14, 66 | "metadata": {}, 67 | "output_type": "execute_result" 68 | } 69 | ], 70 | "source": [ 71 | "round(neg_bernoulli(inspection, defective_prob), 3)" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 16, 77 | "metadata": { 78 | "collapsed": false 79 | }, 80 | "outputs": [ 81 | { 82 | "data": { 83 | "text/plain": [ 84 | "(-1.6301200434487646-0.6454101829039246j)" 85 | ] 86 | }, 87 | "execution_count": 16, 88 | "metadata": {}, 89 | "output_type": "execute_result" 90 | } 91 | ], 92 | "source": [ 93 | "neg_bernoulli(12/100.0, 100)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": { 100 | "collapsed": true 101 | }, 102 | "outputs": [], 103 | "source": [] 104 | } 105 | ], 106 | "metadata": { 107 | "kernelspec": { 108 | "display_name": "Python 3", 109 | "language": "python", 110 | "name": "python3" 111 | }, 112 | "language_info": { 113 | "codemirror_mode": { 114 | "name": "ipython", 115 | "version": 3 116 | }, 117 | "file_extension": ".py", 118 | "mimetype": "text/x-python", 119 | "name": "python", 120 | "nbconvert_exporter": "python", 121 | "pygments_lexer": "ipython3", 122 | "version": "3.5.0" 123 | } 124 | }, 125 | "nbformat": 4, 126 | "nbformat_minor": 1 127 | } 128 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_5_Normal_Distribution_I.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 5: Normal Distribution I" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "https://www.hackerrank.com/challenges/s10-normal-distribution-1\n", 15 | "\n", 16 | "#### Objective \n", 17 | "In this challenge, we learn about normal distributions. Check out the Tutorial tab for learning materials!\n", 18 | "\n", 19 | "#### Task \n", 20 | "In a certain plant, the time taken to assemble a car is a random variable, **X**, having a normal distribution with a mean of **20** hours and a standard deviation of **2** hours. What is the probability that a car can be assembled at this plant in:\n", 21 | "\n", 22 | "##### Question 1:\n", 23 | "Less than 19.5 hours?\n", 24 | "\n", 25 | "#### Question 2:\n", 26 | "Between 20 and 22 hours?\n", 27 | "\n", 28 | "#### Input Format\n", 29 | "There are lines of input (shown below):\n", 30 | "```\n", 31 | "20 2\n", 32 | "19.5\n", 33 | "20 22\n", 34 | "```\n", 35 | "The first line contains 2 space-separated values denoting the respective mean and standard deviation for X. The second line contains the number associated with question 1. The third line contains 2 space-separated values describing the respective lower and upper range boundaries for question 2.\n", 36 | "\n", 37 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 38 | "\n", 39 | "\n" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": 7, 45 | "metadata": { 46 | "collapsed": true 47 | }, 48 | "outputs": [], 49 | "source": [ 50 | "import math\n", 51 | "from matplotlib import pylab as plt\n", 52 | "%matplotlib inline" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 8, 58 | "metadata": { 59 | "collapsed": true 60 | }, 61 | "outputs": [], 62 | "source": [ 63 | "def pdf(x, m, variance):\n", 64 | " sigma = math.sqrt(variance)\n", 65 | " \"\"\"probability density function\"\"\"\n", 66 | " return 1 / (sigma * math.sqrt(2 * math.pi)) * math.e ** (-1 * ((x - m)**2 / (2 * variance ** 2)))" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 26, 72 | "metadata": { 73 | "collapsed": false 74 | }, 75 | "outputs": [ 76 | { 77 | "data": { 78 | "text/plain": [ 79 | "0.19947114020071635" 80 | ] 81 | }, 82 | "execution_count": 26, 83 | "metadata": {}, 84 | "output_type": "execute_result" 85 | } 86 | ], 87 | "source": [ 88 | "pdf(20, 20, 4)" 89 | ] 90 | }, 91 | { 92 | "cell_type": "markdown", 93 | "metadata": {}, 94 | "source": [ 95 | "### Example" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 28, 101 | "metadata": { 102 | "collapsed": false 103 | }, 104 | "outputs": [ 105 | { 106 | "data": { 107 | "text/plain": [ 108 | "[]" 109 | ] 110 | }, 111 | "execution_count": 28, 112 | "metadata": {}, 113 | "output_type": "execute_result" 114 | }, 115 | { 116 | "data": { 117 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAD8CAYAAACb4nSYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl0W+d95vHvD+AucBVJbaRWUpYlL5Ity0lq2W7qJE6a\nkTMTJ7WT5jinTt209Wk73U48PSdp3dM17TSdqc8kbuyTZZo4btJFmSp1ndSJlKZJRFmyrcWSqF3U\nQlJcQYoLiHf+ACDTDCmCJIAL3Pt8zpEJXFwAv2tRD16873vfa845REQkGEJeFyAiIrmj0BcRCRCF\nvohIgCj0RUQCRKEvIhIgCn0RkQBR6IuIBIhCX0QkQBT6IiIBUuR1AVPV19e71atXe12GiEhB2bdv\nX7dzrmG2/fIu9FevXk1bW5vXZYiIFBQzO5POfureEREJEIW+iEiAKPRFRAJEoS8iEiAKfRGRAFHo\ni4gEiEJfRCRAF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UlEQVSF0SWznHPOzHw5LcvMIsA3gN9wzg2kLnIP/j3u5NXmNptZDfCPwAaP\nS8o6M3sv0Omc22dm93pdjwfucs51mFkj8KKZvT75wYX8rvulpZ/WBdh97rKZLQNI/uz0uJ6MM7Ni\nEoH/d865f0hu9v1xpzjn+oCXgLcCNWaWarT58ff9p4AdZnaaRHft24G/xv/HDYBzriP5s5PEB/02\nMvS77pfQT+fi7X43+eL0jwD/7GEtGZfsz30GOOKc+5+THvL7cTckW/iYWTnwDhLjGS8BDyZ3891x\nO+eecM41OedWk/j3/O/OuQ/j8+MGMLNFZlaZug28EzhIhn7XfXNylpm9h0QfYOri7X/kcUlZY2Zf\nBe4lsfLeZeBTwD8BzwMrSaxS+kHn3NTB3oJlZncBe4DXeKOP93+Q6Nf383HfQmLQLkyikfa8c+5J\nM1tLogVcB+wHft45N+pdpdmT7N75befce4Nw3Mlj/Mfk3SLgK865PzKzxWTgd903oS8iIrPzS/eO\niIikQaEvIhIgCn0RkQBR6IuIBIhCX0QkQBT6IiIBotAXEQkQhb6ISID8f4IRg/OMaHFTAAAAAElF\nTkSuQmCC\n", 118 | "text/plain": [ 119 | "" 120 | ] 121 | }, 122 | "metadata": {}, 123 | "output_type": "display_data" 124 | } 125 | ], 126 | "source": [ 127 | "N = range(50)\n", 128 | "mean = 15\n", 129 | "variance = 3\n", 130 | "plt.plot(N, [pdf(i, mean, variance) for i in N])" 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": 79, 136 | "metadata": { 137 | "collapsed": true 138 | }, 139 | "outputs": [], 140 | "source": [ 141 | "def cumulative(x, m, stdv):\n", 142 | " return 0.5 * (1 + math.erf((x-m)/ (stdv * math.sqrt(2)) ))" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 56, 148 | "metadata": { 149 | "collapsed": false 150 | }, 151 | "outputs": [ 152 | { 153 | "data": { 154 | "text/plain": [ 155 | "[(1, 0.0),\n", 156 | " (2, 0.0),\n", 157 | " (3, 0.0),\n", 158 | " (4, 0.0),\n", 159 | " (5, 0.0),\n", 160 | " (6, 0.0),\n", 161 | " (7, 0.0),\n", 162 | " (8, 6.106226635438361e-16),\n", 163 | " (9, 1.1224354778960333e-13),\n", 164 | " (10, 1.3083922834056239e-11),\n", 165 | " (11, 9.865876449133282e-10),\n", 166 | " (12, 4.8213033676525185e-08),\n", 167 | " (13, 1.5306267365233772e-06),\n", 168 | " (14, 3.167124183311998e-05),\n", 169 | " (15, 0.0004290603331968401),\n", 170 | " (16, 0.003830380567589775),\n", 171 | " (17, 0.022750131948179264),\n", 172 | " (18, 0.09121121972586788),\n", 173 | " (19, 0.2524925375469229),\n", 174 | " (20, 0.5),\n", 175 | " (21, 0.7475074624530771),\n", 176 | " (22, 0.9087887802741321),\n", 177 | " (23, 0.9772498680518207),\n", 178 | " (24, 0.9961696194324102),\n", 179 | " (25, 0.9995709396668031),\n", 180 | " (26, 0.9999683287581669),\n", 181 | " (27, 0.9999984693732635),\n", 182 | " (28, 0.9999999517869663),\n", 183 | " (29, 0.9999999990134123)]" 184 | ] 185 | }, 186 | "execution_count": 56, 187 | "metadata": {}, 188 | "output_type": "execute_result" 189 | } 190 | ], 191 | "source": [ 192 | "[(i, cumulative(i, 20.0, 3.0)) for i in range(1, 30)]" 193 | ] 194 | }, 195 | { 196 | "cell_type": "code", 197 | "execution_count": 58, 198 | "metadata": { 199 | "collapsed": false 200 | }, 201 | "outputs": [], 202 | "source": [ 203 | "mean = 20 \n", 204 | "variance = 4" 205 | ] 206 | }, 207 | { 208 | "cell_type": "markdown", 209 | "metadata": {}, 210 | "source": [ 211 | "### Question 1\n", 212 | "Less than 19.5 hours?" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 80, 218 | "metadata": { 219 | "collapsed": false 220 | }, 221 | "outputs": [ 222 | { 223 | "data": { 224 | "text/plain": [ 225 | "0.4012936743170763" 226 | ] 227 | }, 228 | "execution_count": 80, 229 | "metadata": {}, 230 | "output_type": "execute_result" 231 | } 232 | ], 233 | "source": [ 234 | "x = 19.5\n", 235 | "q1_answer = cumulative(x, mean, math.sqrt(variance))\n", 236 | "q1_answer" 237 | ] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "metadata": {}, 242 | "source": [ 243 | "### Question 2\n", 244 | "Between 20 and 22 hours?" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": 81, 250 | "metadata": { 251 | "collapsed": false 252 | }, 253 | "outputs": [ 254 | { 255 | "data": { 256 | "text/plain": [ 257 | "0.34134474606854304" 258 | ] 259 | }, 260 | "execution_count": 81, 261 | "metadata": {}, 262 | "output_type": "execute_result" 263 | } 264 | ], 265 | "source": [ 266 | "lower_hour, upper_hour = 20.0, 22.0\n", 267 | "q2_answer = cumulative(upper_hour, mean, math.sqrt(variance)) - cumulative(lower_hour, mean, math.sqrt(variance))\n", 268 | "q2_answer" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": null, 274 | "metadata": { 275 | "collapsed": true 276 | }, 277 | "outputs": [], 278 | "source": [] 279 | } 280 | ], 281 | "metadata": { 282 | "kernelspec": { 283 | "display_name": "Python 3", 284 | "language": "python", 285 | "name": "python3" 286 | }, 287 | "language_info": { 288 | "codemirror_mode": { 289 | "name": "ipython", 290 | "version": 3 291 | }, 292 | "file_extension": ".py", 293 | "mimetype": "text/x-python", 294 | "name": "python", 295 | "nbconvert_exporter": "python", 296 | "pygments_lexer": "ipython3", 297 | "version": "3.5.0" 298 | } 299 | }, 300 | "nbformat": 4, 301 | "nbformat_minor": 1 302 | } 303 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_5_Normal_Distribution_II.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 5: Normal Distribution II\n", 8 | "https://www.hackerrank.com/challenges/s10-normal-distribution-2\n", 9 | "\n", 10 | "#### Objective \n", 11 | "In this challenge, we go further with normal distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.\n", 12 | "\n", 13 | "#### Task \n", 14 | "The final grades for a Physics exam taken by a large group of students have a mean of **m=70** and a standard deviation of **stdv = 10**. If we can approximate the distribution of these grades by a normal distribution, what percentage of the students:\n", 15 | "\n", 16 | "- Scored higher than 80 (i.e., have a > 80)?\n", 17 | "- Passed the test (i.e., have a >= 60)?\n", 18 | "- Failed the test (i.e., have a < 60)?\n", 19 | "\n", 20 | "Find and print the answer to each question on a new line, rounded to a scale of decimal places.\n", 21 | "\n" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 1, 27 | "metadata": { 28 | "collapsed": true 29 | }, 30 | "outputs": [], 31 | "source": [ 32 | "import math" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 2, 38 | "metadata": { 39 | "collapsed": true 40 | }, 41 | "outputs": [], 42 | "source": [ 43 | "def cumulative(x, m, stdv):\n", 44 | " return 0.5 * (1 + math.erf((x-m)/ (stdv * math.sqrt(2)) ))" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 3, 50 | "metadata": { 51 | "collapsed": true 52 | }, 53 | "outputs": [], 54 | "source": [ 55 | "mean = 70\n", 56 | "stdv = 10" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 4, 62 | "metadata": { 63 | "collapsed": false 64 | }, 65 | "outputs": [], 66 | "source": [ 67 | "# gt80 = cumulative(100, mean, stdv) - cumulative(80, mean, stdv)\n", 68 | "# gte60 = cumulative(100, mean, stdv) - cumulative(60, mean, stdv)\n", 69 | "# lt60 = cumulative(60, mean, stdv)\n", 70 | "gt80 = 1 - cumulative(80, mean, stdv)\n", 71 | "gte60 = 1 - cumulative(60, mean, stdv)\n", 72 | "lt60 = cumulative(60, mean, stdv)" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 5, 78 | "metadata": { 79 | "collapsed": false 80 | }, 81 | "outputs": [ 82 | { 83 | "name": "stdout", 84 | "output_type": "stream", 85 | "text": [ 86 | "0.1587\n", 87 | "0.8413\n", 88 | "0.1587\n" 89 | ] 90 | } 91 | ], 92 | "source": [ 93 | "print(round(gt80, 4))\n", 94 | "print(round(gte60, 4))\n", 95 | "print(round(lt60, 4))" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "collapsed": true 103 | }, 104 | "outputs": [], 105 | "source": [] 106 | } 107 | ], 108 | "metadata": { 109 | "kernelspec": { 110 | "display_name": "Python 3", 111 | "language": "python", 112 | "name": "python3" 113 | }, 114 | "language_info": { 115 | "codemirror_mode": { 116 | "name": "ipython", 117 | "version": 3 118 | }, 119 | "file_extension": ".py", 120 | "mimetype": "text/x-python", 121 | "name": "python", 122 | "nbconvert_exporter": "python", 123 | "pygments_lexer": "ipython3", 124 | "version": "3.5.0" 125 | } 126 | }, 127 | "nbformat": 4, 128 | "nbformat_minor": 1 129 | } 130 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_5_Poisson_Distribution_I.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 5: Poisson Distribution I \n", 8 | "https://www.hackerrank.com/challenges/s10-poisson-distribution-1\n", 9 | "\n", 10 | "#### Objective \n", 11 | "In this challenge, we learn about Poisson distributions. Check out the Tutorial tab for learning materials!\n", 12 | "\n", 13 | "#### Task \n", 14 | "A random variable, , follows Poisson distribution with mean of . Find the probability with which the random variable is equal to .\n", 15 | "\n", 16 | "#### Input Format\n", 17 | "The first line contains 's mean. The second line contains the value we want the probability for:\n", 18 | "\n", 19 | "```\n", 20 | "2.5\n", 21 | "5\n", 22 | "```\n", 23 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 24 | "\n", 25 | "#### Output Format\n", 26 | "Print a single line denoting the answer, rounded to a scale of decimal places (i.e., format).\n", 27 | "\n" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 19, 33 | "metadata": { 34 | "collapsed": false 35 | }, 36 | "outputs": [], 37 | "source": [ 38 | "import math\n", 39 | "from matplotlib import pylab as plt\n", 40 | "%matplotlib inline\n" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 20, 46 | "metadata": { 47 | "collapsed": true 48 | }, 49 | "outputs": [], 50 | "source": [ 51 | "def posion_dist(m, k):\n", 52 | " return (m**k * math.e**(-m)) / math.factorial(k)" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "### Example\n", 60 | "Acme Realty company sells an average of 2 homes per day. \n", 61 | "\n", 62 | "What is the probability that exactly 3 homes will be sold tomorrow? " 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 34, 68 | "metadata": { 69 | "collapsed": false 70 | }, 71 | "outputs": [ 72 | { 73 | "data": { 74 | "text/plain": [ 75 | "0.1804470443154836" 76 | ] 77 | }, 78 | "execution_count": 34, 79 | "metadata": {}, 80 | "output_type": "execute_result" 81 | } 82 | ], 83 | "source": [ 84 | "posion_dist(2, 3)" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 30, 90 | "metadata": { 91 | "collapsed": false 92 | }, 93 | "outputs": [ 94 | { 95 | "data": { 96 | "text/plain": [ 97 | "[]" 98 | ] 99 | }, 100 | "execution_count": 30, 101 | "metadata": {}, 102 | "output_type": "execute_result" 103 | }, 104 | { 105 | "data": { 106 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX0AAAD8CAYAAACb4nSYAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3Xl8VOXd9/HPbyYLEEKA7ARIggmEsGNklyooglVwV7SK\nlT60r5ba3q21tr1rrffz3HWptYt2odUKWou4x8rigjtrQJaENUCA7AmErGSd6/ljBo0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wNXAPc4fqAOosb75NuZYwpMca0GGMcwN87+P1e8XoC\niEgQcAPwUkdtrH5NL4QW/Q64+vKeAfYaY37XQZs4VztEZBLO1/NEz6UEEQkTkfAzyzgP6mW3aZYJ\n3OUaxTMFqGzVbdHTOtxz8obXs41M4MxonEXAm+20WQfMEZEBru6KOa51PUZE5gL3A/ONMXUdtHHn\nfdKt2hxHur6D378VSBWRZNe3wttw/jtY4QpgnzEmv72N3vCaXhCrjyR76w2YgfPr/C5gh+t2NfAd\n4DuuNkuBHJwjDDYB0yzIOcz1+3e6svzCtb51TgGexjkqYjeQYdFrGoaziEe0WucVryfOD6IioAln\nP/JiIBJ4HzgIvAcMdLXNAP7R6rH3ALmu2zctyJmLsx/8zPv0r662g4DV53qf9HDO513vv104C3l8\n25yu+1fjHC13qLtzdpTVtf65M+/NVm0te009ddMzcpVSKoBo945SSgUQLfpKKRVAtOgrpVQA0aKv\nlFIBRIu+UkoFEC36SikVQLToK6VUANGir5RSAeT/A5wJnW/cD3/SAAAAAElFTkSuQmCC\n", 107 | "text/plain": [ 108 | "" 109 | ] 110 | }, 111 | "metadata": {}, 112 | "output_type": "display_data" 113 | } 114 | ], 115 | "source": [ 116 | "N = range(1, 20)\n", 117 | "M = 7\n", 118 | "plt.plot(N, [posion_dist(M, i) for i in N])" 119 | ] 120 | } 121 | ], 122 | "metadata": { 123 | "kernelspec": { 124 | "display_name": "Python 3", 125 | "language": "python", 126 | "name": "python3" 127 | }, 128 | "language_info": { 129 | "codemirror_mode": { 130 | "name": "ipython", 131 | "version": 3 132 | }, 133 | "file_extension": ".py", 134 | "mimetype": "text/x-python", 135 | "name": "python", 136 | "nbconvert_exporter": "python", 137 | "pygments_lexer": "ipython3", 138 | "version": "3.5.0" 139 | } 140 | }, 141 | "nbformat": 4, 142 | "nbformat_minor": 1 143 | } 144 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_5_Poisson_Distribution_II .ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 5: Poisson Distribution II \n", 8 | "https://www.hackerrank.com/challenges/s10-poisson-distribution-2\n", 9 | "\n", 10 | "### Objective \n", 11 | "In this challenge, we go further with Poisson distributions. We recommend reviewing the previous challenge's Tutorial before attempting this problem.\n", 12 | "\n", 13 | "### Task \n", 14 | "The manager of a industrial plant is planning to buy a machine of either type or type . For each day’s operation:\n", 15 | "\n", 16 | "- The number of repairs, , that machine needs is a Poisson random variable with mean . The daily cost of operating is .\n", 17 | "- The number of repairs, , that machine needs is a Poisson random variable with mean . The daily cost of operating is .\n", 18 | "Assume that the repairs take a negligible amount of time and the machines are maintained nightly to ensure that they operate like new at the start of each day. Find and print the expected daily cost for each machine.\n", 19 | "\n", 20 | "### Input Format\n", 21 | "\n", 22 | "A single line comprised of space-separated values denoting the respective means for and :\n", 23 | "\n", 24 | "```\n", 25 | "0.88 1.55\n", 26 | "```\n", 27 | "If you do not wish to read this information from stdin, you can hard-code it into your program.\n", 28 | "\n", 29 | "### Output Format\n", 30 | "\n", 31 | "There are two lines of output. Your answers must be rounded to a scale of decimal places (i.e., format):\n", 32 | "\n", 33 | "On the first line, print the expected daily cost of machine .\n", 34 | "On the second line, print the expected daily cost of machine .\n" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 13, 40 | "metadata": { 41 | "collapsed": false 42 | }, 43 | "outputs": [ 44 | { 45 | "name": "stdout", 46 | "output_type": "stream", 47 | "text": [ 48 | "0.88 1.55\n", 49 | "226.176\n", 50 | "286.1\n" 51 | ] 52 | } 53 | ], 54 | "source": [ 55 | "a_m, b_m = [float(i) for i in input().split(\" \")]\n", 56 | "\n", 57 | "print(round(160 + 40 * (a_m + a_m ** 2), 3))\n", 58 | "print(round(128 + 40 * (b_m + b_m ** 2), 3))" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "collapsed": true 66 | }, 67 | "outputs": [], 68 | "source": [] 69 | } 70 | ], 71 | "metadata": { 72 | "kernelspec": { 73 | "display_name": "Python 3", 74 | "language": "python", 75 | "name": "python3" 76 | }, 77 | "language_info": { 78 | "codemirror_mode": { 79 | "name": "ipython", 80 | "version": 3 81 | }, 82 | "file_extension": ".py", 83 | "mimetype": "text/x-python", 84 | "name": "python", 85 | "nbconvert_exporter": "python", 86 | "pygments_lexer": "ipython3", 87 | "version": "3.5.0" 88 | } 89 | }, 90 | "nbformat": 4, 91 | "nbformat_minor": 1 92 | } 93 | -------------------------------------------------------------------------------- /python/10daysOfStatistics/Day_7_Pearson_Correlation_Coefficient_I.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Day 7: Pearson Correlation Coefficient I\n", 8 | "\n", 9 | "https://www.hackerrank.com/challenges/s10-pearson-correlation-coefficient\n", 10 | "\n", 11 | "#### Objective \n", 12 | "In this challenge, we practice calculating the Pearson correlation coefficient. Check out the Tutorial tab for learning materials!\n", 13 | "\n", 14 | "#### Task\n", 15 | "Given two -element data sets, X and Y, calculate the value of the Pearson correlation coefficient.\n", 16 | "The first line contains an integer, n , denoting the size of data sets X and Y. \n", 17 | "\n", 18 | "- The second line contains n space-separated real numbers (scaled to at most one decimal place), defining data set X. \n", 19 | "- The third line contains n space-separated real numbers (scaled to at most one decimal place), defining data set Y.\n", 20 | "\n", 21 | "#### Output Format\n", 22 | "Print the value of the Pearson correlation coefficient, rounded to a scale of decimal places.\n", 23 | "\n", 24 | "#### Sample Input\n", 25 | "```\n", 26 | "10\n", 27 | "10 9.8 8 7.8 7.7 7 6 5 4 2 \n", 28 | "200 44 32 24 22 17 15 12 8 4\n", 29 | "```\n", 30 | "#### Sample Output\n", 31 | "```\n", 32 | "0.612\n", 33 | "```\n" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 44, 39 | "metadata": { 40 | "collapsed": true 41 | }, 42 | "outputs": [], 43 | "source": [ 44 | "import math\n", 45 | "\n", 46 | "def input_floats():\n", 47 | " return [float(i) for i in input().split(\" \")]\n", 48 | "\n", 49 | "def variance(x, m):\n", 50 | " return sum((i - m) ** 2 for i in x) / len(x)\n", 51 | "\n", 52 | "def covariance(x, y, xm, ym):\n", 53 | " return sum((i - xm) * (j - ym) for i, j in zip(x, y)) / len(x)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 45, 59 | "metadata": { 60 | "collapsed": false 61 | }, 62 | "outputs": [], 63 | "source": [ 64 | "#x = input_floats()\n", 65 | "# y = input_floats()\n", 66 | "x = [10, 9.8, 8, 7.8, 7.7, 7, 6, 5, 4, 2] \n", 67 | "y = [200, 44, 32, 24, 22, 17, 15, 12, 8, 4]\n", 68 | "N = len(x)\n", 69 | "\n", 70 | "x_mean = sum(x) / N\n", 71 | "y_mean = sum(y)/ N\n", 72 | "\n", 73 | "x_var = variance(x, x_mean)\n", 74 | "y_var = variance(y, y_mean)\n", 75 | "\n", 76 | "covxy = covariance(x, y, x_mean, y_mean)\n", 77 | "\n", 78 | "pearson = covxy / (math.sqrt(x_var) * math.sqrt(y_var))" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 46, 84 | "metadata": { 85 | "collapsed": false 86 | }, 87 | "outputs": [ 88 | { 89 | "data": { 90 | "text/plain": [ 91 | "(6.730000000000001, 5.724100000000002, 2.392509143138225)" 92 | ] 93 | }, 94 | "execution_count": 46, 95 | "metadata": {}, 96 | "output_type": "execute_result" 97 | } 98 | ], 99 | "source": [ 100 | "x_mean, x_var, math.sqrt(x_var)" 101 | ] 102 | }, 103 | { 104 | "cell_type": "code", 105 | "execution_count": 47, 106 | "metadata": { 107 | "collapsed": false 108 | }, 109 | "outputs": [ 110 | { 111 | "data": { 112 | "text/plain": [ 113 | "(37.8, 3046.959999999999, 55.199275357562435)" 114 | ] 115 | }, 116 | "execution_count": 47, 117 | "metadata": {}, 118 | "output_type": "execute_result" 119 | } 120 | ], 121 | "source": [ 122 | "y_mean, y_var, math.sqrt(y_var)" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 49, 128 | "metadata": { 129 | "collapsed": false 130 | }, 131 | "outputs": [ 132 | { 133 | "data": { 134 | "text/plain": [ 135 | "80.886" 136 | ] 137 | }, 138 | "execution_count": 49, 139 | "metadata": {}, 140 | "output_type": "execute_result" 141 | } 142 | ], 143 | "source": [ 144 | "covxy" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": 48, 150 | "metadata": { 151 | "collapsed": false 152 | }, 153 | "outputs": [ 154 | { 155 | "data": { 156 | "text/plain": [ 157 | "0.6124721937208478" 158 | ] 159 | }, 160 | "execution_count": 48, 161 | "metadata": {}, 162 | "output_type": "execute_result" 163 | } 164 | ], 165 | "source": [ 166 | "pearson" 167 | ] 168 | } 169 | ], 170 | "metadata": { 171 | "kernelspec": { 172 | "display_name": "Python 3", 173 | "language": "python", 174 | "name": "python3" 175 | }, 176 | "language_info": { 177 | "codemirror_mode": { 178 | "name": "ipython", 179 | "version": 3 180 | }, 181 | "file_extension": ".py", 182 | "mimetype": "text/x-python", 183 | "name": "python", 184 | "nbconvert_exporter": "python", 185 | "pygments_lexer": "ipython3", 186 | "version": "3.5.0" 187 | } 188 | }, 189 | "nbformat": 4, 190 | "nbformat_minor": 1 191 | } 192 | -------------------------------------------------------------------------------- /python/DiameterOfBTree/GreatestDistance.py: -------------------------------------------------------------------------------- 1 | 2 | class Diameter(object): 3 | def __init__(self, left, distanceLeft, right, distanceRight, diameter): 4 | super(Diameter, self).__init__() 5 | self.left = left 6 | self.right = right 7 | self.distanceRight = distanceRight 8 | self.distanceLeft = distanceLeft 9 | self.diameter = diameter 10 | 11 | def getMaxDistance(self): 12 | return max(self.distanceRight, self.distanceLeft) 13 | 14 | def getEndmostNode(self): 15 | if self.distanceLeft > self.distanceRight: 16 | return self.left 17 | else: 18 | return self.right 19 | 20 | def increaseBy(self, tree): 21 | if self.distanceLeft > self.distanceRight: 22 | self.right = tree 23 | self.distanceRight = 0 24 | self.distanceLeft += 1 25 | else: 26 | self.left = tree 27 | self.distanceLeft = 0 28 | self.distanceRight += 1 29 | 30 | self.diameter += 1 31 | 32 | def __str__(self): 33 | return "diameter length: {}, left: {}, right: {}".format( 34 | self.diameter, self.left.key, self.right.key 35 | ) 36 | 37 | 38 | def findDiameter(tree): 39 | if tree.left: 40 | leftSub = findDiameter(tree.left) 41 | if tree.right: 42 | rightSub = findDiameter(tree.right) 43 | 44 | if tree.left and tree.right: 45 | diameter = max(leftSub.diameter, rightSub.diameter) 46 | newPath = leftSub.getMaxDistance() + rightSub.getMaxDistance() + 2 47 | if newPath > diameter: 48 | r = Diameter( 49 | leftSub.getEndmostNode(), 50 | leftSub.getMaxDistance() + 1, 51 | rightSub.getEndmostNode(), 52 | rightSub.getMaxDistance() + 1, 53 | newPath 54 | ) 55 | else: 56 | r = leftSub.diameter \ 57 | if leftSub.diameter > rightSub.diameter else rightSub 58 | 59 | elif tree.left or tree.right: 60 | r = leftSub if tree.left else rightSub 61 | if r.getMaxDistance() + 1 > r.diameter: 62 | r.increaseBy(tree) 63 | else: 64 | r.distanceLeft += 1 65 | r.distanceRight += 1 66 | else: 67 | r = Diameter( 68 | tree, 69 | 0, 70 | tree, 71 | 0, 72 | 0 73 | ) 74 | 75 | return r 76 | -------------------------------------------------------------------------------- /python/DiameterOfBTree/btree.py: -------------------------------------------------------------------------------- 1 | 2 | class BTree(object): 3 | def __init__(self, key): 4 | super(BTree, self).__init__() 5 | self.right = None 6 | self.left = None 7 | self.key = key 8 | self.root = self 9 | 10 | def insert(self, key): 11 | if self.key > key: 12 | if self.left: 13 | self.left.insert(key) 14 | else: 15 | self.left = BTree(key) 16 | elif self.key < key: 17 | if self.right: 18 | self.right.insert(key) 19 | else: 20 | self.right = BTree(key) 21 | 22 | def display(self): 23 | if self.left: 24 | self.left.display() 25 | if self.right: 26 | self.right.display() 27 | print(self.key) 28 | 29 | -------------------------------------------------------------------------------- /python/DiameterOfBTree/main.py: -------------------------------------------------------------------------------- 1 | from btree import BTree 2 | from GreatestDistance import findDiameter 3 | 4 | t = BTree("h") 5 | t.insert("d") 6 | t.insert("f") 7 | t.insert("a1") 8 | t.insert("a2") 9 | t.insert("a3") 10 | t.insert("a4") 11 | t.insert("m1") 12 | t.insert("m2") 13 | t.insert("m3") 14 | t.insert("m4") 15 | t.display() 16 | 17 | print findDiameter(t) 18 | -------------------------------------------------------------------------------- /python/calculating_tangent_line.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 7, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "import matplotlib.pyplot as plt" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 8, 17 | "metadata": { 18 | "collapsed": true 19 | }, 20 | "outputs": [], 21 | "source": [ 22 | "def f(x):\n", 23 | " y = 1*(x**2) - (22*x) + 150\n", 24 | " return y\n", 25 | "\n", 26 | "def calcDerivative(x):\n", 27 | " return 2 * x - 22\n", 28 | "\n", 29 | "def getTangentLine(m, x, x1, y1):\n", 30 | " y = m * x - m * x1 + y1\n", 31 | " return y" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 9, 37 | "metadata": { 38 | "collapsed": false 39 | }, 40 | "outputs": [ 41 | { 42 | "data": { 43 | "text/plain": [ 44 | "[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" 45 | ] 46 | }, 47 | "execution_count": 9, 48 | "metadata": {}, 49 | "output_type": "execute_result" 50 | } 51 | ], 52 | "source": [ 53 | "x = range(3, 20)\n", 54 | "x\n" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 10, 60 | "metadata": { 61 | "collapsed": false 62 | }, 63 | "outputs": [ 64 | { 65 | "data": { 66 | "text/plain": [ 67 | "[93, 78, 65, 54, 45, 38, 33, 30, 29, 30, 33, 38, 45, 54, 65, 78, 93]" 68 | ] 69 | }, 70 | "execution_count": 10, 71 | "metadata": {}, 72 | "output_type": "execute_result" 73 | } 74 | ], 75 | "source": [ 76 | "y = [f(i) for i in x]\n", 77 | "y" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 11, 83 | "metadata": { 84 | "collapsed": false 85 | }, 86 | "outputs": [], 87 | "source": [ 88 | "point1_x = 11.4\n", 89 | "point1_y = f(point1_x)\n", 90 | "m = calcDerivative(point1_x)\n", 91 | "\n", 92 | "tangent = [ getTangentLine(m, i, point1_x, point1_y) for i in x]" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": 14, 98 | "metadata": { 99 | "collapsed": false 100 | }, 101 | "outputs": [], 102 | "source": [ 103 | "plt.plot(x, y)\n", 104 | "plt.plot(x, tangent)\n", 105 | "plt.plot(point1_x, getTangentLine(m, point1_x, point1_x, point1_y), 'ro')\n", 106 | "plt.show()" 107 | ] 108 | }, 109 | { 110 | "cell_type": "code", 111 | "execution_count": null, 112 | "metadata": { 113 | "collapsed": true 114 | }, 115 | "outputs": [], 116 | "source": [] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": { 122 | "collapsed": true 123 | }, 124 | "outputs": [], 125 | "source": [] 126 | } 127 | ], 128 | "metadata": { 129 | "kernelspec": { 130 | "display_name": "Python 2", 131 | "language": "python", 132 | "name": "python2" 133 | }, 134 | "language_info": { 135 | "codemirror_mode": { 136 | "name": "ipython", 137 | "version": 2 138 | }, 139 | "file_extension": ".py", 140 | "mimetype": "text/x-python", 141 | "name": "python", 142 | "nbconvert_exporter": "python", 143 | "pygments_lexer": "ipython2", 144 | "version": "2.7.10" 145 | } 146 | }, 147 | "nbformat": 4, 148 | "nbformat_minor": 0 149 | } 150 | -------------------------------------------------------------------------------- /python/challenge-array-permutationof.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def permutationOf(string1, string2):\n", 12 | " return set(string1) == set(string2)\n", 13 | "\n", 14 | "def permutationOf2(string1, string2):\n", 15 | " if len(string1) != len(string2):\n", 16 | " return False\n", 17 | " for i in string1:\n", 18 | " if i not in string2:\n", 19 | " return False\n", 20 | " return True" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 12, 26 | "metadata": { 27 | "collapsed": false 28 | }, 29 | "outputs": [], 30 | "source": [ 31 | "from nose.tools import assert_equal\n", 32 | "\n", 33 | "assert_equal(permutationOf('', 'foo'), False)\n", 34 | "assert_equal(permutationOf('Nib', 'bin'), False)\n", 35 | "assert_equal(permutationOf('act', 'cat'), True)\n", 36 | "assert_equal(permutationOf('a ct', 'ca t'), True)\n" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": { 43 | "collapsed": true 44 | }, 45 | "outputs": [], 46 | "source": [] 47 | } 48 | ], 49 | "metadata": { 50 | "kernelspec": { 51 | "display_name": "Python 2", 52 | "language": "python", 53 | "name": "python2" 54 | }, 55 | "language_info": { 56 | "codemirror_mode": { 57 | "name": "ipython", 58 | "version": 2 59 | }, 60 | "file_extension": ".py", 61 | "mimetype": "text/x-python", 62 | "name": "python", 63 | "nbconvert_exporter": "python", 64 | "pygments_lexer": "ipython2", 65 | "version": "2.7.10" 66 | } 67 | }, 68 | "nbformat": 4, 69 | "nbformat_minor": 0 70 | } 71 | -------------------------------------------------------------------------------- /python/challenge-find-non-repeative.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def find_nonrepeative(string):\n", 12 | " if not string:\n", 13 | " return None\n", 14 | " for i, char in enumerate(string):\n", 15 | " repeated = False\n", 16 | " for k, char2 in enumerate(string):\n", 17 | " if i != k and char == char2:\n", 18 | " repeated = True\n", 19 | " break\n", 20 | " if not repeated:\n", 21 | " return char\n", 22 | "\n", 23 | "def find_nonrepeative_python_way(string):\n", 24 | " if not string:\n", 25 | " return None\n", 26 | " for char in string:\n", 27 | " if string.count(char) == 1:\n", 28 | " return char\n", 29 | "\n", 30 | "def find_nonrepeative_hash(string):\n", 31 | " if not string:\n", 32 | " return None\n", 33 | " \n", 34 | " counter = [0] * 256 # each letter will be represetned with its ASCII\n", 35 | " for char in string:\n", 36 | " counter[ord(char)] += 1\n", 37 | " for char in string:\n", 38 | " if counter[ord(char)] == 1:\n", 39 | " return char\n" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": null, 45 | "metadata": { 46 | "collapsed": false 47 | }, 48 | "outputs": [], 49 | "source": [] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": null, 54 | "metadata": { 55 | "collapsed": false 56 | }, 57 | "outputs": [], 58 | "source": [ 59 | "find_nonrepeative_hash(\"sealames\")\n" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "metadata": { 66 | "collapsed": false 67 | }, 68 | "outputs": [], 69 | "source": [ 70 | "from nose.tools import assert_equal\n", 71 | "\n", 72 | "\n", 73 | "def testWith(func):\n", 74 | " assert_equal(func(\"selam\"), \"s\")\n", 75 | " assert_equal(func(\"selasm\"), \"e\")\n", 76 | " assert_equal(func(\"aa\"), None)\n", 77 | " assert_equal(func(\"aab\"), \"b\")\n", 78 | " assert_equal(func(\"b\"), \"b\")\n", 79 | " assert_equal(func(\"ackmdbmkca\"), \"d\")\n", 80 | " assert_equal(func(\"\"), None)\n", 81 | " assert_equal(func(None), None)\n", 82 | " assert_equal(func(\"baaaab\"), None)\n", 83 | "testWith(find_nonrepeative_python_way)\n", 84 | "testWith(find_nonrepeative)\n" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": 3, 90 | "metadata": { 91 | "collapsed": false 92 | }, 93 | "outputs": [ 94 | { 95 | "name": "stdout", 96 | "output_type": "stream", 97 | "text": [ 98 | "find_nonrepeative_hash 3.78166294098\n", 99 | "find_nonrepeative_python_way 1.26318311691\n", 100 | "find_nonrepeative 6.08177089691\n" 101 | ] 102 | } 103 | ], 104 | "source": [ 105 | "import timeit\n", 106 | "print \"find_nonrepeative_hash\", timeit.timeit(\n", 107 | " \"find_nonrepeative_hash('hakfeackmdbmkcahakf')\",\n", 108 | " \"from __main__ import find_nonrepeative_hash\", number=900000)\n", 109 | "print \"find_nonrepeative_python_way\", timeit.timeit(\n", 110 | " \"find_nonrepeative_python_way('hakfeackmdbmkcahakf')\",\n", 111 | " \"from __main__ import find_nonrepeative_python_way\", number=900000)\n", 112 | "print \"find_nonrepeative\", timeit.timeit(\n", 113 | " \"find_nonrepeative('hakfeackmdbmkcahakf')\",\n", 114 | " \"from __main__ import find_nonrepeative\", number=900000)" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": { 121 | "collapsed": true 122 | }, 123 | "outputs": [], 124 | "source": [] 125 | } 126 | ], 127 | "metadata": { 128 | "kernelspec": { 129 | "display_name": "Python 2", 130 | "language": "python", 131 | "name": "python2" 132 | }, 133 | "language_info": { 134 | "codemirror_mode": { 135 | "name": "ipython", 136 | "version": 2 137 | }, 138 | "file_extension": ".py", 139 | "mimetype": "text/x-python", 140 | "name": "python", 141 | "nbconvert_exporter": "python", 142 | "pygments_lexer": "ipython2", 143 | "version": "2.7.10" 144 | } 145 | }, 146 | "nbformat": 4, 147 | "nbformat_minor": 0 148 | } 149 | -------------------------------------------------------------------------------- /python/challenge-remove-character-from-string.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Constraints\n", 8 | "\n", 9 | "* Can I assume the string is ASCII?\n", 10 | " * Yes\n", 11 | " * Note: Unicode strings could require special handling depending on your language\n", 12 | "\n", 13 | "Test Case\n", 14 | "\n", 15 | "* \"a\" from \"tamamdir arAda\" -> \"tmmdir rAd\"\n" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "### Algorithm\n", 23 | "\n", 24 | "Since Python strings are immutable, we'll use a list of chars instead to exercise in-place string manipulation as you would get with a C string.\n", 25 | "\n", 26 | "create a list as a string builder\n", 27 | "\n", 28 | "* for each character in string\n", 29 | "* * checks whether the current char is not equal to removalChar\n", 30 | "* * keep the char in the list\n", 31 | " \n", 32 | "#### Complexity:\n", 33 | "\n", 34 | "* Time: O(n)\n", 35 | "* Space: O(n)" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 45, 41 | "metadata": { 42 | "collapsed": false 43 | }, 44 | "outputs": [], 45 | "source": [ 46 | "def remove_char(string, char):\n", 47 | " newString = []\n", 48 | " for i in string:\n", 49 | " if char != i:\n", 50 | " newString.append(i)\n", 51 | " return \"\".join(newString)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "metadata": {}, 57 | "source": [ 58 | "### Pythonic way\n", 59 | "\n", 60 | "You can achive the same goal in a concise way by using python's string modidication methods as follows:" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 46, 66 | "metadata": { 67 | "collapsed": true 68 | }, 69 | "outputs": [], 70 | "source": [ 71 | "def remove_char2(string, char):\n", 72 | " return string.translate(None, char)\n", 73 | "\n", 74 | "def remove_char3(string, char):\n", 75 | " return string.replace(char, \"\")\n" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "### Unittests" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 47, 88 | "metadata": { 89 | "collapsed": false 90 | }, 91 | "outputs": [ 92 | { 93 | "name": "stdout", 94 | "output_type": "stream", 95 | "text": [ 96 | "Success\n", 97 | "Success\n", 98 | "Success\n" 99 | ] 100 | } 101 | ], 102 | "source": [ 103 | "from nose.tools import assert_equal\n", 104 | "\n", 105 | "\n", 106 | "def testWith(func):\n", 107 | " assert_equal(func(\"tamamdir arAda\", \"a\"), \"tmmdir rAd\")\n", 108 | " assert_equal(func(\"wlkwlkfew wifiw longgglonggggw\", \"w\"), \"lklkfe ifi longgglongggg\")\n", 109 | " assert_equal(func(\"yu*lkke*\", \"*\"), \"yulkke\")\n", 110 | " \n", 111 | " print('Success')\n", 112 | "testWith(remove_char)\n", 113 | "testWith(remove_char2)\n", 114 | "testWith(remove_char3)\n" 115 | ] 116 | }, 117 | { 118 | "cell_type": "markdown", 119 | "metadata": {}, 120 | "source": [ 121 | "### Benchmark" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": 49, 127 | "metadata": { 128 | "collapsed": false 129 | }, 130 | "outputs": [ 131 | { 132 | "name": "stdout", 133 | "output_type": "stream", 134 | "text": [ 135 | "remove_char 5.82854199409\n", 136 | "remove_char2 0.402535915375\n", 137 | "remove_char3 0.377779960632\n" 138 | ] 139 | } 140 | ], 141 | "source": [ 142 | "import timeit\n", 143 | "print \"remove_char\", timeit.timeit(\n", 144 | " \"remove_char('wlkwlkfew wifiw longgglonggggw', 'a')\",\n", 145 | " \"from __main__ import remove_char\", number=1200000)\n", 146 | "print \"remove_char2\", timeit.timeit(\n", 147 | " \"remove_char2('wlkwlkfew wifiw longgglonggggw', 'a')\",\n", 148 | " \"from __main__ import remove_char2\", number=1200000)\n", 149 | "print \"remove_char3\", timeit.timeit(\n", 150 | " \"remove_char3('wlkwlkfew wifiw longgglonggggw', 'a')\",\n", 151 | " \"from __main__ import remove_char3\", number=1200000)" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": { 158 | "collapsed": true 159 | }, 160 | "outputs": [], 161 | "source": [] 162 | } 163 | ], 164 | "metadata": { 165 | "kernelspec": { 166 | "display_name": "Python 2", 167 | "language": "python", 168 | "name": "python2" 169 | }, 170 | "language_info": { 171 | "codemirror_mode": { 172 | "name": "ipython", 173 | "version": 2 174 | }, 175 | "file_extension": ".py", 176 | "mimetype": "text/x-python", 177 | "name": "python", 178 | "nbconvert_exporter": "python", 179 | "pygments_lexer": "ipython2", 180 | "version": "2.7.10" 181 | } 182 | }, 183 | "nbformat": 4, 184 | "nbformat_minor": 0 185 | } 186 | -------------------------------------------------------------------------------- /python/challenge-reverse-string.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 2, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def list_of_chars(chars):\n", 12 | " if not chars:\n", 13 | " return chars\n", 14 | " length = len(chars)\n", 15 | " for i in range(length/2):\n", 16 | " chars[i], chars[length - (i+1)] = chars[length - (i+1)], chars[i]\n", 17 | " return chars\n", 18 | "\n", 19 | "def list_of_chars1(chars):\n", 20 | " if not chars:\n", 21 | " return chars\n", 22 | " chars = list(chars)\n", 23 | " return [chars[i] for i in range(len(chars)-1, -1, -1)]\n", 24 | "\n", 25 | "def list_of_chars4(list_chars):\n", 26 | " if not list_chars:\n", 27 | " return list_chars\n", 28 | " rchars = []\n", 29 | " i = len(list_chars) - 1\n", 30 | " while i > -1:\n", 31 | " rchars.append(list_chars[i])\n", 32 | " i -= 1\n", 33 | " return rchars\n", 34 | "\n", 35 | "def list_of_chars2(chars):\n", 36 | " return chars[::-1]\n", 37 | "\n", 38 | "def list_of_chars3(chars):\n", 39 | " if not chars:\n", 40 | " return chars\n", 41 | " return list(reversed(chars))\n" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": 3, 47 | "metadata": { 48 | "collapsed": false 49 | }, 50 | "outputs": [ 51 | { 52 | "name": "stdout", 53 | "output_type": "stream", 54 | "text": [ 55 | "['m', 'a', 't', ' ', 'm', 'i', 'd', ' ', 'e', 'l', 'y', 'o', 's']\n" 56 | ] 57 | } 58 | ], 59 | "source": [ 60 | "a = list(\"soyle dim tam\")\n", 61 | "print str(list_of_chars(a))" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 95, 67 | "metadata": { 68 | "collapsed": false 69 | }, 70 | "outputs": [ 71 | { 72 | "name": "stdout", 73 | "output_type": "stream", 74 | "text": [ 75 | "Success: test_reverse\n" 76 | ] 77 | } 78 | ], 79 | "source": [ 80 | "from nose.tools import assert_equal\n", 81 | "\n", 82 | "assert_equal(list_of_chars(None), None)\n", 83 | "assert_equal(list_of_chars(['']), [''])\n", 84 | "assert_equal(list_of_chars(\n", 85 | " ['f', 'o', 'o', ' ', 'b', 'a', 'r']),\n", 86 | " ['r', 'a', 'b', ' ', 'o', 'o', 'f'])\n", 87 | "print('Success: test_reverse')\n" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 7, 93 | "metadata": { 94 | "collapsed": true 95 | }, 96 | "outputs": [], 97 | "source": [ 98 | "a = \"ferferf\"" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 8, 104 | "metadata": { 105 | "collapsed": false 106 | }, 107 | "outputs": [ 108 | { 109 | "name": "stdout", 110 | "output_type": "stream", 111 | "text": [ 112 | "ferferf\n" 113 | ] 114 | } 115 | ], 116 | "source": [ 117 | "print a" 118 | ] 119 | }, 120 | { 121 | "cell_type": "code", 122 | "execution_count": null, 123 | "metadata": { 124 | "collapsed": true 125 | }, 126 | "outputs": [], 127 | "source": [] 128 | } 129 | ], 130 | "metadata": { 131 | "kernelspec": { 132 | "display_name": "Python 2", 133 | "language": "python", 134 | "name": "python2" 135 | }, 136 | "language_info": { 137 | "codemirror_mode": { 138 | "name": "ipython", 139 | "version": 2 140 | }, 141 | "file_extension": ".py", 142 | "mimetype": "text/x-python", 143 | "name": "python", 144 | "nbconvert_exporter": "python", 145 | "pygments_lexer": "ipython2", 146 | "version": "2.7.10" 147 | } 148 | }, 149 | "nbformat": 4, 150 | "nbformat_minor": 0 151 | } 152 | -------------------------------------------------------------------------------- /python/challenge-reverse-words.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Constraints\n", 8 | "\n", 9 | "* Can I assume the string is ASCII?\n", 10 | " * Yes\n", 11 | " * Note: Unicode strings could require special handling depending on your language" 12 | ] 13 | }, 14 | { 15 | "cell_type": "markdown", 16 | "metadata": {}, 17 | "source": [ 18 | "### Algorithm\n", 19 | "\n", 20 | "Since Python strings are immutable, we'll use a list of words instead to exercise in-place string manipulation as you would get with a C string.\n", 21 | "\n", 22 | "create a list as a string builder for reversed sentence\n", 23 | "* split string into words\n", 24 | "* for each word\n", 25 | "* * create a list as a string builder for reversed word\n", 26 | "* * for each character in current word:\n", 27 | "* * * insert character into the begining of reversed word string\n", 28 | "* * * inserts reversed word string into the reversed sentence list\n", 29 | " \n", 30 | "#### Complexity:\n", 31 | "\n", 32 | "* Time: O(len(string))\n", 33 | "* Space: O(len(string))" 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": 28, 39 | "metadata": { 40 | "collapsed": false 41 | }, 42 | "outputs": [], 43 | "source": [ 44 | "def reverse_words(string):\n", 45 | " if not string:\n", 46 | " return string\n", 47 | " newString = []\n", 48 | " for word in string.split():\n", 49 | " newWord = []\n", 50 | " for char in word:\n", 51 | " newWord.insert(0, char)\n", 52 | " newString.insert(0, \"\".join(newWord))\n", 53 | " return \" \".join(newString)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "### Pythonic way\n", 61 | "\n", 62 | "You can achive the same goal in a concise way by using python's list modidication methods as follows:" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 24, 68 | "metadata": { 69 | "collapsed": false 70 | }, 71 | "outputs": [], 72 | "source": [ 73 | "def reverse_words2(string):\n", 74 | " string = list(string)\n", 75 | " string.reverse()\n", 76 | " return \"\".join(string)\n", 77 | "\n", 78 | "def reverse_words3(string):\n", 79 | " return string[::-1]\n" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "### Unittests" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 23, 92 | "metadata": { 93 | "collapsed": false 94 | }, 95 | "outputs": [ 96 | { 97 | "name": "stdout", 98 | "output_type": "stream", 99 | "text": [ 100 | "Success: reverse_words\n", 101 | "Success: reverse_words\n", 102 | "Success: reverse_words\n" 103 | ] 104 | } 105 | ], 106 | "source": [ 107 | "from nose.tools import assert_equal\n", 108 | "\n", 109 | "\n", 110 | "def testWith(func):\n", 111 | " assert_equal(reverse_words(\"this is an Example.\"), \".elpmaxE na si siht\")\n", 112 | " assert_equal(reverse_words(\"hello friend\"), \"dneirf olleh\")\n", 113 | " assert_equal(reverse_words(\"COOL\"), \"LOOC\")\n", 114 | " assert_equal(reverse_words(None), None)\n", 115 | " print('Success: reverse_words')\n", 116 | " \n", 117 | "testWith(reverse_words)\n", 118 | "testWith(reverse_words2)\n", 119 | "testWith(reverse_words3)" 120 | ] 121 | }, 122 | { 123 | "cell_type": "markdown", 124 | "metadata": {}, 125 | "source": [ 126 | "### Benchmark" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 27, 132 | "metadata": { 133 | "collapsed": false 134 | }, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "reverse_words 0.73145699501\n", 141 | "reverse_words2 0.122512102127\n", 142 | "reverse_words3 0.0340781211853\n" 143 | ] 144 | } 145 | ], 146 | "source": [ 147 | "import timeit\n", 148 | "print \"reverse_words\", timeit.timeit(\n", 149 | " \"reverse_words('this is an Example.')\",\n", 150 | " \"from __main__ import reverse_words\", number=99000)\n", 151 | "print \"reverse_words2\", timeit.timeit(\n", 152 | " \"reverse_words2('this is an Example.')\",\n", 153 | " \"from __main__ import reverse_words2\", number=99000)\n", 154 | "print \"reverse_words3\", timeit.timeit(\n", 155 | " \"reverse_words3('this is an Example.')\",\n", 156 | " \"from __main__ import reverse_words3\", number=99000)" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 2, 162 | "metadata": { 163 | "collapsed": false 164 | }, 165 | "outputs": [ 166 | { 167 | "name": "stdout", 168 | "output_type": "stream", 169 | "text": [ 170 | "hellasdasd\n" 171 | ] 172 | } 173 | ], 174 | "source": [ 175 | "print \"hellasdasd\"" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": { 182 | "collapsed": true 183 | }, 184 | "outputs": [], 185 | "source": [] 186 | } 187 | ], 188 | "metadata": { 189 | "kernelspec": { 190 | "display_name": "Python 2", 191 | "language": "python", 192 | "name": "python2" 193 | }, 194 | "language_info": { 195 | "codemirror_mode": { 196 | "name": "ipython", 197 | "version": 2 198 | }, 199 | "file_extension": ".py", 200 | "mimetype": "text/x-python", 201 | "name": "python", 202 | "nbconvert_exporter": "python", 203 | "pygments_lexer": "ipython2", 204 | "version": "2.7.10" 205 | } 206 | }, 207 | "nbformat": 4, 208 | "nbformat_minor": 0 209 | } 210 | -------------------------------------------------------------------------------- /python/challenges-array-unique.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 8, 6 | "metadata": { 7 | "collapsed": true 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def uniqueChars(string):\n", 12 | " temp = set()\n", 13 | " for i in string:\n", 14 | " if i in temp:\n", 15 | " return False\n", 16 | " temp.add(i)\n", 17 | " return True\n", 18 | "\n", 19 | "def uniqueChars2(string):\n", 20 | " temp = set()\n", 21 | " for i in string:\n", 22 | " if string.count(i) > 1:\n", 23 | " return False\n", 24 | " return True\n", 25 | "\n", 26 | "def uniqueChars3(string):\n", 27 | " return len(set(string)) == len(string)" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 11, 33 | "metadata": { 34 | "collapsed": false 35 | }, 36 | "outputs": [ 37 | { 38 | "name": "stdout", 39 | "output_type": "stream", 40 | "text": [ 41 | "True\n" 42 | ] 43 | } 44 | ], 45 | "source": [ 46 | "print(uniqueChars(\"fro\"))" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 12, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "from nose.tools import assert_equal\n", 58 | "assert_equal(uniqueChars3(''), True)\n", 59 | "assert_equal(uniqueChars3('foo'), False)\n", 60 | "assert_equal(uniqueChars3('bar'), True)" 61 | ] 62 | } 63 | ], 64 | "metadata": { 65 | "kernelspec": { 66 | "display_name": "Python 3", 67 | "language": "python", 68 | "name": "python3" 69 | }, 70 | "language_info": { 71 | "codemirror_mode": { 72 | "name": "ipython", 73 | "version": 3 74 | }, 75 | "file_extension": ".py", 76 | "mimetype": "text/x-python", 77 | "name": "python", 78 | "nbconvert_exporter": "python", 79 | "pygments_lexer": "ipython3", 80 | "version": "3.5.0" 81 | } 82 | }, 83 | "nbformat": 4, 84 | "nbformat_minor": 0 85 | } 86 | -------------------------------------------------------------------------------- /python/challenges-string-compress.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 36, 6 | "metadata": { 7 | "collapsed": false 8 | }, 9 | "outputs": [], 10 | "source": [ 11 | "def compress_string_contiguous(string):\n", 12 | " \"\"\"\n", 13 | " assuming any numeric character will not be present in the string.\n", 14 | " assuming same characters are contiguous.\n", 15 | " \"\"\"\n", 16 | " compressed = []\n", 17 | " wordLength = len(string)\n", 18 | " starts = 0\n", 19 | " while starts < wordLength:\n", 20 | " c = string[starts]\n", 21 | " ends = string.rfind(c, starts+1)\n", 22 | " print \"char, starts, ends \", c, starts, ends\n", 23 | " length = ends - starts + 1\n", 24 | " compressed.append(c + str(length if length > 1 else \"\"))\n", 25 | " if length > 1:\n", 26 | " starts = ends + 1 # seek to the next char different than c\n", 27 | " else:\n", 28 | " starts += 1\n", 29 | " return \"\".join(compressed)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 37, 35 | "metadata": { 36 | "collapsed": false 37 | }, 38 | "outputs": [], 39 | "source": [ 40 | "def compress_string(string):\n", 41 | " if not string:\n", 42 | " return string\n", 43 | " \n", 44 | " compressed = []\n", 45 | " def insert(char, length):\n", 46 | " if length > 2:\n", 47 | " compressed.append(char + str(length))\n", 48 | " else:\n", 49 | " compressed.append(char * length)\n", 50 | " \n", 51 | " wordLength = len(string)\n", 52 | " previousC = \"\"\n", 53 | " length = 1\n", 54 | " i = 0\n", 55 | " while i < wordLength:\n", 56 | " currentC = string[i]\n", 57 | " if previousC != currentC:\n", 58 | " insert(previousC, length)\n", 59 | " previousC = currentC\n", 60 | " length = 0\n", 61 | " \n", 62 | " length += 1\n", 63 | " i += 1\n", 64 | " insert(previousC, length)\n", 65 | " return \"\".join(compressed)" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 43, 71 | "metadata": { 72 | "collapsed": false 73 | }, 74 | "outputs": [ 75 | { 76 | "name": "stdout", 77 | "output_type": "stream", 78 | "text": [ 79 | "aaBCCEF4KKM6P ta3mmanlaar4 se9k to3\n" 80 | ] 81 | } 82 | ], 83 | "source": [ 84 | "s = \"aaBCCEFFFFKKMMMMMMP taaammanlaarrrr seeeeeeeeek tooo\"\n", 85 | "print compress_string(s)" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 39, 91 | "metadata": { 92 | "collapsed": false 93 | }, 94 | "outputs": [ 95 | { 96 | "name": "stdout", 97 | "output_type": "stream", 98 | "text": [ 99 | "Success: test_compress\n" 100 | ] 101 | } 102 | ], 103 | "source": [ 104 | "from nose.tools import assert_equal\n", 105 | "\n", 106 | "assert_equal(compress_string(None), None)\n", 107 | "assert_equal(compress_string(''), '')\n", 108 | "assert_equal(compress_string('AABBCC'), 'AABBCC')\n", 109 | "\n", 110 | "# I changed the compressed value from A3B1C2D4 to A3BCCD4,\n", 111 | "# since it obviously looks better\n", 112 | "assert_equal(compress_string('AAABCCDDDD'), 'A3BCCD4')\n", 113 | "print('Success: test_compress')\n" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "metadata": { 120 | "collapsed": true 121 | }, 122 | "outputs": [], 123 | "source": [] 124 | } 125 | ], 126 | "metadata": { 127 | "kernelspec": { 128 | "display_name": "Python 2", 129 | "language": "python", 130 | "name": "python2" 131 | }, 132 | "language_info": { 133 | "codemirror_mode": { 134 | "name": "ipython", 135 | "version": 2 136 | }, 137 | "file_extension": ".py", 138 | "mimetype": "text/x-python", 139 | "name": "python", 140 | "nbconvert_exporter": "python", 141 | "pygments_lexer": "ipython2", 142 | "version": "2.7.10" 143 | } 144 | }, 145 | "nbformat": 4, 146 | "nbformat_minor": 0 147 | } 148 | -------------------------------------------------------------------------------- /python/hackerrankrandom/pdf_viewer.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Designer PDF Viewer\n", 8 | "https://www.hackerrank.com/challenges/designer-pdf-viewer\n", 9 | "\n", 10 | "### input\n", 11 | "The first line contains 26 space-separated integers describing the respective heights of each consecutive lowercase English letters.\n", 12 | "\n", 13 | "The second line contains a single word, consisting of lowercase English alphabetic letters.\n", 14 | "\n", 15 | "#### Sample Input\n", 16 | "```\n", 17 | "1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5\n", 18 | "abc\n", 19 | "```" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 5, 25 | "metadata": { 26 | "collapsed": false 27 | }, 28 | "outputs": [ 29 | { 30 | "name": "stdout", 31 | "output_type": "stream", 32 | "text": [ 33 | "1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5\n", 34 | "abc\n", 35 | "9\n" 36 | ] 37 | } 38 | ], 39 | "source": [ 40 | "h = [int(i) for i in input().strip().split(\" \")]\n", 41 | "word = input().strip()\n", 42 | "\n", 43 | "h = dict(zip([chr(i+97) for i in range(26)], h))\n", 44 | "\n", 45 | "maxH = None\n", 46 | "for i in word:\n", 47 | " if maxH == None or h[i] > maxH:\n", 48 | " maxH = h[i]\n", 49 | "\n", 50 | "print(maxH * len(word))" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "collapsed": true 58 | }, 59 | "outputs": [], 60 | "source": [] 61 | } 62 | ], 63 | "metadata": { 64 | "kernelspec": { 65 | "display_name": "Python 3", 66 | "language": "python", 67 | "name": "python3" 68 | }, 69 | "language_info": { 70 | "codemirror_mode": { 71 | "name": "ipython", 72 | "version": 3 73 | }, 74 | "file_extension": ".py", 75 | "mimetype": "text/x-python", 76 | "name": "python", 77 | "nbconvert_exporter": "python", 78 | "pygments_lexer": "ipython3", 79 | "version": "3.5.0" 80 | } 81 | }, 82 | "nbformat": 4, 83 | "nbformat_minor": 1 84 | } 85 | --------------------------------------------------------------------------------