How to resolve the algorithm Cartesian product of two or more lists step by step in the Groovy programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Cartesian product of two or more lists step by step in the Groovy programming language

Table of Contents

Problem Statement

Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: and, in contrast: Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Cartesian product of two or more lists step by step in the Groovy programming language

Source code in the groovy programming language

class CartesianCategory {
    static Iterable multiply(Iterable a, Iterable b) {
        assert [a,b].every { it != null }
        def (m,n) = [a.size(),b.size()]
        (0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].flatten() }
    }
}


Iterable.metaClass.mixin CartesianCategory

println "\nCore Solution:"
println "[1, 2] × [3, 4] = ${[1, 2] * [3, 4]}"
println "[3, 4] × [1, 2] = ${[3, 4] * [1, 2]}"
println "[1, 2] × [] = ${[1, 2] * []}"
println "[] × [1, 2] = ${[] * [1, 2]}"

println "\nExtra Credit:"
println "[1776, 1789] × [7, 12] × [4, 14, 23] × [0, 1] = ${[1776, 1789] * [7, 12] * [4, 14, 23] * [0, 1]}"
println "[1, 2, 3] × [30] × [500, 100] = ${[1, 2, 3] * [30] * [500, 100]}"
println "[1, 2, 3] × [] × [500, 100] = ${[1, 2, 3] * [] * [500, 100]}"

println "\nNon-Numeric Example:"
println "[John,Paul,George,Ringo] × [Emerson,Lake,Palmer] × [Simon,Garfunkle] = ["
( ["John","Paul","George","Ringo"] * ["Emerson","Lake","Palmer"] * ["Simon","Garfunkle"] ).each { println "\t${it}," }
println "]"


  

You may also check:How to resolve the algorithm Self-describing numbers step by step in the K programming language
You may also check:How to resolve the algorithm Range consolidation step by step in the Clojure programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the Sidef programming language
You may also check:How to resolve the algorithm Pick random element step by step in the Quackery programming language
You may also check:How to resolve the algorithm Faulhaber's triangle step by step in the JavaScript programming language