How to resolve the algorithm Loop over multiple arrays simultaneously step by step in the GAP programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loop over multiple arrays simultaneously step by step in the GAP programming language

Table of Contents

Problem Statement

Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop.

For this example, loop over the arrays: to produce the output:

If possible, also describe what happens when the arrays are of different lengths.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loop over multiple arrays simultaneously step by step in the GAP programming language

Source code in the gap programming language

# The Loop function will apply some function to every tuple built by 
taking
# the i-th element of each list. If one of them is exhausted before the 
others,
# the loop continues at its begining. Only the longests lists will be 
precessed only once.
Loop := function(a, f)
    local i, j, m, n, v;
    n := Length(a);
    v := List(a, Length);
    m := Maximum(v);
    for j in [1 .. m] do
        f(List([1 .. n], i -> a[i][1 + RemInt(j - 1, v[i])]));
    od;
end;

# Here we simply print each "row"
f := function(u)
    Perform(u, Print);
    Print("\n");
end;

Loop([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]], f);

aA1
bB2
cC3

Loop([["a", "b"], ["A", "B", "C", "D", "E"], [1, 2, 3]], f);

aA1
bB2
aC3
bD1
aE2


  

You may also check:How to resolve the algorithm Calculating the value of e step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Self numbers step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Balanced brackets step by step in the Stata programming language
You may also check:How to resolve the algorithm Rep-string step by step in the Arturo programming language
You may also check:How to resolve the algorithm First-class functions step by step in the GAP programming language