Loop over multiple arrays simultaneously: Difference between revisions
Loop over multiple arrays simultaneously (view source)
Revision as of 20:57, 27 August 2022
, 1 year agosyntax highlighting fixup automation
m (→{{header|Haskell}}: ZipList version tidied for legibility) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
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!}}==
<
CHAR ARRAY a="abc",b="ABC"
BYTE ARRAY c=[1 2 3]
Line 235:
PrintF("%C%C%B%E",a(i+1),b(i+1),c(i))
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loop_over_multiple_arrays_simultaneously.png Screenshot from Atari 8-bit computer]
Line 245:
=={{header|Ada}}==
<
procedure Array_Loop_Test is
Line 257:
(Index))(2));
end loop;
end Array_Loop_Test;</
=={{header|ALGOL 68}}==
Line 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 284:
=={{header|ALGOL W}}==
<
% declare the three arrays %
string(1) array a, b ( 1 :: 3 );
Line 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.
Line 307:
vectors, zeroes for numeric vectors) to match the longest vector.
<syntaxhighlight lang
{{out}}
Line 323:
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 413:
end script
end if
end mReturn</
{{Out}}
<pre>aA1
Line 421:
But a transpose function might be simpler:
<
on run
Line 495:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>aA1
Line 503:
=={{header|Arturo}}==
<
loop 0..2 'x ->
print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|"</
{{out}}
Line 518:
[http://www.autohotkey.com/docs/commands/StringSplit.htm StringSplit]
creates a pseudo-array
<
List2 = A,B,C
List3 = 1,2,3
Line 543:
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 556:
([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 572:
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 584:
print a[i] b[i] c[i];
}
}</
=={{header|Axe}}==
Line 590:
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 601:
For(I,0,2)
Disp {L₁+I}►Char,{L₂+I}►Char,{L₃+I}►Dec,i
End</
=={{header|Babel}}==
Line 607:
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 624:
each list using a user-defined cdrall operator:
<
simul_array }
Line 642:
{ zap 0 last }
{ nil }
if} each }</
This solution is formally identical to the first and will handle lists
Line 652:
=={{header|BaCon}}==
<
DECLARE a1$[] = {"a", "b", "c"} TYPE STRING
DECLARE a2$[] = {"A", "B", "C"} TYPE STRING
Line 662:
INCR i
WEND
</
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
dim arr2$(3) : arr2$ = {"A", "B", "C"}
dim arr3(3) : arr3 = {1, 2, 3}
Line 674:
print arr1$[i]; arr2$[i]; arr3[i]
next i
end</
{{out}}
<pre>
Line 684:
=={{header|BBC BASIC}}==
<
array1$() = "a", "b", "c"
array2$() = "A", "B", "C"
Line 691:
FOR index% = 0 TO 2
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT</
=={{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 703:
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 714:
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 727:
application-specific way.
<
char a1[] = {'a','b','c'};
Line 737:
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 750:
=={{header|C sharp|C#}}==
<
{
static void Main(string[] args)
Line 762:
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 773:
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 792:
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 816:
std::cout << *lIt << *uIt << *nIt << "\n";
}
}</
Using static arrays:
<
int main(int argc, char* argv[])
Line 835:
"\n";
}
}</
===C++11===
With <code>std::vector</code>s:
<
#include <vector>
Line 859:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
Using static arrays:
<
#include <iterator>
Line 882:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
With <code>std::array</code>s:
<
#include <array>
Line 905:
std::cout << *ilow << *iup << *inum << "\n";
}
}</
With <code>std::array</code>s by indexes:
<
#include <array>
#include <algorithm>
Line 930:
std::cout << lowers[i] << uppers[i] << nums[i] << "\n";
}
}</
===C++23===
<
#include <ranges>
#include <format>
Line 947:
std::cout << std::format("{}{}{}\n", x, y, z);
}
}</
=={{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 992:
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 1,019:
((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 1,029:
=={{header|D}}==
<
void main () {
foreach (a, b, c; zip("abc", "ABC", [1, 2, 3]))
writeln(a, b, c);
}</
{{out}}
<pre>aA1
Line 1,042:
On default it stops when the shortest range is exhausted
(same as StoppingPolicy.shortest):
<
void main () {
Line 1,062:
foreach (p; zip(sp.requireSameLength, a1, a2))
writeln(p.tupleof);
}</
{{out}}
<pre>11
Line 1,077:
There is also std.range.lockstep:
<
void main() {
Line 1,091:
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,102:
foreach (i; 0 .. min(s1.length, s2.length, a1.length))
writeln(s1[i], s2[i], a1[i]);
}</
{{out}}
<pre>aA1
Line 1,108:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 1,125:
Readln;
end.</
=={{header|Diego}}==
<
add_mat(myMatrix)_row(a,b,c)_row(A,B,C)_row(1,2,3);
Line 1,139:
me_msg([output]);
reset_namespace[];</
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>.
<
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'
Line 1,153:
me_msg([output]);
reset_ns[];</
{{out}}
<pre>
Line 1,169:
element.
<
const a2 = ['A', 'B', 'C'];
const a3 = [1, 2, 3];
Line 1,175:
var i : Integer;
for i := 0 to 2 do
PrintLn(Format('%s%s%d', [a1[i], a2[i], a3[i]]));</
=={{header|E}}==
Line 1,184:
indexes as keys, so a not entirely awful idiom exists:
<
def a2 := ["A","B","C"]
def a3 := ["1","2","3"]
Line 1,190:
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,197:
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,209:
collections.
<
to run(l1, l2) {
def zipped {
Line 1,236:
zipped
}
}</
(This will stop when the end of the shortest collection is reached.)
=={{header|EchoLisp}}==
<
;; looping over different sequences : infinite stream, string, list and vector
;; loop stops as soon a one sequence ends.
Line 1,256:
1004 "E" 4 s
1005 "F" 5 t
</syntaxhighlight>
=={{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,303:
>>
end
</syntaxhighlight>
{{out}}
aA1
Line 1,323:
=={{header|Ela}}==
<
xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c']
Line 1,334:
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,341:
composition operator:
<
"123"</
=={{header|Elena}}==
ELENA 5.0 :
<
import extensions;
Line 1,361:
console.readChar()
}</
Using zipBy extension:
<
import extensions.
Line 1,379:
console.readChar();
}</
{{out}}
<pre>
Line 1,389:
=={{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,425:
are.
If they are all "strings", it's quite easy:
<syntaxhighlight lang="euphoria">
sequence a, b, c
Line 1,435:
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,449:
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,455:
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,468:
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,477:
=={{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,485:
=={{header|Factor}}==
<
3each</
=={{header|Fantom}}==
This will stop when it reaches the end of the shortest list.
<
class LoopMultiple
{
Line 1,505:
}
}
</syntaxhighlight>
=={{header|Fermat}}==
<
[b] := [('A','B','C')];
[c] := [(1,2,3)];
Line 1,516:
;{instead of a numerical ASCII code, and the}
;{:1 causes the integer to take up exactly one}
;{space, ie. no leading or trailing spaces.}</
{{out}}</pre>aA1
bB2
Line 1,522:
=={{header|Forth}}==
<
create b char A , char B , char C ,
create c char 1 , char 2 , char 3 ,
Line 1,540:
loop
drop drop drop
;</
=={{header|Fortran}}==
<
implicit none
Line 1,559:
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.
Line 1,566:
=={{header|FreeBASIC}}==
<
Function min(x As Integer, y As Integer) As Integer
Line 1,594:
Print
Sleep</
{{out}}
Line 1,607:
=={{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,630:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=3a69e733694aeab3b72c6a5c0316535b Click this link to run this code]'''
<
Dim a1 As String[] = ["a", "b", "c"]
Dim a2 As String[] = ["A", "B", "C"]
Line 1,640:
Next
End</
Output:
Line 1,650:
=={{header|GAP}}==
<
# The Loop function will apply some function to every tuple built by
taking
Line 1,685:
aC3
bD1
aE2</
=={{header|Go}}==
Line 1,700:
conditions are meaningful in your application and explicitly handle
whatever errors are plausible.
<
import "fmt"
Line 1,712:
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,725:
=={{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,746:
=={{header|Harbour}}==
'''Using FOR EACH ... NEXT statement'''
<
PROCEDURE Main()
LOCAL a1 := { "a", "b", "c" }, ;
Line 1,757:
NEXT
RETURN
</syntaxhighlight>
Output:
aA1
Line 1,768:
'''Using list comprehension'''
<
main = sequence [ putStrLn [x, y, z] | x <- "abd" | y <- "ABC" | z <- "123"]</
'''Using Transpose'''
Line 1,775:
In this special case of transposing strings.
<
main = mapM putStrLn $ transpose ["abd", "ABC", "123"]</
'''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 [()]
Line 1,795:
<$> ZipList "abd"
<*> ZipList "ABC"
<*> ZipList "123"</
=={{header|Haxe}}==
<
using Std;
Line 1,819:
Sys.println(a[i] + b[i] + c[i].string());
}
}</
=={{header|HicEst}}==
<
REAL :: C(3)
Line 1,829:
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,853:
every i := 1 to max(*a,*b,*c) do
write(a[i]|"","\t",b[i]|"","\t",c[i]|"")
end</
{{libheader|Icon Programming Library}}
Line 1,861:
=={{header|J}}==
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,877:
Other options include:
<
aA1
bB2
cC3</
<
aA1
bB2
cC3</
These implementations pad short arrays with spaces.
Or:
<
┌─┬─┬─┐
│a│A│1│
Line 1,896:
├─┼─┼─┤
│c│C│3│
└─┴─┴─┘</
This implementation puts each item from each of the original lists
Line 1,910:
=={{header|Java}}==
<
for (int i = 0; i < list1.length; i++) {
for (String[] lista : list1) {
Line 1,916:
}
System.out.println();
}</
=={{header|JavaScript}}==
Line 1,923:
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,930:
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,936:
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,949:
);
// lstOut --> ["aA1", "bB2", "cC3"]</
===Functional composition===
Line 1,961:
Reduce / fold:
<
return lstArrays.reduce(
Line 1,977:
["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,996:
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 2,024:
)
.join('\n');
})();</
{{Out}}
<syntaxhighlight lang="javascript">aA1
bB2
cC3</
====ES6====
By transposition:
<
'use strict';
Line 2,065:
map(concat, transpose(xs))
);
})();</
{{Out}}
<pre>aA1
Line 2,079:
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,120:
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,129:
([]; . + [ [ $row[$i] ] + $t[$i] ])
end;
</syntaxhighlight>
=={{header|Jsish}}==
<
var a1 = ['a', 'b', 'c'];
var a2 = ['A', 'B', 'C'];
Line 2,168:
undefinedundefinedundefinedundefined7
=!EXPECTEND!=
*/</
{{out}}
Line 2,176:
=={{header|Julia}}==
'''With a higher order function''':
<
'''With a loop''':
<
println(i, j, k)
end</
{{out}}
Line 2,189:
=={{header|K}}==
<
{{out}}
Line 2,202:
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,223:
then the arrays must be converted to strings.
<syntaxhighlight lang="k">
{a:,/'($:'x);+a[;!(&/#:'a)]}("abc";"ABC";1 2 3 4)
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 2,242:
val minSize = Math.min(a2.size, Math.min(a4.size, a5.size)) // minimum size of a2, a4 and a5
for(i in 0 until minSize) println("${a2[i]}${a4[i]}${a5[i]}")
}</
{{out}}
Line 2,255:
=={{header|Lambdatalk}}==
<
1) loop over 3 sentences of equal length and returning 3 sentences
Line 2,308:
e d
s
</syntaxhighlight>
=={{header|LFE}}==
<
(lists:zipwith3
(lambda (i j k)
Line 2,318:
'(A B C)
'(1 2 3))
</syntaxhighlight>
If any of the data lists differ in size from the other,
Line 2,332:
=={{header|Liberty BASIC}}==
<
b$(1)="A" : b$(2)="B" : b$(3)="C"
c(1)=1 : c(2)=2 : c(3)=3
Line 2,339:
for i = 1 to 3
print a$(i);b$(i);c(i)
next</
=={{header|Lisaac}}==
<
+ name := ARRAY_LOOP_TEST;
Line 2,368:
'\n'.print;
};
);</
=={{header|LiveCode}}==
Arrays
<
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,387:
put z
end loopArrays</
"list" processing
<
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,401:
put z
end loopDelimitedList</
Output - both behave similarly for this exercise.
<pre>aA1
Line 2,418:
{{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,442:
for u, v, w in iter(a1, a2, a3) do print(u..v..w) end
</syntaxhighlight>
=={{header|Maple}}==
<
L := [["a", "b", "c"],["A", "B", "C"], ["1", "2", "3"]];
M := Array(1..3, 1..3, L);
Line 2,459:
end proc:
multi_loop(M);</
{{out}}
<pre>
Line 2,469:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This can be done with a built-in function:
<
All arguments must be lists of the same length.
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module multi_array_loop.
:- interface.
Line 2,493:
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,499:
=={{header|Modula-3}}==
<
IMPORT IO, Fmt;
Line 2,515:
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,529:
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,542:
Local arrays version
<syntaxhighlight lang="mumps">
LOOPMULU
N A,B,C,D,%
Line 2,552:
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,578:
=={{header|Nanoquery}}==
{{trans|Java}}
<
for i in range(0, len(list1) - 1)
for lista in list1
Line 2,584:
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,613:
WriteLine($"$x$y$z");
}
}</
Alternately: {{trans|C#}}
<
module LoopMult
Line 2,631:
WriteLine("{0}{1}{2}", first[i], second[i], third[i]);
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 2,679:
return smp
</syntaxhighlight>
{{out}}
<pre style="overflow:scroll">
Line 2,695:
=={{header|NewLISP}}==
<
3))</
=={{header|Nim}}==
<
a = @['a','b','c']
b = @["A","B","C"]
Line 2,705:
for i in 0..2:
echo a[i], b[i], c[i]</
=={{header|NS-HUBASIC}}==
<
20 DIM B$(3)
30 DIM C$(3)
Line 2,722:
130 FOR I=1 TO 3
140 PRINT A$(I)B$(I)C$(I)
150 NEXT</
=={{header|Oberon-2}}==
Works with oo2c version 2
<
MODULE LoopMArrays;
IMPORT
Line 2,751:
DoLoop
END LoopMArrays.
</syntaxhighlight>
Output:<br/>
<pre>
Line 2,760:
=={{header|Objeck}}==
<
class MultipleArrayAccess {
function : Main(args : String[]) ~ Nil {
Line 2,774:
}
}
</syntaxhighlight>
If the arrays are different lengths,
Line 2,781:
=={{header|OCaml}}==
an immediate solution:
<
and a2 = [| 'A'; 'B'; 'C' |]
and a3 = [| '1'; '2'; '3' |] ;;
Line 2,790:
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,805:
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,811:
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,826:
If arrays don't have the same size, zipAll reduces to the minimum size
<
zipAll(3) apply(#[ apply(#print) printcr ])</
{{out}}
Line 2,837:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
x = .array~of("a", "b", "c")
y = .array~of("A", "B", "C")
Line 2,845:
say x[i]y[i]z[i]
end
</syntaxhighlight>
=={{header|Oz}}==
<
I in [a b c]
J in ['A' 'B' 'C']
Line 2,854:
do
{System.showInfo I#J#K}
end</
The loop will stop when the shortest list is exhausted.
Line 2,860:
=={{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,869:
print()
)
};</
This version prints blanks when a vector is exhausted.
<
my(l=0);
for(i=1,#V,l=max(l,#V[i]));
Line 2,885:
print()
)
};</
=={{header|Pascal}}==
Line 2,891:
=={{header|Perl}}==
<
{
my $code = shift;
Line 2,903:
my @a3 = qw( 1 2 3 );
zip { print @_,"\n" }\(@a1, @a2, @a3);</
This implementation will stop producing items when the shortest array
Line 2,913:
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,922:
<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,933:
=={{header|Phixmonti}}==
<
( "abc" "ABC" "123" )
Line 2,948:
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,961:
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
Line 2,973:
If the lists/arrays are of uneven lengths, then the elements in the longer arrays are skipped.
<
go =>
Line 2,997:
println([A,B,C,D].join(''))
end,
nl.</
{{out}}
Line 3,016:
=={{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 3,028:
avoids the usual off-by-one errors
<syntaxhighlight lang="pike">
array a1 = ({ "a", "b", "c" });
array a2 = ({ "A", "B", "C" });
Line 3,035:
foreach(a1; int index; string char_dummy)
write("%s%s%s\n", a1[index], a2[index], a3[index]);
</syntaxhighlight>
{{Out}}
<pre>
Line 3,044:
=={{header|PL/I}}==
<
declare P(3) character (1) initial ('a', 'b', 'c'),
Q(3) character (1) initial ('A', 'B', 'C'),
Line 3,052:
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 3,068:
% using it.
[[/a /b /c] [/A /B /C] [1 2 3]] transpose
</syntaxhighlight>
=={{header|PowerBASIC}}==
<
DIM x(2), y(2) AS STRING * 1
DIM z(2) AS LONG
Line 3,093:
NEXT
CLOSE
END FUNCTION</
=={{header|PowerShell}}==
A cheap and chEasy 'zip' function:
<syntaxhighlight lang="powershell">
function zip3 ($a1, $a2, $a3)
{
Line 3,108:
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
zip3 @('a','b','c') @('A','B','C') @(1,2,3)
</syntaxhighlight>
{{Out}}
<pre>
Line 3,120:
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 3,132:
=={{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,152:
=={{header|PureBasic}}==
<
; Fill arrays
Dim a.s(2)
Line 3,166:
PrintN(a(Arrayposition) + b(Arrayposition) + Str(c(Arrayposition)))
Next
Input() ;wait for Enter before ending</
If they have different lengths there are two cases:<br>
Line 3,182:
=={{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,213:
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,221:
#D4
##5
>>></
(The Python 2.X equivalent is itertools.izip_longest)
Line 3,228:
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,235:
2drop ] is task ( $ $ $ --> )
$ "abc" $ "ABC" $ "123" task</
{{out}}
Line 3,245:
=={{header|R}}==
<
{
# Retrieve inputs and convert to a list of character strings
Line 3,265:
}
}
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,280:
of sequences of any kind at once:
<
#lang racket
Line 3,288:
[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,302:
=== 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,314:
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,330:
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,340:
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,355:
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,361:
a A 1
b B 2
c C 3</
=={{header|REXX}}==
Line 3,369:
<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,377:
output = x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,388:
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,396:
output=x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</
'''output'''
<pre>
Line 3,407:
===dissimilar sized lists===
<
x = 'a b c d'
y = 'A B C'
Line 3,414:
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,424:
===idiomatic method for lists===
<
x = 'a b c d'
y = 'A B C'
Line 3,430:
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,441:
=={{header|Ring}}==
<
array1 = ["a", "b", "c"]
array2 = ["A", "B", "C"]
Line 3,449:
see array1[n] + array2[n] + array3[n] + nl
next
</syntaxhighlight>
=={{header|Ruby}}==
<
or
<
Both of these loops print <code>aA1</code>, <code>bB2</code>, <code>cC3</code>.
Line 3,461:
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,467:
=> 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|Run BASIC}}==
<
a$(i) = chr$(i+96)
b$(i) = chr$(i+64)
Line 3,478:
for i = 1 to 3
print a$(i);b$(i);c(i)
next</
=={{header|Rust}}==
<
let a1 = ["a", "b", "c"];
let a2 = ["A", "B", "C"];
Line 3,490:
println!("{}{}{}", x, y, z);
}
}</
{{out}}
<pre>aA1
Line 3,497:
=={{header|Salmon}}==
<
any
// number of lists together.
Line 3,521:
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,529:
some lists are shorter than the longest:
<
any
// number of lists together.
Line 3,555:
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"|;
Line 3,568:
end;
end;
</syntaxhighlight>
=={{header|Scala}}==
<
("abc", "ABC", "123").zipped foreach { (x, y, z) =>
println(x.toString + y + z)
}
</syntaxhighlight>
=={{header|Scheme}}==
Line 3,585:
into a new list.
<
(let ((a '("a" "b" "c"))
(b '("A" "B" "C"))
Line 3,596:
(newline))
a b c))
</syntaxhighlight>
Scheme has a <code>vector</code> datatype with constant-time
Line 3,603:
and <code>vector-map</code>:
<
(let ((a (vector "a" "b" "c"))
(b (vector "A" "B" "C"))
Line 3,614:
(newline))
a b c))
</syntaxhighlight>
Note, the lists or vectors must all be of the same length.
Line 3,620:
=={{header|Sidef}}==
The simplest way is by using the Array.zip{} method:
<
say (i, j, k)
}</
{{out}}
<pre>
Line 3,633:
{{works with|GNU Smalltalk}}
<
a := OrderedCollection new addAll: #('a' 'b' 'c').
b := OrderedCollection new addAll: #('A' 'B' 'C').
Line 3,642:
(b at: i) display.
(c at: i) displayNl.
].</
If index ''i'' is out of bound, a runtime error is raised.
Line 3,649:
<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,656:
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,667:
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.
Line 3,674:
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,684:
(* ["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,706:
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,744:
for i in 0 ..< a1.count {
println("\(a1[i])\(a2[i])\(a3[i])")
}</
{{out}}
<pre>aA1
Line 3,752:
=={{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,759:
1..$x::length -> '$x($);$y($);$z($);
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,767:
</pre>
A simple transpose method that gives the same output and also errors on uneven sizes
<
templates transpose
def a: $;
Line 3,776:
[$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,799:
[$u,$v,$w] -> transpose2... -> '$...;
' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,812:
=={{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,828:
=={{header|TorqueScript}}==
<syntaxhighlight lang="torquescript">
$var[0] = "a b c"
$var[1] = "A B C";
Line 3,835:
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,846:
PRINT a,b,c
ENDLOOP
</syntaxhighlight>
{{out}}
<pre>
Line 3,858:
===Pattern language===
<
@(bind b ("A" "B" "C"))
@(bind c ("1" "2" "3"))
Line 3,868:
aA1
bB2
cC3</
===TXR Lisp, using <code>mapcar</code>===
Line 3,876:
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,894:
{{trans|Scheme}}
<
;; that happily works over strings and lists.
;; We don't need "srfi-43".
Line 3,915:
(display i3)
(newline))
a b c))</
===Translation of Logo===
Line 3,921:
{{trans|Logo}}
<
(defun question-var-to-meta-num (var)
^(sys:var ,(int-str (cdr (symbol-name var))))))
Line 3,936:
(defun show (x) (pprinl x))
(show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]))</
{{out}}
Line 3,942:
== {{header|TypeScript}} ==
<
var arr1: string[] = ['a', 'b', 'c'];
var arr2: string[] = ['A', 'B', 'C'];
Line 3,948:
for (var i = 0; i <= 2; i++)
console.log(`${arr1[i]}${arr2[i]}${arr3[i]}`);
</syntaxhighlight>
{{out}}
<pre>
Line 3,966:
{{works with|Bourne Shell}}
<
b=A:B:C
c=1:2:3
Line 3,981:
i=`expr $i + 1`
done
IFS=$oldifs</
{{out}}
Line 4,003:
{{works with|Bourne Shell}}
<
B='b1 b2 b3'
Line 4,011:
printf "$a $1\n"
shift
done</
{{out}}
Line 4,027:
{{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 4,044:
{{works with|pdksh}}
<
set -A b A B C
set -A c 1 2 3
Line 4,051:
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 4,067:
shell to exit with an error like ''b: Subscript out of range.''
<
set b=(A B C)
set c=(1 2 3)
Line 4,074:
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 4,088:
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 4,094:
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 4,105:
=={{header|Vala}}==
<
const char a2[] = {'A','B','C'};
const int a3[] = {1, 2, 3};
Line 4,112:
for (int i = 0; i < 3; i++)
stdout.printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}</
=={{header|VBA}}==
{{works with|VBA|VBA Excel 2013}}
<
Sub Main()
Line 4,126:
Next
Debug.Print Mid(buf,3)
End Sub </
{{out}}
<pre>
Line 4,135:
=={{header|VBScript}}==
<
a = Array("a","b","c")
Line 4,143:
buf = buf & vbCrLf & a(i) & b(i) & c(i)
Next
WScript.Echo Mid(buf,3) </
{{out}}
<pre>
Line 4,154:
=={{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.
<
Module Program
Sub Main()
Line 4,172:
Next
End Sub
End Module</
{{out}}
Line 4,184:
=={{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,221:
? "Solution using a cursor"
LIST OFF FIELDS c4
</syntaxhighlight>
{{out}}
<pre>
Line 4,239:
=={{header|Vlang}}==
<
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]}')
}
}</
=={{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,267:
{{works with|nasm}}
{{works with|windows}}
<
extern _printf
Line 4,319:
xor eax, eax
ret
</syntaxhighlight>
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<
PROGRAM "loopoverarrays"
Line 4,338:
END FUNCTION
END PROGRAM
</syntaxhighlight>
=={{header|XPL0}}==
<
include c:\cxpl\codes; \intrinsic 'code' declarations
char A1, A2;
Line 4,354:
CrLf(0);
];
]</
{{out}}
Line 4,364:
=={{header|Z80 Assembly}}==
<
Line 4,391:
db "ABC"
array3:
db "123"</
{{out}}
Line 4,406:
=={{header|zkl}}==
<
or
<
["a".."c"],T("A","B","C"),[1..])</
{{out}}
<pre>
Line 4,420:
=={{header|Zig}}==
<
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
Line 4,429:
for (a1) |_, i|
try std.io.getStdOut().writer().print("{c} {c} {d}\n", .{ a1[i], a2[i], a3[i] });
}</
=={{header|ZX Spectrum Basic}}==
<
20 LET szb = 3: REM size of b
30 LET szc = 3: REM size of c
Line 4,453:
170 PRINT "and C$ runs down the right."
180 STOP
200 DATA "a","b","c","A","B","C","1","2","3"</
Simplification
<
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"</
|