简体   繁体   中英

Java String array getting all combinations based on n!/r!(n-r)!

I have tried to search about it, but have not found a definitive answer yet. I am trying to write a program which compares a string array against all combinations of another string array, but these combinations have the same number of elements as the previous array. To explain better, lets say I have two string arrays, n = {alpha,beta,gamma,delta,epsilon} and r ={beta,gamma,delta}. Now what I want to do is, get all combinations (of three strings in each combination) from the set 'n' and compare the set 'r' against them all. If I get a match, then perform some action. I am aware that to get all combinations, I need to apply the formula,

                            nCr = n!/r!(n-r)!   (where 0<=r<=n)

in my case, n = 5, and r = 3, which gives 10 combinations in total. I need to generate all these combinations(10 in this case) and compare them against the array 'r'. I do not have a starting point yet, and I do not expect to get an answer but a little light towards how it can be implemented (will be probably done recursively?) would be great! Thanks in advance.

Given the additional context you've provided in the comments, here's what I'd suggest.

Turn n into a set for easier querying:

String[] n = {"alpha", "beta", "gamma", "delta", "epsilon"};
Set<String> nset = new HashSet<String>();
nset.addAll(Arrays.asList(n));

Now you can check if it contains all the elements of r :

String[] r = {"beta", "gamma", "delta"};
if (nset.containsAll(Arrays.asList(r))) {
  // do something
}

This can be repeated with multiple different r arrays, and it will be more efficient than iterating over all the possible subsets of n and comparing them with a particular r .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM