How to resolve the algorithm Cartesian product of two or more lists step by step in the Modula-2 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 Modula-2 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 Modula-2 programming language

Source code in the modula-2 programming language

MODULE CartesianProduct;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(a : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
    FormatString("%i", buf, a);
    WriteString(buf)
END WriteInt;

PROCEDURE Cartesian(a,b : ARRAY OF INTEGER);
VAR i,j : CARDINAL;
BEGIN
    WriteString("[");
    FOR i:=0 TO HIGH(a) DO
        FOR j:=0 TO HIGH(b) DO
            IF (i>0) OR (j>0) THEN
                WriteString(",");
            END;
            WriteString("[");
            WriteInt(a[i]);
            WriteString(",");
            WriteInt(b[j]);
            WriteString("]")
        END
    END;
    WriteString("]");
    WriteLn
END Cartesian;

TYPE
    AP = ARRAY[0..1] OF INTEGER;
    E = ARRAY[0..0] OF INTEGER;
VAR
    a,b : AP;
BEGIN
    a := AP{1,2};
    b := AP{3,4};
    Cartesian(a,b);

    a := AP{3,4};
    b := AP{1,2};
    Cartesian(a,b);

    (* If there is a way to create an empty array, I do not know of it *)

    ReadChar
END CartesianProduct.


  

You may also check:How to resolve the algorithm XML/Output step by step in the Python programming language
You may also check:How to resolve the algorithm Compile-time calculation step by step in the Oforth programming language
You may also check:How to resolve the algorithm Hello world/Graphical step by step in the Yabasic programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Hamming numbers step by step in the AutoHotkey programming language