I am building a big Algo. and I got stuck trying to code a helping algo.
I found some good examples in the Interner but all of them are missing a small and important detail:
I need to code a methode: combine(int[] numbers, int n)
numbers
is an array of unique numbers, for example: {1,2,3,4,5,6,7,8,9}
and n
is the length of the combinations, for example: n=3 -> [1,2,3] or [7,2,5]
as simple example of the method:
int[] numbers = {1,2,3,4}
System.out.println(combine(numbers,2))
the output should look like this:
1,2
1,3
1,4
2,3
2,4
3,4
its very important that redundant does not come out, such as: 1,2
and 2,1
and also not same numbers such as 1,1
or 2,2
the code that I found looks like this: (it does not remove redundant and that is my problem)
public static List<int[]> combinations(int n, int[] arr) {
List<int[]> list = new ArrayList<>();
// Calculate the number of arrays we should create
int numArrays = (int)Math.pow(arr.length, n);
// Create each array
for(int i = 0; i < numArrays; i++) {
list.add(new int[n]);
}
// Fill up the arrays
for(int j = 0; j < n; j++) {
// This is the period with which this position changes, i.e.
// a period of 5 means the value changes every 5th array
int period = (int) Math.pow(arr.length, n - j - 1);
for(int i = 0; i < numArrays; i++) {
int[] current = list.get(i);
// Get the correct item and set it
int index = i / period % arr.length;
current[j] = arr[index];
}
}
return list;
}
and I did call it in main like this:
public static void main(String[] args) {
int[] current = {1,2,3,4,5,6,7,8,9};
List<int[]> s = combinations(2,current);
for(int j = 0; j < s.size(); j++) {
System.out.println(((int[])s.get(j))[0] +"," +((int[])s.get(j))[1]);
}
}
and the output looks the same like the one before but with more combinations and alot of redundants
how to edit the code above to get the output with out redundants?