generating unique combinations from an array but having every element in each combination. (java)

爱⌒轻易说出口 提交于 2020-01-24 01:55:06

问题


I am trying to generate every possible unique combination from an array, but its not as straightforward as generating all combinations..... Eg. I have an array {a,b,c,d,e,f} ... my result should be like this...

  1. ab, cd, ef
  2. abc, def
  3. ac, bd, ef
  4. abcf, ed
  5. ....etc

...... basically in every result set all elements of the array should be included .... Also 'ab' is the same as'ba' and 'abcd' is the same as 'dcba' or 'cbda' .... The position does not matter .... and no repetition allowed ... 'aaa' or 'aa' is not valid ... would be grateful if someone could provide a solution for this problem ....


回答1:


I suggest that you build all possible unique sets of set sizes. Then insert all possible values in all possible orders. For example, with 5 possible values, you have the set sizes:

1 1 1 1 1
1 1 1 2
1 2 2
1 1 3
1 4
2 3
5

Now, put the actual values in to the sets. For the first set of set sizes, we get:

a, b, c, d, e

That isn't very interesting because all the sets are the same size, so skip to the third set of set sizes. Here, we fill the sets and then shift them, giving us:

a, bc, de
b, cd, ea
c, de, ab
d, ea, bc
e, ab, cd

This isn't a full solution, but I've split the problem in two and I think you can take it from there.




回答2:


 String [] new_array=new String[N];
 array.length=length.of("befdac");
 for(int i=0;i < array.length;i++) //this is first digit

{

for(int j=0;j < array.length;j++) //this is second digit
{
if(i==j)continue;
       ................ same with other digits

        {
         if((i==j)||(i==k)) continue;
        // start counting in this most inner block
        new_array[i][j][k][l]...[last_digit]=byte(i+65)+byte(j+65)+byte(k+65)+.....+byte(last_digit+65);
        //65=a, 66=b,......

         }
 }
}

new_array[][][][]...[] will be your code i didnt tried . best thing u do it yourself. this is not optimized. just made for first answer to get some points



来源:https://stackoverflow.com/questions/11162226/generating-unique-combinations-from-an-array-but-having-every-element-in-each-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!