Created
September 27, 2018 16:43
-
-
Save uvwild/1e4714c83e70ef1e5c291015881da8e4 to your computer and use it in GitHub Desktop.
Write a function, that given a list (or array) of integers and an integer s, prints all combinations of 2 numbers in the list that sum to s.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a function, that given a list (or array) of integers and an integer s, | |
prints all combinations of 2 numbers in the list that sum to s. | |
*/ | |
import java.util.*; | |
public class CombinationSearch { | |
static Random r = new Random(); | |
static int printCombinations(List<Integer> list, Integer value) { | |
if (list.size() == 0) { | |
return 0; | |
} | |
Collections.sort(list); | |
Integer[] array = new Integer[list.size()]; | |
array = list.toArray(array); | |
int count = 0; | |
for (int i = 0; i < list.size(); i++) { | |
int current = array[i]; | |
int foundKey = Arrays.binarySearch(array, 0, list.size(), value - current); | |
if (foundKey >= 0) { | |
System.out.printf("Found:\t%d\t%d\n", current, array[foundKey]); | |
count++; | |
} else { | |
if (current > value) break; | |
} | |
} | |
return count; | |
} | |
static int printCombinationsSlow(List<Integer> list, Integer value) { | |
if (list.size() == 0) { | |
return 0; | |
} | |
Collections.sort(list); | |
int count = 0; | |
for (Integer i : list) { | |
for (Integer j : list) { | |
if (i + j == value) { | |
System.out.printf("Found:\t%d\t%d\n", i, j); | |
count++; | |
} else { | |
if (i + j > value) break; | |
} | |
} | |
} | |
return count; | |
} | |
private static List<Integer> createRandomList(int length, int bound) { | |
List<Integer> randomList = new ArrayList<>(length); | |
for (int i = 0; i < length; i++) { | |
randomList.add(r.nextInt(bound)); | |
} | |
return randomList; | |
} | |
public static void main(String[] args) { | |
long start = System.currentTimeMillis(); | |
int length = Integer.valueOf((args.length > 0) ? args[0] : "99"); | |
int value = Integer.valueOf((args.length > 1) ? args[1] : "50"); | |
int algo = Integer.valueOf((args.length > 2) ? args[2] : "0"); | |
List<Integer> list = createRandomList(length, length * 2); | |
System.out.printf("Looking in a list with length %d for sums adding to %d ", length, value); | |
int count=0; | |
String method; | |
if (algo > 0) { | |
count = printCombinationsSlow(list, value); | |
method = "printCombinationsSlow"; | |
} else { | |
count = printCombinations(list, value); | |
method = "printCombinations"; | |
} | |
long end = System.currentTimeMillis(); | |
System.out.printf("\n\nThis took %d ms for %d matches using %s algorithm", end - start, count, method); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment