Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- Loop modifiers
from: http://rosettacode.org/wiki/Loops/Nested
note: Iteration

View file

@ -0,0 +1,25 @@
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over <math>[1,\ldots,20]</math>.
The loops iterate rows and columns of the array printing the elements until the value <math>20</math> is met.
Specifically, this task also shows how to [[Loop/Break|break]] out of nested loops.
;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,9 @@
[[Int]] mat
L 10
mat [+]= (1..10).map(x -> random:(1..20))
L(row) mat
L(el) row
print(el, end' )
I el == 20
L(row).break

View file

@ -0,0 +1,74 @@
* Loop nested 12/08/2015
LOOPNEST CSECT
USING LOOPNEST,R12
LR R12,R15
BEGIN LA R6,0 i
LA R8,1
LA R9,20
LOOPI1 BXH R6,R8,ELOOPI1 do i=1 to hbound(x,1)
LA R7,0 j
LA R10,1
LA R11,20
LOOPJ1 BXH R7,R10,ELOOPJ1 do j=1 to hbound(x,2)
L R5,RANDSEED n
M R4,=F'397204094' r4r5=n*const
D R4,=X'7FFFFFFF' r5=r5 div (2^31-1)
ST R4,RANDSEED r4=r5 mod (2^31-1) ; n=r4
LR R5,R4 r5=n
LA R4,0
D R4,=F'20' r5=n div nn; r4=n mod nn
LR R2,R4 r2=randint(nn) [0:nn-1]
LA R2,1(R2) randint(nn)+1
LR R1,R6 i
BCTR R1,0
MH R1,=H'20'
LR R5,R7 j
BCTR R5,0
AR R1,R5
SLA R1,2
ST R2,X(R1) x(i,j)=randint(20)+1
B LOOPJ1
ELOOPJ1 B LOOPI1
ELOOPI1 MVC MVCZ,=CL80' '
LA R6,0 i
LA R8,1
LA R9,20
LOOPI2 BXH R6,R8,ELOOPI2 do i=1 to hbound(x,1)
LA R7,0 j
LA R10,1
LA R11,20
LOOPJ2 BXH R7,R10,ELOOPJ2 do j=1 to hbound(x,2)
LR R1,R6
BCTR R1,0
MH R1,=H'20'
LR R5,R7
BCTR R5,0
AR R1,R5
SLA R1,2
L R5,X(R1) x(i,j)
LR R2,R5
LA R3,MVCZ
AH R3,MVCI
XDECO R2,XDEC
MVC 0(4,R3),XDEC+8
LH R3,MVCI
LA R3,4(R3)
STH R3,MVCI
L R5,X(R1)
C R5,=F'20' if x(i,j)=20
BE ELOOPI2 then exit
B LOOPJ2
ELOOPJ2 XPRNT MVCZ,80
MVC MVCI,=H'0'
MVC MVCZ,=CL80' '
B LOOPI2
ELOOPI2 XPRNT MVCZ,80
RETURN XR R15,R15
BR R14
X DS 400F
MVCZ DS CL80
MVCI DC H'0'
XDEC DS CL16
RANDSEED DC F'16807' running n
YREGS
END LOOPNEST

View file

@ -0,0 +1,22 @@
'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/06/2018;
'INTEGER' SEED;
'INTEGER' 'PROCEDURE' RANDOM(N);
'VALUE' N; 'INTEGER' N;
'BEGIN'
SEED:=(SEED*19157+12347) '/' 21647;
RANDOM:=SEED-(SEED '/' N)*N+1
'END' RANDOM;
'INTEGER' 'ARRAY' A(/1:10,1:10/);
'INTEGER' I,J;
SEED:=31569;
'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO'
A(/I,J/):=RANDOM(20);
SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print;
'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO'
'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN'
OUTINTEGER(1,A(/I,J/));
'IF' A(/I,J/)=20 'THEN' 'GOTO' LAB;
'END';
LAB:
'END'

View file

@ -0,0 +1,20 @@
main: (
[10][10]INT a; INT i, j;
FOR i FROM LWB a TO UPB a DO
FOR j FROM LWB a[i] TO UPB a[i] DO
a[i][j] := ENTIER (random * 20 + 1)
OD
OD ;
FOR i FROM LWB a TO UPB a DO
FOR j FROM LWB a[i] TO UPB a[i] DO
print(whole(a[i][j], -3));
IF a[i][j] = 20 THEN
GO TO xkcd com 292 # http://xkcd.com/292/ #
FI
OD;
print(new line)
OD;
xkcd com 292:
print(new line)
)

View file

@ -0,0 +1,228 @@
/* ARM assembly Raspberry PI */
/* program loopnested.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBVALUECOL, 10
.equ NBLIGNES, 10
.equ MAXVALUE, 20
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii " "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 314159
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
tiValues: .skip 4 * NBVALUECOL * NBLIGNES
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r3,iAdrtiValues
mov r4,#0 @ loop indice
mov r5,#0
mov r7,#4 * NBVALUECOL
1: @ begin loop 1
mov r0,#MAXVALUE + 1
bl genereraleas @ result 0 to MAXVALUE
mul r6,r5,r7
add r6,r4,lsl #2
str r0,[r3,r6]
add r4,#1
cmp r4,#NBVALUECOL
blt 1b
mov r4,#0
add r5,#1
cmp r5,#NBLIGNES
blt 1b
mov r4,#0 @ loop indice
mov r5,#0 @ total
ldr r3,iAdrtiValues @ table values address
2:
mul r6,r5,r7
add r6,r4,lsl #2
ldr r0,[r3,r6]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call conversion decimal
mov r1,#0
ldr r0,iAdrsMessResult
strb r1,[r0,#4]
ldr r0,iAdrsMessResult
bl affichageMess @ display message
ldr r0,[r3,r6]
cmp r0,#MAXVALUE
beq 3f
add r4,#1
cmp r4,#NBVALUECOL
blt 2b
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
mov r4,#0
add r5,#1
cmp r5,#NBLIGNES
blt 2b
b 100f
3:
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrtiValues: .int tiValues
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* Generation random number */
/***************************************************/
/* r0 contains limit */
genereraleas:
push {r1-r4,lr} @ save registers
ldr r4,iAdriGraine
ldr r2,[r4]
ldr r3,iNbDep1
mul r2,r3,r2
ldr r3,iNbDep1
add r2,r2,r3
str r2,[r4] @ maj de la graine pour l appel suivant
cmp r0,#0
beq 100f
mov r1,r0 @ divisor
mov r0,r2 @ dividende
bl division
mov r0,r3 @ résult = remainder
100: @ end function
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/*****************************************************/
iAdriGraine: .int iGraine
iNbDep1: .int 0x343FD
iNbDep2: .int 0x269EC3
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr

View file

@ -0,0 +1,26 @@
BEGIN {
rows = 5
columns = 5
# Fill ary[] with random numbers from 1 to 20.
for (r = 1; r <= rows; r++) {
for (c = 1; c <= columns; c++)
ary[r, c] = int(rand() * 20) + 1
}
# Find a 20.
b = 0
for (r = 1; r <= rows; r++) {
for (c = 1; c <= columns; c++) {
v = ary[r, c]
printf " %2d", v
if (v == 20) {
print
b = 1
break
}
}
if (b) break
print
}
}

View file

@ -0,0 +1,37 @@
PROC Main()
DEFINE PTR="CARD"
BYTE i,j,found
PTR ARRAY a(10)
BYTE ARRAY tmp,
a0(10),a1(10),a2(10),a3(10),a4(10),
a5(10),a6(10),a7(10),a8(10),a9(10)
a(0)=a0 a(1)=a1 a(2)=a2 a(3)=a3 a(4)=a4
a(5)=a5 a(6)=a6 a(7)=a7 a(8)=a8 a(9)=a9
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
tmp(i)=Rand(20)+1
OD
OD
found=0
FOR j=0 TO 9
DO
tmp=a(j)
FOR i=0 TO 9
DO
PrintB(tmp(i)) Put(32)
IF tmp(i)=20 THEN
found=1 EXIT
FI
OD
IF found THEN
EXIT
FI
PutE()
OD
RETURN

View file

@ -0,0 +1,21 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Test_Loop_Nested is
type Value_Type is range 1..20;
package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
use Random_Values;
Dice : Generator;
A : array (1..10, 1..10) of Value_Type :=
(others => (others => Random (Dice)));
begin
Outer :
for I in A'Range (1) loop
for J in A'Range (2) loop
Put (Value_Type'Image (A (I, J)));
exit Outer when A (I, J) = 20;
end loop;
New_Line;
end loop Outer;
end Test_Loop_Nested;

View file

@ -0,0 +1,16 @@
on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set outRow to {}
repeat with j from 1 to (count inRow)
set n to item j of inRow
set end of outRow to n
if (n = stopVal) then exit repeat # <--
end repeat
set end of out to outRow
if (n = stopVal) then exit repeat # <--
end repeat
return out
end loopDemo

View file

@ -0,0 +1,19 @@
on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set len to (count inRow)
set n to beginning of inRow
set outRow to {n}
set j to 2
repeat until ((j > len) or (n = stopVal)) # <--
set n to item j of inRow
set end of outRow to n
set j to j + 1
end repeat
set end of out to outRow
if (n = stopVal) then exit repeat # <--
end repeat
return out
end loopDemo

View file

@ -0,0 +1,15 @@
on loopDemo(array, stopVal)
set out to {}
repeat with i from 1 to (count array)
set inRow to item i of array
set outRow to {}
repeat with j from 1 to (count inRow)
set n to item j of inRow
set end of outRow to n
if (n = stopVal) then return out & {outRow} # <--
end repeat
set end of out to outRow
end repeat
return out
end loopDemo

View file

@ -0,0 +1,11 @@
local array, stopVal, row
set array to {}
set stopVal to 20
repeat 10 times
set row to {}
repeat 10 times
set end of row to (random number from 1 to stopVal)
end repeat
set end of array to row
end repeat
loopDemo(array, stopVal) -- Any of the handlers above.

View file

@ -0,0 +1 @@
{{15, 8, 9, 8, 9, 9, 10, 16, 3, 6}, {11, 3, 14, 18, 17, 1, 16, 15, 14, 7}, {4, 20}}

View file

@ -0,0 +1,9 @@
1 C = 5
2 R = 4
3 C = C - 1:R = C - 1: DIM A(C,R)
4 FOR J = 0 TO R: FOR I = 0 TO C:N = N + 1:A(I,J) = N: NEXT I,J
5 FOR J = 0 TO R: FOR I = 0 TO C:X = INT ( RND (1) * C):Y = INT ( RND (1) * R):N = A(I,J):A(I,J) = A(X,Y):A(X,Y) = N: NEXT I,J
6 FOR J = 0 TO R
7 FOR I = 0 TO C
8 PRINT S$A(I,J);:S$ = " "
9 IF A(I,J) < > 20 THEN NEXT I,J

View file

@ -0,0 +1,24 @@
printTable: function [tbl][
; wrapping the nested loop in a function
; allows us to use return to exit all of the loops
; since `break` only exits the inner loop
loop 0..dec size tbl 'x [
loop 0..dec size tbl\[x] 'y [
prints pad to :string tbl\[x]\[y] 2
if tbl\[x]\[y] = 20 -> return ø
prints ", "
]
print ""
]
]
a: []
loop 1..10 'x [
row: []
loop 1..10 'y [
'row ++ random 1 20
]
'a ++ @[row]
]
printTable a

View file

@ -0,0 +1,24 @@
Loop, 10
{
i := A_Index
Loop, 10
{
j := A_Index
Random, a%i%%j%, 1, 20
}
}
Loop, 10
{
i := A_Index
Loop, 10
{
j := A_Index
If (a%i%%j% == 20)
Goto finish
}
}
finish:
MsgBox % "a[" . i . "][" . j . "]" is 20
Return

View file

@ -0,0 +1,14 @@
DIM a(1 TO 10, 1 TO 10) AS INTEGER
CLS
FOR row = 1 TO 10
FOR col = 1 TO 10
a(row, col) = INT(RND * 20) + 1
NEXT col
NEXT row
FOR row = LBOUND(a, 1) TO UBOUND(a, 1)
FOR col = LBOUND(a, 2) TO UBOUND(a, 2)
PRINT a(row, col)
IF a(row, col) = 20 THEN END
NEXT col
NEXT row

View file

@ -0,0 +1,16 @@
dim a(20, 20)
for i = 0 to 19
for j = 0 to 19
a[i, j] = int(rand * 20) + 1
next j
next i
for i = 0 to 19
for j = 0 to 19
print a[i, j];" ";
if a[i, j] = 20 then end
next j
next i
end

View file

@ -0,0 +1,12 @@
DIM array(10,10)
FOR row% = 0 TO 10
FOR col% = 0 TO 10
array(row%,col%) = RND(20) + 1
NEXT
NEXT row%
FOR row% = 0 TO 10
FOR col% = 0 TO 10
PRINT "row "; row%, "col ";col%, "value "; array(row%,col%)
IF array(row%,col%) = 20 EXIT FOR row%
NEXT
NEXT row%

View file

@ -0,0 +1,46 @@
s = 1 /* Seed of the random number generator */
/* Random number from 1 to 20. */
define r() {
auto r
while (1) {
/*
* Formula (from POSIX) for random numbers of low
* quality, from 0 to 32767.
*/
s = (s * 1103515245 + 12345) % 4294967296
r = (s / 65536) % 32768
/* Prevent modulo bias. */
if (r >= 32768 % 20) break
}
return ((r % 20) + 1)
}
r = 5 /* Total rows */
c = 5 /* Total columns */
/* Fill array a[] with random numbers from 1 to 20. */
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
a[i * c + j] = r()
}
}
/* Find a 20. */
b = 0
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
v = a[i * c + j]
v /* Print v and a newline. */
if (v == 20) {
b = 1
break
}
}
if (b) break
/* Print "==" and a newline. */
"==
"
}
quit

View file

@ -0,0 +1,23 @@
#include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
}

View file

@ -0,0 +1,24 @@
#include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
for(auto& row : arr) {
for(auto& col: row) {
cout << ' ' << col;
if (col == 20) goto out;
}
cout << endl;
}
out:
return 0;
}

View file

@ -0,0 +1,26 @@
using System;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
a[i, j] = r.Next(0, 21) + 1;
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Console.Write(" {0}", a[i, j]);
if (a[i, j] == 20) {
goto Done;
}
}
Console.WriteLine();
}
Done:
Console.WriteLine();
}
}

View file

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main(string[] args) {
int[,] a = new int[10, 10];
Random r = new Random();
// prepare linq statement with two 'from' which makes nested loop
var pairs = from i in Enumerable.Range(0, 10)
from j in Enumerable.Range(0, 10)
select new { i = i, j = j};
// iterates through the full nested loop with a sigle foreach statement
foreach (var p in pairs)
{
a[p.i, p.j] = r.Next(0, 21) + 1;
}
// iterates through the nested loop until find element = 20
pairs.Any(p => { Console.Write(" {0}", a[p.i, p.j]); return a[p.i, p.j] == 20; });
Console.WriteLine();
}
}

View file

@ -0,0 +1,24 @@
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
goto Done;
}
printf("\n");
}
Done:
printf("\n");
return 0;
}

View file

@ -0,0 +1,25 @@
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
int main() {
int a[10][10], i, j;
srand(time(NULL));
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
a[i][j] = rand() % 20 + 1;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf(" %d", a[i][j]);
if (a[i][j] == 20)
break;
}
if (a[i][j] == 20)
break;
printf("\n");
}
printf("\n");
return 0;
}

View file

@ -0,0 +1,45 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. Nested-Loop.
DATA DIVISION.
LOCAL-STORAGE SECTION.
78 Table-Size VALUE 10.
01 Table-Area.
03 Table-Row OCCURS Table-Size TIMES
INDEXED BY Row-Index.
05 Table-Element PIC 99 OCCURS Table-Size TIMES
INDEXED BY Col-Index.
01 Current-Time PIC 9(8).
PROCEDURE DIVISION.
* *> Seed RANDOM.
ACCEPT Current-Time FROM TIME
MOVE FUNCTION RANDOM(Current-Time) TO Current-Time
* *> Put random numbers in the table.
* *> The AFTER clause is equivalent to a nested PERFORM VARYING
* *> statement.
PERFORM VARYING Row-Index FROM 1 BY 1
UNTIL Table-Size < Row-Index
AFTER Col-Index FROM 1 BY 1
UNTIL Table-Size < Col-Index
COMPUTE Table-Element (Row-Index, Col-Index) =
FUNCTION MOD((FUNCTION RANDOM * 1000), 20) + 1
END-PERFORM
* *> Search through table for 20.
* *> Using proper nested loops.
PERFORM VARYING Row-Index FROM 1 BY 1
UNTIL Table-Size < Row-Index
PERFORM VARYING Col-Index FROM 1 BY 1
UNTIL Table-Size < Col-Index
IF Table-Element (Row-Index, Col-Index) = 20
EXIT PERFORM
ELSE
DISPLAY Table-Element (Row-Index, Col-Index)
END-IF
END-PERFORM
END-PERFORM
GOBACK
.

View file

@ -0,0 +1,16 @@
use Random;
var nums:[1..10, 1..10] int;
var rnd = new RandomStream();
[ n in nums ] n = floor(rnd.getNext() * 21):int;
delete rnd;
// this shows a clumsy explicit way of iterating, to actually create nested loops:
label outer for i in nums.domain.dim(1) {
for j in nums.domain.dim(2) {
write(" ", nums(i,j));
if nums(i,j) == 20 then break outer;
}
writeln();
}

View file

@ -0,0 +1,18 @@
(ns nested)
(defn create-matrix [width height]
(for [_ (range width)]
(for [_ (range height)]
(inc (rand-int 20)))))
(defn print-matrix [matrix]
(loop [[row & rs] matrix]
(when (= (loop [[x & xs] row]
(println x)
(cond (= x 20) :stop
xs (recur xs)
:else :continue))
:continue)
(when rs (recur rs)))))
(print-matrix (create-matrix 10 10))

View file

@ -0,0 +1,9 @@
<Cfset RandNum = 0>
<Cfloop condition="randNum neq 20">
<Cfloop from="1" to="5" index="i">
<Cfset randNum = RandRange(1, 20)>
<Cfoutput>#randNum# </Cfoutput>
<Cfif RandNum eq 20><cfbreak></Cfif>
</Cfloop>
<br>
</Cfloop>

View file

@ -0,0 +1,11 @@
10 dim a$(20,20):print "initializing...":print
20 for r=1 to 20:for c=1 to 20
30 a$(r,c)=chr$(int(rnd(1)*20)+1)
40 next c,r
50 rem now search array
60 for r=1 to 20:for c=1 to 20
70 e=asc(a$(r,c))
80 print "(";r;","c;") =";e
90 if e=20 then print "found 20. stopping search.":end
100 next c,r
110 print "search complete. no 20 found.":end

View file

@ -0,0 +1,14 @@
(let ((a (make-array '(10 10))))
(dotimes (i 10)
(dotimes (j 10)
(setf (aref a i j) (1+ (random 20)))))
(block outer
(dotimes (i 10)
(dotimes (j 10)
(princ " ")
(princ (aref a i j))
(if (= 20 (aref a i j))
(return-from outer)))
(terpri))
(terpri)))

View file

@ -0,0 +1,18 @@
import std.stdio, std.random;
void main() {
int[10][10] mat;
foreach (ref row; mat)
foreach (ref item; row)
item = uniform(1, 21);
outer:
foreach (row; mat)
foreach (item; row) {
write(item, ' ');
if (item == 20)
break outer;
}
writeln();
}

View file

@ -0,0 +1,68 @@
1 ss [Seed of the random number generator.]sz
[*
* lrx -- (number)
* Push a random number from 1 to 20.
*]sz
[
[ [If preventing modulo bias:]sz
sz [Drop this random number.]sz
lLx [Loop.]sz
]SI
[ [Loop:]sz
[*
* Formula (from POSIX) for random numbers of low quality.
* Push a random number from 0 to 32767.
*]sz
ls 1103515245 * 12345 + 4294967296 % ss
ls 65536 / 32768 %
d 32768 20 % >I [Prevent modulo bias.]sz
]d SL x
20 % 1 + [Be from 1 to 20.]sz
LLsz LIsz [Restore L, I.]sz
]sr
5 sb [b = Total rows]sz
5 sc [c = Total columns]sz
[Fill array a[] with random numbers from 1 to 20.]sz
[ [Inner loop for j:]sz
lrx [Push random number.]sz
li lc * lj + [Push index of a[i, j].]sz
:a [Put in a[].]sz
lj 1 + d sj [j += 1]sz
lc >I [Loop while c > j.]sz
]sI
[ [Outer loop for i:]sz
0 d sj [j = 0]sz
lc >I [Enter inner loop.]sz
li 1 + d si [i += 1]sz
lb >L [Loop while b > i.]sz
]sL
0 d si [i = 0]sz
lb >L [Enter outer loop.]sz
[Find a 20.]sz
[ [If detecting a 20:]sz
li lj + 3 + Q [Break outer loop.]sz
]sD
[ [Inner loop for j:]sz
li lc * lj + [Push index of a[i,j].]sz
;a [Push value from a[].]sz
p [Print value and a newline.]sz
20 =D [Detect a 20.]sz
lj 1 + d sj [j += 1]sz
lc >I [Loop while c > j.]sz
]sI
[ [Outer loop for i:]sz
0 d sj [j = 0]sz
lc >I [Enter inner loop.]sz
[==
]P [Print "==" and a newline.]sz
li 1 + d si [i += 1]sz
lb >L [Loop while b > i.]sz
]sL
0 d si [i = 0]sz
lb >L [Enter outer loop.]sz

View file

@ -0,0 +1,27 @@
var
matrix: array[1..10,1..10] of Integer;
row, col: Integer;
broken: Boolean;
begin
// Launch random number generator
randomize;
// Filling matrix with random numbers
for row := 1 to 10 do
for col := 1 to 10 do
matrix[row, col] := Succ(Random(20));
// Displaying values one by one, until at the end or reached number 20
Broken := False;
for row := 1 to 10 do
begin
for col := 1 to 10 do
begin
ShowMessage(IntToStr(matrix[row, col]));
if matrix[row, col] = 20 then
begin
Broken := True;
break;
end;
end;
if Broken then break;
end;
end;

View file

@ -0,0 +1,13 @@
let array = [[2, 12, 10, 4], [18, 11, 20, 2]]
for row in array {
break when {
for element in row {
print("\(element)")
if element == 20 {
break true
}
}
}
}
print("*Done")

View file

@ -0,0 +1,14 @@
def array := accum [] for i in 1..5 { _.with(accum [] for i in 1..5 { _.with(entropy.nextInt(20) + 1) }) }
escape done {
for row in array {
for x in row {
print(`$x$\t`)
if (x == 20) {
done()
}
}
println()
}
}
println("done.")

View file

@ -0,0 +1,18 @@
DIM A%[10,10] ! in declaration part
.............
PRINT(CHR$(12);) !CLS
FOR ROW=1 TO 10 DO
FOR COL=1 TO 10 DO
A%[ROW,COL]=INT(RND(1)*20)+1 ! INT and RND are ERRE predeclared functions
! RND generates random numbers between 0 and 1
END FOR
END FOR
FOR ROW=1 TO 10 DO
FOR COL=1 TO 10 DO
PRINT(A%[ROW,COL])
EXIT IF A%[ROW,COL]=20
END FOR
EXIT IF A%[ROW,COL]=20 ! EXIT breaks the current loop only: you must repeat it,
! use a boolean variable or a GOTO label statement
END FOR

View file

@ -0,0 +1,9 @@
arr[][] = [ [ 2 12 10 4 ] [ 18 11 20 2 ] ]
for i to len arr[][]
for j to len arr[i][]
if arr[i][j] = 20
print "20 at " & i & "," & j
break 2
.
.
.

View file

@ -0,0 +1,8 @@
(lib 'math) ;; for 2D-arrays
(define array (build-array 42 42 (lambda(i j) (1+ (random 20)))))
→ array
;;
(for* ((row array) (aij row)) (write aij) #:break (= aij 20))
→ 9 8 11 1 14 11 1 9 16 1 10 5 5 6 5 4 13 17 14 13 6 10 16 4 8 5 1 17 16 19 4 6 18 1 15 3 4 13 19
6 12 5 5 17 19 16 3 7 2 15 16 14 16 16 19 18 14 16 6 18 14 17 20

View file

@ -0,0 +1,23 @@
defmodule Loops do
def nested do
list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
try do
nested(list)
catch
:find -> IO.puts "done"
end
end
def nested(list) do
Enum.each(list, fn row ->
Enum.each(row, fn x ->
IO.write "#{x} "
if x == 20, do: throw(:find)
end)
IO.puts ""
end)
end
end
Loops.nested

View file

@ -0,0 +1,10 @@
list = Enum.shuffle(1..20) |> Enum.chunk(5)
IO.inspect list, char_lists: :as_lists
Enum.any?(list, fn row ->
IO.puts ""
Enum.any?(row, fn x ->
IO.write "#{x} "
x == 20
end)
end)
IO.puts "done"

View file

@ -0,0 +1,21 @@
-module( loops_nested ).
-export( [task/0] ).
task() ->
Size = 20,
Two_dimensional_array = [random_array(Size) || _X <- lists:seq(1, Size)],
print_until_found( [], 20, Two_dimensional_array ).
print_until_found( [], N, [Row | T] ) -> print_until_found( print_until_found_row(N, Row), N, T );
print_until_found( _Found, _N, _Two_dimensional_array ) -> io:fwrite( "~n" ).
print_until_found_row( _N, [] ) -> [];
print_until_found_row( N, [N | T] ) -> [N | T];
print_until_found_row( N, [H | T] ) ->
io:fwrite( "~p ", [H] ),
print_until_found_row( N, T ).
random_array( Size ) -> [random:uniform(Size) || _X <- lists:seq(1, Size)].

View file

@ -0,0 +1,18 @@
sequence a
a = rand(repeat(repeat(20, 10), 10))
integer wantExit
wantExit = 0
for i = 1 to 10 do
for j = 1 to 10 do
printf(1, "%g ", {a[i][j]})
if a[i][j] = 20 then
wantExit = 1
exit
end if
end for
if wantExit then
exit
end if
end for

View file

@ -0,0 +1,5 @@
//Nigel Galloway: November 10th., 2017
let n = System.Random()
let g = Array2D.init 8 8 (fun _ _ -> 1+n.Next()%20)
Array2D.iter (fun n -> printf "%d " n) g; printfn ""
g |> Seq.cast<int> |> Seq.takeWhile(fun n->n<20) |> Seq.iter (fun n -> printf "%d " n)

View file

@ -0,0 +1,4 @@
USING: io kernel math.ranges prettyprint random sequences ;
10 [ 20 [ 20 [1,b] random ] replicate ] replicate ! make a table of random values
[ [ dup pprint bl 20 = ] find nl drop ] find 2drop ! print values until 20 is found

View file

@ -0,0 +1,7 @@
USING: continuations io kernel math.ranges prettyprint random
sequences ;
10 [ 20 [ 20 [1,b] random ] replicate ] replicate ! make a table of random values
[
[ [ dup pprint bl 20 = [ return ] when ] each nl ] each ! print values until 20 is found
] with-return drop

View file

@ -0,0 +1,34 @@
class Main
{
public static Void main ()
{
rows := 10
cols := 10
// create and fill an array of given size with random numbers
Int[][] array := [,]
rows.times
{
row := [,]
cols.times { row.add(Int.random(1..20)) }
array.add (row)
}
// now do the search
try
{
for (i := 0; i < rows; i++)
{
for (j := 0; j < cols; j++)
{
echo ("now at ($i, $j) which is ${array[i][j]}")
if (array[i][j] == 20) throw (Err("found it"))
}
}
}
catch (Err e)
{
echo (e.msg)
return // and finish
}
echo ("No 20")
}
}

View file

@ -0,0 +1,18 @@
include random.fs
10 constant X
10 constant Y
: ,randoms ( range n -- ) 0 do dup random 1+ , loop drop ;
create 2darray 20 X Y * ,randoms
: main
Y 0 do
cr
X 0 do
j X * i + cells 2darray + @
dup .
20 = if unloop unloop exit then
loop
loop ;

View file

@ -0,0 +1,76 @@
PROGRAM LOOPNESTED
INTEGER A, I, J, RNDINT
C Build a two-dimensional twenty-by-twenty array.
DIMENSION A(20,20)
C It doesn't matter what number you put here.
CALL SDRAND(123)
C Fill the array with random numbers.
DO 20 I = 1, 20
DO 10 J = 1, 20
A(I, J) = RNDINT(1, 20)
10 CONTINUE
20 CONTINUE
C Print the numbers.
DO 40 I = 1, 20
DO 30 J = 1, 20
WRITE (*,5000) I, J, A(I, J)
C If this number is twenty, break out of both loops.
IF (A(I, J) .EQ. 20) GOTO 50
30 CONTINUE
40 CONTINUE
C If we had gone to 40, the DO loop would have continued. You can
C label STOP instead of adding another CONTINUE, but it is good
C form to only label CONTINUE statements as much as possible.
50 CONTINUE
STOP
C Print the value so that it looks like one of those C arrays that
C makes everybody so comfortable.
5000 FORMAT('A[', I2, '][', I2, '] is ', I2)
END
C FORTRAN 77 does not come with a random number generator, but it is
C easy enough to type "fortran 77 random number generator" into your
C preferred search engine and to copy and paste what you find.
C The following code is a slightly-modified version of:
C
C http://www.tat.physik.uni-tuebingen.de/
C ~kley/lehre/ftn77/tutorial/subprograms.html
SUBROUTINE SDRAND (IRSEED)
COMMON /SEED/ UTSEED, IRFRST
UTSEED = IRSEED
IRFRST = 0
RETURN
END
INTEGER FUNCTION RNDINT (IFROM, ITO)
INTEGER IFROM, ITO
PARAMETER (MPLIER=16807, MODLUS=2147483647, &
& MOBYMP=127773, MOMDMP=2836)
COMMON /SEED/ UTSEED, IRFRST
INTEGER HVLUE, LVLUE, TESTV, NEXTN
SAVE NEXTN
IF (IRFRST .EQ. 0) THEN
NEXTN = UTSEED
IRFRST = 1
ENDIF
HVLUE = NEXTN / MOBYMP
LVLUE = MOD(NEXTN, MOBYMP)
TESTV = MPLIER*LVLUE - MOMDMP*HVLUE
IF (TESTV .GT. 0) THEN
NEXTN = TESTV
ELSE
NEXTN = TESTV + MODLUS
ENDIF
IF (NEXTN .GE. 0) THEN
RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + IFROM
ELSE
RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + ITO + 1
ENDIF
RETURN
END

View file

@ -0,0 +1,19 @@
program Example
implicit none
real :: ra(5,10)
integer :: ia(5,10)
integer :: i, j
call random_number(ra)
ia = int(ra * 20.0) + 1
outer: do i = 1, size(ia, 1)
do j = 1, size(ia, 2)
write(*, "(i3)", advance="no") ia(i,j)
if (ia(i,j) == 20) exit outer
end do
write(*,*)
end do outer
end program Example

View file

@ -0,0 +1,22 @@
' FB 1.05.0 Win64
Randomize
Dim a(1 To 20, 1 To 20) As Integer
For i As Integer = 1 To 20
For j As Integer = 1 To 20
a(i, j) = Int(Rnd * 20) + 1
Next j
Next i
For i As Integer = 1 To 20
For j As Integer = 1 To 20
Print Using "##"; a(i, j);
Print " ";
If a(i, j) = 20 Then Exit For, For '' Exits both for loops
Next j
Print
Next i
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,14 @@
array = new array[[10,10], {|x,y| random[1,20]}]
println["array is:\n" + formatTable[array, "right"] + "\n"]
[rows,cols] = array.dimensions[]
ROW:
for r = 0 to rows-1
for c = 0 to cols-1
{
print[array@r@c + " " ]
if array@r@c == 20
break ROW
}

View file

@ -0,0 +1,18 @@
# You can't break an outer loop unless you return from the whole function.
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;
Find := function(a, x)
local i, j, n;
n := Length(a);
for i in [1 .. n] do
for j in [1 .. n] do
if a[i][j] = x then
return [i, j];
fi;
od;
od;
return fail;
end;
Find(a, 20);

View file

@ -0,0 +1,25 @@
Public Sub Main()
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Dim bBreak As Boolean
For siCount0 = 0 To 4
For siCount1 = 0 To 4
siArray[siCount0, siCount1] = Rand(1, 20)
siArray[siCount0, siCount1] = Rand(1, 20)
Next
Next
For siCount0 = 0 To 4
For siCount1 = 0 To 4
If siArray[siCount0, siCount1] = 20 Then
bBreak = True
Break
Endif
Next
If bBreak Then Break
Next
Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"
End

View file

@ -0,0 +1,32 @@
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
values := make([][]int, 10)
for i := range values {
values[i] = make([]int, 10)
for j := range values[i] {
values[i][j] = rand.Intn(20) + 1
}
}
outerLoop:
for i, row := range values {
fmt.Printf("%3d)", i)
for _, value := range row {
fmt.Printf(" %3d", value)
if value == 20 {
break outerLoop
}
}
fmt.Printf("\n")
}
fmt.Printf("\n")
}

View file

@ -0,0 +1,22 @@
final random = new Random()
def a = []
(0..<10).each {
def row = []
(0..<10).each {
row << (random.nextInt(20) + 1)
}
a << row
}
a.each { println it }
println ()
Outer:
for (i in (0..<a.size())) {
for (j in (0..<a[i].size())) {
if (a[i][j] == 20){
println ([i:i, j:j])
break Outer
}
}
}

View file

@ -0,0 +1,5 @@
import Data.List
breakIncl :: (a -> Bool) -> [a] -> [a]
breakIncl p = uncurry ((. take 1). (++)). break p
taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`)

View file

@ -0,0 +1,13 @@
*Main> mapM_ (mapM_ print) $ taskLLB 20 [[2,6,17,5,14],[1,9,11,18,10],[13,20,8,7,4],[16,15,19,3,12]]
2
6
17
5
14
1
9
11
18
10
13
20

View file

@ -0,0 +1,12 @@
REAL :: n=20, array(n,n)
array = NINT( RAN(10,10) )
DO row = 1, n
DO col = 1, n
WRITE(Name) row, col, array(row,col)
IF( array(row, col) == 20 ) GOTO 99
ENDDO
ENDDO
99 END

View file

@ -0,0 +1,10 @@
procedure main()
every !(!(L := list(10)) := list(10)) := ?20 # setup a 2d array of random numbers up to 20
every i := 1 to *L do # using nested loops
every j := 1 to *L[i] do
if L[i,j] = 20 then
break break write("L[",i,",",j,"]=20")
end

View file

@ -0,0 +1,4 @@
every x := L[i := 1 to *L,1 to *L[i]] do
if x = 20 then break write("L[",i,",",j,"]=20") # more succinctly
every if !!L = 20 then break write("Found !!L=20") # even more so (but looses the values of i and j

View file

@ -0,0 +1 @@
use=: ({.~ # <. 1+i.&20)@:,

View file

@ -0,0 +1,8 @@
doubleLoop=: {{
for_row. i.#y do.
for_col. i.1{$y do.
echo t=.(<row,col) { y
if. 20=t do. return. end.
end.
end.
}}

View file

@ -0,0 +1,21 @@
import java.util.Random;
public class NestedLoopTest {
public static final Random gen = new Random();
public static void main(String[] args) {
int[][] a = new int[10][10];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
a[i][j] = gen.nextInt(20) + 1;
Outer:for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" " + a[i][j]);
if (a[i][j] == 20)
break Outer; //adding a label breaks out of all loops up to and including the labelled loop
}
System.out.println();
}
System.out.println();
}
}

View file

@ -0,0 +1,13 @@
// a "random" 2-D array
var a = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]];
outer_loop:
for (var i in a) {
print("row " + i);
for (var j in a[i]) {
print(" " + a[i][j]);
if (a[i][j] == 20)
break outer_loop;
}
}
print("done");

View file

@ -0,0 +1,43 @@
var lst = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1,
20, 16, 5]];
var takeWhile = function (lst, fnTest) {
'use strict';
var varHead = lst.length ? lst[0] : null;
return varHead ? (
fnTest(varHead) ? [varHead].concat(
takeWhile(lst.slice(1), fnTest)
) : []
) : []
},
// The takeWhile function terminates when notTwenty(n) returns false
notTwenty = function (n) {
return n !== 20;
},
// Leftward groups containing no 20
// takeWhile nested within takeWhile
lstChecked = takeWhile(lst, function (group) {
return takeWhile(
group,
notTwenty
).length === 4;
});
// Return the trail of numbers preceding 20 from a composable expression
console.log(
// Numbers before 20 in a group in which it was found
lstChecked.concat(
takeWhile(
lst[lstChecked.length], notTwenty
)
)
// flattened
.reduce(function (a, x) {
return a.concat(x);
}).join('\n')
);

View file

@ -0,0 +1,21 @@
2
12
10
4
18
11
9
3
14
15
7
17
6
19
8
13
6
19
8
13
1

View file

@ -0,0 +1,11 @@
# Given an m x n matrix,
# produce a stream of the matrix elements (taken row-wise)
# up to but excluding the first occurrence of $max
def stream($max):
. as $matrix
| length as $m
| (.[0] | length) as $n
| label $ok
| {i: range(0;$m), j: range(0;$n)}
| $matrix[.i][.j] as $m
| if $m == $max then break $ok else $m end ;

View file

@ -0,0 +1,9 @@
# Create an array of arrays by using the items in the stream, s,
# to create successive rows, each row having at most n items.
def reshape(s; n):
reduce s as $s ({i:0, j:0, matrix: []};
.matrix[.i][.j] = $s
| if .j + 1 == n then .i += 1 | .j = 0
else .j += 1
end)
| .matrix;

View file

@ -0,0 +1,10 @@
# Create an m x n matrix filled with numbers in [1 .. max]
def randomMatrix(m; n; max):
reshape(limit(m * n; rand(max) + 1); n);
# Present the matrix up to but excluding the first occurrence of $max
def show($m; $n; $max):
reshape( randomMatrix($m; $n; $max) | stream($max); $n)[] ;
# Main program for the problem at hand.
show(20; 4; 20)

View file

@ -0,0 +1,17 @@
# LCG::Microsoft generates 15-bit integers using the same formula
# as rand() from the Microsoft C Runtime.
# Input: [ count, state, random ]
def next_rand_Microsoft:
.[0] as $count
| ((214013 * .[1]) + 2531011) % 2147483648 # mod 2^31
| [$count+1 , ., (. / 65536 | floor) ];
def rand_Microsoft(seed):
[0,seed]
| next_rand_Microsoft # the seed is not so random
| recurse( next_rand_Microsoft )
| .[2];
# A random integer in [0 ... (n-1)]:
# rand_Microsoft returns an integer in 0 .. 32767
def rand(n): n * (rand_Microsoft($seed|tonumber) / 32768) | trunc;

View file

@ -0,0 +1,36 @@
/* Loops/Nested in Jsish */
Math.srand(0);
var nrows = Math.floor(Math.random() * 4) + 4;
var ncols = Math.floor(Math.random() * 6) + 6;
var matrix = new Array(nrows).fill(0).map(function(v, i, a):array { return new Array(ncols).fill(0); } );
var i,j;
for (i = 0; i < nrows; i++) for (j = 0; j < ncols; j++) matrix[i][j] = Math.floor(Math.random() * 20) + 1;
/* Labelled break point */
outer_loop:
for (i in matrix) {
printf("row %d:", i);
for (j in matrix[i]) {
printf(" %d", matrix[i][j]);
if (matrix[i][j] == 20) {
printf("\n");
break outer_loop;
}
}
printf("\n");
}
puts(matrix);
/*
=!EXPECTSTART!=
row 0: 2 18 12 16 14 8 18 15 9 8
row 1: 15 6 8 16 17 12 15 2 10 3
row 2: 11 8 12 20
[ [ 2, 18, 12, 16, 14, 8, 18, 15, 9, 8 ],
[ 15, 6, 8, 16, 17, 12, 15, 2, 10, 3 ],
[ 11, 8, 12, 20, 18, 4, 6, 6, 19, 9 ],
[ 16, 3, 2, 19, 1, 4, 8, 4, 11, 18 ] ]
=!EXPECTEND!=
*/

View file

@ -0,0 +1,17 @@
M = [rand(1:20) for i in 1:5, j in 1:10]
R, C = size(M)
println("The full matrix is:")
println(M, "\n")
println("Find the first 20:")
for i in 1:R, j in 1:C
n = M[i,j]
@printf "%4d" n
if n == 20
println()
break
elseif j == C
println()
end
end

View file

@ -0,0 +1,18 @@
import kotlin.random.Random
fun main() {
val a = Array(10) { IntArray(10) { Random.nextInt(1..20) } }
println("array:")
for (i in a.indices) println("row $i: ${a[i].contentToString()}")
println("search:")
outer@ for (i in a.indices) {
print("row $i:")
for (j in a[i].indices) {
print(" " + a[i][j])
if (a[i][j] == 20) break@outer
}
println()
}
println()
}

View file

@ -0,0 +1,66 @@
1) the A.find function gets a value and a unidimensional array,
then retuns the item matching the value else -1
{def A.find
{def A.find.r
{lambda {:val :arr :n :i :acc}
{if {> :i :n}
then -1
else {if {= :val {A.get :i :arr}}
then :i
else {A.find.r :val :arr :n {+ :i 1} {A.addlast! :i :acc}}}}}}
{lambda {:val :arr}
{A.find.r :val :arr {- {A.length :arr} 1} 0 {A.new}}}}
-> A.find
{def A {A.new {S.serie 0 20}}}
-> A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
{A.find 12 {A}}
-> 12 // the index
{A.find 21 {A}}
-> -1 // not found
2) the AA.find function gets a value and a bidimensional array,
then returns the sequence of rows until the row containing the value,
and diplays the row containing the value if it exists else displays "the value was not found".
{def AA.find
{def AA.find.r
{lambda {:val :arr :n :i}
{if {> :i :n}
then {br}:val was not found
else {if {not {= {A.find :val {A.get :i :arr}} -1}} // call the A.find function on each row
then {br}:val was found in {A.get :i :arr}
else {br}{A.get :i :arr} {AA.find.r :val :arr :n {+ :i 1}} }}}}
{lambda {:val :arr}
{AA.find.r :val :arr {- {A.length :arr} 1} 0}}}
-> AA.find
3) testing
3.1) the rn function returns a random integer between 0 and n
{def rn {lambda {:n} {round {* :n {random}}}}}
-> rn
3.2) creating a bidimensional array containing random integers between 0 and 20
{def AA {A.new {A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}
{A.new {rn 20} {rn 20} {rn 20} {rn 20} {rn 20}}}}
-> AA = [[9,4,10,14,1],[4,12,7,18,13],[7,13,19,12,11],[18,4,2,14,15]]
3.3) calling with a value which can be in the array
{AA.find 12 {AA}}
->
[9,4,10,14,1]
12 was found in [4,12,7,18,13]
3.4) calling with a value outside of the array
{AA.find 21 {AA}}
->
[9,4,10,14,1]
[4,12,7,18,13]
[7,13,19,12,11]
[18,4,2,14,15]
21 was not found

View file

@ -0,0 +1,28 @@
&values = fn.arrayMake(10)
$i
repeat($[i], 10) {
&array = fn.arrayMake(10)
$j
repeat($[j], 10) {
&array[$j] $= fn.randRange(20) + 1
}
&values[$i] ::= &array
}
$row
foreach($[row], &values) {
$ele
foreach($[ele], $row) {
fn.print(\s$ele)
if($ele === 20) {
con.break(2) # Number of loops we want to break out of
}
}
fn.println()
}
fn.println()

View file

@ -0,0 +1,21 @@
local(a) = array(
array(2, 12, 10, 4),
array(18, 11, 9, 3),
array(14, 15, 7, 17),
array(6, 19, 8, 13),
array(1, 20, 16, 5)
)
// Query expression
with i in delve(#a) do {
stdoutnl(#i)
#i == 20 ? return
}
// Nested loops
#a->foreach => {
#1->foreach => {
stdoutnl(#1)
#1 == 20 ? return
}
}

View file

@ -0,0 +1,19 @@
dim ar(10,10)
for i = 1 to 10
for j = 1 to 10
ar(i, j) = int(rnd(1) * 20) + 1
next
next
flag=0
for x = 1 to 10
for y = 1 to 10
print ar(x,y)
if ar(x,y) = 20 then
flag=1
exit for
end if
next
if flag then exit for
next
print "Completed row ";x;" and column ";y

View file

@ -0,0 +1,18 @@
-- create two-dimensional array with random numbers
a = []
repeat with i = 1 to 20
a[i] = []
repeat with j = 1 to 20
a[i][j] = random(20)
end repeat
end repeat
-- iterate over rows and columns, print value, exit both loops if it's 20
repeat with i = 1 to 20
repeat with j = 1 to 20
v = a[i][j]
put v
if v=20 then exit repeat
end repeat
if v=20 then exit repeat
end repeat

View file

@ -0,0 +1,35 @@
Section Header
+ name := TEST_LOOP_NESTED;
- external := `#include <time.h>`;
Section Public
- main <- (
+ a : ARRAY2[INTEGER];
+ i, j: INTEGER;
`srand(time(NULL))`;
a := ARRAY2[INTEGER].create(0, 0) to (9, 9);
0.to 9 do { ii : INTEGER;
0.to 9 do { jj : INTEGER;
a.put (`rand()`:INTEGER % 20 + 1) to (ii, jj);
};
};
{ i < 10 }.while_do {
j := 0;
{ j < 10 }.while_do {
' '.print;
a.item(i, j).print;
(a.item(i, j) = 20).if {
i := 999;
j := 999;
};
j := j + 1;
};
i := i + 1;
'\n'.print;
};
'\n'.print;
);

View file

@ -0,0 +1,21 @@
repeat with i = 1 to 10
repeat with j = 1 to 10
put random(20) into aNums[i,j]
end repeat
end repeat
repeat with i = 1 to 10
repeat with j = 1 to 10
if aNums[i,j] = 20 then
put true into exitLoop
exit repeat
end if
end repeat
if exitLoop then exit repeat
end repeat
if exitLoop then
put "20 found in" && i & comma & j
else
put "20 not found"
end if

View file

@ -0,0 +1,15 @@
make "a mdarray [10 10]
for [j 1 10] [for [i 1 10] [mdsetitem list :i :j :a (1 + random 20)]]
to until.20
for [j 1 10] [
for [i 1 10] [
type mditem list :i :j :a
type "| |
if equal? 20 mditem list :i :j :a [stop]
]
print "||
]
end
until.20

View file

@ -0,0 +1,15 @@
t = {}
for i = 1, 20 do
t[i] = {}
for j = 1, 20 do t[i][j] = math.random(20) end
end
function exitable()
for i = 1, 20 do
for j = 1, 20 do
if t[i][j] == 20 then
return i, j
end
end
end
end
print(exitable())

View file

@ -0,0 +1,14 @@
Module Checkit {
Dim A(10,10)<<Random(1, 20)
For k=1 to 2 {
For i=0 to 9 {
For j=0 to 9 {
Print A(i,j)
if A(i,j)=20 then goto there
}
}
there:
Print "...ok", k
}
}
Checkit

View file

@ -0,0 +1,2 @@
a = ceil(rand(100,100)*20);
[ix,iy]=find(a==20,1)

View file

@ -0,0 +1,11 @@
fn scan_Nested arr =
(
for subArray in arr where classof subArray == Array do
(
for item in subArray do
(
print item as string
if item == 20 do return OK
)
)
)

View file

@ -0,0 +1,11 @@
testArray = #(#(1,5,2,19),#(11,20,7,2))
scan_nested testArray
#(#(1, 5, 2, 19), #(11, 20, 7, 2))
1
5
2
19
11
20
OK

View file

@ -0,0 +1,18 @@
a = make(10, make(10));
for i in [1..10]
for j in [1..10]
a[i][j] = random(20);
endfor
endfor
for i in [1..10]
s = "";
for j in [1..10]
s += tostr(" ", a[i][j]);
if (a[i][j] == 20)
break i;
endif
endfor
player:tell(s);
s = "";
endfor
player:tell(s);

View file

@ -0,0 +1,13 @@
NESTLOOP
;.../loops/nested
;set up the 2D array with random values
NEW A,I,J,K,FLAG,TRIGGER
SET K=15 ;Magic - just to give us a size to work with
SET TRIGGER=20 ;Magic - the max value, and the end value
FOR I=1:1:K FOR J=1:1:K SET A(I,J)=$RANDOM(TRIGGER)+1
;Now, search through the array, halting when the value of TRIGGER is found
SET FLAG=0
SET (I,J)=0
FOR I=1:1:K Q:FLAG W ! FOR J=1:1:K WRITE A(I,J),$SELECT(J'=K:", ",1:"") SET FLAG=(A(I,J)=TRIGGER) Q:FLAG
KILL A,I,J,K,FLAG,TRIGGER
QUIT

View file

@ -0,0 +1,9 @@
(m,n) := LinearAlgebra:-Dimensions(M):
for i from 1 to m do
for j from 1 to n do
print(M[i,j]);
if M[i,j] = 20 then
(i,j):=m,n; next;
end if;
end do;
end do:

View file

@ -0,0 +1,4 @@
Do[ Print[m[[i, j]]];
If[m[[i, j]] === 20, Return[]],
{i, 1, Dimensions[m][[1]]},
{j, 1, Dimensions[m][[2]]}]

View file

@ -0,0 +1,15 @@
data: apply(matrix, makelist(makelist(random(100), 20), 20))$
find_value(a, x) := block(
[p, q],
[p, q]: matrix_size(a),
catch(
for i thru p do
for j thru q do
if a[i, j] = x then throw([i, j]),
'not\ found
)
)$
find_value(data, 100);
not found

View file

@ -0,0 +1,14 @@
For row = 0 To 10
For col = 0 To 10
array[row][col] = Math.GetRandomNumber(20)
EndFor
EndFor
For row = 0 To 10
For col = 0 To 10
TextWindow.WriteLine("row "+row+" col "+col+" value "+array[row][col])
If array[row][col] = 20 Then
Goto exit_for_row
EndIf
EndFor
EndFor
exit_for_row:

View file

@ -0,0 +1,14 @@
10 DIM A(20)
20 FOR I=1 TO 20
30 A(I)=RND(20)+1
40 NEXT
50 PRINT "THE FULL LIST:";
60 FOR I=1 TO 20
70 PRINT A(I);
80 NEXT
90 PRINT
100 PRINT "THE FULL LIST UP TO THE FIRST ";"INSTANCE OF 20:";
110 FOR I=1 TO 20
120 PRINT A(I);
130 IF A(I)=20 THEN END
140 NEXT

View file

@ -0,0 +1,43 @@
/**
Loops/Nested in Neko
Tectonics:
nekoc loops-nested.neko
neko loops-nested.neko
*/
var random = $loader.loadprim("std@random_new", 0)();
var random_int = $loader.loadprim("std@random_int", 2);
var values = $amake(10);
var row = 0;
var col = 0;
while row < 10 {
values[row] = $amake(10);
col = 0;
while col < 10 {
values[row][col] = random_int(random, 20) + 1;
col += 1;
}
row += 1;
}
/* Look for a 20 */
/*
To break out of nested loops, (without using labels and $goto),
Neko needs the value of the inner loop(s).
The break statement sets the return value of a loop expression.
Without a break, the value of a loop expression is unspecified.
*/
var inner;
row = 0;
while row < 10 {
col = 0;
inner = while col < 10 {
$print("values[", row, "][", col, "] = ", values[row][col], "\n");
if values[row][col] == 20 break true;
col += 1;
}
if $istrue(inner) break;
row += 1;
}

View file

@ -0,0 +1,24 @@
using System;
using System.Console;
using Nemerle.Imperative;
module NestedLoops
{
Main() : void
{
def arr = array(10, 10);
def rnd = Random();
foreach ((i, j) in $[(i, j) | i in [0 .. 9], j in [0 .. 9]])
arr[i, j] = rnd.Next(1, 21);
Finish:
{
foreach ((i, j) in $[(i, j) | i in [0 .. 9], j in [0 .. 9]])
{
Write("{0} ", arr[i, j]);
when (arr[i, j] == 20) Finish();
}
}
}
}

View file

@ -0,0 +1,28 @@
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/Nested'
rnd = Random()
dim2 = int[10, 10]
-- build sample data
loop i1 = 0 for dim2.length
loop i2 = 0 for dim2[i1].length
dim2[i1, i2] = rnd.nextInt(20) + 1
end i2
end i1
-- run test
loop x1 = 0 for dim2.length
say Rexx(x1 + 1).right(4)': \-'
loop x2 = 0 for dim2[x1].length
say Rexx(dim2[x1, x2]).right(3) || '\-'
if dim2[x1, x2] = 20 then leave x1
finally
say
end x2
finally
say
end x1

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