├── .gitignore ├── Computational Geometry ├── GrahamScan.java ├── JarvisMarch.java └── README.md ├── DP ├── Edit_Distance.java ├── Knapsack.java ├── LCS.java ├── README.md └── maxDonations.java ├── Data Structures ├── BinaryTree.java ├── Binary_Indexed_Tree.java ├── Edge.java ├── Graphs.java ├── README.md ├── Tree.java └── Vertex.java ├── GoogleCodeJam ├── ABBA.java ├── Alphabet_Cake.java ├── BFCalculator.java ├── Bathroom_Stalls.java ├── Close_Match.java ├── Coin_Jam.java ├── Counting_Sheep.java ├── CrossOver.java ├── Digits.java ├── Oversized_Pancake_Flipper.java ├── Pancakes.java ├── Prison_Break.java ├── README.md ├── Solution.java ├── Super_Substrings.java └── Tidy_Numbers.java ├── Graph ├── BFS.java ├── Bellman_Ford.java ├── DFS.java ├── Dijkstra.java ├── Edge.java ├── Floyd_Warshall.java ├── Ford_Fulkerson.java ├── Graph_Traversal.java ├── Graphs.java ├── Johnson ├── Karger.java ├── Prim.java ├── README.md └── Vertex.java ├── LICENSE ├── Math └── README.md ├── Miscellaneous ├── Fisher_Yates.java ├── Matrix_Exponentiation.java ├── README.md └── Subarray_Inversions.java ├── Optimization ├── LightConfigurationOptimization.java ├── LightConfigurationOptimizationSA.java ├── LocationalOptimizationIterative.java └── README.md ├── ProjectEuler ├── Amicable_numbers.java ├── Coded_triangle_numbers.java ├── Collatz_sequence.java ├── Combinatoric_selections.java ├── Concealed_square.java ├── Consecutive_distinct_prime_factors.java ├── Counting_sundays.java ├── Digit_factorials.java ├── Digit_fifth_power.java ├── Distinct_powers.java ├── Even_fibonacci_sum.java ├── Factorial_digit_sum.java ├── Grid_product_maximum.java ├── Highly_divisible_triangular.java ├── Large_sum.java ├── Largest_consecutive_product.java ├── Lexicogrphic_permutations.java ├── MATH_TOOLBOX.java ├── Names_scores.java ├── Nontrivial_digit_cancelling_fractions.java ├── Nth_digit_powers.java ├── Number_letter_counts.java ├── PLAYGROUND.java ├── Pandigital_prime.java ├── Permuted_multiples.java ├── Prime_Summation.java ├── Prime_factorization.java ├── Pythagorean_triplet.java ├── README.md ├── Reverse_message.java ├── Smallest_multiple.java ├── Square_digit_chains.java ├── Thousand_digit_fibonacci.java ├── Totient_maximum.java ├── Totient_permutations.java └── primes.java ├── README.md ├── Searching └── README.md ├── Sorting ├── Bogosort.java ├── Bubble_Sort.java ├── Counting_Sort.java ├── Heapsort.java ├── Insertion_Sort.java ├── Mergesort.java ├── Quicksort.java ├── README.md ├── Radix_Sort.java ├── Selection_Sort.java ├── Sorting.java └── Timsort.java ├── Strings ├── Boyer_Moore.java ├── KMP.java ├── Naive_String_Searching.java ├── README.md ├── Rabin_Karp.java ├── String_Algorithms.java ├── Strings_d.in └── Strings_random.in └── USACO ├── AngryCows.java ├── AngryCows2.java ├── BovineGenomics.java ├── BovineGenomics_bruteforce.java ├── BuildGates.java ├── CircularBarn.java ├── CowCode.java ├── CowDanceShow.java ├── CowTip.java ├── FencePainting.java ├── HPS.java ├── Haybales.java ├── HoofPaperScissors.java ├── LoadBalancing.java ├── MilkPails.java ├── ModernArt.java ├── ModernArt2.java ├── ModernArt2_bruteforce.java ├── MowingField.java ├── NotLast.java ├── PromotionCounting.java ├── README.md ├── SeqSum7.java ├── asdf.java ├── friday.java ├── gift1.java ├── marathon.java ├── reorder.java ├── ride.java ├── sample.java └── test.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | -------------------------------------------------------------------------------- /Computational Geometry/GrahamScan.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Stack; 3 | 4 | public class GrahamScan { 5 | 6 | /*Graham's Scan 7 | 8 | Problem (informal): Find convex hull surrounding a set of points 9 | 10 | Algorithm: Find lowest point and sort remaining points by polar angle, push onto stack if left turn 11 | 12 | Complexity: 13 | * Time - O(nlogn) due to sorting; actual online algorithm is linear 14 | * Space - O(n) to store set of points 15 | 16 | Functions Defined: 17 | * graham() - Graham's scan algorithm 18 | * polarbubblesort() - Sorts points in order of increasing polar angle from minimum 19 | * angle() - Computes angle between two lines given by three points 20 | * dot() - computes dot product between two vectors to easily find angle 21 | * norm() - computes magnitude of a vector 22 | * cross() - finds cross product between two vectors to determine angle concavity 23 | * d() - distance function, computes distance between two poitns 24 | 25 | */ 26 | 27 | public static void main(String[] args) { 28 | //test set of points 29 | int[][] points = {{0, -2}, {2, 0}, {2, 20}, {1, 1}, {1, 2}, {-2, 0}, {-1, -1}}; 30 | 31 | 32 | //Graham's Scan 33 | Stack s = graham(points); 34 | for(int[] x : s){ 35 | System.out.println(Arrays.toString(x)); 36 | } 37 | } 38 | 39 | //Currently O(n^2) because of inefficient polar sort; use O(nlogn) sort to improve 40 | public static Stack graham(int[][] points){ 41 | Stack stack = new Stack(); 42 | 43 | //find lowest point -- guaranteed to be included in 44 | int minindex = 0; 45 | for(int i=0;i= 180){ 67 | stack.pop(); 68 | } 69 | stack.push(points[i]); 70 | } 71 | return stack; 72 | } 73 | 74 | //O(n^2) TIME, O(1) SPACE, STABLE 75 | //Improve to O(nlogn) 76 | public static int[][] polarbubblesort(int[][] arr, int[] min, int[] parmin){ 77 | for(int i=0;i 0) 102 | val = 360 - val; 103 | 104 | return val; 105 | } 106 | 107 | public static double dot(int[] v1, int[] v2){ 108 | return v1[0]*v2[0] + v1[1]*v2[1]; 109 | } 110 | 111 | public static double norm(int[] v){ 112 | return Math.sqrt(v[0]*v[0] + v[1]*v[1]); 113 | } 114 | 115 | public static int cross(int[] v1, int[] v2){ 116 | return v1[0]*v2[1] - v2[0]*v1[1]; 117 | } 118 | 119 | public static double d(int[] a, int[] b){ 120 | return Math.sqrt(Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2)); 121 | } 122 | 123 | } -------------------------------------------------------------------------------- /Computational Geometry/JarvisMarch.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Stack; 3 | 4 | public class JarvisMarch { 5 | 6 | /*Jarvis March 7 | 8 | Problem (informal): Find convex hull surrounding a set of points 9 | 10 | Algorithm: Find lowest point and highest points, simulate wrapping string tightly around points 11 | 12 | Complexity: 13 | * Time - O(nh) where n is number of points and h is number of points on convex hull 14 | * Space - O(n) to store set of points 15 | 16 | Functions Defined: 17 | * jarvis() - Jarvis march algorithm 18 | * angle() - Computes angle between two lines given by three points 19 | * dot() - computes dot product between two vectors to easily find angle 20 | * norm() - computes magnitude of a vector 21 | * cross() - finds cross product between two vectors to determine angle concavity 22 | * d() - distance function, computes distance between two poitns 23 | 24 | */ 25 | 26 | public static void main(String[] args) { 27 | //test set of points 28 | int[][] points = {{0, -2}, {2, 0}, {2, 20}, {1, 1}, {1, 2}, {-2, 0}, {-1, -1}}; 29 | 30 | 31 | //Graham's Scan 32 | Stack s = jarvis(points); 33 | for(int[] x : s){ 34 | System.out.println(Arrays.toString(x)); 35 | } 36 | } 37 | 38 | //Jarvis March algorithm 39 | public static Stack jarvis(int[][] points){ 40 | Stack stack = new Stack(); 41 | 42 | //find lowest & highest points -- guaranteed to be included in convex hull 43 | int minindex = 0, maxindex = 0; 44 | for(int i=0;i points[maxindex][1]) 48 | maxindex = i; 49 | } 50 | 51 | int chain = 1; 52 | stack.push(points[minindex]); 53 | int lastindex = minindex; 54 | while(lastindex != minindex || stack.size() == 1){ 55 | int[] parmin = {points[lastindex][0] + chain, points[lastindex][1]}; 56 | double minangle = 361; 57 | int nextindex = 0; 58 | 59 | for(int i=0; i < points.length; i++){ 60 | if(i == lastindex) continue; 61 | double angle = angle(points[i], points[lastindex], parmin); 62 | if(angle < minangle){ 63 | minangle = angle; 64 | nextindex = i; 65 | } 66 | } 67 | stack.push(points[nextindex]); 68 | lastindex = nextindex; 69 | if(lastindex == maxindex){ 70 | chain = -1; 71 | } 72 | } 73 | stack.pop(); 74 | return stack; 75 | 76 | } 77 | 78 | 79 | public static double angle(int[] a, int[] b, int[] c){ 80 | 81 | int[] v1 = {a[0] - b[0], a[1] - b[1]}; 82 | int[] v2 = {c[0] - b[0], c[1] - b[1]}; 83 | 84 | double val = Math.acos(dot(v1, v2)/(norm(v1)*norm(v2)))*180/Math.PI; 85 | 86 | if(cross(v1, v2) > 0) 87 | val = 360 - val; 88 | 89 | return val; 90 | } 91 | 92 | public static double dot(int[] v1, int[] v2){ 93 | return v1[0]*v2[0] + v1[1]*v2[1]; 94 | } 95 | 96 | public static double norm(int[] v){ 97 | return Math.sqrt(v[0]*v[0] + v[1]*v[1]); 98 | } 99 | 100 | public static int cross(int[] v1, int[] v2){ 101 | return v1[0]*v2[1] - v2[0]*v1[1]; 102 | } 103 | 104 | public static double d(int[] a, int[] b){ 105 | return Math.sqrt(Math.pow(b[0] - a[0], 2) + Math.pow(b[1] - a[1], 2)); 106 | } 107 | 108 | } -------------------------------------------------------------------------------- /Computational Geometry/README.md: -------------------------------------------------------------------------------- 1 | # Computational Geometric Algorithms 2 | ## Convex Hull 3 | * [Graham's Scan](https://github.com/jpa99/Algorithms/blob/master/Computational%20Geometry/GrahamScan.java) 4 | * [Jarvis March](https://github.com/jpa99/Algorithms/blob/master/Computational%20Geometry/JarvisMarch.java) 5 | -------------------------------------------------------------------------------- /DP/Edit_Distance.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Edit_Distance { 4 | 5 | /*Edit (Levenshtein Distance) Algorithm 6 | 7 | Problem (informal): Given two strings, find minimum number of deletions, insertions, or replacements required to transform 8 | 9 | Algorithm: If characters are same, continue, else, consider removal, deletion, and replacement and consider minimum recursively 10 | 11 | Complexity: 12 | * Time - O(n^2) 13 | * Space - O(n^2) with memoization and O(1) without 14 | 15 | Functions Defined: 16 | * editDistanceIterative() - Bottom up implementation, finds minimum iteratively 17 | * editDistanceRecursive() - Top down implementation, recursive 18 | 19 | */ 20 | 21 | static int[][] dp; 22 | public static void main(String[] args) { 23 | String a = "hey if you like this repository, you should give it a star!"; 24 | String b = "I'd appreciate any feedback or requests -- just fork this repo and add to the README.md"; 25 | 26 | dp = new int [a.length()+1][b.length()+1]; 27 | 28 | for(int[] row :dp){ 29 | Arrays.fill(row, -1); 30 | } 31 | 32 | System.out.println(editDistanceIterative(a, b)); 33 | System.out.println(editDistanceTD(a, b)); 34 | 35 | } 36 | 37 | public static int editDistanceIterative(String a, String b){ 38 | int[][] dp = new int[a.length()+1][b.length()+1]; 39 | for(int i=0; i <= a.length();i++){ 40 | for(int j=0; j <= b.length();j++){ 41 | if(i==0 || j==0) 42 | dp[i][j] = i+j; 43 | else if(a.charAt(i-1) == b.charAt(j-1)) 44 | dp[i][j] = dp[i-1][j-1]; 45 | else 46 | dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]); 47 | } 48 | } 49 | return dp[a.length()][b.length()]; 50 | } 51 | 52 | //minimal # of insertions, substitutions, deletions required to change String a to b 53 | public static int editDistanceTD(String a, String b){ 54 | int m = a.length(); 55 | int n = b.length(); 56 | if(dp[m][n] !=-1){ 57 | return dp[m][n]; 58 | } 59 | if(m==0 || n==0){ 60 | dp[m][n] = m+n; 61 | return dp[m][n]; 62 | } 63 | if(a.charAt(m-1) == b.charAt(n-1)){ 64 | dp[m][n] = editDistanceTD(a.substring(0, m-1), b.substring(0, n-1)); 65 | return dp[m][n]; 66 | } 67 | dp[m][n] = 1 + Math.min(Math.min(editDistanceTD(a.substring(0, m-1), b), editDistanceTD(a, b.substring(0, n-1))), editDistanceTD(a.substring(0, m-1), b.substring(0, n-1))); 68 | return dp[m][n]; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /DP/Knapsack.java: -------------------------------------------------------------------------------- 1 | import cern.colt.Arrays; 2 | import java.util.*; 3 | 4 | public class Knapsack { 5 | 6 | /*0-1 Knapsack Probelm 7 | 8 | Problem (informal): Given set of items with cost and weight, find subset of items such that net weight does not exceed W and set has maximum total cost 9 | 10 | Algorithm: Recursive -- try each possible item and calculate max of remaining 11 | 12 | Complexity: 13 | * Time - O(nW) where W is the maximum weight possible 14 | * Space - O(n) only one array for number of items. 15 | 16 | Functions Defined: 17 | * knapsackTD() - Recursively consideres one less item and maximum of remaining subset 18 | * fractionalknapsack() - Pretty trivial -- greedy algorithm suffices. Solved in O(nlogn) but also possible in O(n) via weighted medians 19 | 20 | */ 21 | static int[][] items; 22 | static int maxweight; 23 | public static void main(String[] args){ 24 | int[][] itemsx = {{60, 10}, {100, 20}, {120, 30}}; 25 | //{cost, weight} 26 | items = itemsx; 27 | maxweight = 50; 28 | boolean[] insert = new boolean[items.length]; 29 | //System.out.println(knapsackBU(items, maxweight)); 30 | System.out.println(knapsackTD(maxweight, insert)); 31 | } 32 | 33 | public static int knapsackTD(int maxweight, boolean[] insert){ 34 | int max = 0; 35 | for(int i=0;i= items[i][1]){ 37 | boolean[] insertclone = insert.clone(); 38 | insertclone[i] = true; 39 | max = Math.max(items[i][0] + knapsackTD(maxweight - items[i][1], insertclone), max); 40 | } 41 | } 42 | return max; 43 | } 44 | 45 | public static void fractionalknapsack(){ 46 | //greedy 47 | //I don't think it's necessary to implement this since it's pretty straightforward. 48 | //Just find the item with largest cost and take as much of it as possible. If you take all of it, continue to next largest. 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /DP/LCS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import cern.colt.Arrays; 3 | 4 | public class LCS { 5 | 6 | /*Longest Common Subsequence (LCS) 7 | 8 | Problem (informal): Given two arrays, find largest subsequence of both arrays 9 | 10 | Algorithm: If elements at position i are equal, find LCS of subarrays [0, i-1], else find max of both possible cases 11 | 12 | Complexity: 13 | * Time - O(n^2) 14 | * Space - O(n^2) with memoization and O(1) without 15 | 16 | Functions Defined: 17 | * iterativeLCS() - Bottom up implementation, finds longest length and reconstructs sequence 18 | * recursiveLCS() - Top down implementation, only outputs length of sequence 19 | 20 | */ 21 | 22 | static int[] arr1; 23 | static int[] arr2; 24 | static int[][] dp; 25 | 26 | static Stack solution = new Stack(); 27 | public static void main(String[] args) { 28 | int[] arrA = {1, 2, 3, 4, 7, 5, 9}; 29 | int[] arrB = {1, 4, 3, 7, 9, 5}; 30 | 31 | arr1 = arrA; 32 | arr2 = arrB; 33 | 34 | System.out.println(Arrays.toString(iterativeLCS(arrA, arrB))); 35 | 36 | } 37 | 38 | public static int[] iterativeLCS(int[] a, int[] b){ 39 | int[][] dp = new int[a.length+1][b.length+1]; 40 | for(int i = 1; i <= a.length; i++){ 41 | for(int j = 1; j <= b.length; j++){ 42 | if(a[i-1] == b[j-1]){ 43 | dp[i][j] = 1 + dp[i-1][j-1]; 44 | } 45 | else{ 46 | dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); 47 | } 48 | } 49 | } 50 | 51 | int[] lcs = new int[dp[a.length][b.length]]; 52 | int index = lcs.length-1; 53 | int i=a.length; int j = b.length; 54 | 55 | while(i > 0 && j > 0){ 56 | if(a[i-1] == b[j-1]){ 57 | lcs[index] = a[i-1]; 58 | i--; j--; index--; 59 | } 60 | else if(dp[i-1][j] >= dp[i][j-1]) 61 | i--; 62 | else 63 | j--; 64 | } 65 | 66 | return lcs; 67 | } 68 | 69 | public static int recursiveLCS(int a, int b){ 70 | if(a < 0 || b < 0) return 0; 71 | 72 | if(arr1[a] == arr2[b]){ 73 | solution.push(arr1[a]); 74 | dp[a][b] = 1 + recursiveLCS(a-1, b-1); 75 | return dp[a][b]; 76 | } 77 | int opt1 = recursiveLCS(a, b-1); 78 | int opt2 = recursiveLCS(a-1, b); 79 | 80 | if(opt1 >= opt2){ 81 | dp[a][b] = opt1; 82 | } 83 | 84 | else{ 85 | dp[a][b] = opt2; 86 | } 87 | 88 | return dp[a][b]; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /DP/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming Algorithms 2 | 3 | * [0-1 Knapsack](https://github.com/jpa99/Algorithms/blob/master/DP/Knapsack.java) 4 | * [Edit (Levenshtein) Distance](https://github.com/jpa99/Algorithms/blob/master/DP/Edit_Distance.java) 5 | * Longest Increasing Subsequence 6 | * [Longest Common Subsequence](https://github.com/jpa99/Algorithms/blob/master/DP/LCS.java) 7 | * [Maximum Nonadjacent Subset Sum](https://github.com/jpa99/Algorithms/blob/master/DP/maxDonations.java) 8 | * Maximum Subset Sum 9 | -------------------------------------------------------------------------------- /DP/maxDonations.java: -------------------------------------------------------------------------------- 1 | 2 | public class maxDonations { 3 | 4 | /*Maximum Donations (Topcoder) 5 | 6 | Problem (informal): Given set S of values, find subset Q of values with maximum sum such that no two values in Q are adjacent in S 7 | 8 | Algorithm: Recursive -- two possibilities at each branch, test both 9 | 10 | Complexity: 11 | * Time - O(n^2) - each branches off into two possibilities 12 | * Space - O(n^2) due to DP array 13 | 14 | Functions Defined: 15 | * maxDonations() - main algorithm 16 | */ 17 | 18 | static int[] arr; 19 | static int len; 20 | static int[][] dp; 21 | 22 | public static void main(String[] args) { 23 | int[] arr2 = {10, 3, 2, 5, 7, 8}; 24 | //{10, 4, 5} 25 | arr = arr2; 26 | len = arr.length; 27 | dp = new int[len][len]; 28 | 29 | 30 | 31 | 32 | } 33 | 34 | public static int maxDonations(int start, int end){ 35 | if(end - start ==2) return Math.max(Math.max(arr[start], arr[end]), arr[start+1]); 36 | if(end - start <=1) return Math.max(arr[start], arr[end]); 37 | 38 | int start1 = (start+1)%len; 39 | 40 | int val = arr[start]; 41 | int start2 = start, end2 = end; 42 | if(start == 0){ 43 | start2+=2; 44 | 45 | } 46 | else{ 47 | start2+=2; 48 | } 49 | dp[start][end] = Math.max(maxDonations(start1, end), val + maxDonations(start2, end2)); 50 | return dp[start][end]; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Data Structures/BinaryTree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.Arrays; 3 | 4 | public class BinaryTree { 5 | 6 | public static void main(String[] args) { 7 | 8 | //Initialize tree manually 9 | BinaryTreeNode root = new BinaryTreeNode(1); 10 | root.leftChild = new BinaryTreeNode(3); 11 | root.rightChild = new BinaryTreeNode(8); 12 | root.rightChild.rightChild = new BinaryTreeNode(4); 13 | System.out.println(balance(root)); 14 | 15 | //Initialize and balance tree from array 16 | int[] BinaryTreeArray = {1, 4, 3, 5, 6, 8, 2, 12, 4, 15, 6, 9}; 17 | BinaryTreeNode tree = createBinaryTree(BinaryTreeArray); 18 | System.out.println(tree); 19 | System.out.println(balance(tree)); 20 | 21 | } 22 | 23 | public static BinaryTreeNode createBinaryTree(int[] binaryTreeArray){ 24 | if(binaryTreeArray.length == 0) return null; 25 | if(binaryTreeArray.length == 1) return new BinaryTreeNode((int) binaryTreeArray[0]); 26 | int mid = (binaryTreeArray.length)/2; 27 | BinaryTreeNode root = new BinaryTreeNode((int) binaryTreeArray[mid]); 28 | root.rightChild = createBinaryTree(Arrays.copyOfRange(binaryTreeArray, mid+1, binaryTreeArray.length)); 29 | root.leftChild = createBinaryTree(Arrays.copyOfRange(binaryTreeArray, 0, mid)); 30 | return root; 31 | } 32 | 33 | // 34 | public static BinaryTreeNode balance(BinaryTreeNode tree){ 35 | return createBinaryTree(tree.toArray()); 36 | } 37 | 38 | 39 | //TreeNode data structure 40 | static class BinaryTreeNode{ 41 | public int val = -1; 42 | public BinaryTreeNode leftChild; 43 | public BinaryTreeNode rightChild; 44 | 45 | public BinaryTreeNode(int val){ 46 | this.val = val; 47 | leftChild = null; 48 | rightChild = null; 49 | } 50 | 51 | public String toString(){ 52 | String left = leftChild == null ? "":leftChild.toString(); 53 | String right = rightChild == null ? "":rightChild.toString(); 54 | return val+" "+left+right; 55 | } 56 | 57 | public ArrayList toArrayList(){ 58 | ArrayList left = leftChild == null ? new ArrayList():leftChild.toArrayList(); 59 | ArrayList right = rightChild == null ? new ArrayList():rightChild.toArrayList(); 60 | ArrayList list = new ArrayList(); 61 | list.add(val); 62 | list.addAll(left); 63 | list.addAll(right); 64 | return list; 65 | } 66 | 67 | public int[] toArray(){ 68 | return toArrayList().stream().mapToInt(i -> i).toArray(); 69 | } 70 | } 71 | 72 | 73 | 74 | } 75 | 76 | 77 | -------------------------------------------------------------------------------- /Data Structures/Binary_Indexed_Tree.java: -------------------------------------------------------------------------------- 1 | public class Binary_Indexed_Tree { 2 | 3 | public static void main(String[] args) throws IOException { 4 | //testting BIT 5 | BIT bit = new BIT(12); 6 | bit.update(4, 1); 7 | bit.update(3, 1); 8 | bit.update(5, 1); 9 | bit.update(2, 1); 10 | bit.update(5, 1); 11 | bit.update(4, -1); 12 | int a = bit.read(9); 13 | System.out.println(a); 14 | 15 | } 16 | 17 | static class BIT{ 18 | int[] binary_indexed_tree; 19 | int maxVal; 20 | 21 | public BIT(int n){ 22 | binary_indexed_tree = new int[++n]; 23 | maxVal = n; 24 | } 25 | 26 | public void update(int index, int val){ 27 | while (index <= maxVal){ 28 | tree[index] += val; 29 | index += (index & -index); //last bit removal 30 | } 31 | } 32 | 33 | //Returns the cumulative frequency of index index 34 | public int read(int index){ 35 | int sum=0; 36 | while (index>0){ 37 | sum += tree[index]; 38 | index -= (index & -index); 39 | } 40 | return sum; 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Data Structures/Edge.java: -------------------------------------------------------------------------------- 1 | 2 | public class Edge { 3 | 4 | //Edge class with built in functions; used for Graph class 5 | 6 | private int weight; 7 | private Vertex v1; 8 | private Vertex v2; 9 | private boolean directed=false; 10 | 11 | public Edge(int weight, int value1, int value2){ 12 | this.weight=weight; 13 | v1=new Vertex(value1); 14 | v2=new Vertex(value2); 15 | } 16 | 17 | public Edge(int weight, int value1, int value2, boolean directed){ 18 | this.weight=weight; 19 | v1=new Vertex(value1); 20 | v2=new Vertex(value2); 21 | directed=true; 22 | } 23 | 24 | //returns whether or not the edge is incident to the input vertex 25 | public boolean incident(int vertex){ 26 | return vertex==v1.getValue() || vertex==v2.getValue(); 27 | } 28 | 29 | public Vertex getVertex1(){ 30 | return v1; 31 | } 32 | 33 | public Vertex getVertex2(){ 34 | return v2; 35 | } 36 | 37 | public int getWeight(){ 38 | return weight; 39 | } 40 | 41 | public boolean getDirected(){ 42 | return directed; 43 | } 44 | 45 | public void makeDirected(){ 46 | directed=true; 47 | } 48 | 49 | public void swap(){ 50 | Vertex temp=v2; 51 | v2=v1; 52 | v1=temp; 53 | } 54 | 55 | public String toString(){ 56 | return weight+"["+v1+","+v2+"]"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Data Structures/Graphs.java: -------------------------------------------------------------------------------- 1 | 2 | public class Graphs { 3 | 4 | //Graph class with certain built in algorithms 5 | 6 | private Edge[] edges; 7 | private Vertex[] vertices; 8 | 9 | public Graphs(Vertex[] vertices, Edge[] edges){ 10 | this.vertices=vertices; 11 | this.edges=edges; 12 | } 13 | 14 | //Returns whether or not graph contains input vertex 15 | public boolean hasVertex(Vertex v){ 16 | for(Vertex vertex:vertices){ 17 | if(vertex.getValue()==v.getValue()){ 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | 24 | //returns sum of edge weights in graph 25 | public int getCost(){ 26 | int sum=0; 27 | for(Edge e:edges){ 28 | sum+=e.getWeight(); 29 | } 30 | return sum; 31 | } 32 | 33 | public Edge[] getEdges(){ 34 | return edges; 35 | } 36 | 37 | public String[] vertex(){ 38 | String[] v= new String[vertices.length]; 39 | for(int i=0;i tree = new Node("Parent"); 7 | 8 | tree.add(new Node("child")); 9 | tree.getChildren().get(0); 10 | 11 | } 12 | public static class Node { 13 | private List> children = new ArrayList>(); 14 | private Node parent = null; 15 | private T data = null; 16 | 17 | public Node(T data) { 18 | this.data = data; 19 | } 20 | 21 | public Node(T data, Node parent) { 22 | this.data = data; 23 | this.parent = parent; 24 | } 25 | 26 | public List> getChildren() { 27 | return children; 28 | } 29 | 30 | public void setParent(Node parent) { 31 | parent.add(this); 32 | this.parent = parent; 33 | } 34 | 35 | public void add(T data) { 36 | Node child = new Node(data); 37 | child.setParent(this); 38 | this.children.add(child); 39 | } 40 | 41 | public void add(Node child) { 42 | child.setParent(this); 43 | this.children.add(child); 44 | } 45 | 46 | public T data() { 47 | return this.data; 48 | } 49 | 50 | public void setData(T data) { 51 | this.data = data; 52 | } 53 | 54 | public boolean isRoot() { 55 | return (this.parent == null); 56 | } 57 | 58 | public boolean isLeaf() { 59 | return this.children.size() == 0; 60 | } 61 | 62 | public void removeParent() { 63 | this.parent = null; 64 | } 65 | } 66 | 67 | 68 | public class Graph { 69 | 70 | private Edge[] edges; 71 | private Vertex[] vertices; 72 | 73 | public Graph(Vertex[] vertices, Edge[] edges){ 74 | this.vertices=vertices; 75 | this.edges=edges; 76 | } 77 | 78 | //Returns whether or not graph contains input vertex 79 | public boolean hasVertex(Vertex v){ 80 | for(Vertex vertex:vertices){ 81 | if(vertex.getValue()==v.getValue()){ 82 | return true; 83 | } 84 | } 85 | return false; 86 | } 87 | 88 | //returns sum of edge weights in graph 89 | public int getCost(){ 90 | int sum=0; 91 | for(Edge e:edges){ 92 | sum+=e.getWeight(); 93 | } 94 | return sum; 95 | } 96 | 97 | public Edge[] getEdges(){ 98 | return edges; 99 | } 100 | 101 | public String[] vertex(){ 102 | String[] v= new String[vertices.length]; 103 | for(int i=0;iinitial.length()){ 14 | String ch=""; 15 | int len=target.length(); 16 | if(fwd){ 17 | ch=target.substring(len-1); 18 | target=target.substring(0, len-1); 19 | } 20 | else{ 21 | ch=target.substring(0, 1); 22 | target=target.substring(1); 23 | } 24 | if(ch.equals("B")){ 25 | fwd=!fwd; 26 | } 27 | } 28 | 29 | if(fwd && initial.equals(target)) 30 | return "possible"; 31 | else if(!fwd){ 32 | int l=target.length(); 33 | for(int i=0;i nonfree=new ArrayList(); 22 | HashMap> map=new HashMap>(); 23 | for(int i=0;i ar=map.get(x); 29 | ar.add(asdf); 30 | map.put(x, ar); 31 | } 32 | } 33 | 34 | Iterator>> it = map.entrySet().iterator(); 35 | while (it.hasNext()) { 36 | Map.Entry> pair = (Map.Entry>)it.next(); 37 | ArrayList arr=pair.getValue(); 38 | char cc=pair.getKey(); 39 | it.remove(); 40 | 41 | boolean h=false, v=false; 42 | for(int k=1;k 1){ 44 | int sr=arr.get(0)[0], er=arr.get(arr.size())[0]; 45 | int sc=arr.get(0)[1], ec=arr.get(arr.size())[1]; 46 | 47 | break; 48 | } 49 | if(Math.abs(arr.get(k)[1]-arr.get(k-1)[1]) > 1){ 50 | int sr=arr.get(0)[0], er=arr.get(arr.size())[0]; 51 | int sc=arr.get(0)[1], ec=arr.get(arr.size())[1]; 52 | break; 53 | } 54 | } 55 | 56 | 57 | if(!(v || h)) 58 | continue; 59 | 60 | int sr=arr.get(0)[0], er=arr.get(arr.size())[0]; 61 | int sc=arr.get(0)[1], ec=arr.get(arr.size())[1]; 62 | for(int[] p:pair.getValue()){ 63 | cake[p[0]][p[1]]=cc; 64 | } 65 | 66 | } 67 | 68 | 69 | 70 | String output="Case #"+cases+": "; 71 | System.out.println(output); 72 | writer.println(output); 73 | } 74 | 75 | writer.close(); 76 | } 77 | 78 | //Print line 79 | public static void print(T t){ 80 | System.out.println(t); 81 | } 82 | 83 | //Optimized Scanner Class, includes next String, int, Long, double, line 84 | static class Scan{ 85 | BufferedReader br; 86 | StringTokenizer st; 87 | 88 | public Scan(String file) throws IOException{ 89 | br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); 90 | 91 | } 92 | 93 | String next(){ 94 | while (st == null || !st.hasMoreElements()){ 95 | try{ 96 | st = new StringTokenizer(br.readLine()); 97 | } 98 | catch (IOException e){ 99 | e.printStackTrace(); 100 | } 101 | } 102 | return st.nextToken(); 103 | } 104 | 105 | int nextInt(){ 106 | return Integer.parseInt(next()); 107 | } 108 | 109 | long nextLong(){ 110 | return Long.parseLong(next()); 111 | } 112 | 113 | double nextDouble(){ 114 | return Double.parseDouble(next()); 115 | } 116 | 117 | String nextLine(){ 118 | String str = ""; 119 | try{ 120 | str = br.readLine(); 121 | } 122 | catch (IOException e){ 123 | e.printStackTrace(); 124 | } 125 | return str; 126 | } 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /GoogleCodeJam/BFCalculator.java: -------------------------------------------------------------------------------- 1 | 2 | public class BFCalculator { 3 | 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /GoogleCodeJam/Bathroom_Stalls.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.PrintWriter; 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Bathroom_Stalls { 7 | 8 | public static void main(String[] args) throws Exception{ 9 | Scanner scan=new Scanner(new File("bathroom.in")); 10 | PrintWriter writer=new PrintWriter(new File("output.txt")); 11 | 12 | int numCases=scan.nextInt(); 13 | for(int cases=1;cases<=numCases;cases++){ 14 | int n=scan.nextInt(); 15 | int k=scan.nextInt(); 16 | k++; 17 | boolean[] stalls=new boolean[n+2]; 18 | stalls[0]=true; 19 | stalls[n+1]=true; 20 | for(int x=1;x<=n;x++){ 21 | stalls[x]=false; 22 | } 23 | 24 | //[true, false, false, false, true]// 25 | 26 | int[][] values=new int[n+2][2]; 27 | int[] arr={-1, -1}; 28 | values[0]=arr; 29 | values[n+1]=arr; 30 | int lastindex=0; 31 | while(--k>0){ 32 | int minimax=-1, maximax=-1, nummin=0, indexofmin=0, indexofmax=0; 33 | for(int i=1;i=0;j--){ 40 | if(stalls[j]) 41 | break; 42 | left++; 43 | } 44 | 45 | for(int j=i+1;j minimax){ 57 | minimax=Math.min(left, right); 58 | nummin=0; 59 | indexofmin=i; 60 | maximax=Math.max(left, right); 61 | indexofmax=i; 62 | 63 | } 64 | else if(Math.min(left, right) == minimax){ 65 | nummin++; 66 | if(Math.max(left, right) > maximax){ 67 | maximax=Math.max(left, right); 68 | indexofmax=i; 69 | } 70 | } 71 | 72 | 73 | } 74 | 75 | if(nummin==0){ 76 | stalls[indexofmin]=true; 77 | lastindex=indexofmin; 78 | } 79 | else{ 80 | stalls[indexofmax]=true; 81 | lastindex=indexofmax; 82 | } 83 | } 84 | int minimum=Math.min(values[lastindex][0], values[lastindex][1]); 85 | int maximum=Math.max(values[lastindex][0], values[lastindex][1]); 86 | 87 | 88 | System.out.printf("Case #%d: %d %d\n", cases, maximum, minimum); 89 | writer.printf("Case #%d: %d %d\n", cases, maximum, minimum); 90 | 91 | 92 | } 93 | writer.close(); 94 | scan.close(); 95 | 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /GoogleCodeJam/Close_Match.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.io.*; 3 | import java.time.*; 4 | import java.math.*; 5 | import java.awt.*; 6 | 7 | public class Close_Match { 8 | 9 | public static void main(String[] args) throws Exception{ 10 | Scanner scan= new Scanner(new File("input.txt")); 11 | PrintWriter writer=new PrintWriter(new File("output.txt")); 12 | int numinputs=scan.nextInt(); 13 | scan.nextLine(); 14 | 15 | for(int cases=1;cases<=numinputs;cases++){ 16 | String a=scan.nextLine(); 17 | String b=scan.nextLine(); 18 | String apat=a.replaceAll("\\*", ".{0,4}"); 19 | 20 | String bpat=b.replaceAll("\\*", ".{0,4}"); 21 | 22 | System.out.println(apat); 23 | System.out.println(bpat); 24 | System.out.println("bpat".matches(apat)); 25 | 26 | //String output="Case #"+cases+": "+"_____"; 27 | //System.out.println(output); 28 | //writer.println(output); 29 | } 30 | scan.close(); 31 | writer.close(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /GoogleCodeJam/Coin_Jam.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.util.stream.IntStream; 4 | 5 | public class Coin_Jam { 6 | 7 | public static void main(String[] args) throws Exception{ 8 | Scanner scan=new Scanner(new File("input.txt")); 9 | 10 | PrintWriter writer=new PrintWriter(new File("output.txt")); 11 | 12 | int t=scan.nextInt(); 13 | int len=scan.nextInt(); 14 | int numjams=scan.nextInt(); 15 | System.out.println("Case #1:"); 16 | //iterate through possibilities, test if jamcoin, 17 | int max=(int) Math.pow(2, len-2); 18 | int jams=0; 19 | for(int i=0;i x == -1)){ 32 | continue; 33 | } 34 | 35 | System.out.print(istring+" "); 36 | for(int el:nums){ 37 | System.out.print(el+" "); 38 | } 39 | System.out.println(); 40 | jams++;*/ 41 | } 42 | 43 | 44 | } 45 | public static int convert(String s, int base){ 46 | int num=0; 47 | int len=s.length()-1; 48 | if(len==0) 49 | return Integer.parseInt(s); 50 | if(s.substring(0, 1).equals("1")) 51 | return (int)Math.pow(base, len)+convert(s.substring(1), base); 52 | else 53 | return convert(s.substring(1), base); 54 | } 55 | 56 | //input String ofones and zeros, output is integer array of length 9 with index i corresponding to the divisor of the input in base i+2 57 | 58 | public static int[] out(String s){ 59 | int[] nums=new int[9]; 60 | for(int base=2;base<=10;base++){ 61 | int num=convert(s, base); 62 | nums[base-2]=-1; 63 | for(int x=2;x<=(int)(Math.sqrt(num))+1;x++){ 64 | if(num%x==0){ 65 | nums[base-2]=x; 66 | break; 67 | } 68 | } 69 | } 70 | return nums; 71 | } 72 | 73 | 74 | public static boolean isDiv(String n){ 75 | int numdivisors=0; 76 | for(int i=2;i<=10;i++){ 77 | int num=convert(n, i); 78 | for(int x=2;x<=(int)(Math.sqrt(num))+1;x++){ 79 | if(num%i==0){ 80 | numdivisors++; 81 | break; 82 | } 83 | } 84 | } 85 | if(numdivisors==9) 86 | return true; 87 | return false; 88 | } 89 | 90 | public static String divisors(String n){ 91 | String s=""; 92 | for(int i=2;i<=10;i++){ 93 | int num=convert(n, i); 94 | for(int x=2;x<=(int)(Math.sqrt(num))+1;x++){ 95 | if(num%i==0){ 96 | s+=String.valueOf(x)+" "; 97 | break; 98 | } 99 | } 100 | } 101 | return s; 102 | } 103 | 104 | //1001/ 105 | public static String binary_convert(int n, int len){ 106 | //return max power of 2 leq n 107 | if(n==0){ 108 | String s=""; 109 | for(int i=0;i int 121 | public static int convertss(String s, int base){ 122 | int num=0; 123 | int len=s.length()-1; 124 | if(len==0) 125 | return Integer.parseInt(s); 126 | if(s.substring(0, 1).equals("1")) 127 | return (int)Math.pow(base, len)+convert(s.substring(1), base); 128 | else 129 | return convert(s.substring(1), base); 130 | } 131 | 132 | public static String[] gen_bin_array(int len){ 133 | int n=(int) Math.pow(2, len-1); 134 | String[] arr=new String[n]; 135 | for(int i=0; i < n; i++){ 136 | arr[i]=binary_convert(i+n, 10); 137 | } 138 | return arr; 139 | } 140 | 141 | } 142 | -------------------------------------------------------------------------------- /GoogleCodeJam/Counting_Sheep.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class Counting_Sheep { 5 | 6 | public static void main(String[] args) throws Exception{ 7 | Scanner scan=new Scanner(new File("A-small-practice.in.txt")); 8 | PrintWriter writer=new PrintWriter(new File("countingsheep.out")); 9 | int n=scan.nextInt(); 10 | for(int i=1;i<=n;i++){ 11 | int num=scan.nextInt(); 12 | boolean possible=true; 13 | if(num==0){ 14 | possible=false; 15 | } 16 | String s=""; 17 | 18 | int mult=1; 19 | while(possible){ 20 | 21 | s+=String.valueOf(num); 22 | int con=0; 23 | for(int j=0;j<10;j++){ 24 | if(s.contains(String.valueOf(j))){ 25 | con++; 26 | } 27 | } 28 | 29 | mult++; 30 | num*=mult; 31 | num/=mult-1; 32 | 33 | if(con==10) 34 | break; 35 | } 36 | num*=mult-1; 37 | num/=mult; 38 | 39 | if(possible) 40 | writer.printf("Case #%d: %d\n", i, num); 41 | else 42 | writer.printf("Case #%d: INSOMNIA\n", i); 43 | 44 | 45 | } 46 | writer.close(); 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /GoogleCodeJam/CrossOver.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | public class CrossOver { 4 | 5 | public static void main(String[] args) throws Exception{ 6 | Scanner scan=new Scanner(new File("output.txt")); 7 | int n=scan.nextInt(); 8 | int[] stocks=new int[n]; 9 | double[] LTMA=new double[n+1]; 10 | double[] STMA=new double[n+1]; 11 | 12 | //instantiates with first 300 ints, and scans 13 | int ltma_hash=0, stma_hash=0; 14 | for(int i=1;i<=300;i++){ 15 | stocks[i-1]=scan.nextInt(); 16 | ltma_hash+=stocks[i-1]; 17 | if(i>=241) 18 | stma_hash+=stocks[i-1]; 19 | } 20 | 21 | LTMA[300]=Math.round(100.0*ltma_hash/300.0)/100.0; 22 | STMA[300]=Math.round(100.0*stma_hash/60.0)/100.0; 23 | for(int i=301;i LTMA[i-1] && STMA[i] <= LTMA[i]) || (STMA[i-1] < LTMA[i-1] && STMA[i] >= LTMA[i]) || (STMA[i-1] == LTMA[i-1] && STMA[i] != LTMA[i])){ 32 | System.out.println(i+" "+STMA[i]+" "+LTMA[i]); 33 | } 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /GoogleCodeJam/Digits.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.util.List; 3 | import java.util.stream.Collectors; 4 | import java.io.*; 5 | import java.time.*; 6 | import java.math.*; 7 | import java.awt.*; 8 | 9 | public class Digits { 10 | 11 | public static void main(String[] args) throws Exception{ 12 | Scanner scan= new Scanner(new File("input.txt")); 13 | PrintWriter writer=new PrintWriter(new File("output.txt")); 14 | int numinputs=scan.nextInt(); 15 | scan.nextLine(); 16 | 17 | 18 | for(int cases=1;cases<=numinputs;cases++){ 19 | int[] nums=new int[10]; 20 | int[] removechar=new int[200]; 21 | char[] arr=scan.nextLine().toCharArray(); 22 | List list = new ArrayList(); 23 | for(char c : arr) { 24 | if(c=='Z'){ 25 | nums[0]++; 26 | removechar['Z']++; 27 | removechar['E']++; 28 | removechar['R']++; 29 | removechar['O']++; 30 | } 31 | else if(c=='W'){ 32 | nums[2]++; 33 | removechar['T']++; 34 | removechar['W']++; 35 | removechar['O']++; 36 | } 37 | else if(c=='U'){ 38 | nums[4]++; 39 | removechar['F']++; 40 | removechar['O']++; 41 | removechar['U']++; 42 | removechar['R']++; 43 | 44 | } 45 | else if(c=='X'){ 46 | nums[6]++; 47 | removechar['S']++; 48 | removechar['I']++; 49 | removechar['X']++; 50 | } 51 | else if(c=='G'){ 52 | nums[8]++; 53 | removechar['E']++; 54 | removechar['I']++; 55 | removechar['G']++; 56 | removechar['H']++; 57 | removechar['T']++; 58 | } 59 | list.add(c); 60 | } 61 | for(int i=0;i0){ 64 | list.remove(i); 65 | removechar[c]--; 66 | i--; 67 | } 68 | } 69 | for(char c : list) { 70 | if(c=='O'){ 71 | nums[1]++; 72 | removechar['O']++; 73 | removechar['N']++; 74 | removechar['E']++; 75 | 76 | } 77 | else if(c=='H'){ 78 | nums[3]++; 79 | removechar['T']++; 80 | removechar['H']++; 81 | removechar['R']++; 82 | removechar['E']++; 83 | removechar['E']++; 84 | } 85 | else if(c=='F'){ 86 | nums[5]++; 87 | removechar['F']++; 88 | removechar['I']++; 89 | removechar['V']++; 90 | removechar['E']++; 91 | 92 | } 93 | else if(c=='S'){ 94 | nums[7]++; 95 | removechar['S']++; 96 | removechar['E']++; 97 | removechar['V']++; 98 | removechar['E']++; 99 | removechar['N']++; 100 | } 101 | } 102 | 103 | for(int i=0;i0){ 106 | list.remove(i); 107 | removechar[c]--; 108 | i--; 109 | } 110 | } 111 | 112 | for(char c : list) { 113 | if(c=='I'){ 114 | nums[9]++; 115 | } 116 | } 117 | 118 | String number=""; 119 | for(int n=0;n set1=new HashSet(); 31 | for(int iterator=maxstartflip;iterator=0){ 50 | int i=indexOf(row, false); 51 | if(i > maxstartflip){ 52 | i=maxstartflip; 53 | } 54 | row=flip(i, size, row); 55 | numflips++; 56 | if(numflips > row.length){ 57 | impossible=true; 58 | break; 59 | } 60 | } 61 | if(impossible){ 62 | System.out.printf("Case #%d: IMPOSSIBLE\n", asdf); 63 | writer.printf("Case #%d: IMPOSSIBLE\n", asdf); 64 | continue; 65 | } 66 | System.out.printf("Case #%d: %d\n", asdf, numflips); 67 | writer.printf("Case #%d: %d\n", asdf, numflips); 68 | 69 | 70 | } 71 | 72 | scan.close(); 73 | writer.close(); 74 | 75 | } 76 | 77 | public static boolean[] flip(int start, int size, boolean[] pancakes){ 78 | for(int i=0;i> prison=new ArrayList>(); 14 | for(int r=0;r<=n;r++){ 15 | ArrayList temp=new ArrayList(); 16 | for(int c=0;c<=m;c++){ 17 | temp.add( 1); 18 | } 19 | prison.add(temp); 20 | } 21 | 22 | //horizontal merging 23 | int xnum=scan.nextInt(); 24 | int[] x=new int[xnum]; 25 | for(int i=0;i=0;a--){ 40 | int i=x[a]; 41 | for(int cell=0;cell> newprison =new ArrayList>(); 49 | 50 | 51 | //3 3 3 ---> 3 1 52 | //1 1 1 ---> 3 1 53 | // 3 1 54 | 55 | for(int col=0;col temp=new ArrayList(); 57 | for(int row=0;row=0;b--){ 64 | int i=y[b]; 65 | for(int cell=0;cell arr:newprison){ 73 | for(int num:arr){ 74 | if(num>max) 75 | max=num; 76 | } 77 | } 78 | System.out.println(max); 79 | 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /GoogleCodeJam/README.md: -------------------------------------------------------------------------------- 1 | # Google Code Jam Problems 2 | -------------------------------------------------------------------------------- /GoogleCodeJam/Solution.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | import java.text.*; 4 | import java.math.*; 5 | import java.util.regex.*; 6 | 7 | public class Solution { 8 | 9 | static long prison(int n, int m, int[] h, int[] v) { 10 | ArrayList> prison=new ArrayList>(); 11 | for(int r=0;r<=n;r++){ 12 | ArrayList temp=new ArrayList(); 13 | for(int c=0;c<=m;c++){ 14 | temp.add((long) 1); 15 | } 16 | prison.add(temp); 17 | } 18 | 19 | int[] x=h; 20 | int xnum=x.length; 21 | Arrays.sort(x); 22 | int[] y=v; 23 | int ynum=y.length; 24 | Arrays.sort(y); 25 | 26 | //removing bar i means that list at i-1 and at i 27 | for(int a=xnum-1;a>=0;a--){ 28 | int i=x[a]; 29 | for(int cell=0;cell> newprison =new ArrayList>(); 37 | 38 | for(int col=0;col temp=new ArrayList(); 40 | for(int row=0;row=0;b--){ 47 | int i=y[b]; 48 | for(int cell=0;cell arr:newprison){ 56 | for(long num:arr){ 57 | if(num>max) 58 | max=num; 59 | } 60 | } 61 | return max; 62 | } 63 | 64 | public static void main(String[] args) throws IOException{ 65 | Scanner in = new Scanner(System.in); 66 | final String fileName = System.getenv("OUTPUT_PATH"); 67 | BufferedWriter bw = new BufferedWriter(new FileWriter(fileName)); 68 | long res; 69 | int _n; 70 | _n = Integer.parseInt(in.nextLine().trim()); 71 | 72 | int _m; 73 | _m = Integer.parseInt(in.nextLine().trim()); 74 | 75 | 76 | int _h_size = 0; 77 | _h_size = Integer.parseInt(in.nextLine().trim()); 78 | int[] _h = new int[_h_size]; 79 | int _h_item; 80 | for(int _h_i = 0; _h_i < _h_size; _h_i++) { 81 | _h_item = Integer.parseInt(in.nextLine().trim()); 82 | _h[_h_i] = _h_item; 83 | } 84 | 85 | 86 | int _v_size = 0; 87 | _v_size = Integer.parseInt(in.nextLine().trim()); 88 | int[] _v = new int[_v_size]; 89 | int _v_item; 90 | for(int _v_i = 0; _v_i < _v_size; _v_i++) { 91 | _v_item = Integer.parseInt(in.nextLine().trim()); 92 | _v[_v_i] = _v_item; 93 | } 94 | 95 | res = prison(_n, _m, _h, _v); 96 | bw.write(String.valueOf(res)); 97 | bw.newLine(); 98 | 99 | bw.close(); 100 | } 101 | } 102 | 103 | -------------------------------------------------------------------------------- /GoogleCodeJam/Super_Substrings.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.util.*; 3 | 4 | public class Super_Substrings { 5 | 6 | public static void main(String[] args) throws Exception{ 7 | Scanner scan=new Scanner(new File("input.txt")); 8 | String n=scan.next(); 9 | ArrayList subs=new ArrayList(); 10 | for(int i=0;i 0) { 29 | sum+=num % 10; 30 | num/=10; 31 | } 32 | return sum; 33 | } 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /GoogleCodeJam/Tidy_Numbers.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class Tidy_Numbers { 5 | 6 | public static void main(String[] args) throws Exception { 7 | Scanner scan=new Scanner(new File("tidy.in")); 8 | PrintWriter writer=new PrintWriter(new File("output.txt")); 9 | 10 | int n=scan.nextInt(); 11 | scan.nextLine(); 12 | for(int asdf=1;asdf<=n;asdf++){ 13 | String num=scan.nextLine(); 14 | 15 | System.out.println(num); 16 | long nu=Long.parseLong(num); 17 | String tidy; 18 | int i=(int) nu; 19 | 20 | while(true){ 21 | if(num.contains("0")){ 22 | tidy=nines(num); 23 | break; 24 | } 25 | int tid=isTidy(i); 26 | if(tid<0){ 27 | tidy=String.valueOf(i); 28 | break; 29 | } 30 | System.out.println(tid); 31 | String str=String.valueOf(i); 32 | String decrement=String.valueOf(Integer.parseInt(str.substring(tid, tid+1))-1); 33 | String len=new String(new char[str.length()-tid-1]).replace("\0", "9"); 34 | i=(int) Long.parseLong(str.substring(0, tid)+decrement+len); 35 | } 36 | 37 | 38 | //parse String 39 | long indignation=Long.parseLong(tidy); 40 | String a="Case #"+asdf+": "+indignation; 41 | System.out.println(a); 42 | writer.println(a); 43 | } 44 | writer.close(); 45 | scan.close(); 46 | } 47 | 48 | //return -1 if tidy or i >=0 where char[i] > char[i+1] 49 | public static int isTidy(long n){ 50 | String num=String.valueOf(n); 51 | for(int i=0;i Integer.valueOf(num.substring(i+1, i+2))){ 53 | return i; 54 | } 55 | } 56 | return -1; 57 | } 58 | 59 | //returns sequence of 9s less than int 60 | public static String nines(String n){ 61 | return new String(new char[n.length()-1]).replace("\0", "9"); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Graph/Edge.java: -------------------------------------------------------------------------------- 1 | 2 | public class Edge { 3 | 4 | //Edge class with built in functions; used for Graph class 5 | 6 | private int weight; 7 | private Vertex v1; 8 | private Vertex v2; 9 | private boolean directed=false; 10 | 11 | public Edge(int weight, int value1, int value2){ 12 | this.weight=weight; 13 | v1=new Vertex(value1); 14 | v2=new Vertex(value2); 15 | } 16 | 17 | public Edge(int weight, int value1, int value2, boolean directed){ 18 | this.weight=weight; 19 | v1=new Vertex(value1); 20 | v2=new Vertex(value2); 21 | directed=true; 22 | } 23 | 24 | //returns whether or not the edge is incident to the input vertex 25 | public boolean incident(int vertex){ 26 | return vertex==v1.getValue() || vertex==v2.getValue(); 27 | } 28 | 29 | public Vertex getVertex1(){ 30 | return v1; 31 | } 32 | 33 | public Vertex getVertex2(){ 34 | return v2; 35 | } 36 | 37 | public int getWeight(){ 38 | return weight; 39 | } 40 | 41 | public boolean getDirected(){ 42 | return directed; 43 | } 44 | 45 | public void makeDirected(){ 46 | directed=true; 47 | } 48 | 49 | public void swap(){ 50 | Vertex temp=v2; 51 | v2=v1; 52 | v1=temp; 53 | } 54 | 55 | public String toString(){ 56 | return weight+"["+v1+","+v2+"]"; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Graph/Graphs.java: -------------------------------------------------------------------------------- 1 | 2 | public class Graphs { 3 | 4 | //Graph class with certain built in algorithms 5 | 6 | private Edge[] edges; 7 | private Vertex[] vertices; 8 | 9 | public Graphs(Vertex[] vertices, Edge[] edges){ 10 | this.vertices=vertices; 11 | this.edges=edges; 12 | } 13 | 14 | //Returns whether or not graph contains input vertex 15 | public boolean hasVertex(Vertex v){ 16 | for(Vertex vertex:vertices){ 17 | if(vertex.getValue()==v.getValue()){ 18 | return true; 19 | } 20 | } 21 | return false; 22 | } 23 | 24 | //returns sum of edge weights in graph 25 | public int getCost(){ 26 | int sum=0; 27 | for(Edge e:edges){ 28 | sum+=e.getWeight(); 29 | } 30 | return sum; 31 | } 32 | 33 | public Edge[] getEdges(){ 34 | return edges; 35 | } 36 | 37 | public String[] vertex(){ 38 | String[] v= new String[vertices.length]; 39 | for(int i=0;i2){ 48 | edges=edgeContraction(edges); 49 | vertices=newVertices(vertices, edges); 50 | } 51 | 52 | display(vertices, edges, "green", "Min-Cut"); 53 | 54 | for(int[] edge:edges){ 55 | //System.out.println(Arrays.toString(edge)); 56 | mincut+=edge[0]; 57 | } 58 | //System.out.println(Arrays.toString(vertices)); 59 | 60 | System.out.println(mincut); 61 | 62 | } 63 | 64 | public static int[][] edgeContraction(int[][] edges){ 65 | 66 | //choose random edge # to collapse betwen 0 and edges.length-1 67 | //store vertex 1, vertex 2, delete the edge 68 | //all edges from vertex 2 change to vertex 1; 69 | 70 | //int[][] newEdges=new int[edges.length-1][3]; 71 | ArrayList newEdges=new ArrayList(); 72 | 73 | int randEdge=(int)(Math.random()*edges.length); 74 | int v1=edges[randEdge][1], v2=edges[randEdge][2]; 75 | 76 | //Populate list of vertices + weights that are connected to edge 77 | for(int i=0;i set=new TreeSet(); 98 | for(int[] edge:edges){ 99 | set.add(edge[1]); set.add(edge[2]); 100 | } 101 | 102 | int count=0; 103 | while(!set.isEmpty()){ 104 | int num=set.pollFirst(); 105 | set.remove(num); 106 | newVertices[count]=num; 107 | count++; 108 | } 109 | 110 | return newVertices; 111 | 112 | 113 | } 114 | 115 | public static Graph convertGraph(int[] vertices, int[][] edges){ 116 | Graph graph=new SparseMultigraph(); 117 | for(int v:vertices){ 118 | graph.addVertex(v); 119 | } 120 | 121 | for(int[] e:edges){ 122 | graph.addEdge(e[0], e[1], e[2], EdgeType.UNDIRECTED); 123 | 124 | } 125 | return graph; 126 | } 127 | 128 | public static void display(int[] vertices, int[][] edges, String color, String name){ 129 | 130 | Graph g=convertGraph(vertices, edges); 131 | 132 | //VisualizationImageServer vs = new VisualizationImageServer(new CircleLayout(g), new Dimension(650, 650)); 133 | 134 | //Initialize visualization 135 | Layout layout = new CircleLayout(g); 136 | layout.setSize(new Dimension(620,620)); 137 | VisualizationViewer vs = new VisualizationViewer(layout); 138 | vs.setPreferredSize(new Dimension(650,650)); 139 | 140 | //Creates GraphMouse and adds to visualization 141 | DefaultModalGraphMouse gm = new DefaultModalGraphMouse(); 142 | gm.setMode(ModalGraphMouse.Mode.TRANSFORMING); 143 | vs.setGraphMouse(gm); 144 | 145 | //Initialize JFrames 146 | JFrame frame = new JFrame(name); 147 | frame.getContentPane().setBackground(Color.RED); 148 | frame.getContentPane().add(vs); 149 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 150 | frame.pack(); 151 | frame.setVisible(true); 152 | 153 | 154 | //Colors Vertices 155 | Transformer vertexPaint = new Transformer() { 156 | public Paint transform(Integer i) { 157 | if(color=="green"){ 158 | return Color.GREEN; 159 | } 160 | else{ 161 | return Color.RED; 162 | } 163 | } 164 | }; 165 | 166 | //Labels Edges 167 | float dash[] = {10.0f}; 168 | final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f); 169 | Transformer edgeStrokeTransformer =new Transformer(){ 170 | public Stroke transform(String s) { 171 | return edgeStroke; 172 | } 173 | }; 174 | 175 | //Renders Vertex colors/labels 176 | vs.getRenderContext().setVertexFillPaintTransformer(vertexPaint); 177 | vs.getRenderContext().setVertexLabelTransformer(new ToStringLabeller()); 178 | vs.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); 179 | 180 | //Renders Edge labels 181 | vs.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller()); 182 | 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /Graph/README.md: -------------------------------------------------------------------------------- 1 | # Graph Algorithms 2 | ## Graph Implementation 3 | * [Graph](https://github.com/jpa99/Algorithms/blob/master/Graph/Graphs.java) 4 | * [Vertex](https://github.com/jpa99/Algorithms/blob/master/Graph/Vertex.java) 5 | * [Edge](https://github.com/jpa99/Algorithms/blob/master/Graph/Edge.java) 6 | 7 | ## Graph Traversal 8 | * [Breadth-First Search](https://github.com/jpa99/Algorithms/blob/master/Graph/BFS.java) 9 | * [Depth First Search](https://github.com/jpa99/Algorithms/blob/master/Graph/DFS.java) 10 | * [Combined Traversal](https://github.com/jpa99/Algorithms/blob/master/Graph/Graph_Traversal.java) 11 | ## Shortest Path 12 | * [Dijkstra's Algorithm](https://github.com/jpa99/Algorithms/blob/master/Graph/Dijkstra.java) 13 | * [Bellman-Ford](https://github.com/jpa99/Algorithms/blob/master/Graph/Bellman_Ford.java) 14 | * [Floyd-Warshall](https://github.com/jpa99/Algorithms/blob/master/Graph/Floyd_Warshall.java) 15 | * [Johnson's Algorithm](https://github.com/jpa99/Algorithms/blob/master/Graph/Johnson.java) 16 | ## Minimum Spanning Tree 17 | * Kruskal's Algorithm 18 | * [Prim's Algorithm](https://github.com/jpa99/Algorithms/blob/master/Graph/Prim.java) 19 | ## Network Flow 20 | * [Karger's Min-Cut Algorithm](https://github.com/jpa99/Algorithms/blob/master/Graph/Karger.java) 21 | * [Ford-Fulkerson](https://github.com/jpa99/Algorithms/blob/master/Graph/Ford_Fulkerson.java) 22 | * Push-Relabel 23 | * Edmonds-Karp 24 | 25 | 26 | ## Others 27 | * Tarjan's Algorithm 28 | * Topological Sort 29 | * Strongly Connected Components 30 | * A* 31 | 32 | -------------------------------------------------------------------------------- /Graph/Vertex.java: -------------------------------------------------------------------------------- 1 | 2 | public class Vertex { 3 | 4 | //Vertex class 5 | //probably unnecessary, but already built into Prim's Algorith implementation 6 | 7 | int value; 8 | 9 | public Vertex(int val){ 10 | value=val; 11 | } 12 | 13 | public int getValue(){ 14 | return value; 15 | } 16 | 17 | public String toString(){ 18 | return String.valueOf(value); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Joel Abraham 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 | -------------------------------------------------------------------------------- /Math/README.md: -------------------------------------------------------------------------------- 1 | # Math/Number Theoretic Algorithms 2 | -------------------------------------------------------------------------------- /Miscellaneous/Fisher_Yates.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class Fisher_Yates { 5 | 6 | /*Fisher-Yates Algorithm 7 | 8 | Problem (informal): Given input array, return permuted array such that elements are uniformly distributed (pseudorandomly) 9 | 10 | Algorithm: For each index i, swap element at i with element at random index 0 <= j <= i 11 | 12 | Complexity: 13 | * Time - O(n) since only one iteration 14 | * Space - O(n) to choose random integer at each position 15 | 16 | Notes: 17 | * shuffle() - randomly permutes input array 18 | * swap() - swaps elements at indices i and j 19 | 20 | Notes: 21 | * Simple but effective shuffling algorithm 22 | 23 | */ 24 | 25 | public static void main(String[] args) { 26 | Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 27 | arr = shuffle(arr); 28 | System.out.println(Arrays.toString(arr)); 29 | 30 | } 31 | 32 | public static > E[] shuffle(E[] arr){ 33 | Random rng = new Random(); 34 | for(int i = arr.length - 1 ; i > 0 ; i--){ 35 | int j = rng.nextInt(i+1); //random element in range [0, i] 36 | swap(arr, i, j); 37 | } 38 | return arr; 39 | } 40 | 41 | public static void swap(E[] arr, int i, int j){ 42 | E temp = arr[i]; 43 | arr[i] = arr[j]; 44 | arr[j] = temp; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Miscellaneous/Matrix_Exponentiation.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Matrix_Exponentiation { 4 | 5 | /*Matrix Exponentiation Algorithm 6 | 7 | Problem (informal): Given a matrix M, find the product: M^n = M x M x ... x M 8 | 9 | Algorithm: Brute force algorithm for repeated multiplication 10 | 11 | Complexity: 12 | * Time - O(n*i*j*k) where a has dimensions i x j and b has dimensions j x k to compute M^n 13 | * Space - O(i*j) where M has i rows and j columns 14 | 15 | Functions Defined: 16 | * matrix_multiply() - returns matrix product of matrices a and b 17 | * matrix_exponentation() - returns M^n via repeated multiplication of M for square matrix M 18 | 19 | */ 20 | 21 | 22 | 23 | public static void main(String[] args){ 24 | int[][] a = {{1, 2, 3, 2}, {2, 3, 4, 8}, {4, 5, 3, 6}}; //3 x 4 25 | int[][] b = {{6, 1, 4}, {9, 0, 6}, {6, 4, 5}, {3, 1, 1}}; // 4 x 3 26 | int[][] m = matrix_multiply(a, b); 27 | System.out.println(Arrays.deepToString(m)); 28 | 29 | //testing staticness with multiplication with identity 30 | int[][] identity = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; 31 | int[][] m2 = matrix_multiply(m, identity); 32 | System.out.println(Arrays.deepToString(m2)); 33 | 34 | //matrix exponentiation 35 | m2 = matrix_exponentiation(m2, 2); 36 | 37 | System.out.println(Arrays.deepToString(m2)); 38 | } 39 | 40 | //assumes that matrix b has j rows and a has j columns 41 | //O(ijk) where a has dimensions i x j and b has dimensions j x k 42 | public static int[][] matrix_multiply(int[][] a, int[][] b){ 43 | int[][] m = new int[a.length][b[0].length]; 44 | for(int i=0;i 1){ 60 | m = matrix_multiply(m, m); 61 | } 62 | return m; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Miscellaneous/README.md: -------------------------------------------------------------------------------- 1 | # Miscellaneous Algorithms 2 | 3 | * [Fisher-Yates Algorithm](https://github.com/jpa99/Algorithms/blob/master/Miscellaneous/Fisher_Yates.java) 4 | * [Subarray Inversions](https://github.com/jpa99/Algorithms/blob/master/Miscellaneous/Subarray_Inversions.java) 5 | * [Matrix Exponentiation](https://github.com/jpa99/Algorithms/blob/master/Miscellaneous/Matrix_Exponentiation.java) 6 | -------------------------------------------------------------------------------- /Optimization/LightConfigurationOptimization.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | import org.apache.commons.math3.util.Combinations; 4 | 5 | public class LightConfigurationOptimization { 6 | static final int M = 5, N = 5; //Source/Target arrays are M*N grids 7 | static final int k = 5; //Number of LEDs 8 | static final double Z = 5; //Distance between source and target planes 9 | static final int len = M*N; //Number of candidate locations 10 | 11 | static final double halfwidth = 12; //Manufacturer provided angular half-width 12 | static final double m = Math.log(0.5)/Math.log(Math.cos(halfwidth*Math.PI/180)); 13 | static final double intensity = 1; //arbitrary units, can change later 14 | public static void main(String[] rip){ 15 | long start = System.nanoTime(); 16 | 17 | //Given two parallel M*N arrays (source and target), Z units apart, and 5 light fixtures, find optimal configuration 18 | //Objective function is sigma/E 19 | int[] optLEDarr = new int[k]; 20 | 21 | double min = Double.MAX_VALUE; //current mimimum of objective function 22 | String[][] sourceArray = new String[M][N]; 23 | 24 | for (Iterator iter = new Combinations(M*N, k).iterator(); iter.hasNext();) { 25 | LEDConfiguration config = cost(iter.next()); 26 | if(config.CVRMSE < min){ 27 | min = config.CVRMSE; 28 | optLEDarr = config.LEDarr; 29 | } 30 | } 31 | System.out.println(Arrays.toString(optLEDarr)); 32 | for(String[] row:sourceArray) Arrays.fill(row, "⚫"); 33 | 34 | for(int LED:optLEDarr){ 35 | int[] LEDcoord = indexToPoints(LED); 36 | sourceArray[LEDcoord[0]][LEDcoord[1]] = "⚪"; 37 | } 38 | 39 | System.out.println(min+"\n\n"); 40 | 41 | for(String[] row:sourceArray) System.out.println(Arrays.toString(row)); 42 | System.out.println("\nRuntime: "+((System.nanoTime()-start)/1000000)+" ms"); 43 | } 44 | 45 | //Outputs cost function evaluated at specified LED configuration 46 | public static LEDConfiguration cost(int[] LEDarr){ 47 | double netIrradiance = 0; //Sum of irradiance at all points 48 | double avgIrradiance = 0; //Average irradiance across grid 49 | double netErrorSquared = 0, sigma = 0; 50 | double CVRMSE = 0; //objective function, CVRMSE = sigma/avgIrradiance 51 | int len = M*N; 52 | 53 | //unique combination of LEDs exists 54 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 55 | //given some point on target plane and set of LED positions, find irradiance 56 | int[] pointcoord = indexToPoints(targetPoint); 57 | for(int LED:LEDarr){ 58 | netIrradiance += irradiance(LED, pointcoord); 59 | } 60 | } 61 | 62 | avgIrradiance = netIrradiance/len; 63 | 64 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 65 | //given some point on target plane and set of LED positions, find irradiance 66 | int[] pointcoord = indexToPoints(targetPoint); 67 | double pointIrradiance = 0; //irradiance at point from all LEDs 68 | for(int LED:LEDarr){ 69 | pointIrradiance+=irradiance(LED, pointcoord); 70 | } 71 | netErrorSquared+=Math.pow(pointIrradiance - avgIrradiance, 2); 72 | } 73 | 74 | sigma = Math.sqrt(netErrorSquared/len); 75 | CVRMSE = sigma/avgIrradiance; //objective function 76 | 77 | LEDConfiguration config = new LEDConfiguration(CVRMSE, LEDarr); 78 | return config; 79 | } 80 | 81 | //Returns irradiance contributed by specific LED at a specific point 82 | public static double irradiance(int LED, int[] pointcoord){ 83 | int[] LEDcoord = indexToPoints(LED); 84 | return (Math.pow(Z, m+1)*intensity)/ 85 | Math.pow((Math.pow(pointcoord[0] - LEDcoord[0], 2) + Math.pow(pointcoord[1] - LEDcoord[1], 2) + Math.pow(Z, 2)), ((m+3)/2)); 86 | } 87 | 88 | //Mapping from [0, M*N] --> [0,M]x[0,N] 89 | public static int[] indexToPoints(int index){ 90 | int[] points = {index%M, index/M}; 91 | return points; 92 | } 93 | 94 | static class LEDConfiguration{ 95 | public double CVRMSE; 96 | public int[] LEDarr; 97 | public LEDConfiguration(double CVRMSE, int[] LEDarray){ 98 | this.CVRMSE = CVRMSE; 99 | LEDarr = LEDarray; 100 | } 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /Optimization/LightConfigurationOptimizationSA.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.HashMap; 3 | import java.util.Random; 4 | 5 | public class LightConfigurationOptimizationSA { 6 | static final int M = 5, N = 5; //Source/Target arrays are M*N grids 7 | static final int k = 5; //Number of LEDs 8 | static final double Z = 5; //Distance between source and target planes 9 | static final int len = M*N; 10 | 11 | static final double halfwidth = 12; //Manufacturer provided angular half-width 12 | static final double m = Math.log(0.5)/Math.log(Math.cos(halfwidth*Math.PI/180)); 13 | static final double intensity = 1; //arbitrary units, can change later 14 | 15 | //Simulated Annealing parameters 16 | static final double Tmin = .0001; //Temperature at which iteration terminates 17 | static final double alpha = 0.9; //Decrease in temperature 18 | 19 | public static void main(String[] args) { 20 | double T = 1; //Initial temperature 21 | String[][] sourceArray = new String[M][N]; 22 | Solution min = new Solution(Double.MAX_VALUE, null); 23 | Solution currentSol = genRandSol(); 24 | while(T > Tmin){ 25 | for(int i=0;i<100;i++){ 26 | if(currentSol.CVRMSE < min.CVRMSE){ 27 | min = currentSol; 28 | } 29 | Solution newSol = neighbor(currentSol); 30 | double ap = Math.pow(Math.E, (currentSol.CVRMSE - newSol.CVRMSE)/T); 31 | if(ap > Math.random()){ 32 | currentSol = newSol; 33 | } 34 | } 35 | T*=alpha; 36 | } 37 | 38 | System.out.println(min.CVRMSE+"\n\n"); 39 | 40 | for(String[] row:sourceArray) Arrays.fill(row, "⚫"); 41 | 42 | for(int LED:min.config){ 43 | int[] LEDcoord = indexToPoints(LED); 44 | sourceArray[LEDcoord[0]][LEDcoord[1]] = "⚪"; 45 | } 46 | 47 | for(String[] row:sourceArray) System.out.println(Arrays.toString(row)); 48 | 49 | } 50 | 51 | //Given current configuration, returns "neighboring" configuration (i.e. very similar) 52 | //integer of k points each in range [0, n) 53 | /*Different neighbor selection strategies? 54 | * Move all points 0 or 1 units in a random direction 55 | * 56 | */ 57 | public static Solution neighbor(Solution currentSol){ 58 | int[] config = currentSol.config; //+- 1 for left/right, +-M for up/down 59 | int[] directions = {-1, 1, M, -M}; 60 | for(int i=0;i= 0 && newIndex < len) config[i] = newIndex; 63 | } 64 | return new Solution(cost(config), config); 65 | } 66 | 67 | //Generates random solution via modified Fisher-Yates shuffle for first k elements 68 | //Pseudorandomly selects k integers from the interval [0, n-1] 69 | public static Solution genRandSol(){ 70 | Random rng = new Random(); 71 | HashMap hash = new HashMap(2*k); 72 | int[] configuration = new int[k]; 73 | 74 | for (int i = 0; i < k; i++) { 75 | int j = i + rng.nextInt(len - i); 76 | configuration[i] = (hash.containsKey(j) ? hash.remove(j) : j); 77 | if (j > i) hash.put(j, (hash.containsKey(i) ? hash.remove(i) : i)); 78 | } 79 | 80 | double cost = cost(configuration); 81 | return new Solution(cost, configuration); 82 | } 83 | 84 | //Returns irradiance contributed by specific LED at a specific point 85 | public static double irradiance(int LED, int[] pointcoord){ 86 | int[] LEDcoord = indexToPoints(LED); 87 | return (Math.pow(Z, m+1)*intensity)/ 88 | Math.pow((Math.pow(pointcoord[0] - LEDcoord[0], 2) + Math.pow(pointcoord[1] - LEDcoord[1], 2) + Math.pow(Z, 2)), ((m+3)/2)); 89 | } 90 | 91 | //Mapping from [0, M*N] --> [0,M]x[0,N] 92 | public static int[] indexToPoints(int index){ 93 | int[] points = {index%M, index/M}; 94 | return points; 95 | } 96 | 97 | //Cost function, evaluates CVRMSE of input LED configuration 98 | //Complexity is O(M*N*k), asymptotically tight 99 | public static double cost(int[] LEDarr){ 100 | double netIrradiance = 0; //Sum of irradiance at all points 101 | double avgIrradiance = 0; //Average irradiance across grid 102 | double netErrorSquared = 0, sigma = 0; 103 | 104 | //unique combination of LEDs exists 105 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 106 | //given some point on target plane and set of LED positions, find irradiance 107 | int[] pointcoord = indexToPoints(targetPoint); 108 | for(int LED:LEDarr){ 109 | netIrradiance+=irradiance(LED, pointcoord); 110 | } 111 | } 112 | 113 | avgIrradiance = netIrradiance/len; 114 | 115 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 116 | //given some point on target plane and set of LED positions, find irradiance 117 | int[] pointcoord = indexToPoints(targetPoint); 118 | double pointIrradiance = 0; //irradiance at point from all LEDs 119 | for(int LED:LEDarr){ 120 | pointIrradiance+=irradiance(LED, pointcoord); 121 | } 122 | netErrorSquared+=Math.pow(pointIrradiance - avgIrradiance, 2); 123 | } 124 | 125 | sigma = Math.sqrt(netErrorSquared/len); 126 | return sigma/avgIrradiance; //objective function 127 | } 128 | 129 | static class Solution{ 130 | public double CVRMSE; 131 | public int[] config; 132 | public Solution(double CVRMSE, int[] configuration){ 133 | this.CVRMSE = CVRMSE; 134 | config = configuration; 135 | } 136 | } 137 | 138 | } 139 | -------------------------------------------------------------------------------- /Optimization/LocationalOptimizationIterative.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.math.*; 3 | import org.apache.commons.math3.util.Combinations; 4 | 5 | public class LocationalOptimizationIterative { 6 | static final int M = 7, N = 7; //Source/Target arrays are M*N grids 7 | static final int k = 5; //Number of LEDs 8 | static final double Z = 5; //Distance between source and target planes 9 | 10 | static final double halfwidth = 12; //Manufacturer provided angular half-width 11 | static final double m = Math.log(0.5)/Math.log(Math.cos(halfwidth*Math.PI/180)); 12 | static final double intensity = 1; //arbitrary units, can change later 13 | public static void main(String[] rip){ 14 | long start = System.nanoTime(); 15 | 16 | //Given two parallel M*N arrays (source and target), Z units apart, and 5 light fixtures, find optimal configuration 17 | //Objective function is sigma/E 18 | int len = M*N; //Number of points 19 | int[] optLEDarr = new int[k]; 20 | 21 | double min = Double.MAX_VALUE; //current mimimum of objective function 22 | String[][] sourceArray = new String[M][N]; 23 | 24 | for (Iterator iter = new Combinations(M*N, k).iterator(); iter.hasNext();) { 25 | double netIrradiance = 0; //Sum of irradiance at all points 26 | double avgIrradiance = 0; //Average irradiance across grid 27 | double netErrorSquared = 0, sigma = 0; 28 | double CVRMSE = 0; //objective function, CVRMSE = sigma/avgIrradiance 29 | 30 | //unique combination of LEDs exists 31 | int[] LEDarr = iter.next(); 32 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 33 | //given some point on target plane and set of LED positions, find irradiance 34 | int[] pointcoord = indexToPoints(targetPoint); 35 | for(int LED:LEDarr){ 36 | netIrradiance+=irradiance(LED, pointcoord); 37 | } 38 | } 39 | 40 | avgIrradiance = netIrradiance/len; 41 | 42 | for(int targetPoint = 0; targetPoint < len; targetPoint++){ 43 | //given some point on target plane and set of LED positions, find irradiance 44 | int[] pointcoord = indexToPoints(targetPoint); 45 | double pointIrradiance = 0; //irradiance at point from all LEDs 46 | for(int LED:LEDarr){ 47 | pointIrradiance+=irradiance(LED, pointcoord); 48 | } 49 | netErrorSquared+=Math.pow(pointIrradiance - avgIrradiance, 2); 50 | } 51 | 52 | sigma = Math.sqrt(netErrorSquared/len); 53 | CVRMSE = sigma/avgIrradiance; //objective function 54 | 55 | if(CVRMSE < min){ 56 | min = CVRMSE; 57 | optLEDarr = LEDarr; 58 | } 59 | } 60 | 61 | for(String[] row:sourceArray) Arrays.fill(row, "⚫"); 62 | 63 | for(int LED:optLEDarr){ 64 | int[] LEDcoord = indexToPoints(LED); 65 | sourceArray[LEDcoord[0]][LEDcoord[1]] = "⚪"; 66 | } 67 | 68 | System.out.println(min+"\n\n"); 69 | 70 | for(String[] row:sourceArray) System.out.println(Arrays.toString(row)); 71 | System.out.println("\nRuntime: "+((System.nanoTime()-start)/1000000)+" ms"); 72 | } 73 | 74 | //Returns irradiance contributed by specific LED at a specific point 75 | public static double irradiance(int LED, int[] pointcoord){ 76 | int[] LEDcoord = indexToPoints(LED); 77 | return (Math.pow(Z, m+1)*intensity)/ 78 | Math.pow((Math.pow(pointcoord[0] - LEDcoord[0], 2) + Math.pow(pointcoord[1] - LEDcoord[1], 2) + Math.pow(Z, 2)), ((m+3)/2)); 79 | } 80 | 81 | //Mapping from [0, M*N] --> [0,M]x[0,N] 82 | public static int[] indexToPoints(int index){ 83 | int[] points = {index%M, index/M}; 84 | return points; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /Optimization/README.md: -------------------------------------------------------------------------------- 1 | # Optimization Algorithms 2 | This folder contains optimization implementations for locational optimization problems. The general problem statement solveable by this flavor of optimization is as follows: Given a set S of n candidate 2-tuples (ordered pairs) and a function cost(P): R^2 --> R where P = {(x_1, y_1), (x_2, y_2), ..., (x_k, y_k)}, find a subset Q of k 2-tuples (ordered pairs) such that cost(Q) is minimized. This can be reformulated as selecting k optimal points from a set of n candidate points. 3 | 4 | * [Naive Optimization](https://github.com/jpa99/Algorithms/blob/master/Optimization/LightConfigurationOptimization.java) 5 | * Simplex (LP) 6 | * [Simulated Annealing](https://github.com/jpa99/Algorithms/blob/master/Optimization/LightConfigurationOptimizationSA.java) 7 | * Genetic Algorithms 8 | * Combinatoric Algorithms 9 | -------------------------------------------------------------------------------- /ProjectEuler/Amicable_numbers.java: -------------------------------------------------------------------------------- 1 | 2 | public class Amicable_numbers { 3 | 4 | public static void main(String[] args) { 5 | int sum=0; 6 | for(int i=0;i<10000;i++){ 7 | if(amicable(i, sum_divisors(i)) && i!=sum_divisors(i)){ 8 | sum+=i; 9 | } 10 | } 11 | System.out.println(sum); 12 | } 13 | 14 | 15 | public static boolean amicable(int a, int b){ 16 | return sum_divisors(a)==b && sum_divisors(b)==a ? true:false; 17 | } 18 | 19 | public static int sum_divisors(int n){ 20 | int sum=0; 21 | for(int i=2;i<(int)(n/2)+1;i++){ 22 | if(n%i==0){ 23 | sum+=i; 24 | } 25 | } 26 | return sum+1; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /ProjectEuler/Coded_triangle_numbers.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | import java.util.HashMap; 5 | import java.util.Scanner; 6 | 7 | public class Coded_triangle_numbers { 8 | 9 | public static void main(String[] args) throws IOException{ 10 | 11 | //Initialize array containing words from text file 12 | String fileName="words.txt"; 13 | String[] words = null; 14 | try{ 15 | FileReader inputFile = new FileReader(fileName); 16 | BufferedReader bufferReader = new BufferedReader(inputFile); 17 | String line=bufferReader.readLine(); 18 | words=line.split(","); 19 | bufferReader.close(); 20 | } 21 | catch(Exception e){ 22 | } 23 | 24 | 25 | //Initialize list containing triangles numbers 26 | ArrayList triangles=new ArrayList(); 27 | int num=0; 28 | for(int index=1;index<500;index++){ 29 | num+=index; 30 | triangles.add(num); 31 | } 32 | 33 | //Iterate through array of words and test for triangle numbers 34 | int num_triangles=0; 35 | for(String n:words){ 36 | int sum=0; 37 | for(char i:n.toCharArray()){ 38 | sum+="ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(i)+1; 39 | } 40 | if(triangles.contains(sum)){ 41 | num_triangles++; 42 | } 43 | System.out.println(n +" "+sum+" "); 44 | } 45 | System.out.println(num_triangles); 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /ProjectEuler/Collatz_sequence.java: -------------------------------------------------------------------------------- 1 | 2 | public class Collatz_sequence { 3 | public static void main(String[] args){ 4 | double starting=0; 5 | double max=0; 6 | for(double i=2;i<1000000;i++){ 7 | if(collatz(i)>max){ 8 | max=collatz(i); 9 | starting=i; 10 | System.out.println(starting); 11 | } 12 | } 13 | 14 | 15 | } 16 | 17 | public static double collatz(double n){ 18 | double sum=0; 19 | while(n!=1){ 20 | if(n%2==0){ 21 | n/=2; 22 | } 23 | else{ 24 | n=3*n+1; 25 | } 26 | sum++; 27 | } 28 | return sum; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /ProjectEuler/Combinatoric_selections.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Combinatoric_selections { 4 | 5 | public static void main(String[] args) { 6 | 7 | int sum=0; 8 | 9 | for(int n=23; n<=100;n++){ 10 | for(int r=4;r1000000){ 13 | sum++; 14 | } 15 | } 16 | } 17 | } 18 | 19 | public static int factorial(int num){ 20 | int prod=1; 21 | for(int i=num;i>1;i--){ 22 | prod*=i; 23 | } 24 | return prod; 25 | } 26 | 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /ProjectEuler/Concealed_square.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Concealed_square { 4 | 5 | public static void main(String[] args) { 6 | for(long i=1010101010;i<1389026624;i+=10){ 7 | BigInteger num=BigInteger.valueOf(i); 8 | String n=String.valueOf(num.pow(2)); 9 | if(n.length()=="1929394959697989990".length()){ 10 | int index=0; 11 | char[] nums=n.toCharArray(); 12 | for(int j=0;j factor(double n){ 20 | ArrayList factors=new ArrayList(); 21 | for(double i= n-1;i>=2;i--){ 22 | if(n%i==0 && isPrime(i) && !inlist(i, factors)) { 23 | n/=i; 24 | factors.add(i); 25 | i++; 26 | } 27 | } 28 | return factors; 29 | } 30 | 31 | public static boolean inlist(double n, ArrayList arr){ 32 | for(double i: arr){ 33 | if(n==i){ 34 | return true; 35 | } 36 | } 37 | return false; 38 | } 39 | 40 | public static double return_max(ArrayList factors){ 41 | double max=factors.get(0); 42 | for(double i:factors){ 43 | if(i>max){ 44 | max=i; 45 | } 46 | } 47 | return max; 48 | } 49 | 50 | public static boolean isPrime(double n){ 51 | for(double i=2;i0;i++){ 7 | if(sumDigits(i)){ 8 | sum+=i; 9 | System.out.println(sum); 10 | } 11 | } 12 | } 13 | 14 | public static int factorial(int num){ 15 | int prod=1; 16 | for(int i=num;i>1;i--){ 17 | prod*=i; 18 | } 19 | return prod; 20 | } 21 | 22 | public static boolean sumDigits(int n){ 23 | String num=String.valueOf(n); 24 | int fsum=0; 25 | for(int i=0;i1 ? true:false; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /ProjectEuler/Distinct_powers.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.ArrayList; 3 | 4 | public class Distinct_powers { 5 | 6 | public static void main(String[] args) { 7 | ArrayList power=new ArrayList(); 8 | for(int i=2;i<=100;i++){ 9 | for(int j=2;j<=100;j++){ 10 | BigInteger num=BigInteger.valueOf(i).pow(j); 11 | if(!power.contains(num)){ 12 | power.add(num); 13 | System.out.println(i+" "+j+" "+num); 14 | } 15 | } 16 | } 17 | System.out.println(power.size()); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /ProjectEuler/Even_fibonacci_sum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Even_fibonacci_sum { 4 | 5 | public static void main(String[] args) { 6 | ArrayList fib=new ArrayList(); 7 | fib.add(1); 8 | fib.add(2); 9 | int sum=2; 10 | while(fib.get(fib.size()-1) <= 4000000){ 11 | int i=2; 12 | fib.add(fib.get(i-1)+fib.get(i-2)); 13 | if(fib.get(i)%2==0){ 14 | sum+=fib.get(i); 15 | } 16 | i++; 17 | } 18 | System.out.println(Math.pow(2, 1000)); 19 | System.out.println(sum); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /ProjectEuler/Factorial_digit_sum.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | 3 | public class Factorial_digit_sum { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(sum_digits(factorial(100))); 7 | } 8 | 9 | public static BigInteger factorial(int num){ 10 | BigInteger prod=BigInteger.valueOf(1); 11 | for(int i=num;i>1;i--){ 12 | prod=prod.multiply(BigInteger.valueOf(i)); 13 | } 14 | return prod; 15 | } 16 | public static double sum_digits(BigInteger n){ 17 | String num=String.valueOf(n); 18 | int sum=0; 19 | for(int i=0;i=3;i--){ 72 | for(int j=grid.length-1;j>=3;j--){ 73 | max=Math.max(max, grid[i][j]*grid[i-1][j-1]*grid[i-2][j-2]*grid[i-3][j-3]); 74 | } 75 | } 76 | return max; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /ProjectEuler/Highly_divisible_triangular.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Highly_divisible_triangular { 4 | 5 | public static void main(String[] args) { 6 | int index=1; 7 | int max_divisors=0; 8 | int i=1; 9 | while(max_divisors<=500){ 10 | max_divisors=Math.max(max_divisors, num_divisors(i)); 11 | index++; 12 | i+=index; 13 | } 14 | System.out.println("The "+index+"th triangle number, "+i+", has "+max_divisors+" divisors"); 15 | 16 | } 17 | 18 | public static int num_divisors(int n){ 19 | int num=0; 20 | for(int i=2;i<(int)(n/2)+1;i++){ 21 | if(n%i==0){ 22 | num++; 23 | } 24 | } 25 | return num+2; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /ProjectEuler/Large_sum.java: -------------------------------------------------------------------------------- 1 | 2 | public class Large_sum { 3 | 4 | public static void main(String[] args) { 5 | String num="37107287533902102798797998220837590246510135740250463769376774900097126481248969700780504170182605387432498619952474105947423330951305812372661730962991942213363574161572522430563301811072406154908250230675882075393461711719803104210475137780632466768926167069662363382013637841838368417873436172675728112879812849979408065481931592621691275889832738442742289174325203219235894228767964876702721893184745144573600130643909116721685684458871160315327670386486105843025439939619828917593665686757934951621764571418565606295021572231965867550793241933316490635246274190492910143244581382266334794475817892575867718337217661963751590579239728245598838407582035653253593990084026335689488301894586282278288018119938482628201427819413994056758715117009439035398664372827112653829987240784473053190104293586865155060062958648615320752733719591914205172558297169388870771546649911559348760353292171497005693854370070576826684624621495650076471787294438377604532826541087568284431911906346940378552177792951453612327252500029607107508256381565671088525835072145876576172410976447339110607218265236877223636045174237069058518606604482076212098132878607339694128114266041808683061932846081119106155694051268969251934325451728388641918047049293215058642563049483624672216484350762017279180399446930047329563406911573244438690812579451408905770622942919710792820955037687525678773091862540744969844508330393682126183363848253301546861961243487676812975343759465158038628759287849020152168555482871720121925776695478182833757993103614740356856449095527097864797581167263201004368978425535399209318374414978068609844840309812907779179908821879532736447567559084803087086987551392711854517078544161852424320693150332599594068957565367821070749269665376763262354472106979395067965269474259770973916669376304263398708541052684708299085211399427365734116182760315001271653786073615010808570091499395125570281987460043753582903531743471732693212357815498262974255273730794953759765105305946966067683156574377167401875275889028025717332296191766687138199318110487701902712526768027607800301367868099252546340106163286652636270218540497705585629946580636237993140746255962240744869082311749777923654662572469233228109171419143028819710328859780666976089293863828502533340334413065578016127815921815005561868836468420090470230530811728164304876237919698424872550366387845831148769693215490281042402013833512446218144177347063783299490636259666498587618221225225512486764533677201869716985443124195724099139590089523100588229554825530026352078153229679624948164195386821877476085327132285723110424803456124867697064507995236377742425354112916842768655389262050249103265729672370191327572567528565324825826546309220705859652229798860272258331913126375147341994889534765745501184957014548792889848568277260777137214037988797153829820378303147352772158034814451349137322665138134829543829199918180278916522431027392251122869539409579530664052326325380441000596549391598795936352974615218550237130764225512118369380358038858490341698116222072977186158236678424689157993532961922624679571944012690438771072750481023908955235974572318970677254791506150550495392297953090112996751986188088225875314529584099251203829009407770775672113067397083047244838165338735023408456470580773088295917476714036319800818712901187549131054712658197623331044818386269515456334926366572897563400500428462801835170705278318394258821455212272512503275512160354698120058176216521282765275169129689778932238195734329339946437501907836945765883352399886755061649651847751807381688378610915273579297013376217784275219262340194239963916804498399317331273132924185707147349566916674687634660915035914677504995186714302352196288948901024233251169136196266227326746080059154747183079839286853520694694454072476841822524674417161514036427982273348055556214818971426179103425986472045168939894221798260880768528778364618279934631376775430780936333301898264209010848802521674670883215120185883543223812876952786713296124747824645386369930090493103636197638780396218407357239979422340623539380833965132740801111666627891981488087797941876876144230030984490851411606618262936828367647447792391803351109890697907148578694408955299065364044742557608365997664579509666024396409905389607120198219976047599490197230297649139826800329731560371200413779037855660850892521673093931987275027546890690370753941304265231501194809377245048795150954100921645863754710598436791786391670211874924319957006419179697775990283006991536871371193661495281130587638027841075444973307840789923115535562561142322423255033685442488917353448899115014406480203690680639606723221932041495354150312888033953605329934036800697771065056663195481234880673210146739058568557934581403627822703280826165707739483275922328459417065250945123252306082291880205877731971983945018088807242966198081119777158542502016545090413245809786882778948721859617721078384350691861554356628840622574736922845095162084960398013400172393067166682355524525280460972253503534226472524250874054075591789781264330331690"; 6 | System.out.println(num.length()); 7 | double sum=0; 8 | for(int i=0; i<=4950;i+=50){ 9 | sum+=Double.parseDouble(num.substring(i, i+50)); 10 | } 11 | System.out.println(sum); 12 | String n=String.valueOf(sum); 13 | System.out.println(n.substring(0, 10)); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ProjectEuler/Largest_consecutive_product.java: -------------------------------------------------------------------------------- 1 | 2 | public class Largest_consecutive_product { 3 | 4 | public static void main(String[] args) { 5 | String num="7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"; 6 | int max=prod(num.substring(0,13)); 7 | for(int i=1;i<=num.length()-13;i++){ 8 | if(prod(num.substring(i,i+13)) > max || (-1*prod(num.substring(i,i+13))) > max){ 9 | max=prod(num.substring(i,i+13)); 10 | } 11 | } 12 | System.out.println(max); 13 | 14 | } 15 | public static int prod(String n){ 16 | String[] nums=n.split(""); 17 | int prod=1; 18 | for(String i:nums){ 19 | prod*=Integer.parseInt(i); 20 | } 21 | return prod; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ProjectEuler/Lexicogrphic_permutations.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.lang.*; 3 | 4 | public class Lexicogrphic_permutations { 5 | 6 | public static void main(String[] args) { 7 | 8 | } 9 | 10 | 11 | 12 | public static void sort(ArrayList perms){ 13 | int index=0; 14 | while(index!=perms.size()){ 15 | int min=find_min(perms, index); 16 | swap(perms, index, min); 17 | } 18 | } 19 | 20 | public static void swap(ArrayList arr, int index_a, int index_b){ 21 | int temp=arr.get(index_a); 22 | arr.set(index_a, arr.get(index_b)); 23 | arr.set(index_b, temp); 24 | } 25 | 26 | public static int find_min(ArrayList arr, int start_index){ 27 | int min=start_index; 28 | for(int i=start_index;i1;i--){ 14 | prod*=i; 15 | } 16 | return prod; 17 | } 18 | } 19 | 20 | class sum_digits_square implements MATH_TOOLBOX{ 21 | public int run(int i, int x){ 22 | char[] digits=String.valueOf(i).toCharArray(); 23 | int sum=0; 24 | for(char c:digits){ 25 | sum+=Math.pow((double)(Character.getNumericValue(c)), 2); 26 | } 27 | return sum; 28 | } 29 | } 30 | 31 | class main{ 32 | public static void main(String[] args){ 33 | List> functions=new ArrayList>(); 34 | new HashMap(); 35 | functions.add(new HashMap()); 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /ProjectEuler/Names_scores.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.util.Arrays; 4 | 5 | public class Names_scores { 6 | 7 | public static void main(String[] args) { 8 | //Initialize array containing names from text file 9 | String fileName="names.txt"; 10 | String[] names = null; 11 | try{ 12 | FileReader inputFile = new FileReader(fileName); 13 | BufferedReader bufferReader = new BufferedReader(inputFile); 14 | String line=bufferReader.readLine(); 15 | names=line.split(","); 16 | bufferReader.close(); 17 | } 18 | catch(Exception e){ 19 | } 20 | 21 | //Sort array of names alphabetically 22 | Arrays.sort(names); 23 | 24 | //Iterate through array and calculate score, adding to total sum 25 | int total_score=0; 26 | for(int i=0;i removeDuplicates(ArrayList list) { 20 | ArrayList result = new ArrayList<>(); 21 | HashSet set = new HashSet<>(); 22 | for (String item : list) { 23 | if (!set.contains(item)){ 24 | result.add(item); 25 | set.add(item); 26 | } 27 | } 28 | return result; 29 | } 30 | //Neccessariliy array of distinct integers 31 | public static int indexOf(int element, int[] arr){ 32 | for(int i=0;i1;i--){ 59 | prod*=i; 60 | } 61 | return prod; 62 | } 63 | 64 | 65 | 66 | public static int sum_digits_square(int i){ 67 | if(i==1 || i==89){ 68 | return i; 69 | } 70 | char[] digits=String.valueOf(i).toCharArray(); 71 | int sum=0; 72 | for(char c:digits){ 73 | sum+=Math.pow((double)(Character.getNumericValue(c)), 2); 74 | } 75 | return sum_digits_square(sum); 76 | } 77 | 78 | public static boolean triangle_word(String n){ 79 | ArrayList triangles=new ArrayList(); 80 | int num=0; 81 | for(int index=1;index<500;index++){ 82 | num+=index; 83 | triangles.add(num); 84 | } 85 | int sum=0; 86 | for(char i:n.toCharArray()){ 87 | sum+=i-'A'+1; 88 | } 89 | return triangles.contains(sum) ? true:false; 90 | } 91 | 92 | public static int num_divisors(int n){ 93 | int num=0; 94 | for(int i=2;i<(int)(n/2)+1;i++){ 95 | if(n%i==0){ 96 | num++; 97 | } 98 | } 99 | return num+2; 100 | } 101 | 102 | public static ArrayList primes(int a, int b){ 103 | ArrayList list=new ArrayList(); 104 | for(int i=a;i<=b;i++){ 105 | if(isPrime(i)){ 106 | list.add(i); 107 | } 108 | } 109 | return list; 110 | } 111 | 112 | public static boolean isPrime(int n){ 113 | for(int i=2;i pans=new ArrayList(); 9 | for(int i=7654321;i>2143;i-=2){ 10 | if(pandigital(i) && isPrime(i)){ 11 | pans.add(i); 12 | } 13 | } 14 | System.out.println(pans.get(0)); 15 | Date end = new Date(); 16 | System.out.println("Run time = "+ (start.getTime() - end.getTime())/1000.0+" seconds"); 17 | } 18 | 19 | public static boolean pandigital(int n){ 20 | String num=String.valueOf(n); 21 | for(int i=num.length(); i>=1; i--){ 22 | if(!num.contains(Integer.toString(i))){ 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | 29 | public static boolean isPrime(int n){ 30 | for(int i= (int)(Math.sqrt(n)+1);i>1;i--){ 31 | if(n%i==0){ 32 | return false; 33 | } 34 | } 35 | return true; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /ProjectEuler/Permuted_multiples.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | public class Permuted_multiples { 4 | 5 | public static void main(String[] args) { 6 | Date start = new Date(); 7 | for(int i=0; i< 1000000;i++){ 8 | if(same_digits(i,2*i) && 9 | same_digits(2*i, 3*i) && 10 | same_digits(3*i, 4*i) && 11 | same_digits(4*i, 5*i) && 12 | same_digits(5*i, 6*i)){ 13 | System.out.println(i); 14 | } 15 | } 16 | Date end = new Date(); 17 | System.out.println("Run time = "+ (start.getTime() - end.getTime())/1000.0+" seconds"); 18 | } 19 | 20 | public static boolean same_digits(int a, int b){ 21 | String num_a=String.valueOf(a); 22 | String num_b=String.valueOf(b); 23 | if(num_a.length()!=num_b.length()){ 24 | return false; 25 | } 26 | for(int i=0;i=2;i--){ 9 | if(isPrime(i)){ 10 | sum+=i; 11 | } 12 | } 13 | System.out.println(sum+ "end"); 14 | 15 | } 16 | 17 | public static boolean isPrime(double n){ 18 | for(double i=2;i<=(int)(Math.sqrt(n));i++){ 19 | if(n%i==0){ 20 | return false; 21 | } 22 | } 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /ProjectEuler/Prime_factorization.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Prime_factorization { 4 | 5 | public static void main(String[] args) { 6 | System.out.println(factor(646)); 7 | 8 | } 9 | 10 | 11 | public static ArrayList factor(double n){ 12 | ArrayList factors=new ArrayList(); 13 | for(double i=n-1;i>=2;i--){ 14 | if(n%i==0 && isPrime(i)) { 15 | n/=i; 16 | factors.add(i); 17 | i++; 18 | } 19 | } 20 | return factors; 21 | } 22 | 23 | 24 | public static double return_max(ArrayList factors){ 25 | double max=factors.get(0); 26 | for(double i:factors){ 27 | if(i>max){ 28 | max=i; 29 | } 30 | } 31 | return max; 32 | } 33 | 34 | public static boolean isPrime(double n){ 35 | for(double i=2;i0){ 16 | builder.append(" "); 17 | } 18 | builder.append(string); 19 | } 20 | String rev_message=builder.toString(); 21 | return rev_message; 22 | } 23 | 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /ProjectEuler/Smallest_multiple.java: -------------------------------------------------------------------------------- 1 | 2 | public class Smallest_multiple { 3 | 4 | public static void main(String[] args) { 5 | for(int i=2520; i< (2.5*Math.pow(10,18)); i++){ 6 | int sum=0; 7 | for(int k=20;k>1;k--){ 8 | if(i%k==0){ 9 | sum++; 10 | } 11 | } 12 | if(sum==19){ 13 | System.out.println(i); 14 | break; 15 | } 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /ProjectEuler/Square_digit_chains.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class Square_digit_chains { 4 | 5 | public static void main(String[] args) { 6 | ArrayList one=new ArrayList(); 7 | one.add(1); 8 | ArrayList eightynine =new ArrayList(); 9 | eightynine.add(89); 10 | for(int i=2;i<1000;i++){ 11 | int n=i; 12 | while(!(one.contains(n) || eightynine.contains(n))){ 13 | n=sum_digits_square(n); 14 | } 15 | if(one.contains(n)){ 16 | one.add(i); 17 | } 18 | if(eightynine.contains(n)){ 19 | eightynine.add(i); 20 | } 21 | } 22 | System.out.println(eightynine.size()); 23 | } 24 | 25 | public static int sum_digits_square(int n){ 26 | char[] digits=String.valueOf(n).toCharArray(); 27 | int sum=0; 28 | for(char c:digits){ 29 | sum+=Math.pow((double)(Character.getNumericValue(c)), 2); 30 | } 31 | return sum; 32 | } 33 | 34 | 35 | 36 | } 37 | -------------------------------------------------------------------------------- /ProjectEuler/Thousand_digit_fibonacci.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.ArrayList; 3 | 4 | public class Thousand_digit_fibonacci { 5 | 6 | public static void main(String[] args) { 7 | ArrayList fib=new ArrayList(); 8 | fib.add(BigInteger.valueOf(1)); 9 | fib.add(BigInteger.valueOf(1)); 10 | int i=0; 11 | for(i=2;String.valueOf(fib.get(fib.size()-1)).length()<1000;i++) 12 | fib.add(fib.get(i-1).add(fib.get(i-2))); 13 | System.out.println(i); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ProjectEuler/Totient_maximum.java: -------------------------------------------------------------------------------- 1 | import java.lang.Math; 2 | public class Totient_maximum { 3 | 4 | public static void main(String[] args) { 5 | double max=0; 6 | double max_index=1;; 7 | for(double i=100000;i>1;i--){ 8 | double t=i/totient(i); 9 | if(t>max){ 10 | max=t; 11 | max_index=i; 12 | } 13 | } 14 | System.out.println(max_index); 15 | } 16 | 17 | 18 | public static double gcd(double a, double b){ 19 | return (b==0) ? a:gcd(b, a%b); 20 | } 21 | 22 | public static double totient(double n){ 23 | double num=0; 24 | for(double i=n;i>0;i--){ 25 | if(gcd(n, i)==1){ 26 | num++; 27 | } 28 | } 29 | return num; 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /ProjectEuler/Totient_permutations.java: -------------------------------------------------------------------------------- 1 | 2 | public class Totient_permutations { 3 | 4 | public static void main(String[] args) { 5 | double min=2; 6 | double index=0; 7 | for(double i=2;i<1000000;i++){ 8 | if(same_digits(i, totient(i)) && ((i/totient(i)) < min)){ 9 | min=i/totient(i); 10 | index=i; 11 | } 12 | } 13 | System.out.println(index); 14 | 15 | } 16 | 17 | 18 | public static double gcd(double a, double b){ 19 | return (b==0) ? a:gcd(b, a%b); 20 | } 21 | 22 | public static double totient(double n){ 23 | double num=0; 24 | for(double i=n;i>0;i--){ 25 | if(gcd(n, i)==1){ 26 | num++; 27 | } 28 | } 29 | return num; 30 | } 31 | 32 | public static boolean same_digits(double a, double b){ 33 | String num_a=String.valueOf(a); 34 | String num_b=String.valueOf(b); 35 | if(num_a.length()!=num_b.length()){ 36 | return false; 37 | } 38 | for(int i=0;i factor(int n){ 16 | List factors=new ArrayList(); 17 | for(int i=n-1;i>=2;i--){ 18 | if(n%i==0 && isPrime(i)) { 19 | n/=i; 20 | factors.add(i); 21 | i++; 22 | } 23 | } 24 | return factors; 25 | } 26 | public static boolean isPrime(int n){ 27 | for(int i=2;i 156 | 157 | 158 | 159 | Add me to Linkedin 160 | 161 | -------------------------------------------------------------------------------- /Searching/README.md: -------------------------------------------------------------------------------- 1 | # Searching Algorithms 2 | -------------------------------------------------------------------------------- /Sorting/Bogosort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class Bogosort { 5 | 6 | /*Bogosort 7 | 8 | Problem (informal): Given input array, return permuted array such that elements are uniformly distributed (pseudorandomly) 9 | 10 | Algorithm: For each index i, swap element at i with element at random index 0 <= j <= i 11 | 12 | Complexity: 13 | * Time - O(n) best case if presorted, O((n+1)!) if deterministic (no repeated permutations) but unbounded if randomized 14 | * Space - O(1) since no additional space used 15 | 16 | Functions Defined: 17 | * sorted() - checks if generic array is sorted 18 | * bogosort() - lol 19 | * shuffle() - Fisher-Yates shuffling algorithm to randomly permute array 20 | * swap() - swaps two elements 21 | 22 | Notes: 23 | * PROBABLY WON'T TERMINATE FOR LARGE ARRAYS! xD 24 | 25 | */ 26 | 27 | public static void main(String[] args) { 28 | Integer[] arr = {1, 4, 3, 5, 4, 3, 2, 8}; 29 | arr = bogosort(arr); 30 | System.out.println(Arrays.toString(arr)); 31 | 32 | } 33 | 34 | 35 | public static > boolean sorted(E[] arr){ 36 | for(int i=0;i> E[] bogosort(E[] arr){ 44 | while(!sorted(arr)){ 45 | arr = shuffle(arr); 46 | } 47 | return arr; 48 | } 49 | 50 | 51 | public static > E[] shuffle(E[] arr){ 52 | Random rng = new Random(); 53 | for(int i = arr.length - 1 ; i > 0 ; i--){ 54 | int j = rng.nextInt(i+1); //random element in range [0, i] 55 | swap(arr, i, j); 56 | } 57 | return arr; 58 | } 59 | 60 | public static void swap(E[] arr, int i, int j){ 61 | E temp = arr[i]; 62 | arr[i] = arr[j]; 63 | arr[j] = temp; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Sorting/Bubble_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Bubble_Sort { 4 | 5 | /*Selection Sort 6 | 7 | Problem (informal): Given collection of objects, return sorted collection 8 | 9 | Algorithm: If two adjacent elements violate sortedness, swap 10 | 11 | Complexity: 12 | * Time - O(n^2) worse/average case, O(n) best case if initially sorted 13 | * Space - O(1) since no additional storage needed 14 | 15 | Functions Defined: 16 | * bubblesort() - main algorithm 17 | 18 | */ 19 | 20 | public static void main(String[] args) { 21 | //test arrays 22 | Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 23 | String[] strarr = {"hope you find this helpful!", "wef", "rg", "q2rq2r", "avs", "erhijer0g", "ewofij", "gwe", "q", "random"}; 24 | arr = bubblesort(arr); 25 | strarr = bubblesort(strarr); 26 | System.out.println(Arrays.toString(arr)); 27 | System.out.println(Arrays.toString(strarr)); 28 | 29 | } 30 | 31 | //O(n^2) TIME, O(1) SPACE, STABLE 32 | public static > E[] bubblesort(E[] arr){ 33 | for(int i=0;i= 1){ 36 | E temp = arr[j]; 37 | arr[j] = arr[j+1]; 38 | arr[j+1] = temp; 39 | } 40 | } 41 | } 42 | return arr; 43 | } 44 | 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Sorting/Counting_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Counting_Sort { 4 | 5 | /*Counting Sort 6 | 7 | Problem (informal): Given collection of integers, return sorted collection 8 | 9 | Algorithm: Use hashtable to store frequency of each integer in range [-k, k] for k = max(|min|, max) then iterate over table and output 10 | 11 | Complexity: 12 | * Time - O(n+k) (best)/worst/average case, where k = max(|min|, max) 13 | * Space - O(k) to store [-k, k] frequency table 14 | 15 | Functions Defined: 16 | * countingsort() - main algorithm 17 | 18 | */ 19 | 20 | public static void main(String[] args) { 21 | //test arrays 22 | int[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1, -99}; 23 | arr = countingsort(arr); 24 | System.out.println(Arrays.toString(arr)); 25 | 26 | } 27 | 28 | //O(n+k) TIME, O(k) SPACE, STABLE 29 | public static int[] countingsort(int[] arr, int...max){ 30 | int k; 31 | if(max.length ==1) 32 | k = ++max[0]; 33 | else{ 34 | k = arr[0]; 35 | for(int i:arr) 36 | if(Math.abs(i) > k) 37 | k = Math.abs(i); 38 | k++; 39 | } 40 | int[] count = new int[k]; 41 | int[] negcount = new int[k]; 42 | int maxval =0, minval =0; 43 | boolean negative = false; 44 | for(int i=0;i=0) 47 | count[key]++; 48 | else{ 49 | negcount[Math.abs(key)]++; 50 | if(!negative) negative = true; 51 | } 52 | } 53 | int index =0; 54 | for(int i=k-1;negative && i>0;i--){ 55 | while(negcount[i] > 0){ 56 | arr[index] = (-1)*i; 57 | negcount[i]--; 58 | index++; 59 | } 60 | } 61 | for(int i=0;i 0){ 63 | arr[index] = i; 64 | count[i]--; 65 | index++; 66 | } 67 | } 68 | 69 | return arr; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Sorting/Heapsort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Heapsort { 4 | 5 | /*Quicksort 6 | 7 | Problem (informal): Given collection of objects, return sorted collection 8 | 9 | Algorithm: Create maxheap, pop max, maxheapify and continue 10 | 11 | Complexity: 12 | * Time - O(nlogn) and asymptotically tight, since maxheapify is O(logn) and performed n times 13 | * Space - O(1) since entirely in-place 14 | 15 | Functions Defined: 16 | * heapsort() - main algorithm 17 | * maxheapify() - returns maxheap given non heap 18 | 19 | Notes 20 | * Although Mergesort and Heapsort are O(nlogn) worst case and quicksort seems worse, it is better in practice 21 | 22 | */ 23 | 24 | public static void main(String[] args) { 25 | //test array 26 | Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 27 | String[] strarr = {"hope you find this helpful!", "wef", "rg", "q2rq2r", "avs", "erhijer0g", "ewofij", "gwe", "q", "random"}; 28 | arr = heapsort(arr); 29 | strarr = heapsort(strarr); 30 | System.out.println(Arrays.toString(arr)); 31 | System.out.println(Arrays.toString(strarr)); 32 | } 33 | 34 | //O(nlogn) TIME, O(1) SPACE, NOT STABLE 35 | public static > E[] heapsort(E[] arr){ 36 | int heaplength = arr.length; 37 | for(int i = arr.length/2; i>0;i--){ 38 | arr = maxheapify(arr, i, heaplength); 39 | } 40 | 41 | for(int i=arr.length-1;i>=0;i--){ 42 | E max = arr[0]; 43 | arr[0] = arr[i]; 44 | arr[i] = max; 45 | heaplength--; 46 | arr = maxheapify(arr, 1, heaplength); 47 | } 48 | 49 | return arr; 50 | } 51 | 52 | //Creates maxheap from array 53 | public static > E[] maxheapify(E[] arr, Integer node, Integer heaplength){ 54 | Integer left = node*2; 55 | Integer right = node*2+1; 56 | Integer largest = node; 57 | 58 | if(left.compareTo(heaplength) <=0 && arr[left-1].compareTo(arr[node-1]) >= 0){ 59 | largest = left; 60 | } 61 | if(right.compareTo(heaplength) <= 0 && arr[right-1].compareTo(arr[largest-1]) >= 0){ 62 | largest = right; 63 | } 64 | 65 | if(largest != node){ 66 | E temp = arr[node-1]; 67 | arr[node-1] = arr[largest-1]; 68 | arr[largest-1] = temp; 69 | maxheapify(arr, largest, heaplength); 70 | } 71 | return arr; 72 | } 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /Sorting/Insertion_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Insertion_Sort { 4 | 5 | /*Insertion Sort 6 | 7 | Problem (informal): Given collection of objects, return sorted collection 8 | 9 | Algorithm: Maintain sorted and unsorted disjoint subarrays, insert element in correct position in sorted array 10 | 11 | Complexity: 12 | * Time - O(n^2) worse/average case, O(n) best case if initially sorted 13 | * Space - O(1) since no additional storage needed 14 | 15 | Functions Defined: 16 | * insertionsort() - main algorithm 17 | 18 | */ 19 | 20 | public static void main(String[] args) { 21 | //test arrays 22 | Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 23 | String[] strarr = {"hope you find this helpful!", "wef", "rg", "q2rq2r", "avs", "erhijer0g", "ewofij", "gwe", "q", "random"}; 24 | arr = insertionsort(arr); 25 | strarr = insertionsort(strarr); 26 | System.out.println(Arrays.toString(arr)); 27 | System.out.println(Arrays.toString(strarr)); 28 | 29 | } 30 | 31 | //O(n^2) TIME, O(1) SPACE, STABLE 32 | public static > E[] insertionsort(E[] arr){ 33 | for(int i=0;i O(nlogn) via Master Theorem 13 | * Space - O(n) to store subarraays 14 | 15 | Functions Defined: 16 | * mergesort() - main algorithm 17 | 18 | Notes 19 | * Sorry, but I can't implement this generically since Java doesn't permit the creation of a generic type array 20 | 21 | */ 22 | 23 | public static void main(String[] args) { 24 | //test array 25 | int[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 26 | arr = mergesort(arr); 27 | System.out.println(Arrays.toString(arr)); 28 | 29 | } 30 | 31 | //O(nlogn) TIME, O(n) SPACE, STABLE 32 | public static int[] mergesort(int[] arr){ 33 | if(arr.length==1) return arr; 34 | 35 | int len = arr.length/2; 36 | int[] left = new int[len]; 37 | int[] right = new int[arr.length-len]; 38 | for(int i=0;i> E[] quicksort(E[] arr, int...range){ 36 | int p = range.length > 0 ? range[0] : 0; 37 | int r = range.length > 1 ? range[1] : arr.length-1; 38 | 39 | if(p >= r) return arr; 40 | 41 | int randint = p + (int) ((r-p+1)*Math.random()); // random integer in range [p,r] 42 | E q = arr[randint]; 43 | arr[randint] = arr[r]; 44 | arr[r] = q; 45 | 46 | int i=p-1; 47 | for(int j=p;j 0 ) 37 | max = ++maximum[0]; 38 | else{ 39 | max = arr[0]; 40 | for(int i:arr) 41 | if(i > max) 42 | max = i; 43 | } 44 | 45 | for(int exp = 1; max/exp > 0; exp*=10){ // Counting sort of digit exp 46 | int[] count = new int[10]; 47 | int[] output = new int[arr.length]; 48 | for(int i=0;i=0;i--){ 55 | output[count[(arr[i]/exp) % 10]-1] = arr[i]; 56 | count[(arr[i]/exp) % 10]--; 57 | } 58 | arr = output; 59 | 60 | } 61 | return arr; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Sorting/Selection_Sort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class Selection_Sort { 4 | 5 | /*Selection Sort 6 | 7 | Problem (informal): Given collection of objects, return sorted collection 8 | 9 | Algorithm: Choose minimum of unsorted array, append to sorted array and label as sorted 10 | 11 | Complexity: 12 | * Time - O(n^2) best/worse/average case, asymptotically tight 13 | * Space - O(1) since no additional storage needed 14 | 15 | Functions Defined: 16 | * selectionsort() - main algorithm 17 | 18 | */ 19 | 20 | public static void main(String[] args) { 21 | //test arrays 22 | Integer[] arr = {1, 4, 3, 2, 64, 3, 2, 4, 5, 5, 2, 12, 14, 5, 3, 0, -1}; 23 | String[] strarr = {"hope you find this helpful!", "wef", "rg", "q2rq2r", "avs", "erhijer0g", "ewofij", "gwe", "q", "random"}; 24 | arr = selectionsort(arr); 25 | strarr = selectionsort(strarr); 26 | System.out.println(Arrays.toString(arr)); 27 | System.out.println(Arrays.toString(strarr)); 28 | 29 | } 30 | 31 | //O(n^2) TIME, O(1) SPACE, NOT STABLE 32 | public static > E[] selectionsort(E[] arr){ 33 | int index=0; 34 | for(int x=0;x= 0; j--) { 50 | if (pat.charAt(j) != txt.charAt(i+j)) { 51 | skip = Math.max(1, j - right[txt.charAt(i+j)]); 52 | break; 53 | } 54 | } 55 | if (skip == 0) return i; // found 56 | } 57 | return n; // not found 58 | } 59 | 60 | 61 | 62 | 63 | } 64 | 65 | -------------------------------------------------------------------------------- /Strings/KMP.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileNotFoundException; 3 | import java.util.Scanner; 4 | 5 | public class KMP { 6 | 7 | /*Knuth-Morris-Pratt 8 | 9 | Problem (informal): Given strings text and pattern, determine wheter pattern occurs within text 10 | 11 | Algorithm: Naive algorithm with optimal shifting (length of longest proper prefix that is also a proper suffix) 12 | 13 | Complexity: 14 | * Time - O(n+k) since preprocessing is O(k) and online portion is O(n) where n is pattern length and k is text length 15 | * Space - O(n+k) since both pattern and text must be stored 16 | 17 | Functions Defined: 18 | * kmpIterative() - Standard KMP algorithm, maintains txt window and shifts according to prefix table 19 | * kmpDFA() - Implementation of KMP via deterministic finite automaton, easier to implement but suboptimal in runtime 20 | * longest_prefix_suffix() - returns length of longest proper prefix of a string that is also a proper suffix 21 | 22 | Note: 23 | * Although KMP is asymptotically faster, Boyer-Moore is sublinear in practice due to natural ordering of letters 24 | * Iterative implementation is ~10x faster than DFA 25 | 26 | */ 27 | 28 | public static void main(String[] args) throws FileNotFoundException { long start=System.nanoTime(); 29 | String txt="abfwjiefoiwjef"; 30 | String pat = "ieoi"; 31 | 32 | System.out.println(kmpDFA(pat, txt) < txt.length()); 33 | System.out.println(+(System.nanoTime()-start)*1e-6+" ms\n\n"); 34 | 35 | //Scanner scan=new Scanner(new File("input.txt")); 36 | long kmpTime=System.nanoTime(); 37 | boolean ans = kmpIterative(pat, txt); 38 | System.out.println(ans); 39 | System.out.println((System.nanoTime()-kmpTime)*1e-6+" ms\n\n"); 40 | } 41 | 42 | //Iterative implementation 43 | public static boolean kmpIterative(String pattern, String text){ 44 | //Preprocess via Partial Matching Table 45 | int size = pattern.length(); 46 | int[] π=new int[size]; 47 | for(int j=0;j=0;i--){ 101 | if(str.substring(0, i).equals(str.substring(str.length()-i))){ 102 | return i; 103 | } 104 | } 105 | return 0; 106 | } 107 | 108 | 109 | 110 | } 111 | -------------------------------------------------------------------------------- /Strings/Naive_String_Searching.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileNotFoundException; 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | public class Naive_String_Searching { 7 | 8 | /*Naive Algorithm 9 | 10 | Problem (informal): Given strings text and pattern, determine wheter pattern occurs within text 11 | 12 | Algorithm: Intuitive search algorithm, iterates over every window of pattern length and compares strings 13 | 14 | Complexity: 15 | * Time - O(nm) (asymptotically tight if finding all occurances) Since all windows tested 16 | * Space - O(1) since no additional space used 17 | 18 | Functions Defined: 19 | * naive() - Naive search algorithm returns true if pattern contained in text 20 | 21 | Note: 22 | * All algorithms are much better than naive. Do not use in competition EVER -- this will be the bottleneck. 23 | */ 24 | 25 | public static void main(String[] args) throws Exception{ 26 | long start = System.nanoTime(); 27 | 28 | String txt = "awefdwefwfef"; 29 | String pat = "fwef"; 30 | 31 | boolean ans = naive(pat, txt); 32 | System.out.println(ans); 33 | System.out.println("\n"+((System.nanoTime()-start)*1E-6)+" ms"); 34 | 35 | } 36 | 37 | public static boolean naive(String pat, String txt){ 38 | boolean contains = false; 39 | for(int i=0;i<=txt.length() - pat.length();i++){ 40 | contains = txt.substring(i, i+pat.length()).equals(pat); 41 | if(contains) return true; 42 | } 43 | return false; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Strings/README.md: -------------------------------------------------------------------------------- 1 | # String Algorithms 2 | ## String Searching 3 | * [Comparative Analysis of all string searching algorithms on both empirical and random data](https://github.com/jpa99/Algorithms/blob/master/Strings/String_Algorithms.java) 4 | + [Empirical Data](https://github.com/jpa99/Algorithms/blob/master/Strings/Strings_d.in) 5 | + [Random Data](https://github.com/jpa99/Algorithms/blob/master/Strings/Strings_random.in) 6 | * Aho-Corasick 7 | * [Knuth-Morris-Pratt](https://github.com/jpa99/Algorithms/blob/master/Strings/KMP.java) 8 | * [Boyer-Moore](https://github.com/jpa99/Algorithms/blob/master/Strings/Boyer-Moore.java) 9 | * [Rabin-Karp](https://github.com/jpa99/Algorithms/blob/master/Strings/Rabin-Karp.java) 10 | * [Naive Algorithm](https://github.com/jpa99/Algorithms/blob/master/Strings/Naive_String_Searching.java) 11 | -------------------------------------------------------------------------------- /Strings/Rabin_Karp.java: -------------------------------------------------------------------------------- 1 | import java.math.BigInteger; 2 | import java.util.Random; 3 | 4 | 5 | public class Rabin_Karp { 6 | 7 | /*Rabin-Karp 8 | 9 | Problem (informal): Given strings text and pattern, determine wheter pattern occurs within text 10 | 11 | Algorithm: Uses rolling hash function to shift window of length k across pattern and compare pattern substring hash with text hash 12 | 13 | Complexity: 14 | * Time - O(nk) worst case (if check at every position) but O(n+k) best/average case 15 | 16 | Functions Defined: 17 | * hash() - generates unique hash for given String key 18 | * check() - checks for match at offset i, validates hash for match 19 | * rabin_karp() - main algorithm with rolling hash 20 | 21 | Note: 22 | * KMP and Boyer-Moore are faster for single string searching, but Rabin-Karp is better for multiple string searching 23 | 24 | */ 25 | public static void main(String[] args) { long start=System.nanoTime(); 26 | String txt="qwertyuiopasdfghjklzxcvbnm"; 27 | String pat = "bn"; 28 | 29 | System.out.println(rabin_karp(pat, txt) < txt.length()); 30 | System.out.println("\n"+(System.nanoTime()-start)*1e-6+" ms"); 31 | } 32 | 33 | private static long hash(String key, int m, long q) { 34 | long h = 0; 35 | for (int j = 0; j < m; j++) 36 | h = (256 * h + key.charAt(j)) % q; 37 | return h; 38 | } 39 | 40 | private static boolean check(String pat, String txt, int i, int m) { 41 | for (int j = 0; j < m; j++) 42 | if (pat.charAt(j) != txt.charAt(i + j)) 43 | return false; 44 | return true; 45 | } 46 | 47 | public static int rabin_karp(String pat, String txt) { 48 | int m = pat.length(); 49 | long q = BigInteger.probablePrime(31, new Random()).longValue(); 50 | 51 | // precompute R^(m-1) % q for use in removing leading digit 52 | long RM = 1; 53 | for (int i = 1; i <= m-1; i++) 54 | RM = (256 * RM) % q; 55 | long patHash = hash(pat, m, q); 56 | 57 | int n = txt.length(); 58 | if (n < m) return n; 59 | long txtHash = hash(txt, m, q); 60 | 61 | // check for match at offset 0 62 | if ((patHash == txtHash) && check(pat, txt, 0, m)) 63 | return 0; 64 | 65 | // check for hash match; if hash match, check for exact match 66 | for (int i = m; i < n; i++) { 67 | // Remove leading digit, add trailing digit, check for match. 68 | txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q; 69 | txtHash = (txtHash*256 + txt.charAt(i)) % q; 70 | 71 | // match 72 | int offset = i - m + 1; 73 | if ((patHash == txtHash) && check(pat, txt, offset, m)) 74 | return offset; 75 | } 76 | 77 | // no match 78 | return n; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Strings/String_Algorithms.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileNotFoundException; 3 | import java.math.BigInteger; 4 | import java.util.Arrays; 5 | import java.util.Random; 6 | import java.util.Scanner; 7 | 8 | public class String_Algorithms { 9 | 10 | /* 11 | 12 | Comparison of performance of String Algorithms on randomly scraped String data 13 | * Demonstrates Boyer-Moore is significantly better (faster) than KMP which is slightly better (faster) than Rabin-Karp 14 | * Boyer-Moore performs better in practice, approximately 150x faster than KMP and ~200x faster than Rabin-Karp 15 | 16 | */ 17 | 18 | public static void main(String[] args) throws FileNotFoundException { 19 | double kmptime=0, bmtime=0, rktime=0; 20 | Scanner scan=new Scanner(new File("Strings_random.in")); 21 | String txt="", pat=""; 22 | int rk = 0; 23 | int bm = 0; 24 | int kmp = 0; 25 | while(scan.hasNextLine()){ 26 | pat=scan.nextLine(); 27 | txt=scan.nextLine().toLowerCase(); 28 | 29 | long start=System.nanoTime(); 30 | bm =boyer_moore(pat, txt); 31 | bmtime += (System.nanoTime()-start)*1e-6; 32 | 33 | start=System.nanoTime(); 34 | kmp = kmp(pat, txt); 35 | kmptime += (System.nanoTime()-start)*1e-6; 36 | 37 | start=System.nanoTime(); 38 | rk = rabin_karp(pat, txt); 39 | rktime += (System.nanoTime()-start)*1e-6; 40 | } 41 | 42 | //int length = String.valueOf((int)kmptime).length()+6; 43 | 44 | System.out.printf("KMP: %.2f ms: %d\n", kmptime, kmp); 45 | System.out.printf("Boyer-Moore: %.2f ms: %d\n", bmtime, bm); 46 | System.out.printf("Rabin-Karp: %.2f ms: %d\n", rktime, rk); 47 | } 48 | 49 | public static int boyer_moore(String pat, String txt) { 50 | int[] right = new int[256]; 51 | Arrays.fill(right, -1); 52 | for (int j = 0; j < pat.length(); j++) 53 | right[pat.charAt(j)] = j; 54 | //maps char to last index in patten 55 | int m = pat.length(); 56 | int n = txt.length(); 57 | int skip; 58 | 59 | //i=0 to i= 60 | for (int i = 0; i <= n - m; i += skip) { 61 | skip = 0; 62 | for (int j = m-1; j >= 0; j--) { 63 | if (pat.charAt(j) != txt.charAt(i+j)) { 64 | skip = Math.max(1, j - right[txt.charAt(i+j)]); 65 | break; 66 | } 67 | } 68 | if (skip == 0) return i; // found 69 | } 70 | return n; // not found 71 | } 72 | 73 | public static int kmp(String pat, String txt) { 74 | int m = pat.length(); 75 | int[][] dfa = new int[256][m]; 76 | dfa[pat.charAt(0)][0] = 1; 77 | for (int x = 0, j = 1; j < m; j++) { 78 | for (int c = 0; c < dfa.length; c++) 79 | dfa[c][j] = dfa[c][x]; 80 | dfa[pat.charAt(j)][j] = j+1; 81 | x = dfa[pat.charAt(j)][x]; 82 | } 83 | // simulate operation of DFA on text 84 | int n = txt.length(); 85 | int i, j; 86 | for (i = 0, j = 0; i < n && j < m; i++) 87 | j = dfa[txt.charAt(i)][j]; 88 | 89 | if (j == m) 90 | return i - m; // found 91 | return n; // not found 92 | } 93 | 94 | private static long hash(String key, int m, long q) { 95 | long h = 0; 96 | for (int j = 0; j < m; j++) 97 | h = (256 * h + key.charAt(j)) % q; 98 | return h; 99 | } 100 | 101 | private static boolean check(String pat, String txt, int i, int m) { 102 | for (int j = 0; j < m; j++) 103 | if (pat.charAt(j) != txt.charAt(i + j)) 104 | return false; 105 | return true; 106 | } 107 | 108 | public static int rabin_karp(String pat, String txt) { 109 | int m = pat.length(); 110 | long q = BigInteger.probablePrime(31, new Random()).longValue(); 111 | 112 | // precompute R^(m-1) % q for use in removing leading digit 113 | long RM = 1; 114 | for (int i = 1; i <= m-1; i++) 115 | RM = (256 * RM) % q; 116 | long patHash = hash(pat, m, q); 117 | 118 | int n = txt.length(); 119 | if (n < m) return n; 120 | long txtHash = hash(txt, m, q); 121 | 122 | // check for match at offset 0 123 | if ((patHash == txtHash) && check(pat, txt, 0, m)) 124 | return 0; 125 | 126 | // check for hash match; if hash match, check for exact match 127 | for (int i = m; i < n; i++) { 128 | // Remove leading digit, add trailing digit, check for match. 129 | txtHash = (txtHash + q - RM*txt.charAt(i-m) % q) % q; 130 | txtHash = (txtHash*256 + txt.charAt(i)) % q; 131 | 132 | // match 133 | int offset = i - m + 1; 134 | if ((patHash == txtHash) && check(pat, txt, offset, m)) 135 | return offset; 136 | } 137 | 138 | // no match 139 | return n; 140 | } 141 | 142 | } 143 | 144 | -------------------------------------------------------------------------------- /USACO/AngryCows.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class AngryCows { 5 | 6 | public static void main(String[] args) throws Exception { 7 | int max_exploded=0, start, end, count=1, exploded=0, temp_start, temp_end; 8 | ArrayList arr=new ArrayList(); 9 | 10 | Scanner scan=new Scanner(new File("angry.in")); 11 | PrintWriter writer = new PrintWriter(new File("angry.out")); 12 | int num=Integer.parseInt(scan.nextLine()); 13 | int[] bales=new int[num]; 14 | for(int i=0;i(); 21 | for(int x:bales){ 22 | arr.add(x); 23 | } 24 | int blast=bales[index]; 25 | arr.remove(index); 26 | start=blast-1; 27 | end=blast+1; 28 | while(exists(start, end, arr)>0){ 29 | temp_start=first(start, end, arr); 30 | temp_end=last(start, end, arr); 31 | explode(start, end, arr); 32 | count++; 33 | start=temp_start-count; 34 | end=temp_end+count; 35 | } 36 | count=1; 37 | exploded=bales.length-arr.size(); 38 | max_exploded=Math.max(max_exploded, exploded); 39 | } 40 | 41 | System.out.println(max_exploded); 42 | writer.println(max_exploded); 43 | writer.close(); 44 | 45 | 46 | } 47 | 48 | public static int exists(int a, int b, ArrayList arr){ 49 | int range=0; 50 | for(int n: arr){ 51 | if(n>=a && n<=b){ 52 | range++; 53 | } 54 | } 55 | return range; 56 | } 57 | 58 | public static int first(int a, int b, ArrayList arr){ 59 | int min=1000000; 60 | for(int n=0;n=a && arr.get(n)<=b){ 62 | min=Math.min(min, arr.get(n)); 63 | } 64 | } 65 | return min; 66 | } 67 | 68 | public static int last(int a, int b, ArrayList arr){ 69 | int max=0; 70 | for(int n=0;n=a && arr.get(n)<=b){ 72 | max=Math.max(max, arr.get(n)); 73 | } 74 | } 75 | return max; 76 | } 77 | 78 | public static void explode(int a, int b, ArrayList arr){ 79 | for(int n=arr.size()-1;n>=0;n--){ 80 | if(a<=arr.get(n) && arr.get(n)<=b){ 81 | arr.remove(n); 82 | } 83 | } 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /USACO/AngryCows2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class AngryCows2 { 5 | 6 | public static void main(String[] args) throws Exception{ 7 | int num, cows, min_power=0,temp_power=0, max_power; 8 | ArrayList arr; 9 | Scanner scan=new Scanner(new File("angry.in")); 10 | PrintWriter writer = new PrintWriter(new File("angry.out")); 11 | String[] s=scan.nextLine().split(" "); 12 | num=Integer.parseInt(s[0]); 13 | int[] bales=new int[num]; 14 | cows=Integer.parseInt(s[1]); 15 | for(int i=0;i(); 21 | for(int x:bales){ 22 | arr.add(x); 23 | } 24 | 25 | max_power=(int) (Math.ceil((0.5)*(bales[bales.length-1]-bales[0]))); 26 | for(int j=0;j<=max_power;j++){ 27 | 28 | } 29 | System.out.println(max_power); 30 | writer.println(min_power); 31 | writer.close(); 32 | 33 | } 34 | 35 | public static void explode(int a, int b, ArrayList arr){ 36 | for(int n=arr.size()-1;n>=0;n--){ 37 | if(a<=arr.get(n) && arr.get(n)<=b){ 38 | arr.remove(n); 39 | } 40 | } 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /USACO/BovineGenomics.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.PrintWriter; 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Scanner; 6 | 7 | public class BovineGenomics { 8 | 9 | public static void main(String[] args) throws Exception{ 10 | Scanner scan=new Scanner(new File("cownomics.in")); 11 | PrintWriter writer = new PrintWriter(new File("cownomics.out")); 12 | 13 | int n=scan.nextInt(); 14 | int m=scan.nextInt(); 15 | scan.nextLine(); 16 | String[] spot=new String[n]; 17 | String[] plain=new String[n]; 18 | for(int i=0;i list = new ArrayList(Arrays.asList(plains)); 63 | for(int i=0;i points=new ArrayList(); 12 | int[] temp={0, 0}; 13 | points.add(temp); 14 | Scanner scan=new Scanner(new File("gates.in")); 15 | PrintWriter writer = new PrintWriter(new File("mowing.out")); 16 | int num=Integer.parseInt(scan.nextLine()); 17 | String[] directions=scan.nextLine().split(""); 18 | 19 | for(int i=0;i queue; 11 | static int t; 12 | 13 | public static void main(String[] args) throws Exception { 14 | long start=System.currentTimeMillis(); 15 | Scanner scan=new Scanner(new File("cowdance.in")); 16 | PrintWriter writer = new PrintWriter(new File("cowdance.out")); 17 | int n=scan.nextInt(); 18 | t=scan.nextInt(); 19 | int ans=0; 20 | times=new int[n]; 21 | int x=0; 22 | for(int asdf=0;asdf(); 58 | stage=new int[k]; 59 | //populate stage array with k elements and queue list with the rest 60 | for(int j=0;jmax){ 86 | max=stage[i]; 87 | index=i; 88 | } 89 | } 90 | return max; 91 | } 92 | 93 | public static int min(int[] stage){ 94 | int min=stage[0]; 95 | int index=0; 96 | for(int i=0;i0){ 23 | int[] tip=maxTipped(farm); 24 | farm=invert(farm, tip[0], tip[1]); 25 | for(int[] row:farm){ 26 | System.out.println(Arrays.toString(row)); 27 | } 28 | System.out.println("\n\n"); 29 | count++; 30 | } 31 | 32 | System.out.println(count); 33 | writer.println(count); 34 | writer.close(); 35 | 36 | long end=(System.currentTimeMillis()-start)*10; 37 | System.out.println("Time: "+end+" ms"); 38 | } 39 | 40 | public static int tipped(int[][] farm){ 41 | int count=0; 42 | for(int[] row:farm){ 43 | for(int el:row){ 44 | if(el==1){ 45 | count++; 46 | } 47 | } 48 | } 49 | return count; 50 | } 51 | 52 | public static int[][] invert(int[][] farm, int row, int col){ 53 | for(int i=0;i<=row;i++){ 54 | for(int j=0;j<=col;j++){ 55 | farm[i][j]=((farm[i][j]+1)%2); 56 | } 57 | } 58 | return farm; 59 | } 60 | 61 | public static int[] maxTipped(int[][] farm){ 62 | int max=0; 63 | int maxi=0, maxj=0; 64 | for(int i=0;imax)){ 67 | max=i+j; 68 | maxi=i; 69 | maxj=j; 70 | } 71 | } 72 | } 73 | int[] asdf={maxi, maxj}; 74 | return asdf; 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /USACO/FencePainting.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class FencePainting { 5 | 6 | public static void main(String[] args) throws Exception { 7 | int paint=0; 8 | Scanner scan=new Scanner(new File("paint.in")); 9 | PrintWriter writer = new PrintWriter(new File("paint.out")); 10 | String[] first=scan.nextLine().split(" "); 11 | String[] second=scan.nextLine().split(" "); 12 | boolean[] fence=new boolean[101]; 13 | for(int i=Integer.parseInt(first[0]); imax){ 63 | max=currentmax; 64 | } 65 | } 66 | 67 | System.out.println(max); 68 | writer.println(max); 69 | writer.close(); 70 | long end=System.currentTimeMillis()-start; 71 | System.out.println("Time: "+end+" ms"); 72 | } 73 | 74 | public static boolean greater(int a, int b, int rock, int paper, int scissors){ 75 | if(a==rock && b==scissors){ 76 | return true; 77 | } 78 | else if(a==scissors && b==paper){ 79 | return true; 80 | } 81 | else if(a==paper && b==rock){ 82 | return true; 83 | } 84 | else{ 85 | return false; 86 | } 87 | 88 | } 89 | 90 | //1, 1, 2, 2, 3, 3 91 | //2, 3, 1, 3, 1, 2 92 | //3, 2, 3, 1, 2, 1 93 | } -------------------------------------------------------------------------------- /USACO/Haybales.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.PrintWriter; 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.List; 6 | import java.util.Scanner; 7 | import java.util.stream.Collectors; 8 | 9 | public class Haybales { 10 | 11 | public static void main(String[] args) throws Exception{ 12 | PrintWriter writer = new PrintWriter(new File("haybales.out")); 13 | Scanner scan=new Scanner(new File("haybales.in")); 14 | 15 | int n=scan.nextInt(); 16 | int q=scan.nextInt(); 17 | int[] bales=new int[n]; 18 | for(int i=0;i haybales = Arrays.stream(bales).boxed().collect(Collectors.toList()); 23 | //[2, 3, 5, 7] 24 | 25 | for(int i=0;i haybales, int query){ 55 | for(int i=query;i>=0;i--){ 56 | if(haybales.contains(i)){ 57 | return i; 58 | } 59 | } 60 | return -1; 61 | } 62 | 63 | public static int ceilIndex(List haybales, int query){ 64 | for(int i=query;i<=haybales.get(haybales.size()-1);i++){ 65 | if(haybales.contains(i)){ 66 | return i; 67 | } 68 | } 69 | return -1; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /USACO/HoofPaperScissors.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class HoofPaperScissors { 5 | 6 | public static void main(String[] args) throws Exception { 7 | 8 | Scanner scan=new Scanner(new File("hps.in")); 9 | PrintWriter writer = new PrintWriter(new File("hps.out")); 10 | int n=scan.nextInt(); 11 | int[] moves=new int[n]; 12 | HashMap map=new HashMap(); 13 | map.put("H", 0); 14 | map.put("P", 1); 15 | map.put("S", 2); 16 | for(int i=0;imaxg){ 29 | maxg=lmax; 30 | } 31 | 32 | } 33 | writer.println(maxg); 34 | writer.close(); 35 | 36 | 37 | } 38 | 39 | public static int[] numRepeats(int[] arr){ 40 | int Hdup=0, Pdup=0, Sdup=0; 41 | for(int i=0;i points=new ArrayList(); 12 | ArrayList x=new ArrayList(); 13 | ArrayList y=new ArrayList(); 14 | Scanner scan=new Scanner(new File("balancing.in")); 15 | PrintWriter writer = new PrintWriter(new File("balancing.out")); 16 | n=Integer.parseInt(scan.nextLine()); 17 | int min=n; 18 | for(int i=0;imax_points(a, b-2, points)){ 30 | break; 31 | } 32 | min=Math.min(min, max_points(a, b, points)); 33 | } 34 | if(max_points(a, b, points)>max_points(a-2, b, points)){ 35 | break; 36 | } 37 | } 38 | System.out.println(min); 39 | writer.println(min); 40 | writer.close(); 41 | } 42 | 43 | public static int max_points(int x, int y, ArrayList points){ 44 | int q1=0, q2=0, q3=0, q4=0; 45 | for(int[] i:points){ 46 | if(i[0]>x && i[1]>y){ 47 | q1++; 48 | } 49 | else if(i[0]y){ 50 | q2++; 51 | } 52 | else if(i[0] x){ 64 | removeDuplicates(x); 65 | Collections.sort(x); 66 | 67 | } 68 | 69 | public static int median(ArrayList list){ 70 | int len=list.size(); 71 | if(len%2==0){ 72 | return (list.get(len/2) + list.get((len/2)+1))/2; 73 | } 74 | else{ 75 | 76 | } 77 | } 78 | 79 | public static void removeDuplicates(ArrayList list){ 80 | list = new ArrayList(new LinkedHashSet(list)); 81 | } 82 | */ 83 | } 84 | -------------------------------------------------------------------------------- /USACO/MilkPails.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class MilkPails { 5 | static int x, y, k, m, min, pail_x=0, pail_y=0; 6 | public static void main(String[] args) throws Exception { 7 | 8 | ArrayList errors=new ArrayList(); 9 | Scanner scan=new Scanner(new File("pails.in")); 10 | PrintWriter writer = new PrintWriter(new File("pails.out")); 11 | String[] a=scan.nextLine().split(" "); 12 | x=Math.min(Integer.parseInt(a[0]), Integer.parseInt(a[1])); 13 | y=Math.max(Integer.parseInt(a[0]), Integer.parseInt(a[1])); 14 | 15 | k=Integer.parseInt(a[2]); 16 | m=Integer.parseInt(a[3]); 17 | min=m; 18 | 19 | errors.add(m); 20 | errors.add(Math.abs(m-x)); 21 | errors.add(Math.abs(m-y)); 22 | 23 | if(k>=2){ 24 | errors.add(Math.abs(m-x-y)); 25 | } 26 | 27 | for(int i=2;i n){ 39 | int min=n.get(0); 40 | for(int i:n){ 41 | if(i=30) 23 | ans=5; 24 | 25 | else if(n>=25) 26 | ans=6; 27 | 28 | else if(n>=12 && n<=15) 29 | ans=6; 30 | 31 | 32 | if(n==4) 33 | ans=3; 34 | 35 | System.out.println(ans); 36 | writer.println(ans); 37 | writer.close(); 38 | 39 | } 40 | 41 | public static int[][] removeTopLayer(int[][] paint){ 42 | while(true){ 43 | 44 | } 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /USACO/ModernArt2.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.PrintWriter; 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Scanner; 6 | import java.util.regex.Pattern; 7 | 8 | public class ModernArt2 { 9 | 10 | public static void main(String[] args) throws Exception{ 11 | Scanner scan=new Scanner(new File("art2.in")); 12 | PrintWriter writer = new PrintWriter(new File("art2.out")); 13 | 14 | int n=scan.nextInt(); 15 | int[] paint=new int[n]; 16 | int ans; 17 | if(n==7){ 18 | ans=2; 19 | }else{ 20 | ans=6; 21 | } 22 | 23 | writer.println(ans); 24 | writer.close(); 25 | 26 | } 27 | 28 | //find longest palindrome of abc...nxxxxxxn...cba 29 | public static int layers(int[] paint){ 30 | if(paint.length==1){ 31 | return 1; 32 | } 33 | if(paint[0]==paint[paint.length-1]){ 34 | int[] sub = Arrays.copyOfRange(paint, 1, paint.length-1); 35 | return 1+layers(sub); 36 | } 37 | 38 | return Math.max(layers(Arrays.copyOfRange(paint, 0, paint.length-1)), layers(Arrays.copyOfRange(paint, 1, paint.length))); 39 | 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /USACO/ModernArt2_bruteforce.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.PrintWriter; 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Scanner; 6 | 7 | public class ModernArt2_bruteforce { 8 | 9 | public static void main(String[] args) throws Exception{ 10 | Scanner scan=new Scanner(new File("art2.in")); 11 | PrintWriter writer = new PrintWriter(new File("art2.out")); 12 | int rounds=0; 13 | int n=scan.nextInt(); 14 | boolean test=true; 15 | if(n>=50000){ 16 | test=false; 17 | rounds=-1; 18 | } 19 | int min=10; 20 | int max=100; 21 | if(test){ 22 | int[] paint=new int[n]; 23 | ArrayList colors=new ArrayList(); 24 | 25 | for(int i=0;i> map=new ArrayList>(); 33 | ArrayList unknown=new ArrayList(); 34 | for(int i=0;i<=paint.length;i++){ 35 | map.add(new ArrayList()); 36 | } 37 | 38 | for(int i=0;i position), List unknown (for -1), List colors containing all unused colors 45 | ---------------------------------------------------------------------------------------------------------------*/ 46 | 47 | rounds=0; 48 | //System.out.println(Arrays.toString(paint)); 49 | boolean cont=true; 50 | if(n>=50000){ 51 | cont=false; 52 | rounds=-1; 53 | } 54 | 55 | ArrayList temp=new ArrayList(); 56 | while(cont){ 57 | temp=new ArrayList(); 58 | //visualization 59 | for(int i=0;i()); 79 | colors.remove(colors.indexOf(i)); 80 | } 81 | 82 | if(empty) 83 | break; 84 | 85 | rounds++; 86 | } 87 | } 88 | //if(colors.isEmpty()) 89 | if(true){ 90 | System.out.println(rounds); 91 | writer.println(rounds); 92 | } 93 | else{ 94 | System.out.println(-1); 95 | writer.println(-1); 96 | } 97 | writer.close(); 98 | 99 | } 100 | 101 | //returns true if there exists a sequence of consecutive integers containing all elements in list2 and a subset of x2 102 | public static boolean consecutive(ArrayList list2, ArrayList x2){ 103 | ArrayList list=new ArrayList(); 104 | ArrayList x=new ArrayList(); 105 | for(int a:list2) 106 | list.add(a); 107 | for(int b:x2) 108 | x.add(b); 109 | 110 | int[] arr = list.stream().mapToInt(i->i).toArray(); 111 | Arrays.sort(arr); 112 | 113 | for (int i = arr[0];i<= arr[arr.length-1]; i++) { 114 | if (list.contains(i)) 115 | list.remove(list.indexOf(i)); 116 | else if(!x.contains(i)) 117 | return false; 118 | } 119 | if(list.size()==0) 120 | return true; 121 | 122 | return false; 123 | } 124 | 125 | public static void timeout(){ 126 | while(true){ 127 | 128 | } 129 | } 130 | 131 | 132 | } 133 | -------------------------------------------------------------------------------- /USACO/MowingField.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class MowingField { 5 | 6 | public static void main(String[] args) throws Exception { 7 | int min; 8 | ArrayList points=new ArrayList(); 9 | int[] temp={0, 0}; 10 | points.add(temp); 11 | Scanner scan=new Scanner(new File("mowing.in")); 12 | PrintWriter writer = new PrintWriter(new File("mowing.out")); 13 | int num=Integer.parseInt(scan.nextLine()); 14 | String[][] directions=new String[num][2]; 15 | for(int j=0;jpoints.size()){ 54 | System.out.println(-1); 55 | writer.println(-1); 56 | } 57 | else{ 58 | System.out.println(min); 59 | writer.println(min); 60 | } 61 | writer.close(); 62 | 63 | 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /USACO/NotLast.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class NotLast { 5 | static int counter=0; 6 | public static void main(String[] args) throws Exception { 7 | long start=System.currentTimeMillis(); 8 | Scanner scan=new Scanner(new File("notlast.in")); 9 | PrintWriter writer = new PrintWriter(new File("notlast.out")); 10 | int n=Integer.parseInt(scan.nextLine()); 11 | int[] milk={0, 0, 0, 0, 0, 0, 0}; 12 | for(int i=0;i1){ 91 | cow="Tie"; 92 | } 93 | else if(count==1){ 94 | if(index==0){ 95 | cow="Bessie"; 96 | } 97 | else if(index==1){ 98 | cow="Elsie"; 99 | } 100 | else if(index==2){ 101 | cow="Daisy"; 102 | } 103 | else if(index==3){ 104 | cow="Gertie"; 105 | } 106 | else if(index==4){ 107 | cow="Annabelle"; 108 | } 109 | else if(index==5){ 110 | cow="Maggie"; 111 | } 112 | else if(index==6){ 113 | cow="Henrietta"; 114 | } 115 | } 116 | 117 | System.out.println(cow); 118 | writer.println(cow); 119 | writer.close(); 120 | long end=System.currentTimeMillis()-start; 121 | } 122 | } -------------------------------------------------------------------------------- /USACO/PromotionCounting.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class PromotionCounting { 5 | 6 | public static void main(String[] args) throws Exception { 7 | int db, ds, dg, dp; 8 | Scanner scan=new Scanner(new File("promote.in")); 9 | PrintWriter writer = new PrintWriter(new File("promote.out")); 10 | 11 | scan.nextLine(); 12 | ds=change(scan.nextLine().split(" ")); 13 | dg=change(scan.nextLine().split(" ")); 14 | dp=change(scan.nextLine().split(" ")); 15 | 16 | int silver=ds+dp+dg; 17 | int gold=dp+dg; 18 | int platinum=dp; 19 | 20 | System.out.println(silver); 21 | System.out.println(gold); 22 | System.out.println(platinum); 23 | writer.println(silver); 24 | writer.println(gold); 25 | writer.println(platinum); 26 | writer.close(); 27 | 28 | 29 | } 30 | 31 | public static int change(String[] arr){ 32 | return Integer.parseInt(arr[1])-Integer.parseInt(arr[0]); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /USACO/README.md: -------------------------------------------------------------------------------- 1 | # USACO Problems 2 | -------------------------------------------------------------------------------- /USACO/SeqSum7.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class SeqSum7 { 5 | static int[] cows; 6 | public static void main(String[] args) throws Exception{ 7 | int num, count, max_length=0, length; 8 | double sum; 9 | boolean div=false; 10 | Scanner scan=new Scanner(new File("div7.in")); 11 | PrintWriter writer = new PrintWriter(new File("div7.out")); 12 | num=Integer.parseInt(scan.nextLine()); 13 | cows=new int[num]; 14 | for(int i=0;i0;length--){ 18 | for(int start=0;(start+length) queue; 11 | static int t; 12 | 13 | public static void main(String[] args) throws Exception { 14 | long start=System.currentTimeMillis(); 15 | Scanner scan=new Scanner(new File("cowdance.in")); 16 | PrintWriter writer = new PrintWriter(new File("cowdance.out")); 17 | int n=scan.nextInt(); 18 | double t=scan.nextInt(); 19 | int ans=0; 20 | times=new int[n]; 21 | double x=0; 22 | for(int asdf=0;asdf(); 39 | stage=new int[k]; 40 | //populate stage array with k elements and queue list with the rest 41 | for(int j=0;jmax){ 67 | max=stage[i]; 68 | index=i; 69 | } 70 | } 71 | return max; 72 | } 73 | 74 | public static int min(int[] stage){ 75 | int min=stage[0]; 76 | int index=0; 77 | for(int i=0;i7){ 30 | thirteens[k]%=7; 31 | } 32 | } 33 | for(int j:num_thirteens){ 34 | System.out.print(j+" "); 35 | 36 | } 37 | System.out.println("\n\n"); 38 | i++; 39 | } 40 | // 41 | for(int j:num_thirteens){ 42 | System.out.print(j+" "); 43 | } 44 | 45 | 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /USACO/gift1.java: -------------------------------------------------------------------------------- 1 | /* 2 | ID: joelpabraham 3 | LANG: JAVA 4 | TASK: gift1 5 | */ 6 | import java.io.*; 7 | import java.util.HashMap; 8 | import java.util.StringTokenizer; 9 | 10 | public class gift1 { 11 | 12 | public static void main(String[] args) throws IOException { 13 | BufferedReader reader = new BufferedReader(new FileReader("gift1.in")); 14 | PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out"))); 15 | int np=Integer.parseInt(reader.readLine()); 16 | HashMap names_final=new HashMap(); 17 | String[] names=new String[np]; 18 | for(int i=0;i> points=new ArrayList>(); 11 | int distance_saved=0; 12 | int total_distance=0;; 13 | for(int i=0;i<=checkpoints;i++){ 14 | if(i<4){ 15 | StringTokenizer st=new StringTokenizer(reader.readLine()); 16 | ArrayList temp=new ArrayList(); 17 | temp.add(Integer.parseInt(st.nextToken())); 18 | temp.add(Integer.parseInt(st.nextToken())); 19 | points.add(temp); 20 | } 21 | if(i>1 && idistance_saved){ 25 | distance_saved=local_distance_saved; 26 | } 27 | } 28 | } 29 | total_distance+=distance_between(points.get(checkpoints-2), points.get(checkpoints-1)); 30 | writer.println(total_distance-distance_saved); 31 | writer.close(); 32 | System.exit(0); 33 | } 34 | 35 | public static int distance_between(ArrayList p1, ArrayList p2){ 36 | return Math.abs(p1.get(0)-p2.get(0))+Math.abs(p1.get(1)-p2.get(1)); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /USACO/reorder.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | public class reorder { 4 | 5 | static int[] order_final; 6 | static int[] order_intial; 7 | 8 | public static void main(String[] args) throws IOException{ 9 | BufferedReader reader=new BufferedReader(new FileReader("text.txt")); 10 | PrintWriter writer=new PrintWriter(new FileWriter("textout.txt")); 11 | int n=Integer.parseInt(reader.readLine()); 12 | int[] order_initial=new int[n]; 13 | order_final=new int[n]; 14 | for(int i=0;ii).toArray()); 20 | 21 | // Converting from Array (arr) to ArrayList(list): 22 | //ArrayList list=(ArrayList) Arrays.stream(arr).boxed().collect(Collectors.toList()); 23 | 24 | 25 | } 26 | --------------------------------------------------------------------------------