Java动态排列

问题描述 投票:0回答:1

我有一个包含可变长度字符串列表的映射。例如

Map<String, List<String> map = new HashMap<>();
map.put("key", "key1, key2);
map.put("name", "name1, name2, name3");
map.put("code", "code1, code2");

这将给出12个不同的排列。下面的代码可以完成这项工作

List<String> values = new ArrayList<>();
for (int i = 0; i < map.get("key").size(); i++) {
     values.add(map.get("key").get(i));
     for (int j = 0; j < map.get("name").size(); j++) {
         values.add(map.get("name").get(j));
         for (int k = 0; k < map.get("code").size(); k++) {
             values.add(map.get("code").get(k));
         }
     }
}

预期输出:

"key1", "name1", "code1",
"key1", "name1", "code2",
"key1", "name2", "code1",
"key1", "name2", "code2",
"key1", "name3", "code1",
"key1", "name3", "code2",
"key2", "name1", "code1",
"key2", "name1", "code2",
"key2", "name2", "code1",
"key2", "name2", "code2",
"key2", "name3", "code1",
"key2", "name3", "code2"

但是问题是这是用3个for循环硬编码的,但是我希望可以支持任意数量的变量。及时的帮助深表感谢。

java for-loop recursion dynamic permutation
1个回答
0
投票

下面有一个示例解决方案,使用递归。

[从一个空的组合(一个空的列表)开始,在每一步(i),我们获取当前元组的N = list(i).size()个副本,将value = list(i)[j]添加到元组,然后递归。当i = list.size时,表示元组已完成,我们可以使用它(例如,将其打印出来)。(可以使用构造函数复制列表)。

package sample;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Consumer;

public class SampleCombinations {

  public static void main(String[] args) {

    Map<String, List<String>> map = new TreeMap<>();
    map.put("x", Arrays.asList("a", "b", "c"));
    map.put("y", Arrays.asList("0", "1", "2", "3"));
    map.put("z", Arrays.asList("!", "-", "=", "%"));

    ArrayList<Entry<String, List<String>>> entries = new ArrayList<>(map.entrySet());

    System.out.println(entries);
    printCombinations(entries);
  }

  private static void printCombinations(ArrayList<Entry<String, List<String>>> entries) {
    Consumer<List<String>> cons = list -> System.out.println(list);
    generateComb(entries, cons, 0, new LinkedList<>());
  }

  private static void generateComb(ArrayList<Entry<String, List<String>>> entries,
      Consumer<List<String>> consumer, int index, List<String> currentTuple) {

    /*
     * terminal condition: if i==entries.size the tuple is complete
     * consume it and return
     */
    if(index==entries.size()) {
      consumer.accept(currentTuple);
    }
    else {
      /*
       * get all elements from the i-th list, generate N new tuples and recurse
       */
      List<String> elems = entries.get(index).getValue();
      for (String elem:elems) {
        // copy the current tuple
        LinkedList<String> newTuple = new LinkedList<>(currentTuple);
        newTuple.add(elem);
        generateComb(entries, consumer, index+1, newTuple);
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.