├── AnagramBuckets.java ├── ArithmeticProgression.java ├── BinaryTrees.java ├── CombinationsThatAddUpToNumber.java ├── EvenFibonacciNumbers.java ├── FileSum.java ├── FileSumFile.txt ├── FlattenLinkedList.java ├── HashTables.java ├── LICENSE.md ├── LargestPalindromeProduct.java ├── LargestPrimeFactor.java ├── MergeSort.java ├── MultiplesOfThreeAndFive.java ├── MultiplicationTables.java ├── NthFibonacci.java ├── PairNumbersTotal.java ├── Palindrome.java ├── QuickSortArray.java ├── QuickSortList.java ├── README.md ├── RGBtoHEX.java ├── ReverseString.java ├── ShuffleSongs.java ├── SmallestMultiple.java ├── StringDuplicates.java ├── StringMatch.java ├── UndirectedGraphs.java └── UnsortedArray.java /AnagramBuckets.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | 9 | /** 10 | * Prints anagrams in the same bucket. 11 | * 12 | * @author joeytawadrous 13 | */ 14 | public class AnagramBuckets 15 | { 16 | public static void main (String[] args) 17 | { 18 | ArrayList input = new ArrayList(); 19 | input.add("star"); 20 | input.add("rats"); 21 | input.add("ice"); 22 | input.add("cie"); 23 | input.add("arts"); 24 | anagramBuckets(input); 25 | } 26 | 27 | /** 28 | * Prints anagrams in the same bucket. 29 | * @param list to sort 30 | */ 31 | public static void anagramBuckets(List input) 32 | { 33 | HashMap> hashMap = new HashMap>(); 34 | 35 | for (String s : input) 36 | { 37 | int hash = 0; 38 | 39 | for (int i = 0; i < s.length(); i++) 40 | { 41 | hash += s.charAt(i); 42 | } 43 | 44 | if (hashMap.containsKey(hash)) 45 | { 46 | ArrayList list = hashMap.get(hash); 47 | list.add(s); 48 | hashMap.put(hash, list); 49 | } 50 | else 51 | { 52 | ArrayList list = new ArrayList(); 53 | list.add(s); 54 | hashMap.put(hash, list); 55 | } 56 | } 57 | 58 | 59 | Set keys = hashMap.keySet(); 60 | 61 | for (Integer key : keys) 62 | { 63 | System.out.println(hashMap.get(key)); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /ArithmeticProgression.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Finds the missing number in an arithmetic progression. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class ArithmeticProgression 10 | { 11 | public static void main(String[] args) 12 | { 13 | int[] list = {1, 3, 7}; 14 | System.out.println(findMissing(list)); 15 | } 16 | 17 | /** 18 | * Finds the missing number in an arithmetic progression. 19 | * @param list 20 | * @return missing number in progression 21 | */ 22 | public static int findMissing(int[] list) 23 | { 24 | int length = list.length; 25 | int sum = (length + 1) * (list[0] + list[length - 1]) / 2; 26 | 27 | for(int i = 0; i < length; i++) 28 | { 29 | sum -= list[i]; 30 | } 31 | 32 | return sum; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /BinaryTrees.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Iterator; 4 | import java.util.LinkedList; 5 | 6 | 7 | /** 8 | * Binary Tree manipulations. Adapted from http://cslibrary.stanford.edu/110/BinaryTrees.html#java 9 | * 10 | * @author joeytawadrous 11 | */ 12 | public class BinaryTrees 13 | { 14 | private static Node root; 15 | 16 | public static void main(String[] args) 17 | { 18 | Tree(2); 19 | printTree(root); 20 | System.out.println(isBST(root, 0, 9)); 21 | } 22 | 23 | /** 24 | * Creates a tree data structure. 25 | * @param data 26 | */ 27 | public static void Tree(int data) 28 | { 29 | root = newNode(data); 30 | root.leftChild = newNode(4); 31 | root.rightChild = newNode(5); 32 | 33 | insertNode(root.rightChild, 7); 34 | 35 | System.out.println("Size: " + size(root, 0)); 36 | } 37 | 38 | /** 39 | * Inserts a new node into the tree. 40 | * @param parent 41 | * @param data 42 | * @return node 43 | */ 44 | public static void insertNode(Node parent, int data) 45 | { 46 | // TODO: Improve insertion, i.e. check if entering node causes to break bst tree (entering node in wrong place). 47 | Node node = newNode(data); 48 | 49 | if(data <= parent.data) 50 | { 51 | parent.leftChild = node; 52 | } 53 | else 54 | { 55 | parent.rightChild = node; 56 | } 57 | } 58 | 59 | /** 60 | * Creates a new node. 61 | * @return node 62 | */ 63 | public static Node newNode(int data) 64 | { 65 | Node node = new Node(); 66 | node.data = data; 67 | node.leftChild = null; 68 | node.rightChild = null; 69 | 70 | return node; 71 | } 72 | 73 | /** 74 | * Returns the size of a tree. 75 | * @param node 76 | * @param size 77 | * @return size 78 | */ 79 | public static int size(Node node, int size) 80 | { 81 | if (node == null) { return(0); } 82 | else 83 | { 84 | return(1 + size(node.leftChild, size) + size(node.rightChild, size)); 85 | } 86 | } 87 | 88 | /** 89 | * Returns true if tree is binary search tree. 90 | * @param node 91 | * @param min 92 | * @param max 93 | * @return boolean 94 | */ 95 | public static boolean isBST(Node node, int min, int max) 96 | { 97 | if(node == null) 98 | return true; 99 | 100 | if(node.leftChild == null && node.rightChild == null) 101 | return true; 102 | 103 | else if(node.data > min && node.data < max) 104 | return(isBST(node.leftChild, min, node.data) && isBST(node.rightChild,node.data,max)); 105 | 106 | else 107 | return false; 108 | } 109 | 110 | /** 111 | * Prints the tree. 112 | * @param node 113 | */ 114 | public static void printTree(Node node) 115 | { 116 | LinkedList currentLevel = new LinkedList(); 117 | LinkedList nextLevel = new LinkedList(); 118 | currentLevel.add(node); 119 | 120 | while (!currentLevel.isEmpty()) 121 | { 122 | Iterator iter = currentLevel.iterator(); 123 | while (iter.hasNext()) 124 | { 125 | Node currentNode = iter.next(); 126 | System.out.print(currentNode.data + " "); 127 | if (currentNode.leftChild != null) 128 | { 129 | nextLevel.add(currentNode.leftChild); 130 | } 131 | if (currentNode.rightChild != null) 132 | { 133 | nextLevel.add(currentNode.rightChild); 134 | } 135 | } 136 | System.out.println(); 137 | currentLevel = nextLevel; 138 | nextLevel = new LinkedList(); 139 | } 140 | } 141 | 142 | /** 143 | * Inner node class. 144 | */ 145 | private static class Node 146 | { 147 | private int data; 148 | private Node leftChild; 149 | private Node rightChild; 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /CombinationsThatAddUpToNumber.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.*; 4 | 5 | 6 | /** 7 | * Given a number N, write a program that returns all possible combinations of numbers that add up to N, as lists. 8 | * (Exclude the N+0=N) 9 | * For example, if N=4 return {{1,1,1,1},{1,1,2},{2,2},{1,3}} 10 | * 11 | * @author joeytawadrous 12 | */ 13 | public class CombinationsThatAddUpToNumber 14 | { 15 | public static void main(String[] args) 16 | { 17 | int target = 5; 18 | ArrayList> results = new ArrayList>(); 19 | ArrayList list; 20 | 21 | for (int last = 1; last < target; last++) 22 | { 23 | list = new ArrayList(); 24 | addNext(results, list, 0, last, target, true); 25 | } 26 | 27 | print(results); 28 | } 29 | 30 | /** 31 | * Adds the next combination to the combinations list. 32 | * @param results 33 | * @param list 34 | * @param sum 35 | * @param last 36 | * @param target 37 | * @param isFirst 38 | */ 39 | public static void addNext(ArrayList> results, ArrayList list, int sum, int last, int target, boolean isFirst) 40 | { 41 | if (sum == target) 42 | { 43 | results.add(list); 44 | return; 45 | } 46 | 47 | while (sum + last > target) 48 | { 49 | last--; 50 | } 51 | 52 | int less = last - 1; 53 | if ( !isFirst && less > 0 && less + last < target ) 54 | { 55 | ArrayList copyList = new ArrayList(list); 56 | addNext(results, copyList, sum, less, target, false); 57 | } 58 | 59 | sum = sum + last; 60 | list.add(last); 61 | 62 | addNext(results, list, sum, last, target, false); 63 | } 64 | 65 | /** 66 | * Prints the array combinations. 67 | * @param results 68 | */ 69 | public static void print(ArrayList> results) 70 | { 71 | for (ArrayList list: results) 72 | { 73 | for (Integer i: list) 74 | { 75 | System.out.print(String.format("%d ", i)); 76 | } 77 | System.out.println("\n----------"); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /EvenFibonacciNumbers.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.ArrayList; 4 | 5 | 6 | /** 7 | * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 8 | * 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 9 | * By considering the terms in the Fibonacci sequence whose values do not exceed four million, 10 | * find the sum of the even-valued terms. 11 | * 12 | * @author joeytawadrous 13 | */ 14 | public class EvenFibonacciNumbers 15 | { 16 | private static ArrayList numbers = new ArrayList(); 17 | 18 | public static void main (String[] args) 19 | { 20 | System.out.print(calc()); 21 | } 22 | 23 | private static int calc() 24 | { 25 | int total = 0; 26 | 27 | numbers.add(1); 28 | numbers.add(2); 29 | 30 | fib(1, 2); 31 | 32 | for(int number : numbers) 33 | { 34 | if(number % 2 == 0) 35 | { 36 | total += number; 37 | } 38 | } 39 | return total; 40 | } 41 | 42 | private static void fib(int f1, int f2) 43 | { 44 | int fib = f1 + f2; 45 | //System.out.println(fib); 46 | 47 | if(fib < 4000000) 48 | { 49 | numbers.add(fib); 50 | 51 | fib(f2, fib); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /FileSum.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | 6 | 7 | /** 8 | * Prints the sum of numbers in a file (one number per line in the file). 9 | * 10 | * @author joeytawadrous 11 | */ 12 | public class FileSum 13 | { 14 | public static void main (String[] args) 15 | { 16 | sumFile("FileSumFile.txt"); 17 | } 18 | 19 | /** 20 | * Prints the sum of numbers in a file. 21 | * @param name 22 | */ 23 | public static void sumFile(String name) 24 | { 25 | try 26 | { 27 | int total = 0; 28 | BufferedReader in = new BufferedReader(new FileReader(name)); 29 | 30 | for(String s = in.readLine(); s != null; s = in.readLine()) 31 | { 32 | total += Integer.parseInt(s); 33 | } 34 | 35 | System.out.println(total); 36 | in.close(); 37 | } 38 | catch (Exception e) 39 | { 40 | e.printStackTrace(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /FileSumFile.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 -------------------------------------------------------------------------------- /FlattenLinkedList.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.ListIterator; 7 | 8 | public class FlattenLinkedList 9 | { 10 | public static void main(String[] args) 11 | { 12 | // List of strings 13 | LinkedList stringList = new LinkedList(); 14 | for (Integer i = 0; i < 10; i++) { 15 | stringList.add("String #" +i.toString()); 16 | } 17 | 18 | // List of integers 19 | LinkedList intList = new LinkedList(); 20 | for (Integer i = 10; i < 20; i++) { 21 | intList.add(i); 22 | } 23 | 24 | // Nested Lists 25 | LinkedList nestedList = new LinkedList(); 26 | 27 | nestedList.add("Nested String 1"); 28 | nestedList.add("Nested String 2"); 29 | 30 | LinkedList bigList = new LinkedList(); 31 | 32 | bigList.add("First item"); 33 | bigList.add(stringList); 34 | bigList.add("Third Item"); 35 | bigList.add(intList); 36 | bigList.add("Fifth Item"); 37 | bigList.add(nestedList); 38 | bigList.add("Seventh Item"); 39 | 40 | List flattenedListRecursion = flattenList(bigList); 41 | List flattenedList = flattenListNoRecursion(bigList); 42 | 43 | printList(flattenedListRecursion); 44 | printList(flattenedList); 45 | } 46 | 47 | @SuppressWarnings("unchecked") 48 | /** 49 | * Flattens a given list. 50 | * @param list 51 | * @return 52 | */ 53 | public static List flattenList(List inList) 54 | { 55 | List newList = new LinkedList(); 56 | 57 | for (Object i : inList) 58 | { 59 | // If it's not a list, just add it to the return list. 60 | if (!(i instanceof List)) 61 | { 62 | newList.add(i); 63 | } 64 | else 65 | { 66 | // It's a list, so add each item to the return list. 67 | newList.addAll(flattenList((List)i)); 68 | } 69 | } 70 | return newList; 71 | } 72 | 73 | @SuppressWarnings("unchecked") 74 | public static List flattenListNoRecursion(List inList) { 75 | List tempList = null; 76 | 77 | // Clone the input list to newList 78 | List newList = new LinkedList(); 79 | newList.addAll(inList); 80 | 81 | ListIterator iterator = newList.listIterator(); 82 | 83 | int currentPosition = 0; 84 | 85 | while (iterator.hasNext()) { 86 | Object i = iterator.next(); 87 | 88 | if (!(i instanceof List)) { 89 | // If it's not a list, advance the position. Don't advance position if this IS a list. 90 | currentPosition++; 91 | } else { 92 | // If the current item is a list, save it to a temp var. 93 | tempList = (List) i; 94 | 95 | // Delete the list from the list 96 | iterator.remove(); 97 | 98 | // Add each item from the temp list to the master list at the same position the sublist was removed. 99 | for (Object obj : tempList) { 100 | iterator.add(obj); 101 | } 102 | 103 | // reset the iterator to re-walk the list that was just inserted (within the master) to check for more lists. 104 | iterator = newList.listIterator(currentPosition); 105 | } 106 | } 107 | return newList; 108 | } 109 | 110 | /** 111 | * Prints a given list. 112 | * @param list 113 | */ 114 | public static void printList(List list) 115 | { 116 | int i = 0; 117 | 118 | for (Object item : list) 119 | { 120 | System.out.println("List item #"+i +": "+item); 121 | i++; 122 | } 123 | } 124 | } -------------------------------------------------------------------------------- /HashTables.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.*; 4 | 5 | 6 | /** 7 | * Simple HashTable operations. 8 | * 9 | * @author joeytawadrous 10 | */ 11 | public class HashTables 12 | { 13 | public static void main(String args[]) 14 | { 15 | // Create a hash map 16 | Hashtable balance = new Hashtable(); 17 | Enumeration names; 18 | String str; 19 | double bal; 20 | 21 | balance.put("Zara", new Double(3434.34)); 22 | balance.put("Ayan", new Double(1378.00)); 23 | balance.put("Paud", new Double(-19.08)); 24 | 25 | 26 | // Show all balances in hash table. 27 | names = balance.keys(); 28 | while(names.hasMoreElements()) 29 | { 30 | str = names.nextElement(); 31 | System.out.println(str + ": " + balance.get(str)); 32 | } 33 | System.out.println(); 34 | 35 | 36 | // Deposit 1,000 into Zara's account 37 | bal = balance.get("Zara"); 38 | balance.put("Zara", new Double(bal+1000)); 39 | System.out.println("Zara's new balance: " + balance.get("Zara")); 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Joey Tawadrous 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 | -------------------------------------------------------------------------------- /LargestPalindromeProduct.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. 6 | * Find the largest palindrome made from the product of two 3-digit numbers. 7 | * 8 | * @author joeytawadrous 9 | */ 10 | public class LargestPalindromeProduct { 11 | 12 | public static void main(String[] args) { 13 | System.out.println(sixDigitPalindrome()); 14 | } 15 | 16 | public static int sixDigitPalindrome() { 17 | 18 | int max = 0; 19 | 20 | for(int i = 999; i > 100; i--) { 21 | 22 | for(int j = i; j > 100; j--) { 23 | String number = Integer.toString((i * j)); 24 | 25 | if(number.length() == 6 26 | && number.charAt(0) == number.charAt(5) 27 | && number.charAt(1) == number.charAt(4) 28 | && number.charAt(2) == number.charAt(3) 29 | && Integer.parseInt(number) > max) { 30 | max = i * j; 31 | } 32 | } 33 | } 34 | 35 | return max; 36 | } 37 | } -------------------------------------------------------------------------------- /LargestPrimeFactor.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * The prime factors of 13195 are 5, 7, 13 and 29. 6 | * What is the largest prime factor of the number 600851475143 ? 7 | * 8 | * @author joeytawadrous 9 | */ 10 | public class LargestPrimeFactor { 11 | 12 | public static void main(String[] args) { 13 | long numberToFactor = 600851475143l; 14 | int currentDivisor = 2; 15 | int largestDivisor = 0; 16 | 17 | while (numberToFactor != 1) { // cannot divide any further 18 | 19 | if(numberToFactor % currentDivisor == 0) { // no remainder 20 | numberToFactor = numberToFactor / currentDivisor; 21 | largestDivisor = currentDivisor; 22 | currentDivisor = 2; 23 | } 24 | else { 25 | currentDivisor++; 26 | } 27 | 28 | } 29 | 30 | System.out.println("NumberToFactor: " + numberToFactor + " :: CurrentDivisor: " + currentDivisor + " :: LargestDivisor: " + largestDivisor); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MergeSort.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | 7 | /** 8 | * Merge sort algorithm (Top down) based on pseudocode at Wikipedia "Merge sort" article. 9 | * 10 | * @see 11 | * @author djitz 12 | */ 13 | public class MergeSort 14 | { 15 | public static void main(String[] args) 16 | { 17 | //Generate an integer array of length 7 18 | int[] input = generateRandomNumbers(7); 19 | 20 | //Before sort 21 | System.out.println(Arrays.toString(input)); 22 | 23 | //After sort 24 | System.out.println(Arrays.toString(mergeSort(input))); 25 | } 26 | 27 | /** 28 | * Sorts the input array using top-down merge sort algorithm. 29 | * @param the array of integers to sort 30 | * @return sorted array of integers 31 | */ 32 | private static int[] mergeSort(int[] input) 33 | { 34 | if(input.length == 1) 35 | { 36 | return input; 37 | } 38 | 39 | int middle = (int) Math.ceil((double)input.length / 2); 40 | int[] left = new int[middle]; 41 | 42 | int rightLength = 0; 43 | if(input.length % 2 == 0) 44 | { 45 | rightLength = middle; 46 | } 47 | else 48 | { 49 | rightLength = middle - 1; 50 | } 51 | int[] right = new int[rightLength]; 52 | 53 | int leftIndex = 0; 54 | int rightIndex = 0; 55 | 56 | for (int i = 0; i < input.length; i++) 57 | { 58 | if(i < middle) 59 | { 60 | left[leftIndex] = input[i]; 61 | leftIndex++; 62 | } 63 | else 64 | { 65 | right[rightIndex] = input[i]; 66 | rightIndex++; 67 | } 68 | } 69 | 70 | left = mergeSort(left); 71 | right = mergeSort(right); 72 | 73 | return merge(left, right); 74 | } 75 | 76 | /** 77 | * Merges two integer arrays into a sorted integer array. 78 | * @param left first array 79 | * @param right second array 80 | * @return a sorted integer array 81 | */ 82 | private static int[] merge(int[] left, int[] right) 83 | { 84 | int[] result = new int[left.length + right.length]; 85 | int leftIndex = 0; 86 | int rightIndex = 0; 87 | int resultIndex = 0; 88 | 89 | while(leftIndex < left.length || rightIndex < right.length) 90 | { 91 | if(leftIndex < left.length && rightIndex < right.length) 92 | { 93 | if(left[leftIndex] < right[rightIndex]) 94 | { 95 | result[resultIndex] = left[leftIndex]; 96 | leftIndex++; 97 | resultIndex++; 98 | } 99 | else 100 | { 101 | result[resultIndex] = right[rightIndex]; 102 | rightIndex++; 103 | resultIndex++; 104 | } 105 | } 106 | else if(leftIndex < left.length) 107 | { 108 | for (int i = resultIndex; i < result.length; i++) 109 | { 110 | result[i] = left[leftIndex]; 111 | leftIndex++; 112 | } 113 | } 114 | else if(rightIndex < right.length) 115 | { 116 | for (int i = resultIndex; i < result.length; i++) 117 | { 118 | result[i] = right[rightIndex]; 119 | rightIndex++; 120 | } 121 | } 122 | } 123 | 124 | return result; 125 | } 126 | 127 | /** 128 | * Generates an array of random integers with length n. 129 | * @param the length of the array to generate 130 | * @return array of random integers with length n 131 | */ 132 | private static int[] generateRandomNumbers(int n) 133 | { 134 | int[] result = new int[n]; 135 | Random random = new Random(); 136 | 137 | for (int i = 0; i < result.length; i++) 138 | { 139 | result[i] = random.nextInt(n * 10); 140 | } 141 | 142 | return result; 143 | } 144 | } -------------------------------------------------------------------------------- /MultiplesOfThreeAndFive.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. 6 | * The sum of these multiples is 23. 7 | * Find the sum of all the multiples of 3 or 5 below 1000. 8 | * 9 | * @author joeytawadrous 10 | */ 11 | public class MultiplesOfThreeAndFive 12 | { 13 | public static void main (String[] args) 14 | { 15 | System.out.print(calc()); 16 | } 17 | 18 | public static int calc() 19 | { 20 | int total = 0; 21 | 22 | for(int i = 0; i < 1000; i++) 23 | { 24 | if(i % 3 == 0 || i % 5 == 0) 25 | { 26 | total += i; 27 | } 28 | } 29 | 30 | return total; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /MultiplicationTables.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Print multiplication tables up to a certain number. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class MultiplicationTables 10 | { 11 | public static void main (String[] args) 12 | { 13 | multTables(12); 14 | } 15 | 16 | /** 17 | * Print multiplication tables up to max. 18 | * @param max 19 | */ 20 | public static void multTables(int max) 21 | { 22 | for (int i = 1; i <= max; i++) 23 | { 24 | for (int j = 1; j <= max; j++) 25 | { 26 | System.out.print(String.format("%4d", j * i )); 27 | } 28 | System.out.println(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NthFibonacci.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Computes the Nth Fibonacci number. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class NthFibonacci 10 | { 11 | public static void main (String[] args) 12 | { 13 | for (int i = 0; i < 10; i++) 14 | { 15 | System.out.print (fib(i) + ", "); 16 | } 17 | 18 | System.out.println (fib(10)); 19 | } 20 | 21 | /** 22 | * Returns the nth Fibonacci number. 23 | * @param n 24 | * @return Nth Fibonacci number 25 | */ 26 | static int fib(int n) 27 | { 28 | return n <= 1 ? n : fib(n-1) + fib(n-2); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /PairNumbersTotal.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Given an array of randomly sorted integers and an integer k, write a function which returns boolean True 6 | * if a pair of numbers exists in the array such that A[i] + A[j] = k and False otherwise. 7 | * Provide an O(N) and an O(N log N) solution. 8 | * 9 | * @author joeytawadrous 10 | */ 11 | public class PairNumbersTotal 12 | { 13 | public static void main (String[] args) 14 | { 15 | int[] array = {1,2,3}; 16 | 17 | System.out.println(IsExistsPairThatThierSumIsK2(array, 3)); 18 | } 19 | 20 | 21 | /* 22 | * O(N log N) 23 | */ 24 | static boolean IsExistsPairThatThierSumIsK(int[] array, int k) 25 | { 26 | for (int i = 0; i < array.length; i++) 27 | { 28 | int j = FindLeftmost(array, k - array[i]); 29 | 30 | if (j == -1) continue; 31 | 32 | if (i != j || (i + 1 < array.length && array[i] == array[i + 1])) return true; 33 | } 34 | 35 | return false; 36 | } 37 | 38 | static int FindLeftmost(int[] array, int k) 39 | { 40 | int l = 0; 41 | int r = array.length - 1; 42 | 43 | while (l < r) 44 | { 45 | int m = l + (r - l) / 2; 46 | 47 | if (array[m] >= k) r = m; 48 | else l = m + 1; 49 | } 50 | 51 | return array[l] == k ? l : -1; 52 | } 53 | 54 | 55 | /* 56 | * O(N) 57 | */ 58 | static boolean IsExistsPairThatThierSumIsK2(int[] array, int k) 59 | { 60 | int l = 0; 61 | int r = array.length - 1; 62 | 63 | while (l < r) 64 | { 65 | if (array[l] + array[r] == k) return true; 66 | else if (array[l] + array[r] > k) r--; 67 | else l++; 68 | } 69 | 70 | return false; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Palindrome.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | 7 | /** 8 | * Prints all Palindromes of a word. 9 | * 10 | * @author joeytawadrous 11 | */ 12 | public class Palindrome 13 | { 14 | public static void main(String[] args) 15 | { 16 | String word = "abba"; 17 | System.out.println(isPalindrome(word.toCharArray())); 18 | System.out.println(isPalindrome2(word)); 19 | System.out.println(isPalindrome3(word)); 20 | System.out.println(substringPalindrome(word)); 21 | } 22 | 23 | /** 24 | * Finds all substring palindromes. 25 | * @param input 26 | * @return result 27 | */ 28 | public static Set substringPalindrome(final String input) 29 | { 30 | final HashSet result = new HashSet(); 31 | 32 | for (int i = 0; i < input.length(); i++) 33 | { 34 | // searching for even length palindromes: 35 | searchForPalindromes(input, i, i+1, result); 36 | // searching for odd length palindromes: 37 | searchForPalindromes(input, i, i, result); 38 | } 39 | return result; 40 | } 41 | 42 | public static void searchForPalindromes(String input, int i, int j, Set result) 43 | { 44 | while (i >= 0 && j < input.length() && input.charAt(i) == input.charAt(j)) 45 | { 46 | result.add(input.substring(i, j+1)); 47 | i--; 48 | j++; 49 | } 50 | } 51 | 52 | /** 53 | * Test's whether input chars form a palindrome or not. 54 | * @param word 55 | * @return boolean 56 | */ 57 | public static boolean isPalindrome(char[] word) 58 | { 59 | int i = 0; 60 | int i2 = word.length - 1; 61 | 62 | while (i2 > i) 63 | { 64 | if (word[i] != word[i2]) 65 | { 66 | return false; 67 | } 68 | i++; 69 | i2--; 70 | } 71 | return true; 72 | } 73 | 74 | /** 75 | * Test's whether input chars form a palindrome or not. 76 | * @param str 77 | * @return boolean 78 | */ 79 | public static boolean isPalindrome2(String str) 80 | { 81 | int n = str.length(); 82 | for (int i = 0; i < n/2; i++) 83 | { 84 | if (str.charAt(i) != str.charAt(n-i-1)) 85 | { 86 | return false; 87 | } 88 | } 89 | return true; 90 | } 91 | 92 | /** 93 | * Test's whether input chars form a palindrome or not. 94 | * @param str 95 | * @return boolean 96 | */ 97 | public static boolean isPalindrome3(String str) 98 | { 99 | return str.equals(new StringBuilder(str).reverse().toString()); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /QuickSortArray.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * An array based implementation of Quick-sort. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class QuickSortArray 10 | { 11 | private static int[] numbers; 12 | private static int number; 13 | 14 | public static void main(String[] args) 15 | { 16 | int[] values = {3, 1, 4, 2}; 17 | 18 | sort(values); 19 | 20 | for(int value: values) 21 | { 22 | System.out.println(value); 23 | } 24 | } 25 | 26 | 27 | public static void sort(int[] values) 28 | { 29 | // check for empty or null array 30 | if (values ==null || values.length == 0) { return; } 31 | 32 | numbers = values; 33 | number = values.length; 34 | quicksort(0, number - 1); 35 | } 36 | 37 | private static void quicksort(int low, int high) 38 | { 39 | int i = low, j = high; 40 | // Get the pivot element from the middle of the list 41 | int pivot = numbers[low + (high-low)/2]; 42 | 43 | // Divide into two lists 44 | while (i <= j) 45 | { 46 | // If the current value from the left list is smaller than the pivot 47 | // element then get the next element from the left list 48 | while (numbers[i] < pivot) 49 | { 50 | i++; 51 | } 52 | 53 | // If the current value from the right list is larger then the pivot 54 | // element then get the next element from the right list 55 | while (numbers[j] > pivot) 56 | { 57 | j--; 58 | } 59 | 60 | // If we have found a values in the left list which is larger then 61 | // the pivot element and if we have found a value in the right list 62 | // which is smaller then the pivot element then we exchange the 63 | // values. 64 | // As we are done we can increase i and j 65 | if (i <= j) 66 | { 67 | exchange(i, j); 68 | i++; 69 | j--; 70 | } 71 | } 72 | 73 | // Recursion 74 | if (low < j) 75 | quicksort(low, j); 76 | if (i < high) 77 | quicksort(i, high); 78 | } 79 | 80 | private static void exchange(int i, int j) 81 | { 82 | int temp = numbers[i]; 83 | numbers[i] = numbers[j]; 84 | numbers[j] = temp; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /QuickSortList.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | 9 | /** 10 | * Quick sort algorithm (simple) based on pseudo code on Wikipedia "Quick Sort" article. 11 | * 12 | * Complexity worst case O(N^2), best case O(N log N) 13 | * 14 | * @see http://en.wikipedia.org/wiki/Quicksort#Simple_version 15 | * @author djitz 16 | */ 17 | public class QuickSortList 18 | { 19 | public static void main(String[] args) 20 | { 21 | //Generate an integer array of length 5 22 | List input = generateRandomNumbers(5); 23 | 24 | //Before sort 25 | System.out.println(input); 26 | 27 | //After sort 28 | System.out.println(quicksort(input)); 29 | } 30 | 31 | /** 32 | * This method sort the input ArrayList using quick sort algorithm. 33 | * @param input the ArrayList of integers. 34 | * @return sorted ArrayList of integers. 35 | */ 36 | private static List quicksort(List input) 37 | { 38 | if(input.size() <= 1) 39 | { 40 | return input; 41 | } 42 | 43 | 44 | int middle = input.size() / 2; 45 | int pivot = input.get(middle); 46 | 47 | 48 | LinkedList less = new LinkedList(); 49 | LinkedList greater = new LinkedList(); 50 | 51 | 52 | for (int i = 0; i < input.size(); i++) 53 | { 54 | if(input.get(i) <= pivot) 55 | { 56 | if(i == middle) 57 | { 58 | continue; 59 | } 60 | less.add(input.get(i)); 61 | } 62 | else 63 | { 64 | greater.add(input.get(i)); 65 | } 66 | } 67 | 68 | 69 | return concatenateLists(quicksort(less), pivot, quicksort(greater)); 70 | } 71 | 72 | /** 73 | * Join the less array, pivot integer, and greater array 74 | * to single array. 75 | * @param less integer ArrayList with values less than pivot. 76 | * @param pivot the pivot integer. 77 | * @param greater integer ArrayList with values greater than pivot. 78 | * @return the integer ArrayList after join. 79 | */ 80 | private static List concatenateLists(List less, int pivot, List greater) 81 | { 82 | List list = new ArrayList(); 83 | for (Integer i : less) 84 | { 85 | list.add(i); 86 | } 87 | 88 | list.add(pivot); 89 | 90 | for (Integer i : greater) 91 | { 92 | list.add(i); 93 | } 94 | 95 | return list; 96 | } 97 | 98 | /** 99 | * This method generate a ArrayList with length n containing random integers . 100 | * @param n the length of the ArrayList to generate. 101 | * @return ArrayList of random integers with length n. 102 | */ 103 | private static List generateRandomNumbers(int n) 104 | { 105 | List list = new ArrayList(); 106 | Random random = new Random(); 107 | 108 | for (int i = 0; i < n; i++) 109 | { 110 | list.add(random.nextInt(n * 10)); 111 | } 112 | 113 | return list; 114 | } 115 | 116 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithm-Implementations 2 | Contains lots of algorithm's & their implementations that have been compiled from a variety of locations, all written in Java. 3 | 4 | # Why? 5 | This is more of a hobby of mine, however these algorithm's may be useful for other's in general, when learning about computer programming and especially when preparing for a coding interview. 6 | 7 | # Future 8 | I will be adding algorithm's regularly as I learn them myself. 9 | 10 | Please feel free to fork and add some algorithm's of your own! -------------------------------------------------------------------------------- /RGBtoHEX.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Format an RGB value (three 1-byte numbers) as a 6-digit hexadecimal string. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class RGBtoHEX 10 | { 11 | public static void main (String[] args) 12 | { 13 | System.out.println(formatRGB(3,3,3)); 14 | } 15 | 16 | /** 17 | * Format an RGB value (three 1-byte numbers) as a 6-digit hexadecimal string. 18 | * @param r 19 | * @param g 20 | * @param b 21 | * @return Hex numbers 22 | */ 23 | public static String formatRGB(int r, int g, int b) 24 | { 25 | return(toHex(r) + toHex(g) + toHex(b)).toUpperCase(); 26 | } 27 | 28 | /** 29 | * Converts int number to Hex. 30 | * @param c 31 | * @return hex number 32 | */ 33 | public static String toHex(int c) 34 | { 35 | String s = Integer.toHexString(c); 36 | return(s.length() == 1) ? "0" + s : s; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /ReverseString.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Simple class to reverse a string. 6 | * 7 | * @author joeytawadrous 8 | */ 9 | public class ReverseString 10 | { 11 | public static void main(String[] args) 12 | { 13 | System.out.println(reverse("tree")); 14 | } 15 | 16 | /** 17 | * Reverse string. 18 | * @param string 19 | * @return revString 20 | */ 21 | public static String reverse(String string) 22 | { 23 | String revString = ""; 24 | char[] charArray = string.toCharArray(); 25 | 26 | for(char c : charArray) 27 | { 28 | revString = c + revString; 29 | } 30 | 31 | return revString; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ShuffleSongs.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | 7 | /** 8 | * Shuffles songs in a play list. 9 | * 10 | * @author joeytawadrous 11 | */ 12 | public class ShuffleSongs 13 | { 14 | static List songsList; 15 | 16 | @SuppressWarnings("unchecked") 17 | public static void main(String[] args) 18 | { 19 | initSongsList(); 20 | System.out.println("Before Shuffle"); 21 | printSongsList(songsList); 22 | 23 | 24 | System.out.println("After Shuffle 1"); 25 | printSongsList(shuffle1(songsList)); 26 | 27 | 28 | initSongsList(); 29 | System.out.println("After Shuffle 2"); 30 | printSongsList(shuffle2(songsList)); 31 | } 32 | 33 | private static void initSongsList() 34 | { 35 | songsList = new LinkedList(); 36 | songsList.add(new Song("Moon Light", "Nature", "AL")); 37 | songsList.add(new Song("Go Next", "Future", "J. J")); 38 | songsList.add(new Song("Fear", "Hell G.", "SD")); 39 | songsList.add(new Song("My name is", "Future", "Khan")); 40 | songsList.add(new Song("My Lord", "K", "Ali")); 41 | } 42 | 43 | /** 44 | * Prints lit of songs. 45 | * @param list 46 | */ 47 | private static void printSongsList(List list) 48 | { 49 | for (int i = 0; i < list.size(); i++) 50 | { 51 | Song song = list.get(i); 52 | System.out.printf("# %d - Title: %13s | Album: %10s | Artist: %10s\n", i+1, song.title, song.album, song.artist); 53 | } 54 | 55 | System.out.println("-------------------------------------------------------------------"); 56 | } 57 | 58 | /** 59 | * Shuffles a play list. O(n) 60 | * @param list 61 | * @return resultList 62 | */ 63 | @SuppressWarnings({ "rawtypes", "unchecked" }) 64 | private static List shuffle1(List list) 65 | { 66 | List resultList = new LinkedList(); 67 | int size = list.size(); 68 | int rand = 0; 69 | Object[] temp = list.toArray(); 70 | int count = 0; 71 | 72 | while(count != size) 73 | { 74 | rand = (int)(Math.random()*list.size()); 75 | if(!resultList.contains(temp[rand])) 76 | { 77 | resultList.add(temp[rand]); 78 | count++; 79 | } 80 | } 81 | 82 | return resultList; 83 | } 84 | 85 | /** 86 | * Shuffles a play list using recursion. O(log n) 87 | * @param list 88 | * @return resultList 89 | */ 90 | @SuppressWarnings({ "unchecked", "rawtypes" }) 91 | private static List shuffle2(List list) 92 | { 93 | if(list.size() == 1) 94 | { 95 | return list; 96 | } 97 | else 98 | { 99 | int rand = (int)(Math.random()*list.size()); 100 | Object song = list.remove(rand); 101 | 102 | list = shuffle2(list); 103 | list.add(song); 104 | 105 | return list; 106 | } 107 | } 108 | 109 | /** 110 | * Inner class. 111 | * @author joeytawadrous 112 | */ 113 | private static class Song 114 | { 115 | private String title; 116 | private String album; 117 | private String artist; 118 | 119 | public Song(String title, String album, String artist) 120 | { 121 | this.title = title; 122 | this.album = album; 123 | this.artist = artist; 124 | } 125 | } 126 | } -------------------------------------------------------------------------------- /SmallestMultiple.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. 6 | * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? 7 | * 8 | * @author joeytawadrous 9 | */ 10 | public class SmallestMultiple { 11 | 12 | public static void main(String[] args) { 13 | smallestMultiple(); 14 | } 15 | 16 | public static void smallestMultiple() { 17 | 18 | int j = 100; 19 | 20 | for(int i = 2; i < 11; i++) { 21 | 22 | while(!(j % i == 0)) { 23 | j++; 24 | } 25 | 26 | System.out.println(j); 27 | } 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /StringDuplicates.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.LinkedHashSet; 4 | 5 | 6 | /** 7 | * Remove duplicates from a string. 8 | * 9 | * @author joeytawadrous 10 | */ 11 | public class StringDuplicates 12 | { 13 | public static void main(String[] args) 14 | { 15 | String string = "aabbccdef"; 16 | LinkedHashSet set = new LinkedHashSet(); 17 | 18 | for(char c : string.toCharArray()) 19 | { 20 | set.add(Character.valueOf(c)); 21 | } 22 | 23 | System.out.println(set); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /StringMatch.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | 4 | /** 5 | * Given a regular expression with characters a-z, ' * ', ' . ' 6 | * the task was to find if that string could match another string with characters from: a-z 7 | * where ' * ' can delete the character before it, and '.' could match whatever character. '*' always appear after a a-z character. 8 | * Example: 9 | * isMatch("a*", "") = true; 10 | * isMatch(".", "") = false; 11 | * isMatch("ab*", "a") = true; 12 | * isMatch("a.", "ab") = true; 13 | * isMatch("a", "a") = true; 14 | * 15 | * @author joeytawadrous 16 | */ 17 | public class StringMatch 18 | { 19 | public static void main(String[] args) { 20 | String s1 = "a*abc"; 21 | String s2 = "abc"; 22 | System.out.println(isMatch(s1, s2, 0, 0)); 23 | 24 | String s3 = "a*a*a"; 25 | String s4 = "a"; 26 | System.out.println(isMatch(s3, s4, 0, 0)); 27 | 28 | String s5 = "a."; 29 | String s6 = "ab"; 30 | System.out.println(isMatch(s5, s6, 0, 0)); 31 | 32 | String s7 = "a*bd*c"; 33 | String s8 = "abdc"; 34 | System.out.println(isMatch(s7, s8, 0, 0)); 35 | 36 | String s9 = "a."; 37 | String s10 = "s"; 38 | System.out.println(isMatch(s9, s10, 0, 0)); 39 | } 40 | 41 | /** 42 | * Checks 43 | * @param s1 44 | * @param s2 45 | * @param posS1 46 | * @param posS2 47 | * @return boolean 48 | */ 49 | public static boolean isMatch(String s1, String s2, int posS1, int posS2) 50 | { 51 | int l1 = s1.length(); 52 | int l2 = s2.length(); 53 | // System.out.println("posS1:"+posS1+" posS2:"+posS2); 54 | 55 | 56 | if(posS1 > l1 || posS2 > l2) 57 | { 58 | return false; 59 | } 60 | else if(posS1 == l1 && posS2 == l2) 61 | { 62 | return true; 63 | } 64 | else 65 | { 66 | if(posS2 < l2 && posS1 < l1 && ((s1.charAt(posS1) == s2.charAt(posS2)) || s1.charAt(posS1) == '.')) 67 | { 68 | return isMatch(s1, s2, posS1+1, posS2+1); 69 | } 70 | else if(posS1 < l1 && s1.charAt(posS1) == '*') 71 | { 72 | if(posS2 > 0) 73 | { 74 | return isMatch(s1, s2, posS1+1, posS2-1) || isMatch(s1, s2, posS1+1, posS2); 75 | } 76 | else 77 | { 78 | return isMatch(s1, s2, posS1+1, posS2); 79 | } 80 | } 81 | else 82 | { 83 | if(posS1+1 < l1 && s1.charAt(posS1+1) == '*') 84 | { 85 | return isMatch(s1, s2, posS1+2, posS2); 86 | } 87 | else 88 | { 89 | return false; 90 | } 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /UndirectedGraphs.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.*; 4 | 5 | 6 | /** 7 | * Implementation of undirected graph represented using adjacency list. 8 | * 9 | * @author joeytawadrous 10 | */ 11 | public final class UndirectedGraphs implements Iterable 12 | { 13 | private final Map> graph = new HashMap>(); 14 | 15 | public boolean addNode(T node) 16 | { 17 | if (graph.containsKey(node)) { return false; } 18 | 19 | graph.put(node, new HashSet()); 20 | 21 | return true; 22 | } 23 | 24 | public void addEdge(T start, T dest) 25 | { 26 | if (!graph.containsKey(start) || !graph.containsKey(dest)) 27 | { 28 | System.out.println("No such nodes in the graph."); 29 | } 30 | else 31 | { 32 | graph.get(start).add(dest); 33 | graph.get(dest).add(start); 34 | } 35 | } 36 | 37 | public void removeEdge(T start, T dest) 38 | { 39 | if (!graph.containsKey(start) || !graph.containsKey(dest)) 40 | { 41 | System.out.println("No such nodes in the graph."); 42 | } 43 | else 44 | { 45 | graph.get(start).remove(dest); 46 | graph.get(dest).remove(start); 47 | } 48 | } 49 | 50 | public boolean isEdgeExists(T start, T end) 51 | { 52 | if (!graph.containsKey(start) || !graph.containsKey(end)) 53 | { 54 | System.out.println("No such nodes in the graph."); 55 | } 56 | 57 | return graph.get(start).contains(end); 58 | } 59 | 60 | public Set getNeighbors(T node) 61 | { 62 | Set neighbors = graph.get(node); 63 | 64 | if (neighbors == null) 65 | { 66 | System.out.println("No such nodes in the graph."); 67 | } 68 | 69 | return Collections.unmodifiableSet(neighbors); 70 | } 71 | 72 | public Iterator iterator() 73 | { 74 | return graph.keySet().iterator(); 75 | } 76 | 77 | public Iterable getNodes() 78 | { 79 | return graph.keySet(); 80 | } 81 | 82 | public int size() 83 | { 84 | return graph.size(); 85 | } 86 | 87 | public boolean isEmpty() 88 | { 89 | return graph.isEmpty(); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /UnsortedArray.java: -------------------------------------------------------------------------------- 1 | package algorithms; 2 | 3 | import java.util.ArrayList; 4 | 5 | 6 | /** 7 | * Determines which number is missing from an unsorted array of values 1-100. 8 | * Iterate through the array and compute the sum of all numbers. 9 | * Now, sum of natural numbers from 1 to N, can be expressed as N(N+1)/2. In your case N=100. 10 | * Subtract the sum of the array from N(N+1)/2, where N=100. 11 | * 12 | * Complexity: O(n) 13 | * 14 | * @author joeytawadrous 15 | */ 16 | public class UnsortedArray 17 | { 18 | public static void main(String[] args) 19 | { 20 | ArrayList list = new ArrayList(); 21 | 22 | for(int i = 0; i < 101; i++) // leave 100 out 23 | { 24 | if(i != 77) 25 | { 26 | list.add(i); 27 | } 28 | } 29 | 30 | getMissingNumber(list); 31 | getMissingNumber2(); 32 | } 33 | 34 | /** 35 | * Prints the missing number in a list of numbers. 36 | * @param list 37 | */ 38 | public static void getMissingNumber(ArrayList list) 39 | { 40 | int sum = 0; 41 | 42 | for (int i = 0; i < list.size(); i++) 43 | { 44 | sum += list.get(i); 45 | } 46 | 47 | // the total sum of numbers between 1 and arr.length. 48 | int total = (list.size() + 1) * list.size() / 2; 49 | 50 | System.out.println("Missing number is: " + (total - sum)); 51 | } 52 | 53 | /** 54 | * Prints the missing number in an array of numbers. 55 | */ 56 | public static void getMissingNumber2() 57 | { 58 | int[] arr = {1,2,3,5}; 59 | 60 | int indexes = 5; 61 | int values = 0; 62 | 63 | for (int i = 0; i < arr.length; i++) 64 | { 65 | indexes += i + 1; 66 | values += arr[i]; 67 | } 68 | 69 | int result = indexes - values; 70 | 71 | System.out.println("Missing number is: " + result); 72 | } 73 | } 74 | --------------------------------------------------------------------------------