Loop over multiple arrays simultaneously: Difference between revisions
Loop over multiple arrays simultaneously (view source)
Revision as of 19:04, 15 June 2024
, 11 days agoAdd Uiua
m (→{{header|Quackery}}: typo) |
(Add Uiua) |
||
(63 intermediate revisions by 34 users not shown) | |||
Line 41:
=={{header|11l}}==
<
print(x‘’y‘’z)</
{{out}}
Line 52:
=={{header|360 Assembly}}==
<
LOOPSIM CSECT
USING LOOPSIM,R12 base register
Line 75:
PG DC CL80' ' buffer
YREGS
END LOOPSIM</
{{out}}
<pre>
Line 103:
and if they are not, it will simply read from the wrong addresses.
<
lxi b,0 ; Let (B)C be the array index
outer: lxi d,As ; Use DE to walk the array-of-arrays
Line 148:
Alen: equ $-A3
;;; Zero-terminated array-of-arrays
As: dw A1,A2,A3,0</
{{out}}
Line 170:
base addresses of the arrays into <code>bx</code> one by one.
<
bits 16
org 100h
Line 200:
;;; Array of arrays
As: dw A1,A2,A3
Aslen: equ ($-As)/2 ; Length of array of arrays (in words)</
Line 212:
=={{header|ACL2}}==
<
(if (or (endp xs) (endp ys) (endp zs))
nil
Line 223:
(rest zs)))))
(print-lists '("a" "b" "c") '(A B C) '(1 2 3))</
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC Main()
CHAR ARRAY a="abc",b="ABC"
BYTE ARRAY c=[1 2 3]
BYTE i
FOR i=0 TO 2
DO
PrintF("%C%C%B%E",a(i+1),b(i+1),c(i))
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loop_over_multiple_arrays_simultaneously.png Screenshot from Atari 8-bit computer]
<pre>
aA1
bB2
cC3
</pre>
=={{header|Ada}}==
<
procedure Array_Loop_Test is
Line 238 ⟶ 257:
(Index))(2));
end loop;
end Array_Loop_Test;</
=={{header|ALGOL 68}}==
Line 252 ⟶ 271:
1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
<
z=(1,2,3);
FOR i TO UPB x DO
printf(($ggd$, x[i], y[i], z[i], $l$))
OD</
{{out}}
<pre>
Line 265 ⟶ 284:
=={{header|ALGOL W}}==
<
% declare the three arrays %
string(1) array a, b ( 1 :: 3 );
Line 275 ⟶ 294:
% loop over the arrays %
for i := 1 until 3 do write( i_w := 1, s_w := 0, a(i), b(i), c(i) );
end. </
If the arrays are not the same length, a subscript range error would occur when a non-existant element was accessed.
=={{header|Amazing Hopper}}==
Versión 1: todos los arrays tienen el mismo tamaño:
<syntaxhighlight lang="txt">
#include <jambo.h>
Main
Void 'x,y,z'
Set '"a","b","c"' Append to list 'x'
Set '"A","B","C"' Append to list 'y'
Set '1,2,3' Append to list 'z'
i=1
Loop
[i++], Printnl ( Get 'x', Get 'y', Get 'z' )
Back if less-equal (i, 3)
End
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
Versión 2: los arrays tienen distinto tamaño:
<syntaxhighlight lang="txt">
#include <jambo.h>
Main
Void 'x,y,z'
Let list ( x := "a","b","c" )
Let list ( y := "A","B","C","D","E" )
Let list ( z := 1,2,3,4 )
i=1, error=0
Loop
[i++]
Try ; Get 'x', Print it ; Catch 'error'; Print (" ") ; Finish
Try ; Get 'y', Print it ; Catch 'error'; Print (" ") ; Finish
Try ; Get 'z', Print it ; Catch 'error'; Print (" ") ; Finish
Prnl
Back if less-equal (i, 5)
End
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
D4
E
</pre>
=={{header|APL}}==
Line 288 ⟶ 357:
vectors, zeroes for numeric vectors) to match the longest vector.
<syntaxhighlight lang
{{out}}
Line 304 ⟶ 373:
If we have a generic Applescript '''map''' function, we can use it to write a generic '''zipListsWith''', which applies a given function over lists derived from the nth members of an arbitrary list of (equal-length) lists. (Where lists are of uneven length, items beyond the maximum shared length are ignored).
<
-- zipListsWith :: ([a] -> b) -> [[a]] -> [[b]]
Line 394 ⟶ 463:
end script
end if
end mReturn</
{{Out}}
<pre>aA1
Line 402 ⟶ 471:
But a transpose function might be simpler:
<
on run
Line 476 ⟶ 545:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>aA1
Line 484 ⟶ 553:
=={{header|Arturo}}==
<
loop 0..2 'x ->
print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|"</
{{out}}
Line 499 ⟶ 568:
[http://www.autohotkey.com/docs/commands/StringSplit.htm StringSplit]
creates a pseudo-array
<
List2 = A,B,C
List3 = 1,2,3
Line 524 ⟶ 593:
Result .= List1_%A_Index% List2_%A_Index% List3_%A_Index% "`n"
Return, Result
}</
An array that is too short on creation will return empty strings when
trying to retrieve further elements. The 2nd Message box shows:
Line 537 ⟶ 606:
([http://l.autohotkey.com/docs/Objects.htm Objects]) and the
[http://l.autohotkey.net/docs/commands/For.htm For loop].
<
List2 := ["A", "B", "C"]
List3 := [ 1 , 2 , 3 ]
Line 553 ⟶ 622:
Result .= value . List2[key] . List3[key] "`n"
Return, Result
}</
The output from this script is identical to the first one.
=={{header|AWK}}==
<
split("a,b,c", a, ",");
split("A,B,C", b, ",");
Line 565 ⟶ 634:
print a[i] b[i] c[i];
}
}</
=={{header|Axe}}==
Line 571 ⟶ 640:
L₃ for simplicity. In practice, one would want to arrange the arrays to
all fit within L₁ to avoid volatility issues with L₂ and L₃.
<
'b'→{L₁+1}
'c'→{L₁+2}
Line 582 ⟶ 651:
For(I,0,2)
Disp {L₁+I}►Char,{L₂+I}►Char,{L₃+I}►Dec,i
End</
=={{header|Babel}}==
Line 588 ⟶ 657:
First, you could transpose the lists:
<
simul_array }
simul_array!:
{ trans
{ { << } each "\n" << } each }</
The 'trans' operator substitutes nil in the portions of each transposed
Line 605 ⟶ 674:
each list using a user-defined cdrall operator:
<
simul_array }
Line 623 ⟶ 692:
{ zap 0 last }
{ nil }
if} each }</
This solution is formally identical to the first and will handle lists
Line 631 ⟶ 700:
short lists.
=={{header|
==={{header|Applesoft BASIC}}===
{{trans|ZX Spectrum Basic}}
<syntaxhighlight lang="basic">REM DEFINE THE ARRAYS AND POPULATE THEM
0 SIZE = 3: DIM A$(SIZE),B$(SIZE),C(SIZE): FOR I = 1 TO SIZE:A$(I) = CHR$ (96 + I):B$(I) = CHR$ (64 + I):C(I) = I: NEXT
REM LOOP OVER MULTIPLE ARRAYS SIMULTANEOUSLY
1 FOR I = 1 TO SIZE
2 PRINT A$(I)B$(I)C(I)
3 NEXT I
</syntaxhighlight>
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
DECLARE a1$[] = {"a", "b", "c"} TYPE STRING
DECLARE a2$[] = {"A", "B", "C"} TYPE STRING
Line 643 ⟶ 722:
INCR i
WEND
</
==={{header|BASIC256}}===
<syntaxhighlight lang="basic">arraybase 1
dim arr1$(3) : arr1$ = {"a", "b", "c"}
dim arr2$(3) : arr2$ = {"A", "B", "C"}
dim arr3(3) : arr3 = {1, 2, 3}
for i =
print arr1$[i]; arr2$[i]; arr3[i]
next i
print
# For arrays of different lengths we would need to iterate up to the mimimm
# length of all 3 in order to get a contribution from each one. For example:
dim arr4$(4) : arr4$ = {"A", "B", "C", "D"}
dim arr5(2) : arr5 = {1, 2}
ub = min(arr1$[?], min((arr4$[?]), (arr5[?])))
for i = 1 To ub
print arr1$[i]; arr4$[i]; arr5[i]
next i
print
end
function min(x,y)
if(x < y) then return x else return y
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> DIM array1$(2), array2$(2), array3%(2)
array1$() = "a", "b", "c"
array2$() = "A", "B", "C"
Line 672 ⟶ 762:
FOR index% = 0 TO 2
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT</
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
Dim arr1(1 To 3) As String = {"a", "b", "c"}
Dim arr2(1 To 3) As String = {"A", "B", "C"}
Dim arr3(1 To 3) As Integer = {1, 2, 3}
For i As Integer = 1 To 3
Print arr1(i) & arr2(i) & arr3(i)
Next
Print
' For arrays of different lengths we would need to iterate up to the mimimm length of all 3 in order
' to get a contribution from each one. For example:
Dim arr4(1 To 4) As String = {"A", "B", "C", "D"}
Dim arr5(1 To 2) As Integer = {1, 2}
Dim ub As Integer = min(UBound(arr1), min(UBound(arr4), UBound(arr5)))
For i As Integer = 1 To ub
Print arr1(i) & arr2(i) & arr3(i)
Next
Print
Sleep</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
aA1
bB2
</pre>
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=3a69e733694aeab3b72c6a5c0316535b Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim a1 As String[] = ["a", "b", "c"]
Dim a2 As String[] = ["A", "B", "C"]
Dim a3 As String[] = ["1", "2", "3"]
Dim siC As Short
For siC = 0 To a1.Max
Print a1[siC] & a2[siC] & a3[siC]
Next
End</syntaxhighlight>
Output:
<pre>
aA1
bB2
cC3
</pre>
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">a$(1)="a" : a$(2)="b" : a$(3)="c"
b$(1)="A" : b$(2)="B" : b$(3)="C"
c(1)=1 : c(2)=2 : c(3)=3
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
==={{header|NS-HUBASIC}}===
<syntaxhighlight lang="ns-hubasic">10 DIM A$(3)
20 DIM B$(3)
30 DIM C$(3)
40 A$(1)="THIS"
50 A$(2)=" LOOPS"
60 A$(3)=" ARRAYS"
70 B$(1)=" NS-HUBASIC"
80 B$(2)=" OVER"
90 B$(3)=" AT"
100 C$(1)=" PROGRAM"
110 C$(2)=" MULTIPLE"
120 C$(3)=" ONCE."
130 FOR I=1 TO 3
140 PRINT A$(I)B$(I)C$(I)
150 NEXT</syntaxhighlight>
==={{header|PowerBASIC}}===
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM x(2), y(2) AS STRING * 1
DIM z(2) AS LONG
'data
ARRAY ASSIGN x() = ("a", "b", "c")
ARRAY ASSIGN y() = ("A", "B", "C")
ARRAY ASSIGN z() = (1, 2, 3)
'set upper bound
C& = UBOUND(x)
IF UBOUND(y) > C& THEN C& = UBOUND(y)
IF UBOUND(z) > C& THEN C& = UBOUND(z)
OPEN "output.txt" FOR OUTPUT AS 1
FOR L& = 0 TO C&
IF L& <= UBOUND(x) THEN PRINT #1, x(L&);
IF L& <= UBOUND(y) THEN PRINT #1, y(L&);
IF L& <= UBOUND(z) THEN PRINT #1, TRIM$(STR$(z(L&)));
PRINT #1,
NEXT
CLOSE
END FUNCTION</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">OpenConsole()
; Fill arrays
Dim a.s(2)
Dim b.s(2)
Dim c(2)
For Arrayposition = 0 To ArraySize(a())
a(Arrayposition) = Chr(Asc("a") + Arrayposition)
b(Arrayposition) = Chr(Asc("A") + Arrayposition)
c(Arrayposition) = Arrayposition + 1
Next
; loop over them
For Arrayposition = 0 To ArraySize(a())
PrintN(a(Arrayposition) + b(Arrayposition) + Str(c(Arrayposition)))
Next
Input() ;wait for Enter before ending</syntaxhighlight>
If they have different lengths there are two cases:<br>
a() is the shortest one: Only elements up to maximum index of a() are
printed <br>
a() is bigger than another one: if exceeding index to much, program
crashes, <br>
else it may work because there is some "free space" after end of
assigned array memory. <br>
For example if a has size 4, line dD4 will also be printed. size 20
leads to an crash <br>
This is because ReDim becomes slow if everytime there is a change to
array size new memory has to be allocated.
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 1 to 3
a$(i) = chr$(i+96)
b$(i) = chr$(i+64)
c(i) = i
next i
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
==={{header|Visual Basic .NET}}===
Two implementations: one determines the shortest of the arrays and uses a simple For loop with element accesses to each array separately; one uses Enumerable.Zip (which can only zip two sequences at once) twice to create 3-tuples. Enumerable.Zip stops when either source runs out of elements, so the behavior of the two implementations is identical for arrays of different lengths.
<syntaxhighlight lang="vbnet">
Module Program
Sub Main()
Dim a As Char() = {"a"c, "b"c, "c"c}
Dim b As Char() = {"A"c, "B"c, "C"c}
Dim c As Integer() = {1, 2, 3}
Dim minLength = {a.Length, b.Length, c.Length}.Min()
For i = 0 To minLength - 1
Console.WriteLine(a(i) & b(i) & c(i))
Next
Console.WriteLine()
For Each el As (a As Char, b As Char, c As Integer) In a.Zip(b, Function(l, r) (l, r)).Zip(c, Function(x, r) (x.l, x.r, r))
Console.WriteLine(el.a & el.b & el.c)
Next
End Sub
End Module</syntaxhighlight>
{{out}}
<pre>aA1
bB2
cC3
aA1
bB2
cC3</pre>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Loop over multiple arrays simultaneously
PROGRAM "loopoverarrays"
DECLARE FUNCTION Entry()
FUNCTION Entry()
DIM arr1$[2], arr2$[2], arr3%[2]
arr1$[0] = "a": arr1$[1] = "b": arr1$[2] = "c"
arr2$[0] = "A": arr2$[1] = "B": arr2$[2] = "C"
arr3%[0] = 1: arr3%[1] = 2: arr3%[2] = 3
FOR i% = 0 TO 2
PRINT arr1$[i%]; arr2$[i%]; FORMAT$("#", arr3%[i%])
NEXT i%
END FUNCTION
END PROGRAM
</syntaxhighlight>
==={{header|Yabasic}}===
<syntaxhighlight lang="basic">dim arr1$(3), arr2$(3), arr3(3)
arr1$(1) = "a"
arr1$(2) = "b"
arr1$(3) = "c"
arr2$(1) = "A"
arr2$(2) = "B"
arr2$(3) = "C"
arr3(1) = 1
arr3(2) = 2
arr3(3) = 3
for i = 1 to 3
print arr1$(i), arr2$(i), arr3(i)
next
print
// For arrays of different lengths we would need to iterate up to the mimimm
// length of all 3 in order to get a contribution from each one. For example:
dim arr4$(4), arr5(2)
arr4$(1) = "A"
arr4$(2) = "B"
arr4$(3) = "C"
arr4$(4) = "D"
arr5(1) = 1
arr5(2) = 2
ub = min(arraysize(arr1$(),1), min(arraysize(arr4$(),1),arraysize(arr5(),1)))
for i = 1 to ub
print arr1$(i), arr4$(i), arr5(i)
next
end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 LET sza = 3: REM size of a
20 LET szb = 3: REM size of b
30 LET szc = 3: REM size of c
40 DIM a$(sza): DIM b$(szb): DIM c$(szc)
50 LET max = sza: REM assume a is the biggest
60 IF szb > max THEN LET max = szb: REM now try b
70 IF szc > max THEN LET max = szc: REM or c
80 REM populate our arrays, and as a bonus we already have our demo loop
90 REM we might as well print as we populate showing the arrays in
columns
100 FOR l = 1 TO max
110 IF l <= sza THEN READ a$(l): PRINT a$(l);
120 IF l <= szb THEN READ b$(l): PRINT b$(l);
130 IF l <= szc THEN READ c$(l): PRINT c$(l);
140 PRINT: REM newline
145 NEXT l
150 PRINT "The arrays are shown in columns."
160 PRINT "A$ runs down the left hand side,"
170 PRINT "and C$ runs down the right."
180 STOP
200 DATA "a","b","c","A","B","C","1","2","3"</syntaxhighlight>
Simplification
<syntaxhighlight lang="zxbasic">10 READ size: DIM a$(size): DIM b$(size): DIM c$(size)
20 FOR i=1 TO size
30 READ a$(i),b$(i),c$(i)
40 PRINT a$(i);b$(i);c$(i)
50 NEXT i
60 DATA 3,"a","A","1","b","B","2","c","C","3"</syntaxhighlight>
=={{header|Beads}}==
This solution accounts for arrays of varying lengths, and if they are interspersed with undefined characters by replacing them with spaces.
<
calc main_init
const
Line 684 ⟶ 1,046:
const largest = max(tree_hi(x), tree_hi(y), tree_hi(z))
loop reps:largest count:i //where u_cc defines what to use for undefined characters
log to_str(x[i], u_cc:' ') & to_str(y[i], u_cc:' ') & to_str(z[i], u_cc:' ')</
{{out}}
<pre>aA1
Line 695 ⟶ 1,057:
For arrays of differing lengths, you'd need to manually check for an out-of-range index and deal with it appropriately.
<
@_^#`2:+1,+55,<
abc
ABC
123</
=={{header|C}}==
Line 708 ⟶ 1,070:
application-specific way.
<
char a1[] = {'a','b','c'};
Line 718 ⟶ 1,080:
printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}
}</
(Note: Some compilers may require a flag to accept this modern C code,
Line 731 ⟶ 1,093:
=={{header|C sharp|C#}}==
<
{
static void Main(string[] args)
Line 743 ⟶ 1,105:
Console.WriteLine("{0}{1}{2}", a[i], b[i], c[i]);
}
}</
Using Enumerable.Zip (stops when either source runs out of elements):
<
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
Line 754 ⟶ 1,116:
second));
</syntaxhighlight>
Like how a perl programmer would write it (still using Zip):
<
Console.WriteLine((new[] { 1, 2, 3, 4 }).Zip(new[] { "a", "b", "c" },
(f, s) => f + " " + s));
</syntaxhighlight>
Custom implementation for arrays of different lengths that pads with spaces after the end of the shorter arrays:
<
public static void Multiloop(char[] A, char[] B, int[] C)
{
Line 773 ⟶ 1,135:
Console.WriteLine($"{(i < A.Length ? A[i] : ' ')}, {(i < B.Length ? B[i] : ' ')}, {(i < C.Length ? C[i] : ' ')}");
}
</syntaxhighlight>
usage:
<
=={{header|C++}}==
With <code>std::vector</code>s:
<
#include <vector>
Line 797 ⟶ 1,159:
std::cout << *lIt << *uIt << *nIt << "\n";
}
}</
Using static arrays:
<
int main(int argc, char* argv[])
Line 816 ⟶ 1,178:
"\n";
}
}</
===C++11===
With <code>std::vector</code>s:
<
#include <vector>
Line 840 ⟶ 1,202:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
Using static arrays:
<
#include <iterator>
Line 863 ⟶ 1,225:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
With <code>std::array</code>s:
<
#include <array>
Line 886 ⟶ 1,248:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
With <code>std::array</code>s by indexes:
<
#include <array>
#include <algorithm>
Line 911 ⟶ 1,273:
std::cout << lowers[i] << uppers[i] << nums[i] << "\n";
}
}</
===C++23===
<syntaxhighlight lang="cpp">#include <array>
#include <ranges>
#include <format>
#include <iostream>
int main() {
auto a1 = std::array{"a", "b", "c"};
auto a2 = std::array{"A", "B", "C"};
auto a3 = std::array{1, 2, 3};
for(const auto& [x, y, z] : std::ranges::views::zip(a1, a2, a3))
{
std::cout << std::format("{}{}{}\n", x, y, z);
}
}</syntaxhighlight>
=={{header|Chapel}}==
<
var a2 = [ "A", "B", "C" ];
var a3 = [ 1, 2, 3 ];
for (x,y,z) in zip(a1, a2, a3) do
writeln(x,y,z);</
=={{header|Clojure}}==
<
(println s))</
The sequence stops when the shortest list is exhausted.
<
(apply map str ["abc" "ABC" "123"])
("aA1" "bB2" "cC3")
</syntaxhighlight>
=={{header|COBOL}}==
<
PROGRAM-ID. Loop-Over-Multiple-Tables.
Line 956 ⟶ 1,335:
GOBACK
.</
=={{header|Common Lisp}}==
=== Using functional application ===
<
(format t "~{~A~}~%" args))
'(|a| |b| |c|)
'(a b c)
'(1 2 3))</
If lists are different lengths, it stops after the shortest one.
=== Using LOOP ===
<
(loop for x in '("a" "b" "c")
for y in '(a b c)
for z in '(1 2 3)
do (format t "~a~a~a~%" x y z))
</syntaxhighlight>
=== Using DO ===
<
(do ((x '("a" "b" "c") (rest x)) ;
(y '("A" "B" "C" "D") (rest y)) ;
Line 983 ⟶ 1,362:
((or (null x) (null y) (null z))) ; Break condition
(format t "~a~a~a~%" (first x) (first y) (first z))) ; On every loop print first elements
</syntaxhighlight>
{{out}}
Line 993 ⟶ 1,372:
=={{header|D}}==
<
void main () {
foreach (a, b, c; zip("abc", "ABC", [1, 2, 3]))
writeln(a, b, c);
}</
{{out}}
<pre>aA1
Line 1,006 ⟶ 1,385:
On default it stops when the shortest range is exhausted
(same as StoppingPolicy.shortest):
<
void main () {
Line 1,026 ⟶ 1,405:
foreach (p; zip(sp.requireSameLength, a1, a2))
writeln(p.tupleof);
}</
{{out}}
<pre>11
Line 1,041 ⟶ 1,420:
There is also std.range.lockstep:
<
void main() {
Line 1,055 ⟶ 1,434:
foreach (index, a, b; lockstep(arr1, arr2))
writefln("Index %s: a = %s, b = %s", index, a, b);
}</
Lower level code that stops at the shortest length:
<
void main () {
Line 1,066 ⟶ 1,445:
foreach (i; 0 .. min(s1.length, s2.length, a1.length))
writeln(s1[i], s2[i], a1[i]);
}</
{{out}}
<pre>aA1
Line 1,072 ⟶ 1,451:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,089 ⟶ 1,468:
Readln;
end.</
=={{header|Diego}}==
<syntaxhighlight lang="diego">set_namespace(rosettacode);
add_mat(myMatrix)_row(a,b,c)_row(A,B,C)_row(1,2,3);
add_var(output,columnArray);
with_mat(myMatrix)_foreach()_bycol()_var(columnArray)
with_var(output)_append()_flat([columnArray])_append(\n);
;
me_msg([output]);
reset_namespace[];</syntaxhighlight>
Diego has no issue when arrays are of a different length, the "missing" array entries will be handled as empty. Note, the <code>matrix</code> will become a <code>clump</code>, but can still be treated as a <code>matrix</code>.
<syntaxhighlight lang="diego">set_ns(rosettacode);
add_clump(myClump)_row(a,b,c,d)_row(A,B,C,D,E,F)_row(-1,0,1,2,3); // The default spread is presumed to be 'origin'
add_var(output,columnArray);
with_clump(myClump)_foreach()_bycol()_var(columnArray)
with_var(output)_append()_flat([columnArray])_append(\n);
;
me_msg([output]);
reset_ns[];</syntaxhighlight>
{{out}}
<pre>
aA-1
bB0
cC1
dD2
E3
F
</pre>
=={{header|DWScript}}==
Line 1,096 ⟶ 1,512:
element.
<
const a2 = ['A', 'B', 'C'];
const a3 = [1, 2, 3];
Line 1,102 ⟶ 1,518:
var i : Integer;
for i := 0 to 2 do
PrintLn(Format('%s%s%d', [a1[i], a2[i], a3[i]]));</
=={{header|E}}==
Line 1,111 ⟶ 1,527:
indexes as keys, so a not entirely awful idiom exists:
<
def a2 := ["A","B","C"]
def a3 := ["1","2","3"]
Line 1,117 ⟶ 1,533:
for i => v1 in a1 {
println(v1, a2[i], a3[i])
}</
This will obviously fail if a2 or a3 are shorter than a1, and omit items
Line 1,124 ⟶ 1,540:
Given a parallel iteration utility, we might write this:
<
println(v1, v2, v3)
}</
<code>zip</code> cannot yet be defined for all collections
Line 1,136 ⟶ 1,552:
collections.
<
to run(l1, l2) {
def zipped {
Line 1,163 ⟶ 1,579:
zipped
}
}</
(This will stop when the end of the shortest collection is reached.)
=={{header|EasyLang}}==
<syntaxhighlight>
a$[] = [ "a" "b" "c" ]
b$[] = [ "A" "B" "C" ]
c[] = [ 1 2 3 ]
for i = 1 to 3
print a$[i] & b$[i] & c[i]
.
</syntaxhighlight>
=={{header|EchoLisp}}==
<
;; looping over different sequences : infinite stream, string, list and vector
;; loop stops as soon a one sequence ends.
Line 1,183 ⟶ 1,609:
1004 "E" 4 s
1005 "F" 5 t
</syntaxhighlight>
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module LoopOverMultipleArrays {
void run() {
Char[] chars = ['a', 'b', 'c'];
String[] strings = ["A", "B", "C"];
Int[] ints = [ 1, 2, 3 ];
@Inject Console console;
console.print("Using array indexing:");
for (Int i = 0, Int longest = chars.size.maxOf(strings.size.maxOf(ints.size));
i < longest; ++i) {
console.print($|{i < chars.size ? chars[i].toString() : ""}\
|{i < strings.size ? strings[i] : ""}\
|{i < ints.size ? ints[i].toString() : ""}
);
}
console.print("\nUsing array iterators:");
val charIter = chars.iterator();
val stringIter = strings.iterator();
val intIter = ints.iterator();
while (True) {
StringBuffer buf = new StringBuffer();
if (Char ch := charIter.next()) {
buf.add(ch);
}
if (String s := stringIter.next()) {
s.appendTo(buf);
}
if (Int n := intIter.next()) {
n.appendTo(buf);
}
if (buf.size == 0) {
break;
}
console.print(buf);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Using array indexing:
aA1
bB2
cC3
Using array iterators:
aA1
bB2
cC3
</pre>
=={{header|Efene}}==
<
run = fn () {
lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) },
lists.zip3("abc", "ABC", "123"))
}
</syntaxhighlight>
If the lists are not all the same length, an error is thrown.
=={{header|Eiffel}}==
<
example (a_array: READABLE_INDEXABLE [BOUNDED [ANY]]): STRING
-- Assemble output for a 2-dim array in `a_array'
Line 1,230 ⟶ 1,711:
>>
end
</syntaxhighlight>
{{out}}
aA1
Line 1,250 ⟶ 1,731:
=={{header|Ela}}==
<
xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c']
Line 1,261 ⟶ 1,742:
return $ each print xss
print_and_calc xs ::: IO</
The code above can be written shorter. First there is no need in lists
Line 1,268 ⟶ 1,749:
composition operator:
<
"123"</
=={{header|Elena}}==
ELENA
<
import extensions;
Line 1,282 ⟶ 1,763:
var a3 := new int[]{1,2,3};
for(int i := 0
{
console.printLine(a1[i], a2[i], a3[i])
Line 1,288 ⟶ 1,769:
console.readChar()
}</
Using zipBy extension:
<
import extensions.
Line 1,302 ⟶ 1,783:
.zipBy(a3, (first,second => first + second.toString() ));
zipped.forEach::(e)
{ console.writeLine:e };
console.readChar();
}</
{{out}}
<pre>
Line 1,316 ⟶ 1,797:
=={{header|Elixir}}==
'''string list:'''
<
l2 = ["A", "B", "C"]
l3 = ["1", "2", "3"]
IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) |> Enum.join end)
#=> ["aA1", "bB2", "cC3"]</
'''char_list:'''
<
l2 = 'ABC'
l3 = '123'
IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) end)
#=> ['aA1', 'bB2', 'cC3']</
When the length of the list is different:
<
['aA1', 'bB2', 'cC3']
iex(2)> List.zip(['abcde','ABC','12']) |> Enum.map(&Tuple.to_list(&1))
['aA1', 'bB2']</
The zipping finishes as soon as any enumerable completes.
=={{header|Erlang}}==
Shortest option:
<
io:format("~s~n",[[A,B,C]]) end, "abc", "ABC", "123").</
However, as every expression in Erlang has to return something, printing text returns 'ok'. A list with as many 'ok's as there are lines printed will thus be created. The technically cleanest way to do things would be with
<tt>lists:foreach/2</tt>, which also guarantees evaluation
order:
<
io:format("~s~n",[[A,B,C]]) end,
lists:zip3("abc", "ABC", "123")).</
If the lists are not all the same length, an error is thrown.
Line 1,352 ⟶ 1,833:
are.
If they are all "strings", it's quite easy:
<syntaxhighlight lang="euphoria">
sequence a, b, c
Line 1,362 ⟶ 1,843:
puts(1, a[i] & b[i] & c[i] & "\n")
end for
</syntaxhighlight>
If not, and the other sequence is known to contain only integers:
<syntaxhighlight lang="euphoria">
sequence a, b, c
Line 1,376 ⟶ 1,857:
printf(1, "%s%s%g\n", {a[i], b[i], c[i]})
end for
</syntaxhighlight>
A general solution for any arbitrary strings of characters or numbers
Line 1,382 ⟶ 1,863:
printed out. One possible answer is as follows, if you know that only
alphanumeric characters are used:
<syntaxhighlight lang="euphoria">
for i = 1 to length(a) do
if (a[i] >= '0' and a[i] <= '9') then
Line 1,395 ⟶ 1,876:
printf(1, "%s%s%s\n", {a[i], b[i], c[i]})
end for
</syntaxhighlight>
Just as in Java, using single quotes around a character gives you its
"char value". In Euphoria, though, it is simply that character's code
Line 1,404 ⟶ 1,885:
=={{header|F_Sharp|F#}}==
<
[1;2;3] do
printfn "%c%c%d" c1 c2 n</
When one sequence is exhausted, any remaining elements in the other
Line 1,412 ⟶ 1,893:
=={{header|Factor}}==
<
3each</
=={{header|Fantom}}==
This will stop when it reaches the end of the shortest list.
<
class LoopMultiple
{
Line 1,432 ⟶ 1,913:
}
}
</syntaxhighlight>
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">[a] := [('a','b','c')];
[b] := [('A','B','C')];
[c] := [(1,2,3)];
for i=1,3 do !!(a[i]:char,b[i]:char,c[i]:1) od;
;{note the :char and :1 suffixes. The former}
;{causes the element to be printed as a char}
;{instead of a numerical ASCII code, and the}
;{:1 causes the integer to take up exactly one}
;{space, ie. no leading or trailing spaces.}</syntaxhighlight>
{{out}}</pre>aA1
bB2
cC3</pre>
=={{header|Forth}}==
<
create b char A , char B , char C ,
create c char 1 , char 2 , char 3 ,
Line 1,453 ⟶ 1,948:
loop
drop drop drop
;</
=={{header|Fortran}}==
<
implicit none
Line 1,472 ⟶ 1,967:
end program main
</syntaxhighlight>
If the arrays are of different length (say, array ns has no third element), then when its turn comes the next unit of storage along from the second element will be accessed, its content interpreted as an integer, and its decimal value printed... If however, array bound checking is activated (or there is a memory access protection scheme that would detect this), a feature unavailable via many compilers and not the default on the rest, then an error will be detected and the run will be terminated, possibly with a somewhat helpful message.
If instead of reading the action had been to store a value into the array, then in the absence of bound checking, arbitrary damage will be done (to code or data) that will possibly result in something going wrong. And if you're lucky, it will happen swiftly.
=={{header|Frink}}==
<
a2 = ["A", "B", "C"]
a3 = ["1", "2", "3"]
m = [a1, a2, a3]
for row = m.transpose[]
println[join["",row]]</
=={{header|FunL}}==
<
for x <- zip3( ['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3] )
println( x.mkString() )</
{{out}}
Line 1,541 ⟶ 1,995:
</pre>
=={{header|
<syntaxhighlight lang="futurebasic">
void local fn DoIt
long i, count = len(a1)
for i = 0 to count - 1
print a1[i]a2[i]a3[i]
next
end fn
fn DoIt
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
aA1
bB2
Cc3
</pre>
=={{header|GAP}}==
<
# The Loop function will apply some function to every tuple built by
taking
Line 1,598 ⟶ 2,055:
aC3
bD1
aE2</
=={{header|GDScript}}==
{{works with|Godot|4.0.1}}
<syntaxhighlight lang="gdscript">
extends MainLoop
# Implementation of zip, same length as the shortest array
func zip(lists: Array[Array]) -> Array[Array]:
var length: int = lists.map(func(arr): return len(arr)).reduce(func(a,b): return min(a,b))
var result: Array[Array] = []
result.resize(length)
for i in length:
result[i] = lists.map(func(arr): return arr[i])
return result
func _process(_delta: float) -> bool:
var a: Array[String] = ["a", "b", "c"]
var b: Array[String] = ["A", "B", "C"]
var c: Array[String] = ["1", "2", "3"]
for column in zip([a,b,c]):
print(''.join(column))
return true # Exit
</syntaxhighlight>
=={{header|Go}}==
Line 1,613 ⟶ 2,095:
conditions are meaningful in your application and explicitly handle
whatever errors are plausible.
<
import "fmt"
Line 1,625 ⟶ 2,107:
fmt.Printf("%v%c%v\n", a1[i], a2[i], a3[i])
}
}</
=={{header|Golfscript}}==
<
["A" "B" "C"]:b;
["1" "2" "3"]:c;
[a b c]zip{puts}/</
If there are arrays of different size, the shorter are treated as
Line 1,638 ⟶ 2,120:
=={{header|Groovy}}==
Solution:
<
assert a1 && a2 && a3
assert a1.size() == a2.size()
assert a2.size() == a3.size()
[a1, a2, a3].transpose().collect { "${it[0]}${it[1]}${it[2]}" }
}</
Test:
<
def y = ['A', 'B', 'C']
def z = [1, 2, 3]
synchedConcat(x, y, z).each { println it }</
{{out}}
Line 1,659 ⟶ 2,141:
=={{header|Harbour}}==
'''Using FOR EACH ... NEXT statement'''
<
PROCEDURE Main()
LOCAL a1 := { "a", "b", "c" }, ;
Line 1,670 ⟶ 2,152:
NEXT
RETURN
</syntaxhighlight>
Output:
aA1
Line 1,681 ⟶ 2,163:
'''Using list comprehension'''
<
main :: IO [()]
main =
sequence
[ putStrLn [x, y, z]
| x <- "abc"
| y <- "ABC"
| z <- "123"
]</syntaxhighlight>
'''Using Transpose'''
Line 1,688 ⟶ 2,178:
In this special case of transposing strings.
<
main = mapM putStrLn $ transpose ["
'''Using ZipWith*'''
<
main = mapM putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123"</
'''Using applicative ZipLists'''
ZipLists generalize zipWith to any number of parameters
<
main :: IO ()
main =
mapM_ putStrLn $
getZipList
( (\x y z -> [x, y, z])
<$> ZipList "abc"
<*> ZipList "ABC"
<*> ZipList "123"
)
<> getZipList
( (\w x y z -> [w, x, y, z])
<$> ZipList "abcd"
<*> ZipList "ABCD"
<*> ZipList "1234"
<*> ZipList "一二三四"
)</syntaxhighlight>
{{Out}}
<pre>aA1
bB2
cC3
aA1一
bB2二
cC3三
dD4四</pre>
=={{header|Haxe}}==
<
using Std;
Line 1,724 ⟶ 2,238:
Sys.println(a[i] + b[i] + c[i].string());
}
}</
=={{header|HicEst}}==
<
REAL :: C(3)
Line 1,734 ⟶ 2,248:
DO i = 1, 3
WRITE() A(i), "ABC"(i), C(i)
ENDDO</
=={{header|Icon}} and {{header|Unicon}}==
The first solution uses co-expressions to produce parallel evaluation.
<
a := create !["a","b","c"]
b := create !["A","B","C"]
c := create !["1","2","3"]
while write(@a,@b,@c)
end</
The second solution is more like other procedural languages
and also handles unequal list lengths.
<
procedure main()
Line 1,758 ⟶ 2,272:
every i := 1 to max(*a,*b,*c) do
write(a[i]|"","\t",b[i]|"","\t",c[i]|"")
end</
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/procs/numbers.htm Uses max from
numbers]
=={{header|Insitux}}==
{{Trans|Clojure}}
<syntaxhighlight lang="insitux">(map str "abc" "ABC" "123")
["aA1" "bB2" "cC3"]</syntaxhighlight>
<syntaxhighlight lang="insitux">(map str ["a" "b" "c"] ["A" "B" "C"] ["1" "2" "3"])
["aA1" "bB2" "cC3"]</syntaxhighlight>
=={{header|J}}==
Since J's primitives are designed for handling what some programmers might think of as "an array monad" of arbitrary rank, a natural approach would be to concatenate the multiple arrays into a single array. In many cases we would already have done so to pass these arrays as an argument to some user defined routine. So, let's first see how that could look:
For arrays of different types:
<
aA1
bB2
cC3</
This approach works by representing the digits as characters.
Where arrays are all the same type (all numeric or all string):
<
aA1
bB2
cC3</
Both of these implementations reject arrays with conflicting lengths.
Line 1,782 ⟶ 2,308:
Other options include:
<
aA1
bB2
cC3</
<
aA1
bB2
cC3</
These implementations pad short arrays with spaces.
Or:
<
┌─┬─┬─┐
│a│A│1│
Line 1,801 ⟶ 2,327:
├─┼─┼─┤
│c│C│3│
└─┴─┴─┘</
This implementation puts each item from each of the original lists
Line 1,813 ⟶ 2,339:
(An "empty box" is what a programmer in another language might call
"a pointer to a zero length array".)
That said, it's also worth noting that a single explicit loop could also be used here. For example,
<syntaxhighlight lang=J>
charcols=: {{
'one two three'=. y
for_a. one do.
echo a,(a_index{two),":a_index{three
end.
}}
charcols 'abc';'ABC';1 2 3
aA1
bB2
cC3</syntaxhighlight>
=={{header|Java}}==
<
for (int i = 0; i < list1.length; i++) {
for (String[] lista : list1) {
Line 1,821 ⟶ 2,362:
}
System.out.println();
}</
=={{header|JavaScript}}==
Line 1,828 ⟶ 2,369:
This loops over the indices of the first array,
and uses that to index into the others.
<
b = ["A","B","C"],
c = [1,2,3],
Line 1,835 ⟶ 2,376:
for (i = 0; i < a.length; i += 1) {
output += a[i] + b[i] + c[i] + "\n";
}</
If the b or c arrays are too "short",
you will see the string "undefined" appear in the output.
Line 1,841 ⟶ 2,382:
Alternatively, we can nest a couple of calls to '''.forEach()''': one for the array of three arrays, and one for each of the three index positions:
<
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].forEach(
Line 1,854 ⟶ 2,395:
);
// lstOut --> ["aA1", "bB2", "cC3"]</
===Functional composition===
Line 1,866 ⟶ 2,407:
Reduce / fold:
<
return lstArrays.reduce(
Line 1,882 ⟶ 2,423:
["A", "B", "C"],
["1", "2", "3"]
]);</
A fixed arity ZipWith:
<
// function of arity 3 mapped over nth items of each of 3 lists
Line 1,901 ⟶ 2,442:
return zipWith3(concat, x, y, z).join('\n')
})(["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]);</
Or we could write a generic '''zipListsWith''' applying some supplied function overs lists derived from the nth members of an arbitrary list of (equal-length) lists.
<
'use strict';
Line 1,929 ⟶ 2,470:
)
.join('\n');
})();</
{{Out}}
<syntaxhighlight lang="javascript">aA1
bB2
cC3</
====ES6====
By transposition:
<
'use strict';
Line 1,970 ⟶ 2,511:
map(concat, transpose(xs))
);
})();</
{{Out}}
<pre>aA1
Line 1,984 ⟶ 2,525:
The first array determines the number of items in the output;
nulls are used for padding.
<
def zip:
. as $in
| [range(0; $in[0]|length) as $i | $in | map( .[$i] ) ];</
Example 1:
Line 2,025 ⟶ 2,566:
that pads all arrays shorter than the longest with nulls.
Here is such a variant:
<syntaxhighlight lang="jq">
# transpose a possibly jagged matrix
def transpose:
Line 2,034 ⟶ 2,575:
([]; . + [ [ $row[$i] ] + $t[$i] ])
end;
</syntaxhighlight>
=={{header|Jsish}}==
<
var a1 = ['a', 'b', 'c'];
var a2 = ['A', 'B', 'C'];
Line 2,073 ⟶ 2,614:
undefinedundefinedundefinedundefined7
=!EXPECTEND!=
*/</
{{out}}
Line 2,081 ⟶ 2,622:
=={{header|Julia}}==
'''With a higher order function''':
<
'''With a loop''':
<
println(i, j, k)
end</
{{out}}
Line 2,094 ⟶ 2,635:
=={{header|K}}==
<
{{out}}
Line 2,107 ⟶ 2,648:
The following is a more general approach where
<syntaxhighlight lang="k">
&/#:'x
</syntaxhighlight>
calculates the minimum length of the arrays
and is used to index the first elements in each array.
<syntaxhighlight lang="k">
{+x[;!(&/#:'x)]}("abc";"ABC";"1234")
</syntaxhighlight>
{{out}}
Line 2,128 ⟶ 2,669:
then the arrays must be converted to strings.
<syntaxhighlight lang="k">
{a:,/'($:'x);+a[;!(&/#:'a)]}("abc";"ABC";1 2 3 4)
</syntaxhighlight>
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.comparisons.minOf
fun main(
val a1 = charArrayOf('a', 'b', 'c')
val a2 = charArrayOf('A', 'B', 'C')
val a3 = intArrayOf(1, 2, 3)
for (i in 0
println()
// For arrays of different sizes, we
val a4 = intArrayOf(4, 5, 6, 7)
val a5 = charArrayOf('d', 'e')
val minSize =
for (i in 0 until minSize) println("${a2[i]}${a4[i]}${a5[i]}")
}</
{{out}}
Line 2,160 ⟶ 2,700:
=={{header|Lambdatalk}}==
<
1) loop over 3 sentences of equal length and returning 3 sentences
Line 2,213 ⟶ 2,753:
e d
s
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
$a $= [a, b, c] # Char values
$b $= [A\e, B\e, C\e] # Text values
$c $= [1, 2, 3] # Int values
# Repeat loop
$i
repeat($[i], @$a) {
fn.println(parser.op($a[$i] ||| $b[$i] ||| $c[$i]))
}
fn.println()
# Foreach loop with zip and reduce
$ele
foreach($[ele], fn.arrayZip($a, $b, $c)) {
fn.println(fn.arrayReduce($ele, \e, fn.concat))
}
fn.println()
# Foreach function with combinator
fn.arrayForEach(fn.arrayZip($a, $b, $c), fn.combB(fn.println, fn.combC3(fn.arrayReduce, fn.concat, \e)))
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
aA1
bB2
cC3
aA1
bB2
cC3
</pre>
=={{header|LFE}}==
<
(lists:zipwith3
(lambda (i j k)
Line 2,223 ⟶ 2,802:
'(A B C)
'(1 2 3))
</syntaxhighlight>
If any of the data lists differ in size from the other,
Line 2,235 ⟶ 2,814:
function with something like <code lisp>(: lists map
...)</code>.
=={{header|Lisaac}}==
<
+ name := ARRAY_LOOP_TEST;
Line 2,273 ⟶ 2,842:
'\n'.print;
};
);</
=={{header|LiveCode}}==
Arrays
<
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,292 ⟶ 2,861:
put z
end loopArrays</
"list" processing
<
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,306 ⟶ 2,875:
put z
end loopDelimitedList</
Output - both behave similarly for this exercise.
<pre>aA1
Line 2,323 ⟶ 2,892:
{{works with|UCB Logo}}
<
; [aA1 bB2 cC3]
(foreach [a b c] [A B C] [1 2 3] [print (word ?1 ?2 ?3)]) ; as above,
one per line</
=={{header|Lua}}==
This can be done with a simple for loop:
<
a1, a2, a3 = {'a' , 'b' , 'c' } , { 'A' , 'B' , 'C' } , { 1 , 2 , 3 }
for i = 1, 3 do print(a1[i]..a2[i]..a3[i]) end
</syntaxhighlight>
but it may be more enlightening
(and in line with the spirit of the challenge) to use the generic for:
<
function iter(a, b, c)
local i = 0
Line 2,347 ⟶ 2,916:
for u, v, w in iter(a1, a2, a3) do print(u..v..w) end
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
While End While can used for iterator type objects. We can use comma to use more than one iterator, or we can use folded While End While. When we use comma the iteration end when any of the iterators before iterate get the false state (no other iteration allowed). So for this example in While End while it is like we use i1 and i2 and i3, but with a comma (this only apply to While structure - and While { } structure - without End While<sup>Superscript text. We can't use and operator because this return Boolean type always. Using the iterator at While we get the object, and Interpreter check if this is an iterator object and go on to advance to next item, or to break the loop. We can use i1^ to get the index of the iteration according to specific object.
<syntaxhighlight lang="m2000 interpreter">module Loop_over_multiple_arrays_simultaneously {
r1=("a","b","c",1,2,3,4,5)
r2=("A","B","C", 4)
r3=(1,2,3)
i1=each(r1)
i2=each(r2)
i3=each(r3)
while i1, i2, i3
print array(i1)+array(i2)+array(i3)
end while
}
Loop_over_multiple_arrays_simultaneously
</syntaxhighlight>
{{out}}
<pre> aA1
bB2
cC3</pre>
=={{header|Maple}}==
<
L := [["a", "b", "c"],["A", "B", "C"], ["1", "2", "3"]];
M := Array(1..3, 1..3, L);
Line 2,364 ⟶ 2,953:
end proc:
multi_loop(M);</
{{out}}
<pre>
Line 2,374 ⟶ 2,963:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This can be done with a built-in function:
<
All arguments must be lists of the same length.
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that loops over multiple arrays simultaneously depending on the list with less length */
lomas(L):=block(
minlen:lmin(map(length,L)),
makelist(makelist(L[i][j],i,1,length(L)),j,1,minlen))$
/* Test case */
lst:[[a,b,c],[A,B,C],[1,2,3]]$
lomas(lst);
</syntaxhighlight>
{{out}}
<pre>
[[a,A,1],[b,B,2],[c,C,3]]
</pre>
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module multi_array_loop.
:- interface.
Line 2,398 ⟶ 3,003:
print_elems(A, B, C, !IO) :-
io.format("%c%c%i\n", [c(A), c(B), i(C)], !IO).
</syntaxhighlight>
The foldl_corresponding family of procedures all throw a
software_error/1
Line 2,404 ⟶ 3,009:
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 2,420 ⟶ 3,025:
Fmt.Int(arr3[i]) & "\n");
END;
END MultiArray.</
=={{header|MUMPS}}==
Pieces of String version
<syntaxhighlight lang="mumps">
LOOPMULT
N A,B,C,D,%
Line 2,434 ⟶ 3,039:
K A,B,C,D,%
Q
</syntaxhighlight>
When there aren't enough elements,
a null string will be returned from the $Piece function.
Line 2,447 ⟶ 3,052:
Local arrays version
<syntaxhighlight lang="mumps">
LOOPMULU
N A,B,C,D,%
Line 2,457 ⟶ 3,062:
S %=$O(A("")) F Q:%="" W !,$G(A(%)),$G(B(%)),$G(C(%)) S %=$O(A(%))
K A,B,C,D,%
</syntaxhighlight>
The commented out line will throw an <UNDEFINED> error when trying
Line 2,483 ⟶ 3,088:
=={{header|Nanoquery}}==
{{trans|Java}}
<
for i in range(0, len(list1) - 1)
for lista in list1
Line 2,489 ⟶ 3,094:
end for
println
end for</
=={{header|Nemerle}}==
It "feels" better to use zip() for this,
unfortunately the built in zip() only takes two lists.
<
using System.Console;
Line 2,518 ⟶ 3,123:
WriteLine($"$x$y$z");
}
}</
Alternately: {{trans|C#}}
<
module LoopMult
Line 2,536 ⟶ 3,141:
WriteLine("{0}{1}{2}", first[i], second[i], third[i]);
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,584 ⟶ 3,189:
return smp
</syntaxhighlight>
{{out}}
<pre style="overflow:scroll">
Line 2,600 ⟶ 3,205:
=={{header|NewLISP}}==
<
3))</
=={{header|Nim}}==
<
a = @['a','b','c']
b = @["A","B","C"]
Line 2,610 ⟶ 3,215:
for i in 0..2:
echo a[i], b[i], c[i]</
=={{header|Oberon-2}}==
Works with oo2c version 2
<
MODULE LoopMArrays;
IMPORT
Line 2,656 ⟶ 3,244:
DoLoop
END LoopMArrays.
</syntaxhighlight>
Output:<br/>
<pre>
Line 2,665 ⟶ 3,253:
=={{header|Objeck}}==
<
class MultipleArrayAccess {
function : Main(args : String[]) ~ Nil {
Line 2,679 ⟶ 3,267:
}
}
</syntaxhighlight>
If the arrays are different lengths,
Line 2,686 ⟶ 3,274:
=={{header|OCaml}}==
an immediate solution:
<
and a2 = [| 'A'; 'B'; 'C' |]
and a3 = [| '1'; '2'; '3' |] ;;
Line 2,695 ⟶ 3,283:
print_char a3.(i);
print_newline()
) a1 ;;</
a more generic solution could be to use a function
which iterates over a list of arrays:
<
| [] -> ()
| x::xs as al ->
Line 2,710 ⟶ 3,298:
let ai = List.map (fun a -> a.(i)) al in
f ai
done</
this function raises Invalid_argument exception if arrays have different
Line 2,716 ⟶ 3,304:
and has this signature:
<
array list -> unit</
how to use it with arrays a1, a2 and a3 defined before:
<
n_arrays_iter [a1; a2; a3] ~f:(fun l ->
List.iter print_char l;
print_newline());
;;</
=={{header|Oforth}}==
Line 2,731 ⟶ 3,319:
If arrays don't have the same size, zipAll reduces to the minimum size
<
zipAll(3) apply(#[ apply(#print) printcr ])</
{{out}}
Line 2,742 ⟶ 3,330:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
x = .array~of("a", "b", "c")
y = .array~of("A", "B", "C")
Line 2,750 ⟶ 3,338:
say x[i]y[i]z[i]
end
</syntaxhighlight>
=={{header|Oz}}==
<
I in [a b c]
J in ['A' 'B' 'C']
Line 2,759 ⟶ 3,347:
do
{System.showInfo I#J#K}
end</
The loop will stop when the shortest list is exhausted.
Line 2,765 ⟶ 3,353:
=={{header|PARI/GP}}==
This version stops when the shortest vector is exhausted.
<
my(l=#V[1]);
for(i=2,#V,l=min(l,#V[i]));
Line 2,774 ⟶ 3,362:
print()
)
};</
This version prints blanks when a vector is exhausted.
<
my(l=0);
for(i=1,#V,l=max(l,#V[i]));
Line 2,790 ⟶ 3,378:
print()
)
};</
=={{header|Pascal}}==
See [[Loop_over_multiple_arrays_simultaneously#Delphi | Delphi]]
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
begin
var a1 := Arr('a','b','c');
var a2 := Arr('A','B','C');
var a3 := Arr(1,2,3);
for var i:=0 to a1.Length-1 do
Writeln(a1[i],a2[i],a3[i]);
Writeln;
foreach var (x,y,z) in a1.Zip(a2,a3) do
Writeln(x,y,z);
Writeln;
a1.Zip(a2,a3).PrintLines(t -> t[0]+t[1]+t[2]);
end.
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
aA1
bB2
cC3
aA1
bB2
cC3
</pre>
=={{header|Perl}}==
<
{
my $code = shift;
Line 2,808 ⟶ 3,426:
my @a3 = qw( 1 2 3 );
zip { print @_,"\n" }\(@a1, @a2, @a3);</
This implementation will stop producing items when the shortest array
Line 2,818 ⟶ 3,436:
If the arguments were not all the same length, attempts to retrieve non-existent elements could trigger a fatal run-time error, were it not for the min(). In print3, fairly obviously, we only extract up to the shortest length. The builtin columnize() routine can perform a similar task: I have provided a space defval and replaced the 3rd array with a string to ensure we get strings back, and extended it to show how columnize uses that default value for missing entries off the end of the first two arrays.
<!--<
<span style="color: #008080;">procedure</span> <span style="color: #000000;">print3</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span> <span style="color: #008080;">do</span>
Line 2,827 ⟶ 3,445:
<span style="color: #000000;">print3</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ABC"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ABC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1234"</span><span style="color: #0000FF;">},{},</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
Line 2,838 ⟶ 3,456:
=={{header|Phixmonti}}==
<
( "abc" "ABC" "123" )
Line 2,853 ⟶ 3,471:
nl
endfor
</syntaxhighlight>
=={{header|PHP}}==
<
$b = array('A', 'B', 'C');
$c = array('1', '2', '3'); //These don't *have* to be strings, but it
Line 2,866 ⟶ 3,484:
foreach ($a as $key => $value){
echo "{$a[$key]}{$b[$key]}{$c[$key]}\n";
}</
This implementation throws an exception if the arrays are not all the
same length.
=={{header|Picat}}==
Picat has a built-in <code>zip/n</code> which only works with lists (not arrays). It returns an array tuple (<code>{A,B,C}</code>) and not a list (<code>[A,B,C]</code>), which is a typical gotcha.
For this task, a foreach loop and list comprenhension are shown.
If the lists/arrays are of uneven lengths, then the elements in the longer arrays are skipped.
<syntaxhighlight lang="picat">import util.
go =>
L1 = ["a","b","c"],
L2 = ["A","B","C"],
L3 = ["1","2","3"],
println("foreach loop:"),
foreach({A,B,C} in zip(L1,L2,L3))
println([A,B,C].join(''))
end,
nl,
println("list comprehension/n:"),
println( [[A,B,C].join('') : {A,B,C} in zip(L1,L2,L3)].join("\n")),
nl,
% With uneven lengths the last elements in the longer lists are skipped.
println("Uneven lengths:"),
L4 = ["P","Q","R","S"], % longer than the other
foreach({A,B,C,D} in zip(L1,L2,L3,L4))
println([A,B,C,D].join(''))
end,
nl.</syntaxhighlight>
{{out}}
<pre>foreach loop:
aA1
bB2
cC3
list comprehension/n:
aA1
bB2
cC3
Uneven lengths:
aA1P
bB2Q
cC3R</pre>
=={{header|PicoLisp}}==
<
'(a b c)
'(A B C)
(1 2 3) )</
The length of the first argument list controls the operation.
If subsequent lists are longer, their remaining values are ignored.
Line 2,884 ⟶ 3,551:
avoids the usual off-by-one errors
<syntaxhighlight lang="pike">
array a1 = ({ "a", "b", "c" });
array a2 = ({ "A", "B", "C" });
Line 2,891 ⟶ 3,558:
foreach(a1; int index; string char_dummy)
write("%s%s%s\n", a1[index], a2[index], a3[index]);
</syntaxhighlight>
{{Out}}
<pre>
Line 2,900 ⟶ 3,567:
=={{header|PL/I}}==
<
declare P(3) character (1) initial ('a', 'b', 'c'),
Q(3) character (1) initial ('A', 'B', 'C'),
Line 2,908 ⟶ 3,575:
put skip edit (P(i), Q(i), R(i)) (2 A, F(1));
end;
</syntaxhighlight>
=={{header|PostScript}}==
{{libheader|initlib}}
<
% transpose is defined in initlib like this.
/transpose {
Line 2,924 ⟶ 3,591:
% using it.
[[/a /b /c] [/A /B /C] [1 2 3]] transpose
</syntaxhighlight>
=={{header|PowerShell}}==
A cheap and chEasy 'zip' function:
<syntaxhighlight lang="powershell">
function zip3 ($a1, $a2, $a3)
{
Line 2,964 ⟶ 3,606:
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
zip3 @('a','b','c') @('A','B','C') @(1,2,3)
</syntaxhighlight>
{{Out}}
<pre>
Line 2,976 ⟶ 3,618:
c C 3
</pre>
<syntaxhighlight lang="powershell">
zip3 @('a','b','c') @('A','B','C') @(1,2,3) | ForEach-Object {$_.Item1 + $_.Item2 + $_.Item3}
</syntaxhighlight>
{{Out}}
<pre>
Line 2,988 ⟶ 3,630:
=={{header|Prolog}}==
Works with SWI-Prolog
<
maplist(display, L1, L2, L3).
display(A,B,C) :-
writef('%s%s%s\n', [[A],[B],[C]]).
</syntaxhighlight>
{{out}}
<pre> ?- multiple_arrays("abc", "ABC", "123").
Line 3,006 ⟶ 3,648:
false.
</pre>
=={{header|Python}}==
Using <tt>zip()</tt>:
<
zip('abc', 'ABC', '123')) )
aA1
bB2
cC3
>>></
If lists are different lengths, <tt>zip()</tt> stops after
the shortest one.
Using <tt>map()</tt>:
<
aA1
bB2
cC3
>>></
If lists are different lengths, <tt>map()</tt> in Python 2.x pretends that the shorter lists were extended with
<tt>None</tt> items; <tt>map()</tt> in Python 3.x stops after the shortest one.
Using <tt>itertools.imap()</tt> (Python 2.x):
<
def join3(a,b,c):
print a+b+c
imap(join3,'abc','ABC','123')</
If lists are differnt lengths, <tt>imap()</tt> stops after
the shortest is exhausted.
Line 3,069 ⟶ 3,682:
fillvalue argument which defaults to <tt>None</tt> (similar to the behavior of
''map()'' in Python 2.x):
<
>>> print ( '\n'.join(''.join(x) for x in zip_longest('abc',
'ABCD', '12345', fillvalue='#')) )
Line 3,077 ⟶ 3,690:
#D4
##5
>>></
(The Python 2.X equivalent is itertools.izip_longest)
Line 3,084 ⟶ 3,697:
The code presented here will loop as many times as the number of characters in the first nest (i.e. "abc" in the example). If either of the other two nests are shorter than the first then the program will report a problem.
<
[ emit
over i^ peek emit
Line 3,091 ⟶ 3,704:
2drop ] is task ( $ $ $ --> )
$ "abc" $ "ABC" $ "123" task</
{{out}}
Line 3,101 ⟶ 3,714:
=={{header|R}}==
<
{
# Retrieve inputs and convert to a list of character strings
Line 3,121 ⟶ 3,734:
}
}
multiloop(letters[1:3], LETTERS[1:3], 1:3)</
Same thing as a single function call.
But throws error if the arrays differ in length.
<syntaxhighlight lang="r">
apply(data.frame(letters[1:3], LETTERS[1:3], 1:3), 1,
function(row) { cat(row, "\n", sep='') })
</syntaxhighlight>
=={{header|Racket}}==
Line 3,136 ⟶ 3,749:
of sequences of any kind at once:
<
#lang racket
Line 3,144 ⟶ 3,757:
[i (in-naturals 1)]) ; 1, 2, ... infinitely
(printf "~s: ~s ~s ~s\n" i x y z))
</syntaxhighlight>
The loop stops as soon as the first sequence terminates -- in the above
Line 3,158 ⟶ 3,771:
=== Basic functionality ===
<syntaxhighlight lang="raku"
say $x, $y, $z;
}</
The <code>Z</code> operator stops emitting items as soon as the shortest input list is exhausted. However, short lists are easily extended by replicating all or part of the list, or by appending any kind of lazy list generator to supply default values as necessary.
Line 3,170 ⟶ 3,783:
Note that we can also factor out the concatenation by making the <tt>Z</tt> metaoperator apply the <tt>~</tt> concatenation operator across each triple:
<syntaxhighlight lang="raku"
We could also use the zip-to-string with the reduction metaoperator:
<syntaxhighlight lang="raku"
We could also write that out "long-hand":
<syntaxhighlight lang="raku"
returns the exact same result so if you aren't comfortable with the concise operators, you have a choice.
Line 3,186 ⟶ 3,799:
The common case of iterating over a list and a list of its indices can be done using the same method:
<syntaxhighlight lang="raku"
or by using the <code>.kv</code> (key and value) method on the list (and dropping the parentheses because the list returned by <code>.kv</code> is a flattened list):
<syntaxhighlight lang="raku"
=== Iterate until all exhausted ===
Line 3,196 ⟶ 3,809:
If you have different sized lists that you want to pull a value from each per iteration, but want to continue until '''all''' of the lists are exhausted, we have <code>roundrobin</code>.
<syntaxhighlight lang="raku"
{{out|yields}}
<pre>a A 0
Line 3,211 ⟶ 3,824:
When a variable is used in a path notation, we put a colon in front of it. :counter
<
== [["a" "b" "c"] ["A" "B" "C"] [1 2 3]]
Line 3,217 ⟶ 3,830:
a A 1
b B 2
c C 3</
=={{header|REXX}}==
Line 3,225 ⟶ 3,838:
<br><br>
When ''all'' elements are blank, then it signifies the end of the arrays.
<
x. = ' '; x.1 = "a"; x.2 = 'b'; x.3 = "c"
y. = ' '; y.1 = "A"; y.2 = 'B'; y.3 = "C"
Line 3,233 ⟶ 3,846:
output = x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,244 ⟶ 3,857:
In this example, two of the arrays are extended (past the 1<sup>st</sup> example).
<br>Also note that REXX doesn't require quotes around non-negative numbers (they're optional).
<
x.=' '; x.1="a"; x.2='b'; x.3="c"; x.4='d'
y.=' '; y.1="A"; y.2='B'; y.3="C";
Line 3,252 ⟶ 3,865:
output=x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,263 ⟶ 3,876:
===dissimilar sized lists===
<
x = 'a b c d'
y = 'A B C'
Line 3,270 ⟶ 3,883:
output = word(x,j) || word(y,j) || word(z,j)
say output
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,280 ⟶ 3,893:
===idiomatic method for lists===
<
x = 'a b c d'
y = 'A B C'
Line 3,286 ⟶ 3,899:
do j=1 for max(words(x), words(y), words(z))
say word(x,j) || word(y,j) || word(z,j)
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,297 ⟶ 3,910:
=={{header|Ring}}==
<
array1 = ["a", "b", "c"]
array2 = ["A", "B", "C"]
Line 3,305 ⟶ 3,918:
see array1[n] + array2[n] + array3[n] + nl
next
</syntaxhighlight>
=={{header|RPL}}==
===1993+ versions===
≪ 3 ≪ + + ≫ DOLIST
OBJ→ DROP
≫ '<span style="color:blue">CONCAT3</span>' STO
{ "a" "b" "c" } { "A" "B" "C" } { "1" "2" "3" } <span style="color:blue">CONCAT3</span>
{{out}}
<pre>
3: "aA1"
2: "bB2"
1: "cC3"
</pre>
===Older versions===
≪ → a b c
≪ 1 a SIZE '''FOR''' j
a j GET b j GET c j GET + +
'''NEXT'''
≫ ≫'<span style="color:blue">CONCAT3</span>' STO
=={{header|Ruby}}==
<
or
<
Both of these loops print <code>aA1</code>, <code>bB2</code>, <code>cC3</code>.
Line 3,317 ⟶ 3,950:
If an argument array is longer, the excess elements are ignored.
If an argument array is shorter, the value <code>nil</code> is supplied.
<
aA1
bB2
Line 3,323 ⟶ 3,956:
=> nil
irb(main):002:0> ['a','b','c'].zip(['A','B'], [1,2,3,4])
=> [["a", "A", 1], ["b", "B", 2], ["c", nil, 3]]</
=={{header|Rust}}==
<
let a1 = ["a", "b", "c"];
let a2 = ["A", "B", "C"];
Line 3,346 ⟶ 3,968:
println!("{}{}{}", x, y, z);
}
}</
{{out}}
<pre>aA1
Line 3,353 ⟶ 3,975:
=={{header|Salmon}}==
<
any
// number of lists together.
Line 3,377 ⟶ 3,999:
c := [1, 2, 3];
iterate (x; zip(a, b, c))
print(x[0], x[1], x[2], "\n");;</
The preceding code will throw an exception if the lists aren't the same
Line 3,385 ⟶ 4,007:
some lists are shorter than the longest:
<
any
// number of lists together.
Line 3,411 ⟶ 4,033:
c := [1, 2, 3];
iterate (x; zip(a, b, c))
print(x[0], x[1], x[2], "\n");;</
=={{header|Sather}}==
<
main is
a :ARRAY{STR} := |"a", "b", "c"|;
b :ARRAY{STR} := |"A", "B", "C"|;
c :ARRAY{STR} := |"1", "2", "3"|;
loop
#OUT + a
end;
end;
end;
</syntaxhighlight>
=={{header|Scala}}==
<
("abc", "ABC", "123").zipped foreach { (x, y, z) =>
println(x.toString + y + z)
}
</syntaxhighlight>
=={{header|Scheme}}==
Line 3,442 ⟶ 4,063:
into a new list.
<
(let ((a '("a" "b" "c"))
(b '("A" "B" "C"))
Line 3,453 ⟶ 4,074:
(newline))
a b c))
</syntaxhighlight>
Scheme has a <code>vector</code> datatype with constant-time
Line 3,460 ⟶ 4,081:
and <code>vector-map</code>:
<
(let ((a (vector "a" "b" "c"))
(b (vector "A" "B" "C"))
Line 3,471 ⟶ 4,092:
(newline))
a b c))
</syntaxhighlight>
Note, the lists or vectors must all be of the same length.
Line 3,477 ⟶ 4,098:
=={{header|Sidef}}==
The simplest way is by using the Array.zip{} method:
<
say (i, j, k)
}</
{{out}}
<pre>
Line 3,490 ⟶ 4,111:
{{works with|GNU Smalltalk}}
<
a := OrderedCollection new addAll: #('a' 'b' 'c').
b := OrderedCollection new addAll: #('A' 'B' 'C').
Line 3,499 ⟶ 4,120:
(b at: i) display.
(c at: i) displayNl.
].</
If index ''i'' is out of bound, a runtime error is raised.
Line 3,506 ⟶ 4,127:
<br>Also, most Smalltalks (all?) can concatenate non-string args¹.
<br>At least in ST/X, the following works ¹:
<
a := #('a' 'b' 'c').
Line 3,513 ⟶ 4,134:
1 to: (a size) do: [ :i |
((a at: i),(b at: i),(c at: i)) displayNl.
].</
Another alternative is to use a multi-collection enumerator,
which hides the element access (transparent to how elements are stored inside the collection):
<
a := #('a' 'b' 'c').
Line 3,524 ⟶ 4,145:
a with:b with:c do:[:ai :bi :ci |
(ai,bi,ci) displayNl.
].</
1) concatenation of integer objects as shown above may require a change in the <tt>,</tt> (comma) implementation, to send "asString" to the argument.
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "arrayloop" )
@( description, "Loop over multiple arrays simultaneously" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure arrayloop is
a1 : constant array( 1..3 ) of character := ('a', 'b', 'c');
a2 : constant array( 1..3 ) of character := ('A', 'B', 'C');
a3 : constant array( 1..3 ) of integer := (1, 2, 3);
begin
for i in arrays.first( a1 )..arrays.last( a1 ) loop
put( a1( i ) )
@( a2( i ) )
@( strings.trim( strings.image( a3( i ) ), trim_end.both ) );
new_line;
end loop;
end arrayloop;</syntaxhighlight>
=={{header|Standard ML}}==
The below code will combine arbitrarily many lists of strings
into a single list with length equal to that of the shortest list.
<syntaxhighlight lang="standard ml">
(*
* val combine_lists : string list list -> string list
Line 3,541 ⟶ 4,189:
(* ["a1Ax","b2By","c3Cz"] *)
combine_lists[["a","b","c"],["1","2","3"],["A","B","C"],["x","y","z"]];
</syntaxhighlight>
=={{header|Stata}}==
Use an index variable.
<
local v A B C
matrix w=1,2,3
forv i=1/3 {
di "`: word `i' of `u''`: word `i' of `v''`=el("w",1,`i')'"
}</
=== Mata ===
<
u="a","b","c"
v="A","B","C"
Line 3,563 ⟶ 4,211:
printf("%s%s%f\n",u[i],v[i],w[i])
}
end</
=={{header|SuperCollider}}==
Using three variables and indexing (SuperCollider posts the last statement in the REPL)
<syntaxhighlight lang="supercollider">
#x, y, z = [["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]];
3.collect { |i| x[i] ++ y[i] ++ z[i] }
</syntaxhighlight>
A more idiomatic way of writing it, independent of the number of dimensions:
<syntaxhighlight lang="supercollider">
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].flop.collect { |x| x.join }
</syntaxhighlight>
Or simpler:
<syntaxhighlight lang="supercollider">
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].flop.collect(_.join)
</syntaxhighlight>
Same with lamination (a concept from APL/[http://rosettacode.org/wiki/Category:J#The_J_language J]):
<syntaxhighlight lang="supercollider">
["a", "b", "c"] +++ ["A", "B", "C"] +++ ["1", "2", "3"]
</syntaxhighlight>
Independent of dimensions:
<syntaxhighlight lang="supercollider">
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].reduce('+++')
</syntaxhighlight>
=={{header|Swift}}==
<
let a2 = ["A", "B", "C"]
let a3 = [1, 2, 3]
Line 3,601 ⟶ 4,249:
for i in 0 ..< a1.count {
println("\(a1[i])\(a2[i])\(a3[i])")
}</
{{out}}
<pre>aA1
Line 3,609 ⟶ 4,257:
=={{header|Tailspin}}==
Simplest iteration with an ordinary "loop" that will error on uneven sizes
<
def x: ['a', 'b', 'c'];
def y: ['A', 'B', 'C'];
Line 3,616 ⟶ 4,264:
1..$x::length -> '$x($);$y($);$z($);
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,624 ⟶ 4,272:
</pre>
A simple transpose method that gives the same output and also errors on uneven sizes
<
templates transpose
def a: $;
Line 3,633 ⟶ 4,281:
[$x, $y, $z] -> transpose... -> '$...;
' -> !OUT::write
</syntaxhighlight>
A more complex transpose that uses "foreach" more in line with the task proposal and handles uneven arrays
<
def u: ['a', 'b'];
def v: ['A', 'B', 'C'];
Line 3,656 ⟶ 4,304:
[$u,$v,$w] -> transpose2... -> '$...;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,669 ⟶ 4,317:
=={{header|Tcl}}==
<
set list2 {A B C}
set list3 {1 2 3}
foreach i $list1 j $list2 k $list3 {
puts "$i$j$k"
}</
If lists are different lengths, the manual
[http://www.tcl.tk/man/tcl8.5/TclCmd/foreach.htm] says:
Line 3,685 ⟶ 4,333:
=={{header|TorqueScript}}==
<syntaxhighlight lang="torquescript">
$var[0] = "a b c"
$var[1] = "A B C";
Line 3,692 ⟶ 4,340:
for(%i=0;%i<3;%i++)
echo(getWord($var[0],%i) @ getWord($var[1],%i) @ getWord($var[2],%i));
</syntaxhighlight>
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
arr1="a'b'c"
Line 3,703 ⟶ 4,351:
PRINT a,b,c
ENDLOOP
</syntaxhighlight>
{{out}}
<pre>
Line 3,715 ⟶ 4,363:
===Pattern language===
<
@(bind b ("A" "B" "C"))
@(bind c ("1" "2" "3"))
Line 3,725 ⟶ 4,373:
aA1
bB2
cC3</
===TXR Lisp, using <code>mapcar</code>===
Line 3,733 ⟶ 4,381:
finally printed in one go.
<
(repeat "\n"
aA1
bB2
cC3</
===TXR Lisp, using <code>each</code>===
<
(put-line `@x@y@z`))'
aA1
bB2
cC3</
===Translation of Scheme===
Line 3,751 ⟶ 4,399:
{{trans|Scheme}}
<
;; that happily works over strings and lists.
;; We don't need "srfi-43".
Line 3,772 ⟶ 4,420:
(display i3)
(newline))
a b c))</
===Translation of Logo===
Line 3,778 ⟶ 4,426:
{{trans|Logo}}
<
(defun question-var-to-meta-num (var)
^(sys:var ,(int-str (cdr (symbol-name var))))))
Line 3,793 ⟶ 4,441:
(defun show (x) (pprinl x))
(show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]))</
{{out}}
<pre>(aA1 bB2 cC3)</pre>
== {{header|TypeScript}} ==
<syntaxhighlight lang="javascript">// Loop over multiple arrays simultaneously
var arr1: string[] = ['a', 'b', 'c'];
var arr2: string[] = ['A', 'B', 'C'];
var arr3: number[] = [1, 2, 3];
for (var i = 0; i <= 2; i++)
console.log(`${arr1[i]}${arr2[i]}${arr3[i]}`);
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
=={{header|Uiua}}==
{{works with|Uiua|0.11.1}}
The <code>≡</code> (rows) modifier inherently iterates over any number of arrays, provided they have the same length or a length of one.
<syntaxhighlight lang="uiua">
≡(⊂⊂) "abc" "ABC" "123"
</syntaxhighlight>
{{out}}
<pre>
╭─
╷ "aA1"
"bB2"
"cC3"
╯
</pre>
=={{header|UNIX Shell}}==
Line 3,808 ⟶ 4,486:
{{works with|Bourne Shell}}
<
b=A:B:C
c=1:2:3
Line 3,823 ⟶ 4,501:
i=`expr $i + 1`
done
IFS=$oldifs</
{{out}}
Line 3,845 ⟶ 4,523:
{{works with|Bourne Shell}}
<
B='b1 b2 b3'
Line 3,853 ⟶ 4,531:
printf "$a $1\n"
shift
done</
{{out}}
Line 3,869 ⟶ 4,547:
{{works with|ksh93}}
<
b=(A B C)
c=(1 2 3)
for ((i = 0; i < ${#a[@]}; i++)); do
echo "${a[$i]}${b[$i]}${c[$i]}"
done</
{{out}}
Line 3,886 ⟶ 4,564:
{{works with|pdksh}}
<
set -A b A B C
set -A c 1 2 3
Line 3,893 ⟶ 4,571:
echo "${a[$i]}${b[$i]}${c[$i]}"
((i++))
done</
{{works with|zsh}}
<
b=(A B C)
c=(1 2 3)
for ((i = 1; i <= $#a; i++)); do
echo "$a[$i]$b[$i]$c[$i]"
done</
==={{header|C Shell}}===
Line 3,909 ⟶ 4,587:
shell to exit with an error like ''b: Subscript out of range.''
<
set b=(A B C)
set c=(1 2 3)
Line 3,916 ⟶ 4,594:
echo "$a[$i]$b[$i]$c[$i]"
@ i += 1
end</
=={{header|Ursa}}==
Looping over multiple arrays in an interactive session:
<
> append (split "abc" "") a
> append (split "ABC" "") b
Line 3,930 ⟶ 4,608:
bB2
cC3
> _</
If either of the arrays are smaller than (size a), then an indexerror is thrown. This could be caught with a <code>try...catch</code> block.
Line 3,936 ⟶ 4,614:
Compute the transpose of the list formed of the three lists.
If they're of unequal lengths, an exception occurs.
<
main = ~&K7 <'abc','ABC','123'></
{{out}}
<pre>
Line 3,947 ⟶ 4,625:
=={{header|Vala}}==
<
const char a2[] = {'A','B','C'};
const int a3[] = {1, 2, 3};
Line 3,954 ⟶ 4,632:
for (int i = 0; i < 3; i++)
stdout.printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}</
=={{header|VBScript}}==
<
a = Array("a","b","c")
Line 3,985 ⟶ 4,643:
buf = buf & vbCrLf & a(i) & b(i) & c(i)
Next
WScript.Echo Mid(buf,3) </
{{out}}
<pre>
Line 3,993 ⟶ 4,651:
</pre>
=={{header|VBA}}==
{{works with|VBA|VBA Excel 2013}}
<syntaxhighlight lang="vb">' Loop over multiple arrays simultaneously - VBA - 08/02/2021
Sub Main()
a = Array("a","b","c")
b = Array("A","B","C")
c = Array(1,2,3)
For i = LBound(a)
buf = buf & vbCrLf
Next
Debug.Print Mid(buf,3)
End Sub </syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
=={{header|Visual FoxPro}}==
<
LOCAL i As Integer, n As Integer, c As String
LOCAL ARRAY a1[3], a2[3], a3[4], a[3]
Line 4,063 ⟶ 4,709:
? "Solution using a cursor"
LIST OFF FIELDS c4
</syntaxhighlight>
{{out}}
<pre>
Line 4,079 ⟶ 4,725:
##4
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
arrays := [['a','b','c'],['A','B','C'],['1','2','3']]
for i in 0..arrays[0].len {
println('${arrays[0][i]}${arrays[1][i]}${arrays[2][i]}')
}
}</syntaxhighlight>
=={{header|Wart}}==
<
prn x X n</
=={{header|Wren}}==
The following script will work as expected provided the lengths of a1 and a2 are at least equal to the length of a3. Otherwise it will produce a 'Subscript out of bounds' error.
<
var a2 = ["A", "B", "C"]
var a3 = [1, 2, 3]
for (i in a3) System.print("%(a1[i-1])%(a2[i-1])%(i)")</
{{out}}
Line 4,101 ⟶ 4,755:
{{works with|nasm}}
{{works with|windows}}
<
extern _printf
Line 4,153 ⟶ 4,807:
xor eax, eax
ret
</syntaxhighlight>
=={{header|XPL0}}==
<
include c:\cxpl\codes; \intrinsic 'code' declarations
char A1, A2;
Line 4,188 ⟶ 4,823:
CrLf(0);
];
]</
{{out}}
Line 4,196 ⟶ 4,831:
cC3
</pre>
=={{header|Z80 Assembly}}==
<syntaxhighlight lang="z80">org &1000
ld b,3
ld ix,array1
loop:
ld a,(ix)
call &bb5a ;prints character to screen
ld a,(ix+3)
call &bb5a
ld a,(ix+6)
call &bb5a
ld a,13
call &bb5a
ld a,10
call &bb5a
inc ix
djnz loop
ret
array1:
db "abc"
array2:
db "ABC"
array3:
db "123"</syntaxhighlight>
{{out}}
<pre>
Ready
call &1000
aA1
bB2
cC3
Ready
</pre>
The program was only written to display the first 3 characters. If they were of different lengths, the wrong characters (or random bytes outside the program) would have been read, depending on which array "ran out" first. The three arrays defined with the <code>db</code> directive are stored sequentially.
=={{header|zkl}}==
<
or
<
["a".."c"],T("A","B","C"),[1..])</
{{out}}
<pre>
Line 4,211 ⟶ 4,888:
which means it can work with infinite sequences
=={{header|
===Limit by minimum length===
'''Works with''': 0.10.x
<syntaxhighlight lang="zig">const std = @import("std");
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
const n = std.math.min3(arr1.len, arr2.len, arr3.len);
for (arr1[0..n]) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
<syntaxhighlight lang="zig">const std = @import("std");
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
const n = @min(arr1.len, arr2.len, arr3.len);
for (arr1[0..n], arr2[0..n], arr3[0..n]) |arr1_e, arr2_e, arr3_e| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2_e, arr3_e });
}
}</syntaxhighlight>
===Limit by length of first array===
'''Works with''': 0.10.x
This example will print up-to arr1 length (asserts that other arrays are at least that long).
<syntaxhighlight lang="zig">const std = @import("std");
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
<syntaxhighlight lang="zig">const std = @import("std");
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1, 0..) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
===Assert that arrays have equal length===
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
This example will print up-to arr1 length (asserts that other arrays are exactly that long => asserts that lengths are equal).
<syntaxhighlight lang="zig">const std = @import("std");
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1, arr2, arr3) |arr1_e, arr2_e, arr3_e| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2_e, arr3_e });
}
}</syntaxhighlight>
|