Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
note: Iteration

View file

@ -0,0 +1,39 @@
;Task:
Loop over multiple arrays   (or lists or tuples or whatever they're called in
your language) &nbsp; and display the &nbsp; <big><big> ''i'' <sup>th</sup> </big></big> &nbsp; element of each.
Use your language's &nbsp; "for each" &nbsp; loop if it has one, otherwise iterate
through the collection in order with some other loop.
For this example, loop over the arrays:
(a,b,c)
(A,B,C)
(1,2,3)
to produce the output:
aA1
bB2
cC3
<br>
If possible, also describe what happens when the arrays are of different lengths.
;Related tasks:
* &nbsp; [[Loop over multiple arrays simultaneously]]
* &nbsp; [[Loops/Break]]
* &nbsp; [[Loops/Continue]]
* &nbsp; [[Loops/Do-while]]
* &nbsp; [[Loops/Downward for]]
* &nbsp; [[Loops/For]]
* &nbsp; [[Loops/For with a specified step]]
* &nbsp; [[Loops/Foreach]]
* &nbsp; [[Loops/Increment loop index within loop body]]
* &nbsp; [[Loops/Infinite]]
* &nbsp; [[Loops/N plus one half]]
* &nbsp; [[Loops/Nested]]
* &nbsp; [[Loops/While]]
* &nbsp; [[Loops/with multiple ranges]]
* &nbsp; [[Loops/Wrong ranges]]
<br><br>

View file

@ -0,0 +1,2 @@
L(x, y, z) zip(abc, ABC, 123)
print(xyz)

View file

@ -0,0 +1,24 @@
* Loop over multiple arrays simultaneously 09/03/2017
LOOPSIM CSECT
USING LOOPSIM,R12 base register
LR R12,R15
LA R6,1 i=1
LA R7,3 counter=3
LOOP LR R1,R6 i
SLA R1,1 *2
LH R2,R-2(R1) r(i)
XDECO R2,PG edit r(i)
LA R1,S-1(R6) @s(i)
MVC PG+3(1),0(R1) output s(i)
LA R1,Q-1(R6) @q(i)
MVC PG+7(1),0(R1) output q(i)
XPRNT PG,80 print s(i),q(i),r(i)
LA R6,1(R6) i++
BCT R7,LOOP decrement and loop
BR R14 exit
S DC C'a',C'b',C'c'
Q DC C'A',C'B',C'C'
R DC H'1',H'2',H'3'
PG DC CL80' ' buffer
YREGS
END LOOPSIM

View file

@ -0,0 +1,46 @@
org 100h
lxi b,0 ; Let (B)C be the array index
outer: lxi d,As ; Use DE to walk the array-of-arrays
inner: xchg ; Swap DE and HL (array-of-array pointer into HL)
mov e,m ; Load low byte of array pointer into E
inx h
mov d,m ; Load high byte of array pointer into D
inx h
xchg ; Array base in HL, array-of-array pointer in DE
mov a,h ; Is HL 0?
ora l
jz azero ; If so, we are done.
dad b ; Otherwise, add index to array base
mov a,m ; Get current item (BC'th item of HL)
call chout ; Output
jmp inner ; Next array
azero: mvi a,13 ; Print newline
call chout
mvi a,10
call chout
inr c ; Increment index (we're only using the low byte)
mvi a,Alen ; Is it equal to the length?
cmp c
jnz outer ; If not, get next item from all the arrays.
ret
;;; Print character in A, saving all registers.
;;; This code uses CP/M to do it.
chout: push psw ; CP/M destroys all registers
push b ; Push them all to the stack
push d
push h
mvi c,2 ; 2 = print character syscall
mov e,a
call 5
pop h ; Restore registers
pop d
pop b
pop psw
ret
;;; Arrays
A1: db 'a','b','c'
A2: db 'A','B','C'
A3: db '1','2','3'
Alen: equ $-A3
;;; Zero-terminated array-of-arrays
As: dw A1,A2,A3,0

View file

@ -0,0 +1,31 @@
cpu 8086
bits 16
org 100h
section .text
mov ah,2 ; Tell MS-DOS to print characters
xor si,si ; Clear first index register (holds _i_)
outer: mov di,As ; Put array-of-arrays in second index register
mov cx,Aslen ; Put length in counter register
inner: mov bx,[di] ; Load array pointer into BX (address) register
mov dl,[bx+si] ; Get SI'th element from array
int 21h ; Print character
inc di ; Go to next array (pointers are 2 bytes wide)
inc di
loop inner ; For each array
mov dl,13 ; Print newline
int 21h
mov dl,10
int 21h
inc si ; Increment index register
cmp si,Alen ; If it is still lower than the array length
jb outer ; Print the next items
ret
section .data
;;; Arrays
A1: db 'a','b','c'
A2: db 'A','B','C'
A3: db '1','2','3'
Alen: equ $-A3 ; Length of arrays (elements are bytes)
;;; Array of arrays
As: dw A1,A2,A3
Aslen: equ ($-As)/2 ; Length of array of arrays (in words)

View file

@ -0,0 +1,12 @@
(defun print-lists (xs ys zs)
(if (or (endp xs) (endp ys) (endp zs))
nil
(progn$ (cw (first xs))
(cw "~x0~x1~%"
(first ys)
(first zs))
(print-lists (rest xs)
(rest ys)
(rest zs)))))
(print-lists '("a" "b" "c") '(A B C) '(1 2 3))

View file

@ -0,0 +1,5 @@
[]UNION(CHAR,INT) x=("a","b","c"), y=("A","B","C"),
z=(1,2,3);
FOR i TO UPB x DO
printf(($ggd$, x[i], y[i], z[i], $l$))
OD

View file

@ -0,0 +1,11 @@
begin
% declare the three arrays %
string(1) array a, b ( 1 :: 3 );
integer array c ( 1 :: 3 );
% initialise the arrays - have to do this element by element in Algol W %
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;
% loop over the arrays %
for i := 1 until 3 do write( i_w := 1, s_w := 0, a(i), b(i), c(i) );
end.

View file

@ -0,0 +1,9 @@
BEGIN {
split("a,b,c", a, ",");
split("A,B,C", b, ",");
split("1,2,3", c, ",");
for(i = 1; i <= length(a); i++) {
print a[i] b[i] c[i];
}
}

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,13 @@
with Ada.Text_IO; use Ada.Text_IO;
procedure Array_Loop_Test is
type Array_Index is range 1..3;
A1 : array (Array_Index) of Character := "abc";
A2 : array (Array_Index) of Character := "ABC";
A3 : array (Array_Index) of Integer := (1, 2, 3);
begin
for Index in Array_Index'Range loop
Put_Line (A1 (Index) & A2 (Index) & Integer'Image (A3
(Index))(2));
end loop;
end Array_Loop_Test;

View file

@ -0,0 +1,12 @@
#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

View file

@ -0,0 +1,16 @@
#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

View file

@ -0,0 +1,91 @@
-- ZIP LISTS WITH FUNCTION ---------------------------------------------------
-- zipListsWith :: ([a] -> b) -> [[a]] -> [[b]]
on zipListsWith(f, xss)
set n to length of xss
script
on |λ|(_, i)
script
on |λ|(xs)
item i of xs
end |λ|
end script
if i n then
apply(f, (map(result, xss)))
else
{}
end if
end |λ|
end script
if n > 0 then
map(result, item 1 of xss)
else
[]
end if
end zipListsWith
-- TEST ( zip lists with concat ) -------------------------------------------
on run
intercalate(linefeed, ¬
zipListsWith(concat, ¬
[["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]]))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- apply (a -> b) -> a -> b
on apply(f, a)
mReturn(f)'s |λ|(a)
end apply
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

View file

@ -0,0 +1,75 @@
-- CONCAT MAPPED OVER A TRANSPOSITION ----------------------------------------
on run
unlines(map(concat, transpose([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- intercalate :: String -> [String] -> String
on intercalate(s, xs)
set {dlm, my text item delimiters} to {my text item delimiters, s}
set str to xs as text
set my text item delimiters to dlm
return str
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- transpose :: [[a]] -> [[a]]
on transpose(xss)
script column
on |λ|(_, iCol)
script row
on |λ|(xs)
item iCol of xs
end |λ|
end script
map(row, xss)
end |λ|
end script
map(column, item 1 of xss)
end transpose
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines

View file

@ -0,0 +1,4 @@
parts: ["abc" "ABC" [1 2 3]]
loop 0..2 'x ->
print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|"

View file

@ -0,0 +1,26 @@
List1 = a,b,c
List2 = A,B,C
List3 = 1,2,3
MsgBox, % LoopMultiArrays()
List1 = a,b,c,d,e
List2 = A,B,C,D
List3 = 1,2,3
MsgBox, % LoopMultiArrays()
;---------------------------------------------------------------------------
LoopMultiArrays()
{ ; print the ith element of each
;---------------------------------------------------------------------------
local Result
StringSplit, List1_, List1, `,
StringSplit, List2_, List2, `,
StringSplit, List3_, List3, `,
Loop, % List1_0
Result .= List1_%A_Index% List2_%A_Index% List3_%A_Index% "`n"
Return, Result
}

View file

@ -0,0 +1,17 @@
List1 := ["a", "b", "c"]
List2 := ["A", "B", "C"]
List3 := [ 1 , 2 , 3 ]
MsgBox, % LoopMultiArrays()
List1 := ["a", "b", "c", "d", "e"]
List2 := ["A", "B", "C", "D"]
List3 := [1,2,3]
MsgBox, % LoopMultiArrays()
LoopMultiArrays() {
local Result
For key, value in List1
Result .= value . List2[key] . List3[key] "`n"
Return, Result
}

View file

@ -0,0 +1,12 @@
'a'→{L₁}
'b'→{L₁+1}
'c'→{L₁+2}
'A'→{L₂}
'B'→{L₂+1}
'C'→{L₂+2}
1→{L₃}
2→{L₃+1}
3→{L₃+2}
For(I,0,2)
Disp {L₁+I}►Char,{L₂+I}►Char,{L₃+I}►Dec,i
End

View file

@ -0,0 +1,26 @@
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 = 1 to 3
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

View file

@ -0,0 +1,8 @@
DIM array1$(2), array2$(2), array3%(2)
array1$() = "a", "b", "c"
array2$() = "A", "B", "C"
array3%() = 1, 2, 3
FOR index% = 0 TO 2
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT

View file

@ -0,0 +1,9 @@
DECLARE a1$[] = {"a", "b", "c"} TYPE STRING
DECLARE a2$[] = {"A", "B", "C"} TYPE STRING
DECLARE a3[] = {1, 2, 3} TYPE int
WHILE (a3[i] <= 3)
PRINT a1$[i], a2$[i], a3[i]
INCR i
WEND

View file

@ -0,0 +1,6 @@
main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3'))
simul_array }
simul_array!:
{ trans
{ { << } each "\n" << } each }

View file

@ -0,0 +1,19 @@
main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3'))
simul_array }
simul_array!:
{{ dup
{ car << } each
cdrall }
{ allnil? not }
while }
cdrall!: { { { cdr } each -1 take } nest }
-- only returns true if all elements of a list are nil
allnil?!:
{ 1 <->
{ car nil?
{ zap 0 last }
{ nil }
if} each }

View file

@ -0,0 +1,9 @@
beads 1 program 'Loop over multiple arrays simultaneously'
calc main_init
const
x = ['a', 'b', 'c']
y = ['A', 'B', 'C']
z = [1, 2, 3]
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:' ')

View file

@ -0,0 +1,5 @@
0 >:2g,:3g,:4gv
@_^#`2:+1,+55,<
abc
ABC
123

View file

@ -0,0 +1,19 @@
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<char> ls(3); ls[0] = 'a'; ls[1] = 'b'; ls[2] = 'c';
std::vector<char> us(3); us[0] = 'A'; us[1] = 'B'; us[2] = 'C';
std::vector<int> ns(3); ns[0] = 1; ns[1] = 2; ns[2] = 3;
std::vector<char>::const_iterator lIt = ls.begin();
std::vector<char>::const_iterator uIt = us.begin();
std::vector<int>::const_iterator nIt = ns.begin();
for(; lIt != ls.end() && uIt != us.end() && nIt !=
ns.end();
++lIt, ++uIt, ++nIt)
{
std::cout << *lIt << *uIt << *nIt << "\n";
}
}

View file

@ -0,0 +1,17 @@
#include <iostream>
int main(int argc, char* argv[])
{
char ls[] = {'a', 'b', 'c'};
char us[] = {'A', 'B', 'C'};
int ns[] = {1, 2, 3};
for(size_t li = 0, ui = 0, ni = 0;
li < sizeof(ls) && ui < sizeof(us) && ni
< sizeof(ns) / sizeof(int);
++li, ++ui, ++ni)
{
std::cout << ls[li] << us[ui] << ns[ni] <<
"\n";
}
}

View file

@ -0,0 +1,21 @@
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
auto lowers = std::vector<char>({'a', 'b', 'c'});
auto uppers = std::vector<char>({'A', 'B', 'C'});
auto nums = std::vector<int>({1, 2, 3});
auto ilow = lowers.cbegin();
auto iup = uppers.cbegin();
auto inum = nums.cbegin();
for(; ilow != lowers.end()
and iup != uppers.end()
and inum != nums.end()
; ++ilow, ++iup, ++inum)
{
std::cout << *ilow << *iup << *inum << "\n";
}
}

View file

@ -0,0 +1,21 @@
#include <iostream>
#include <iterator>
int main(int argc, char* argv[])
{
char lowers[] = {'a', 'b', 'c'};
char uppers[] = {'A', 'B', 'C'};
int nums[] = {1, 2, 3};
auto ilow = std::begin(lowers);
auto iup = std::begin(uppers);
auto inum = std::begin(nums);
for(; ilow != std::end(lowers)
and iup != std::end(uppers)
and inum != std::end(nums)
; ++ilow, ++iup, ++inum )
{
std::cout << *ilow << *iup << *inum << "\n";
}
}

View file

@ -0,0 +1,21 @@
#include <iostream>
#include <array>
int main(int argc, char* argv[])
{
auto lowers = std::array<char, 3>({'a', 'b', 'c'});
auto uppers = std::array<char, 3>({'A', 'B', 'C'});
auto nums = std::array<int, 3>({1, 2, 3});
auto ilow = lowers.cbegin();
auto iup = uppers.cbegin();
auto inum = nums.cbegin();
for(; ilow != lowers.end()
and iup != uppers.end()
and inum != nums.end()
; ++ilow, ++iup, ++inum )
{
std::cout << *ilow << *iup << *inum << "\n";
}
}

View file

@ -0,0 +1,23 @@
#include <iostream>
#include <array>
#include <algorithm>
int main(int argc, char* argv[])
{
auto lowers = std::array<char, 3>({'a', 'b', 'c'});
auto uppers = std::array<char, 3>({'A', 'B', 'C'});
auto nums = std::array<int, 3>({1, 2, 3});
auto const minsize = std::min(
lowers.size(),
std::min(
uppers.size(),
nums.size()
)
);
for(size_t i = 0; i < minsize; ++i)
{
std::cout << lowers[i] << uppers[i] << nums[i] << "\n";
}
}

View file

@ -0,0 +1,15 @@
#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);
}
}

View file

@ -0,0 +1,8 @@
set a=(a b c)
set b=(A B C)
set c=(1 2 3)
@ i = 1
while ( $i <= $#a )
echo "$a[$i]$b[$i]$c[$i]"
@ i += 1
end

View file

@ -0,0 +1,13 @@
class Program
{
static void Main(string[] args)
{
char[] a = { 'a', 'b', 'c' };
char[] b = { 'A', 'B', 'C' };
int[] c = { 1, 2, 3 };
int min = Math.Min(a.Length, b.Length);
min = Math.Min(min, c.Length);
for (int i = 0; i < min; i++)
Console.WriteLine("{0}{1}{2}", a[i], b[i], c[i]);
}
}

View file

@ -0,0 +1,4 @@
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
Console.WriteLine(numbers.Zip(words, (first, second) => first + " " +
second));

View file

@ -0,0 +1,2 @@
Console.WriteLine((new[] { 1, 2, 3, 4 }).Zip(new[] { "a", "b", "c" },
(f, s) => f + " " + s));

View file

@ -0,0 +1,6 @@
public static void Multiloop(char[] A, char[] B, int[] C)
{
var max = Math.Max(Math.Max(A.Length, B.Length), C.Length);
for (int i = 0; i < max; i++)
Console.WriteLine($"{(i < A.Length ? A[i] : ' ')}, {(i < B.Length ? B[i] : ' ')}, {(i < C.Length ? C[i] : ' ')}");
}

View file

@ -0,0 +1 @@
Multiloop(new char[] { 'a', 'b', 'c', 'd' }, new char[] { 'A', 'B', 'C' }, new int[] { 1, 2, 3, 4, 5 });

View file

@ -0,0 +1,11 @@
#include <stdio.h>
char a1[] = {'a','b','c'};
char a2[] = {'A','B','C'};
int a3[] = {1,2,3};
int main(void) {
for (int i = 0; i < 3; i++) {
printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}
}

View file

@ -0,0 +1,23 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. Loop-Over-Multiple-Tables.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A VALUE "abc".
03 A-Vals PIC X OCCURS 3 TIMES.
01 B VALUE "ABC".
03 B-Vals PIC X OCCURS 3 TIMES.
01 C VALUE "123".
03 C-Vals PIC 9 OCCURS 3 TIMES.
01 I PIC 9.
PROCEDURE DIVISION.
PERFORM VARYING I FROM 1 BY 1 UNTIL 3 < I
DISPLAY A-Vals (I) B-Vals (I) C-Vals (I)
END-PERFORM
GOBACK
.

View file

@ -0,0 +1,6 @@
var a1 = [ "a", "b", "c" ];
var a2 = [ "A", "B", "C" ];
var a3 = [ 1, 2, 3 ];
for (x,y,z) in zip(a1, a2, a3) do
writeln(x,y,z);

View file

@ -0,0 +1,2 @@
(doseq [s (map #(str %1 %2 %3) "abc" "ABC" "123")]
(println s))

View file

@ -0,0 +1,2 @@
(apply map str ["abc" "ABC" "123"])
("aA1" "bB2" "cC3")

View file

@ -0,0 +1,5 @@
(mapc (lambda (&rest args)
(format t "~{~A~}~%" args))
'(|a| |b| |c|)
'(a b c)
'(1 2 3))

View file

@ -0,0 +1,4 @@
(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))

View file

@ -0,0 +1,5 @@
(do ((x '("a" "b" "c") (rest x)) ;
(y '("A" "B" "C" "D") (rest y)) ;
(z '(1 2 3 4 6) (rest z))) ; Initialize lists and set to rest on every loop
((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

View file

@ -0,0 +1,6 @@
import std.stdio, std.range;
void main () {
foreach (a, b, c; zip("abc", "ABC", [1, 2, 3]))
writeln(a, b, c);
}

View file

@ -0,0 +1,21 @@
import std.stdio, std.range;
void main () {
auto a1 = [1, 2];
auto a2 = [1, 2, 3];
alias StoppingPolicy sp;
// Stops when the shortest range is exhausted
foreach (p; zip(sp.shortest, a1, a2))
writeln(p.tupleof);
writeln();
// Stops when the longest range is exhausted
foreach (p; zip(sp.longest, a1, a2))
writeln(p.tupleof);
writeln();
// Requires that all ranges are equal
foreach (p; zip(sp.requireSameLength, a1, a2))
writeln(p.tupleof);
}

View file

@ -0,0 +1,15 @@
import std.stdio, std.range;
void main() {
auto arr1 = [1, 2, 3, 4, 5];
auto arr2 = [6, 7, 8, 9, 10];
foreach (ref a, ref b; lockstep(arr1, arr2))
a += b;
assert(arr1 == [7, 9, 11, 13, 15]);
// Lockstep also supports iteration with an index variable
foreach (index, a, b; lockstep(arr1, arr2))
writefln("Index %s: a = %s, b = %s", index, a, b);
}

View file

@ -0,0 +1,10 @@
import std.stdio, std.algorithm;
void main () {
auto s1 = "abc";
auto s2 = "ABC";
auto a1 = [1, 2];
foreach (i; 0 .. min(s1.length, s2.length, a1.length))
writeln(s1[i], s2[i], a1[i]);
}

View file

@ -0,0 +1,7 @@
const a1 = ['a', 'b', 'c'];
const a2 = ['A', 'B', 'C'];
const a3 = [1, 2, 3];
var i : Integer;
for i := 0 to 2 do
PrintLn(Format('%s%s%d', [a1[i], a2[i], a3[i]]));

View file

@ -0,0 +1,18 @@
program LoopOverArrays;
{$APPTYPE CONSOLE}
uses SysUtils;
const
ARRAY1: array [1..3] of string = ('a', 'b', 'c');
ARRAY2: array [1..3] of string = ('A', 'B', 'C');
ARRAY3: array [1..3] of Integer = (1, 2, 3);
var
i: Integer;
begin
for i := 1 to 3 do
Writeln(Format('%s%s%d', [ARRAY1[i], ARRAY2[i], ARRAY3[i]]));
Readln;
end.

View file

@ -0,0 +1,12 @@
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[];

View file

@ -0,0 +1,12 @@
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[];

View file

@ -0,0 +1,7 @@
def a1 := ["a","b","c"]
def a2 := ["A","B","C"]
def a3 := ["1","2","3"]
for i => v1 in a1 {
println(v1, a2[i], a3[i])
}

View file

@ -0,0 +1,3 @@
for [v1, v2, v3] in zip(a1, a2, a3) {
println(v1, v2, v3)
}

View file

@ -0,0 +1,28 @@
def zip {
to run(l1, l2) {
def zipped {
to iterate(f) {
for i in int >= 0 {
f(i, [l1.fetch(i, fn { return }),
l2.fetch(i, fn { return })])
}
}
}
return zipped
}
match [`run`, lists] {
def zipped {
to iterate(f) {
for i in int >= 0 {
var tuple := []
for l in lists {
tuple with= l.fetch(i, fn { return })
}
f(i, tuple)
}
}
}
zipped
}
}

View file

@ -0,0 +1,14 @@
;; looping over different sequences : infinite stream, string, list and vector
;; loop stops as soon a one sequence ends.
;; the (iota 6) = ( 0 1 2 3 4 5) sequence will stop first.
(for ((i (in-naturals 1000)) (j "ABCDEFGHIJK") (k (iota 6)) (m #(o p q r s t u v w)))
(writeln i j k m))
1000 "A" 0 o
1001 "B" 1 p
1002 "C" 2 q
1003 "D" 3 r
1004 "E" 4 s
1005 "F" 5 t

View file

@ -0,0 +1,38 @@
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);
}
}
}

View file

@ -0,0 +1,5 @@
@public
run = fn () {
lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) },
lists.zip3("abc", "ABC", "123"))
}

View file

@ -0,0 +1,34 @@
example (a_array: READABLE_INDEXABLE [BOUNDED [ANY]]): STRING
-- Assemble output for a 2-dim array in `a_array'
require
non_zero: ∀ nzitem:a_array ¦ nzitem.count > 0
local
min_count: INTEGER
do
⟳ v_item:a_array ¦
min_count := if min_count = 0 then
v_item.count
else
v_item.count.min (min_count)
end
create Result.make_empty
⟳ j:1 |..| min_count ¦
⟳ i:a_array ¦
if attached {READABLE_INDEXABLE [ANY]} i as al_i then
Result.append_string_general (al_i [j].out)
end
Result.append_string_general ("%N")
end
input_data: ARRAY [BOUNDED [ANY]]
-- Sample `input_data' for `example' (above).
do
Result := <<
"abcde",
"ABC",
<<1, 2, 3, 4>>
>>
end

View file

@ -0,0 +1,12 @@
open monad io list imperative
xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c']
['A','B','C'] [1,2,3]
print x = do putStrLn x
print_and_calc xs = do
xss <- return xs
return $ each print xss
print_and_calc xs ::: IO

View file

@ -0,0 +1,2 @@
xs = zipWith3 (\x -> (x++) >> (++)) "abc" "ABC"
"123"

View file

@ -0,0 +1,16 @@
import system'routines;
import extensions;
public program()
{
var a1 := new string[]{"a","b","c"};
var a2 := new string[]{"A","B","C"};
var a3 := new int[]{1,2,3};
for(int i := 0, i < a1.Length, i += 1)
{
console.printLine(a1[i], a2[i], a3[i])
};
console.readChar()
}

View file

@ -0,0 +1,16 @@
import system'routines.
import extensions.
public program
{
var a1 := new string[]{"a","b","c"};
var a2 := new string[]{"A","B","C"};
var a3 := new int[]{1,2,3};
var zipped := a1.zipBy(a2,(first,second => first + second.toString() ))
.zipBy(a3, (first,second => first + second.toString() ));
zipped.forEach:(e)
{ console.writeLine:e };
console.readChar();
}

View file

@ -0,0 +1,5 @@
l1 = ["a", "b", "c"]
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"]

View file

@ -0,0 +1,5 @@
l1 = 'abc'
l2 = 'ABC'
l3 = '123'
IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) end)
#=> ['aA1', 'bB2', 'cC3']

View file

@ -0,0 +1,4 @@
iex(1)> List.zip(['abc','ABCD','12345']) |> Enum.map(&Tuple.to_list(&1))
['aA1', 'bB2', 'cC3']
iex(2)> List.zip(['abcde','ABC','12']) |> Enum.map(&Tuple.to_list(&1))
['aA1', 'bB2']

View file

@ -0,0 +1,2 @@
lists:zipwith3(fun(A,B,C)->
io:format("~s~n",[[A,B,C]]) end, "abc", "ABC", "123").

View file

@ -0,0 +1,3 @@
lists:foreach(fun({A,B,C}) ->
io:format("~s~n",[[A,B,C]]) end,
lists:zip3("abc", "ABC", "123")).

View file

@ -0,0 +1,9 @@
sequence a, b, c
a = "abc"
b = "ABC"
c = "123"
for i = 1 to length(a) do
puts(1, a[i] & b[i] & c[i] & "\n")
end for

View file

@ -0,0 +1,9 @@
sequence a, b, c
a = "abc"
b = "ABC"
c = {1, 2, 3}
for i = 1 to length(a) do
printf(1, "%s%s%g\n", {a[i], b[i], c[i]})
end for

View file

@ -0,0 +1,12 @@
for i = 1 to length(a) do
if (a[i] >= '0' and a[i] <= '9') then
a[i] -= '0'
end if
if (b[i] >= '0' and b[i] <= '9') then
b[i] -= '0'
end if
if (c[i] >= '0' and c[i] <= '9') then
c[i] -= '0'
end if
printf(1, "%s%s%s\n", {a[i], b[i], c[i]})
end for

View file

@ -0,0 +1,3 @@
for c1,c2,n in Seq.zip3 ['a';'b';'c'] ['A';'B';'C']
[1;2;3] do
printfn "%c%c%d" c1 c2 n

View file

@ -0,0 +1,2 @@
"abc" "ABC" "123" [ [ write1 ] tri@ nl ]
3each

View file

@ -0,0 +1,13 @@
class LoopMultiple
{
public static Void main ()
{
List arr1 := ["a", "b", "c"]
List arr2 := ["A", "B", "C"]
List arr3 := [1, 2, 3]
[arr1.size, arr2.size, arr3.size].min.times |Int i|
{
echo ("${arr1[i]}${arr2[i]}${arr3[i]}")
}
}
}

View file

@ -0,0 +1,9 @@
[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.}

View file

@ -0,0 +1,19 @@
create a char a , char b , char c ,
create b char A , char B , char C ,
create c char 1 , char 2 , char 3 ,
: main
3 0 do cr
a i cells + @ emit
b i cells + @ emit
c i cells + @ emit
loop
cr
a b c
3 0 do cr
3 0 do
rot dup @ emit cell+
loop
loop
drop drop drop
;

View file

@ -0,0 +1,15 @@
program main
implicit none
integer,parameter :: n_vals = 3
character(len=*),dimension(n_vals),parameter :: ls = ['a','b','c']
character(len=*),dimension(n_vals),parameter :: us = ['A','B','C']
integer,dimension(n_vals),parameter :: ns = [1,2,3]
integer :: i !counter
do i=1,n_vals
write(*,'(A1,A1,I1)') ls(i),us(i),ns(i)
end do
end program main

View file

@ -0,0 +1,29 @@
' 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

View file

@ -0,0 +1,6 @@
a1 = ["a", "b", "c"]
a2 = ["A", "B", "C"]
a3 = ["1", "2", "3"]
m = [a1, a2, a3]
for row = m.transpose[]
println[join["",row]]

View file

@ -0,0 +1,4 @@
import lists.zip3
for x <- zip3( ['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3] )
println( x.mkString() )

View file

@ -0,0 +1,35 @@
# The Loop function will apply some function to every tuple built by
taking
# the i-th element of each list. If one of them is exhausted before the
others,
# the loop continues at its begining. Only the longests lists will be
precessed only once.
Loop := function(a, f)
local i, j, m, n, v;
n := Length(a);
v := List(a, Length);
m := Maximum(v);
for j in [1 .. m] do
f(List([1 .. n], i -> a[i][1 + RemInt(j - 1, v[i])]));
od;
end;
# Here we simply print each "row"
f := function(u)
Perform(u, Print);
Print("\n");
end;
Loop([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]], f);
aA1
bB2
cC3
Loop([["a", "b"], ["A", "B", "C", "D", "E"], [1, 2, 3]], f);
aA1
bB2
aC3
bD1
aE2

View file

@ -0,0 +1,19 @@
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

View file

@ -0,0 +1,11 @@
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

View file

@ -0,0 +1,13 @@
package main
import "fmt"
var a1 = []string{"a", "b", "c"}
var a2 = []byte{'A', 'B', 'C'}
var a3 = []int{1, 2, 3}
func main() {
for i := range a1 {
fmt.Printf("%v%c%v\n", a1[i], a2[i], a3[i])
}
}

View file

@ -0,0 +1,4 @@
["a" "b" "c"]:a;
["A" "B" "C"]:b;
["1" "2" "3"]:c;
[a b c]zip{puts}/

View file

@ -0,0 +1,6 @@
def synchedConcat = { a1, a2, a3 ->
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]}" }
}

View file

@ -0,0 +1,5 @@
def x = ['a', 'b', 'c']
def y = ['A', 'B', 'C']
def z = [1, 2, 3]
synchedConcat(x, y, z).each { println it }

View file

@ -0,0 +1,10 @@
PROCEDURE Main()
LOCAL a1 := { "a", "b", "c" }, ;
a2 := { "A", "B", "C", "D" }, ; // the last element "D" of this array will be ignored
a3 := { 1, 2, 3 }
LOCAL e1, e2, e3
FOR EACH e1, e2, e3 IN a1, a2, a3
Qout( e1 + e2 + hb_ntos( e3 ) )
NEXT
RETURN

View file

@ -0,0 +1,2 @@
{-# LANGUAGE ParallelListComp #-}
main = sequence [ putStrLn [x, y, z] | x <- "abc" | y <- "ABC" | z <- "123"]

View file

@ -0,0 +1,2 @@
import Data.List
main = mapM putStrLn $ transpose ["abc", "ABC", "123"]

View file

@ -0,0 +1,2 @@
import Data.List
main = mapM putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123"

View file

@ -0,0 +1,18 @@
import Control.Applicative (ZipList (ZipList, getZipList))
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 "一二三四"
)

View file

@ -0,0 +1,22 @@
using Lambda;
using Std;
class Main
{
static function main()
{
var a = ['a', 'b', 'c'];
var b = ['A', 'B', 'C'];
var c = [1, 2, 3];
//Find smallest array
var len = [a, b, c]
.map(function(a) return a.length)
.fold(Math.min, 0x0FFFFFFF)
.int();
for (i in 0...len)
Sys.println(a[i] + b[i] + c[i].string());
}
}

View file

@ -0,0 +1,8 @@
CHARACTER :: A = "abc"
REAL :: C(3)
C = $ ! 1, 2, 3
DO i = 1, 3
WRITE() A(i), "ABC"(i), C(i)
ENDDO

View file

@ -0,0 +1,6 @@
procedure main()
a := create !["a","b","c"]
b := create !["A","B","C"]
c := create !["1","2","3"]
while write(@a,@b,@c)
end

Some files were not shown because too many files have changed in this diff Show more