Generating nCr combinations of given set in java [closed]

懵懂的女人 提交于 2019-12-24 19:26:00

问题


I want java implementation of generating nCr combinations of given set. e.g if set is {"java","php",".net","python"} program should return all possible nCr sets of given set.


回答1:


Adapting Gosper's hack, this works up to n = 64.

List<String> inputs;
List<List<String>> ncr = new ArrayList<List<String>>();
for (long x = (1 << r) - 1; (x >>> r) == 0;) {
  // x contains a 1 bit for each input we should choose;
  // iterate over the 1 bits of x
  long y = x;
  List<String> combination = new ArrayList<String>();
  for (int i = Long.numberOfTrailingZeros(y);
       y != 0; i = Long.numberOfTrailingZeros(y)) {
    combination.add(inputs.get(i));
    y &= ~(1 << i);
  }
  long u = x & -x;
  long v = u + x;
  x = v + ((v ^ x) / u) >>> 2;
}


来源:https://stackoverflow.com/questions/11945682/generating-ncr-combinations-of-given-set-in-java

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