Java Cartesian product of lists

How can I implement a function using Java 8 to take some number of streams, and produce a stream in which each element is a list consisting of one member of the Cartesian product of the streams?

I've looked at this question -- that question uses an aggregator that is a BinaryOperator [taking two items of like type and producing an item of the same type]. I'd like the items in the end result to be Lists rather than the types of the elements in the input streams.

Concretely, supposing my desired function is called product, the following:

Stream result = product[ Stream.of["A", "B", "C", "D"], Stream.of["I", "J", "K"], Stream.of["Y", "Z"] ]; result.forEach[System.out::println];

should print:

[A, I, Y] [A, I, Z] [A, J, Y] [A, J, Z] [A, K, Y] [A, K, Z] [B, I, Y] ... [D, K, Y] [D, K, Z]

Ideally, I'd like for this operation to be as lazy as possible. For example, if the input streams are produced by Stream.generate[], it'd be great if the suppliers of those streams weren't executed until absolutely needed.

A possible solution is as follows:

private static Stream product[Stream... streams] { if [streams.length == 0] { return Stream.empty[]; } List cartesian = streams[streams.length - 1] .map[x -> Collections.singletonList[x]] .collect[Collectors.toList[]]; for [int i = streams.length - 2; i >= 0; i--] { final List previous = cartesian; cartesian = streams[i].flatMap[x -> previous.stream[].map[p -> { final List list = new ArrayList[p.size[] + 1]; list.add[x]; list.addAll[p]; return list; }]].collect[Collectors.toList[]]; } return cartesian.stream[]; } public static void main[String... args] { final Stream result = product[ Stream.of["A", "B", "C", "D"], Stream.of["I", "J", "K"], Stream.of["Y", "Z"] ]; result.forEach[System.out::println]; }

The product-call returns a Stream result which prints as

[A, I, Y] [A, I, Z] [A, J, Y] [A, J, Z] [A, K, Y] [A, K, Z] [B, I, Y] [B, I, Z] [B, J, Y] [B, J, Z] [B, K, Y] [B, K, Z] [C, I, Y] [C, I, Z] [C, J, Y] [C, J, Z] [C, K, Y] [C, K, Z] [D, I, Y] [D, I, Z] [D, J, Y] [D, J, Z] [D, K, Y] [D, K, Z]

  • There are 2 same arrays, A=np.array[['A','B','C']],B=np.array[['A','B','C']], I calculated the Cartesian product of A and B: import numpy as np from itertools import product b=product[A,B] the result ...

    5 months ago

  • Given an unknown amount of lists, each with an unknown length, I need to generate a singular list with all possible unique combinations. For example, given the following lists: X: [A, B, C] Y: [W, X,...

    4 months ago

  • 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: 1,4 1,5 2,4 2,5 3,4 3,5 There can be an arbitrary ...

    4 months ago

  • Right now I can only implement the Cartesian product of two collections, here is the code: public static R getCartesianProduct[ ...

    4 months ago

  • I have an array of objects with names and options and I need all possible combinations of products. The important part is that this array has an N number of objects with N number of options in every ...

    3 months ago

  • I have this dictionary : d = { 'hosts': [{'hostname': 'ijk,uvw,xyz', 'ip': '127.0.0.3,127.0.0.4,127.0.0.5', 'extra': 'check-me,check-this,check-it'},{'hostname': 'abc,def', 'ip': '127.0.0.1,127.0....

    2 months ago

Let A and B be two sets, Cartesian productA × B is the set of all ordered pair of elements from A and B 
A × B = {{x, y} : x ∈ A, y ∈ B}
 

Let A = {a, b, c} and B = {d, e, f} The Cartesian product of two sets is A x B = {a, d}, {a, e}, {a, f}, {b, d}, {b, e}, {b, f}, {c, d}, {c, e}, {c, f}}A has 3 elements and B also has 3 elements. The Cartesian Product has 3 x 3 = 9 elements.

In general, if there are m elements in set A and n elements in B, the number of elements in the Cartesian Product is m x n

 
Given two finite non-empty sets, write a program to print Cartesian Product. 
Examples : 
 

Input : A = {1, 2}, B = {3, 4} Output : A × B = {{1, 3}, {1, 4}, {2, 3}, {2, 4}} Input : A = {1, 2, 3} B = {4, 5, 6} Output : A × B = {{1, 4}, {1, 5}, {1, 6}, {2, 4}, {2, 5}, {2, 6}, {3, 4}, {3, 5}, {3, 6}}

 

#include

void findCart[int arr1[], int arr2[], int n, int n1]

{

    for [int i = 0; i < n; i++]

        for [int j = 0; j < n1; j++]

            printf["{%d, %d}, ", arr1[i], arr2[j]];

}

int main[]

{

    int arr1[] = { 1, 2, 3 };

    int arr2[] = { 4, 5, 6 };

    int n1 = sizeof[arr1] / sizeof[arr1[0]];

    int n2 = sizeof[arr2] / sizeof[arr2[0]];

    findCart[arr1, arr2, n1, n2];

    return 0;

}

import java.io.*;

import java.util.*;

class GFG {

    static void findCart[int arr1[], int arr2[],

                                    int n, int n1]

    {

        for [int i = 0; i < n; i++]

          for [int j = 0; j < n1; j++]

            System.out.print["{"+ arr1[i]+", "

                             + arr2[j]+"}, "];

    }

    public static void main [String[] args] {

        int arr1[] = { 1, 2, 3 };

        int arr2[] = { 4, 5, 6 };

        int n1 = arr1.length;

        int n2 = arr2.length;

        findCart[arr1, arr2, n1, n2];

    }

}

def findCart[arr1, arr2, n, n1]:

    for i in range[0,n]:

        for j in range[0,n1]:

            print["{",arr1[i],", ",arr2[j],"}, ",sep="",end=""]

arr1 = [ 1, 2, 3 ]

arr2 = [ 4, 5, 6 ]

n1 = len[arr1]

n2 = len[arr2]

findCart[arr1, arr2, n1, n2];

using System;

class GFG {

    static void findCart[int []arr1, int []arr2,

                                    int n, int n1]

    {

        for [int i = 0; i < n; i++]

            for [int j = 0; j < n1; j++]

                Console.Write["{" + arr1[i] + ", "

                                + arr2[j] + "}, "];

    }

    public static void Main [] {

        int []arr1 = { 1, 2, 3 };

        int []arr2 = { 4, 5, 6 };

        int n1 = arr1.Length;

        int n2 = arr2.Length;

        findCart[arr1, arr2, n1, n2];

    }

}

    function findCart[arr1, arr2, n, n1]

    {

        for [let i = 0; i < n; i++]

          for [let j = 0; j < n1; j++]

            document.write["{"+ arr1[i]+", "

                             + arr2[j]+"}, "];

    }

        let arr1 = [ 1, 2, 3 ];

        let arr2 = [4, 5, 6 ];

        let n1 = arr1.length;

        let n2 = arr2.length;

        findCart[arr1, arr2, n1, n2];

Output : 
 

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

Practical Examples: 1] A set of playing cards is Cartesian product of a four element set to a set of 13 elements.2] A two dimensional coordinate system is a Cartesian product of two sets of real numbers.

Reference: 


//en.wikipedia.org/wiki/Cartesian_product
 

Video liên quan

Chủ Đề