Java algorithm for all-pairs
Given a collection of integers, what's a Java algorithm that will give all pairs of items as follows..
Given the example collection: [1,3,5], we'd want the output:
[1-1]
[3-3]
[5-5]
[1-3]
[1-5]
[3-5]
Note that ordering is not important, so we want one of [1-3], [3-1] but not both.
This should work with a collection of n numbers, not just the the three numbers as in this exa开发者_如何转开发mple.
Below function should do this
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] +"]");
}
}
}
Example call to this function
int[] numbers={1,2,3};
printPermutations(numbers);
Sounds like homework...but here it is anyway. 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());
}
}
Here's the logic you want.
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;
}
精彩评论