Get a list of combinations of lists' elements

前端 未结 4 1291
栀梦
栀梦 2020-12-11 07:55

Suppose I have 3 lists: [\'q\',\'w\'], [\'a\',\'s\'], [\'z\',\'x\']. How to get a list of possible combinations out of these lists? So I get a list [[\'q\',\'a\',\'z\'],[\'q

4条回答
  •  遥遥无期
    2020-12-11 08:21

    You might want to have a look at the class https://github.com/javagl/Combinatorics/blob/master/src/main/java/de/javagl/utils/math/combinatorics/MixedRangeCombinationIterable.java (a "standalone" class, just copy & insert into your project)

    Example usage:

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class Combinations
    {
        public static void main(String[] args)
        {
            List> lists = new ArrayList>();
            lists.add(Arrays.asList('q','w'));
            lists.add(Arrays.asList('a','s'));
            lists.add(Arrays.asList('z','x'));
    
            MixedRangeCombinationIterable iterable = 
                new MixedRangeCombinationIterable(lists);
            for (List element : iterable)
            {
                System.out.println(element);
            }
        }
    }
    

    You are actually computing the elements of the http://en.wikipedia.org/wiki/Cartesian_product of the input sets

提交回复
热议问题