How to create cartesian product over arbitrary groups of numbers in Java?

后端 未结 4 1333
野性不改
野性不改 2021-02-08 07:36

Let\'s say I have 2 groups of numbers:

{1, 2, 3},
{4, 5}

I\'d like to create an algorithm (in Java) that outputs the following 6 combinations:<

4条回答
  •  无人及你
    2021-02-08 08:06

    How about the following pseudo code (w/o recursion)

    // Create the initial result filled with the first set of numbers
    List result = new List()
    For each number in the first set
       result.add(new List(number))
    
    // Iterate over the following sets to permutate over
    For each remaining set S
       List newResult = new List()
       For each list L in result
         For each number N in S
           newResult.add(copy of L with N added)
       result = newResult
    

提交回复
热议问题