在Java中生成给定集合的nCr组合 [英] Generating nCr combinations of given set in java

查看:79
本文介绍了在Java中生成给定集合的nCr组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要生成给定集合的nCr组合的Java实现。
例如,如果set为{ java, php,。net, python},则
程序应返回给定集合的所有可能的nCr集。

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.

推荐答案

适应闲聊的人 ,则最多可使用n = 64。

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;
}

这篇关于在Java中生成给定集合的nCr组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆