Java combinational algorithm

Given a set of integers, which Java algorithm will produce combinations as follows.

Given the collection example: [1,3,5], we need the conclusion:

[1-1] [3-3] [5-5] [1-3] [1-5] [3-5] 

Note that order is not important, so we want one of [1-3], [3-1], but not both.

This should work with a set of n numbers, not just three numbers, as in this example.

+4
source share
3 answers

Below function should do it

  private void printPermutations(int[] numbers) { for(int i=0;i<numbers.length; i++) { for (int j=i; j<numbers.length; j++) { System.out.println("[" + numbers[i] + "-"+ numbers[j] +"]"); } } } 

An example of calling this function

 int[] numbers={1,2,3}; printPermutations(numbers); 
+5
source

Sounds like homework ... but it doesn't matter here. Obviously, you can do without an ArrayList, etc. - just quick and dirty.

 import java.util.ArrayList; public class Test { public static void main(String[] args) { int[] input = {1, 3, 5}; ArrayList<String> output = new ArrayList<String>(); int n = input.length; for (int left = 0; left < n; left++) { output.add("["+input[left]+"-"+input[left]+"]"); for (int right = left + 1; right < n; right++) { output.add("["+input[left]+"-"+input[right]+"]"); } } System.out.println(output.toString()); } } 
+2
source

Here we need logic.

 function subsequences (arr) { arr.sort (); var subseqs = []; for (var i = 0; i < arr.length; ++i) { for (var j = i; j < arr.length; ++j) { subseqs.push ("" + arr [i] + "-" + arr [j]); } } return subseqs; } 
0
source

All Articles