【问题标题】:How to generate combinations from a set of objects?如何从一组对象生成组合?
【发布时间】:2019-12-16 06:02:56
【问题描述】:

我需要从 7 个对象的集合中获取所有可能的5 个对象的组合。不重复的组合(选择的顺序无所谓,相同的对象以不同的顺序被选择视为相同的组合)。

我有实现,它可以正常工作并产生正确的结果:

String[] vegetablesSet = {"Pepper", "Cabbage", "Tomato", "Carrot", "Beans", "Cucumber", "Peas"};
final int SALAD_COMBINATION_SIZE = 5; // Example: {"Tomato", "Cabbage", "Cucumber", "Pepper", "Carrot"} 

Set<Set<String>> allSaladCombinations = new HashSet<>();
for (int i = 1, max = 1 << vegetablesSet.length; i < max; i++) {
   Set<String> set = new HashSet<>();
   int count = 0;
   for (int j = 0, k = 1; j < vegetablesSet.length; j++, k <<= 1) {
      if ((k & i) != 0) {
         set.add(vegetablesSet[j]);
         count++;
      }
   }
   if (count == SALAD_COMBINATION_SIZE) {
      allSaladCombinations.add(set);
   }
}

for (Set<String> set : allSaladCombinations) {
   for (String vegatable : set) {
      System.out.print(vegatable + " ");
   }
   System.out.println();
}

输出正确:已找到 21 个正确的组合。

但它使用按位运算符,在我的评估中,它的可读性、可维护性和可扩展性都不是很好。我想将它重构或完全重写为更灵活和更易于理解的面向对象方法。我对如何使用 OOP 和递归来做到这一点非常感兴趣。

我没有在我的项目中使用Google GuavaApache CommonsCombinatoricsLib。而且我不想只为一种方法包含整个第三方库。我在网站上搜索类似的问题,但只找到了很好的清晰排列实现:https://stackoverflow.com/a/14486955

这些情况的含义有些相似,但对象的顺序对我来说并不重要,在我的情况下,它们被认为是相同的组合,不应计算。

【问题讨论】:

标签: java algorithm oop java-8 combinatorics


【解决方案1】:

你可以试试这个代码:

    public static void main(String[] args) {
        String[] vegetablesSet = { "Pepper", "Cabbage", "Tomato", "Carrot", "Beans", "Cucumber", "Peas" };
        Set<Set<String>> result = new HashSet<>();      
        combinations(vegetablesSet, new ArrayList<>(), result, 5, 0);
        result.forEach(System.out::println);
    }

    public static void combinations(String[] values, List<String> current, Set<Set<String>> accumulator, int size, int pos) {
        if (current.size() == size) {
            Set<String> toAdd = current.stream().collect(Collectors.toSet());
            if (accumulator.contains(toAdd)) {
                throw new RuntimeException("Duplicated value " + current);
            }
            accumulator.add(toAdd);
            return;
        }
        for (int i = pos; i <= values.length - size + current.size(); i++) {
            current.add(values[i]);
            combinations(values, current, accumulator, size, i + 1);
            current.remove(current.size() - 1);
        }
    }

基本思想是仅从当前位置开始获取元素,并使用递归来混合不同的选项。

如果你想要一个更简单的方法调用,你可以像这样创建一个包装器方法:

    public static Set<Set<String>> combinations(String[] values) {
        Set<Set<String>> result = new HashSet<>();
        combinations(values, new ArrayList<>(), result, SALAD_COMBINATION_SIZE, 0);
        return result;
    }

编辑: 另一种方法是对 1 和 0(在这种情况下为 5 个 1 和 2 个 0)进行不同的排列来创建掩码,然后在组合中进行转换。我觉得它比以前的解决方案更自然,因为它不使用循环,除了掩码应用程序(隐式在流操作中):

    public static void combinations2(String[] values, String current, Set<Set<String>> accumulator, int ones, int zeroes) {
        if (ones + zeroes == 0) {
            accumulator.add(IntStream.range(0, values.length)
                    .filter(position -> '1' == current.charAt(position))
                    .mapToObj(position -> values[position])
                    .collect(Collectors.toSet()));
            return;
        }
        if (ones > 0) {
            combinations2(values, current + "1", accumulator, ones - 1, zeroes);
        }
        if (zeroes > 0) {
            combinations2(values, current + "0", accumulator, ones, zeroes - 1);
        }
    }

包装方法:

public static Set<Set<String>> combinations(String[] values) {
        Set<Set<String>> result = new HashSet<>();
        combinations2(values, "", result, SALAD_COMBINATION_SIZE, values.length - SALAD_COMBINATION_SIZE);
        return result;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多