Movatterモバイル変換


[0]ホーム

URL:


Jump to content
Rosetta Code
Search

Loops/Break

From Rosetta Code
<Loops
Task
Loops/Break
You are encouraged tosolve this task according to the task description, using any language you may know.
Task

Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).

If a number is 10, stop the loop after printing it, and do not generate any further numbers.

Otherwise, generate and print a second random number before restarting the loop.

If the number 10 is never generated as the first number in a loop, loop forever.


Related tasks



11l

Translation of:Python
L   V a = random:(20)   print(a)   I a == 10      L.break   V b = random:(20)   print(b)

360 Assembly

*        Loops Break               15/02/2017LOOPBREA CSECT         USING  LOOPBREA,R13       base register         B      72(R15)            skip savearea         DC     17F'0'             savearea         STM    R14,R12,12(R13)    prolog         ST     R13,4(R15)         " <-         ST     R15,8(R13)         " ->         LR     R13,R15            " addressabilityLOOP     MVC    PG,=CL80' '        clean buffer         LA     R8,PG              ipg=0         BAL    R14,RANDINT        call randint         C      R6,=F'10'          if k=10 then leave         BE     ENDLOOP             <-- loop break         BAL    R14,RANDINT        call randint         XPRNT  PG,L'PG            print buffer         B      LOOP               loop foreverENDLOOP  XPRNT  PG,L'PG            print buffer         L      R13,4(0,R13)       epilog          LM     R14,R12,12(R13)    " restore         XR     R15,R15            " rc=0         BR     R14                exitRANDINT  L      R5,RANDSEED        randint         M      R4,=F'397204091'   "         D      R4,=X'7FFFFFFF'    "         ST     R4,RANDSEED        "         LR     R5,R4              "         SR     R4,R4              "         D      R4,=F'20'          "         LR     R6,R4              k=randint(20)         XDECO  R6,XDEC            edit k         MVC    0(4,R8),XDEC+8     output k         LA     R8,4(R8)           ipg=ipg+4         BR     R14                returnRANDSEED DC     F'39710831'        seedPG       DS     CL80               bufferXDEC     DS     CL12         YREGS         END    LOOPBREA
Output:
   2   3   9  10  14   5  18  16   5   0   1   3   7  17  19   8  17  12  10

6502 Assembly

Code is called as a subroutine (i.e. JSR LoopBreakSub). Specific OS/hardware routines for generating random numbers and printing are left unimplemented.

LoopBreakSub:PHA;push accumulator onto stackBreakLoop:JSR GenerateRandomNum;routine not implemented;generates random number and puts in memory location RandomNumberLDA RandomNumberJSR DisplayAccumulator;routine not implementedCMP #10BEQ BreakJSR GenerateRandomNumLDA RandomNumberJSR DisplayAccumulatorJMP BreakLoopBreak:PLA;restore accumulator from stackRTS;return from subroutine

AArch64 Assembly

Works with:as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B *//*  program loopbreak64.s   */ /*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc"/*********************************//* Initialized data              *//*********************************/.dataszMessEndLoop: .asciz "loop break with value : \n"szMessResult:  .asciz "Resultat = @ \n"      // message result.align 4qGraine:  .quad 12345678/*********************************//* UnInitialized data            *//*********************************/.bss sZoneConv:               .skip 24/*********************************//*  code section                 *//*********************************/.text.global main main:                          // entry of program 1:                             // begin loop     mov x4,202:    mov x0,19    bl genereraleas            // generate number    cmp x0,10                  // compar value    beq 3f                     // break if equal    ldr x1,qAdrsZoneConv       // display value    bl conversion10            // call function with 2 parameter (x0,x1)    ldr x0,qAdrszMessResult    ldr x1,qAdrsZoneConv    bl strInsertAtCharInc      // insert result at third @ character    bl affichageMess           // display message final    subs x4,x4,1                 // decrement counter    bgt 2b                     // loop if greather    b 1b                       // begin loop one 3:    mov x2,x0                  // save value    ldr x0,qAdrszMessEndLoop    bl affichageMess           // display message    mov x0,x2    ldr x1,qAdrsZoneConv                    bl conversion10            // call function with 2 parameter (x0,x1)    ldr x0,qAdrszMessResult    ldr x1,qAdrsZoneConv    bl strInsertAtCharInc      // insert result at third @ character    bl affichageMess           // display message 100:                           // standard end of the program     mov x0,0                   // return code    mov x8,EXIT                // request to exit program    svc 0                      // perform the system call qAdrsZoneConv:            .quad sZoneConvqAdrszMessResult:         .quad szMessResultqAdrszMessEndLoop:        .quad szMessEndLoop /***************************************************//*   Generation random number                  *//***************************************************//* x0 contains limit  */genereraleas:    stp x1,lr,[sp,-16]!    // save  registers    stp x2,x3,[sp,-16]!    // save  registers    ldr x3,qAdrqGraine     // load graine    ldr x2,[x3]    lsr x1,x2,17           // see xorshift on wikipedia    eor x2,x2,x1    lsl x1,x2,31    eor x2,x2,x1    lsr x1,x2,8    eor x1,x2,x1    str x1,[x3]            // save graine for the next call     udiv x1,x2,x0          // divide by value maxi    msub x0,x1,x0,x2       // résult = remainder100:                       // end function    ldp x2,x3,[sp],16      // restaur  2 registers    ldp x1,lr,[sp],16      // restaur  2 registers    ret                    // return to address lr x30/********************************************************************/qAdrqGraine: .quad qGraine/********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"
Output:
Resultat = 1Resultat = 8Resultat = 11Resultat = 11Resultat = 5Resultat = 3Resultat = 5Resultat = 12Resultat = 18Resultat = 14loop break with value :Resultat = 10

Action!

PROC Main()  BYTE v  PrintE("Before loop")  DO    v=Rand(20)    PrintBE(v)    IF v=10 THEN      EXIT    FI  OD  PrintE("After loop")RETURN
Output:

Screenshot from Atari 8-bit computer

Before loop2634111751710After loop

Ada

withAda.Text_IO;useAda.Text_IO;withAda.Numerics.Discrete_Random;procedureTest_Loop_BreakistypeValue_Typeisrange0..19;packageRandom_Valuesis newAda.Numerics.Discrete_Random(Value_Type);useRandom_Values;Dice:Generator;A,B:Value_Type;beginloopA:=Random(Dice);Put_Line(Value_Type'Image(A));exitwhenA=10;B:=Random(Dice);Put_Line(Value_Type'Image(B));endloop;endTest_Loop_Break;

Aime

integermain(void){    integer a, b;    while (1) {        a = drand(19);        o_integer(a);        o_byte('\n');        if (a == 10) {            break;        }        b = drand(19);        o_integer(b);        o_byte('\n');    }    return 0;}

ALGOL 60

Works with:ALGOL 60 version OS/360
'BEGIN' 'COMMENT' Loops/Break - ALGOL60 - 18/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' I,J,K;  SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print;  SEED:=31567;  J:=0;  'FOR' I:=1, I+1 'WHILE' I 'LESS' 100 'DO' 'BEGIN'    J:=J+1;    K:=RANDOM(20);    OUTINTEGER(1,K);    'IF' J=8 'THEN' 'BEGIN'       SYSACT(1,14,1);  'COMMENT' skip line;       J:=0    'END';    'IF' K=10 'THEN' 'GOTO' LAB  'END';LAB:  SYSACT(1,14,1);  'COMMENT' skip line;'END'
Output:
        +17           +4          +20           +3          +16           +5           +1          +17          +11           +2          +12           +5           +7           +6          +10

ALGOL 68

Translation of:C – Note: This specimen retains the original C coding style.
#main#(    WHILE        INT a = ENTIER (random * 20);        print((a));        a /= 10    DO        print((ENTIER (random * 20), new line))    OD;    print(new line))
Output:
         +1        +19        +17         +9         +4        +19         +2         +2        +19         +7        +18        +19        +18        +12         +6        +19        +18         +0         +9         +7         +1         +3        +14         +5        +14         +7        +16        +18         +9         +6         +7        +18         +9         +2         +2        +16        +11         +2         +6         +7        +19         +8        +11        +18         +9         +6        +12         +9        +13        +10        +18        +15         +0        +18         +4        +10         +6        +16        +17        +19        +19         +8         +0        +17         +7         +3         +0        +14        +11         +2        +18         +3        +16        +19         +0        +19         +7        +13         +7         +4         +5        +19         +0         +4         +2         +7         +3        +15        +12        +18        +16        +12        +19         +1        +17        +13         +2        +10        +17        +12        +19        +14         +6        +17         +5         +2         +4         +3         +5        +15        +18        +18         +8        +13         +4         +8         +2         +9        +12         +1        +12         +4         +8        +11         +4        +14        +14        +12        +17        +14         +0        +17        +18        +11        +12         +2        +14         +0         +9         +1         +2        +14        +10

Amazing Hopper

Flavour "Jambo"

#include<jambo.h>MainLoopBreakif'Intrand(20)---show---Isequalto(10)'Printnl("--",Intrand(20))BackPrint'"\nEnd of Loop\n"'End

Assembler Hopper version of this program:

main:____CODE_JUMP____997416047:,;{20};rand;int;show;eqto(10);jt(____CODE_JUMP____803885359){"--"};{20};rand;int;{"\n"}print;,jmp(____CODE_JUMP____997416047),____CODE_JUMP____803885359:,{"\nEnd of Loop\n"};print;emptystack?do{{0}};return
Output:
xxxx@debian:~/Proy$ hopper3 jm/rand.jambo11--194--41--90--1319--1812--610End of Loopxxxx@debian:~/Proy$ hopper3 jm/rand.jambo19--1010End of Loopxxxx@debian:~/Proy$ hopper3 jm/rand.jambo10 End of Loopxxxx@debian:~/Proy$ hopper3 jm/rand.jambo0--147--118--1115--1517--97--110End of Loopxxxx@debian:~/Proy$ hopper3 jm/rand.jambo13--017--1216--219--142--619--1010End of Loopxxxx@debian:~/Proy$

AppleScript

repeatsetatorandom numberfrom0to19ifais10thenlogaexitrepeatendifsetbtorandom numberfrom0to19loga&bendrepeat


Output:
(*12, 6*)(*7, 8*)(*17, 4*)(*7, 2*)(*0, 5*)(*6, 3*)(*5, 5*)(*3, 14*)(*7, 7*)(*3, 11*)(*5, 16*)(*18, 2*)(*5, 2*)(*15, 17*)(*16, 10*)(*4, 18*)(*8, 5*)(*4, 15*)(*11, 14*)(*7, 2*)(*1, 7*)(*7, 7*)(*4, 9*)(*12, 17*)(*8, 16*)(*9, 1*)(*16, 15*)(*8, 2*)(*9, 6*)(*13, 6*)(*17, 0*)(*17, 18*)(*4, 7*)(*8, 10*)(*11, 0*)(*14, 17*)(*9, 8*)(*2, 17*)(*1, 5*)(*4, 5*)(*5, 2*)(*10*)

Arc

(point break  (while t    (let x (rand 20)      (prn "a: " x)      (if (is x 10)        (break)))    (prn "b: " (rand 20))))

ARM Assembly

Works with:as version Raspberry Pi
/* ARM assembly Raspberry PI  *//*  program loopbreak.s   *//* Constantes    */.equ STDOUT, 1     @ Linux output console.equ EXIT,   1     @ Linux syscall.equ WRITE,  4     @ Linux syscall/*********************************//* Initialized data              *//*********************************/.dataszMessEndLoop: .asciz "loop break with value : \n"szMessResult:  .ascii "Resultat = "      @ message resultsMessValeur:   .fill 12, 1, ' '                   .asciz "\n".align 4iGraine:  .int 123456/*********************************//* UnInitialized data            *//*********************************/.bss /*********************************//*  code section                 *//*********************************/.text.global main main:                @ entry of program     push {fp,lr}      @ saves 2 registers 1:    @ begin loop     mov r4,#202:    mov r0,#19    bl genereraleas               @ generate number    cmp r0,#10                       @ compar value    beq 3f                         @ break if equal    ldr r1,iAdrsMessValeur     @ display value    bl conversion10             @ call function with 2 parameter (r0,r1)    ldr r0,iAdrszMessResult    bl affichageMess            @ display message    subs r4,#1                   @ decrement counter    bgt 2b                      @ loop if greather    b 1b                          @ begin loop one3:    mov r2,r0             @ save value    ldr r0,iAdrszMessEndLoop    bl affichageMess            @ display message    mov r0,r2    ldr r1,iAdrsMessValeur                    bl conversion10       @ call function with 2 parameter (r0,r1)    ldr r0,iAdrszMessResult    bl affichageMess            @ display message100:   @ standard end of the program     mov r0, #0                  @ return code    pop {fp,lr}                 @restaur 2 registers    mov r7, #EXIT              @ request to exit program    svc #0                       @ perform the system calliAdrsMessValeur:          .int sMessValeuriAdrszMessResult:         .int szMessResultiAdrszMessEndLoop:        .int szMessEndLoop/******************************************************************//*     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                                 */ /******************************************************************//* r0 contains value and r1 address area   */conversion10:    push {r1-r4,lr}    @ save registers     mov r3,r1    mov r2,#101:   @ start loop    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1    add r1,#48        @ digit    strb r1,[r3,r2]  @ store digit on area    sub r2,#1         @ previous position    cmp r0,#0         @ stop if quotient = 0 */    bne 1b          @ else loop    @ and move spaces in first on area    mov r1,#' '   @ space2:    strb r1,[r3,r2]  @ store space in area    subs r2,#1       @ @ previous position    bge 2b           @ loop if r2 >= zéro 100:    pop {r1-r4,lr}    @ restaur registres     bx lr          @return/***************************************************//*   division par 10   signé                       *//* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*  /* and   http://www.hackersdelight.org/            *//***************************************************//* r0 dividende   *//* r0 quotient *//* r1 remainder  */divisionpar10:  /* r0 contains the argument to be divided by 10 */    push {r2-r4}   /* save registers  */    mov r4,r0     mov r3,#0x6667   @ r3 <- magic_number  lower    movt r3,#0x6666  @ r3 <- magic_number  upper    smull r1, r2, r3, r0   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)     mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */    mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */    add r0, r2, r1         /* r0 <- r2 + r1 */    add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */    sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */    pop {r2-r4}    bx lr                  /* leave function *//***************************************************//*   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     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 iGraineiNbDep1: .int 0x343FDiNbDep2: .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 2f1:          @ 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

Arturo

whileø[a:random019prints[a""]ifa=10->breakb:random019printb]print""
Output:
11  111  1619  1417  018  119  91  155  51  167  1010

AutoHotkey

Loop{Random,var,0,19output=%output%`n%var%If(var=10)BreakRandom,var,0,19output=%output%`n%var%}MsgBox%output

Avail

rng ::= a pRNG;checked : [0..19];Do [    checked : = rng's next [0..19];    Print: “checked”;] while checked ≠ 10 alternate with [    Print: " " ++ “rng's next [0..19]” ++ "\n";];

This demonstrates two interesting Avail features: thealternate with loop structures, which provide two separate code blocks that are run with a check in between, and the random number generator's ability to pick an item from the ranger of a given number type ([0..19] is an expression generating atype whose values are integers in the range 0-19 inclusive).

AWK

BEGIN{srand()# randomize the RNGfor(;;){printn=int(rand()*20)if(n==10)breakprintint(rand()*20)}}

Axe

Because Axe only supports breaking out of loops as end conditions, the behavior must be simulated using a return statement. Note, however, that this will exit the current call context, not the necessarily just the current loop.

While 1 rand^20→A Disp A▶Dec ReturnIf A=10 rand^20→B Disp B▶Dec,iEnd

Ballerina

importballerina/io;importballerina/random;publicfunctionmain()returnserror?{whiletrue{intn=checkrandom:createIntInRange(0,20);io:println(n);ifn==10{break;}n=checkrandom:createIntInRange(0,20);io:println(n);}}
Output:

Sample run:

01131210

BASIC

Applesoft BASIC

FORI=0TO1STEP0:N=INT(RND(1)*20):PRINT" "N;:IFN<>10THEN?","INT(RND(1)*20);:NEXT

BaCon

REPEATnumber=RANDOM(20)PRINT"first  ",numberIFnumber=10THENBREAKENDIFPRINT"second  ",RANDOM(20)UNTILFALSE

BASIC256

doi = int(rand * 19)print i; "  ";if i = 10 then exit doi = int(rand * 19)print i; "  ";until falseprintend

bootBASIC

In bootBASIC, the rnd statement returns an unsigned integer between 0 and 255. 255 divided by 19 gives us 13 without the fraction part, so 13 is the number to divide the random number by to get a range of 0 to 19. All division is integer division.

10a=rnd/1320printa;30ifa-10goto5040goto10050a=rnd/1355print", ";60printa70goto10100print
Output:
13, 19                                                                          11, 14                                                                          18, 4                                                                           17, 0                                                                           12, 15                                                                          0, 13                                                                           7, 19                                                                           2, 7                                                                            1, 3                                                                            6, 18                                                                           13, 6                                                                           9, 10                                                                           4, 7                                                                            15, 7                                                                           10

Commodore BASIC

In Commodore BASIC, the function RND() generates a floating point number from 0.0 to 1.0 (exclusive).

10 X = RND(-TI) : REM SEED RN GENERATOR20 A = INT(RND(1)*20)30 PRINT A40 IF A = 10 THEN 8050 B = INT(RND(1)*20)60 PRINT B70 GOTO 2080 END

IS-BASIC

100 RANDOMIZE 110 DO120   LET A=RND(20)+1130   PRINT A,140   IF A=10 THEN EXIT DO150   PRINT RND(20)+1160 LOOP

QuickBASIC

Works with:QuickBasic version 4.5
doa=int(rnd*20)printaifa=10thenexitloop'EXIT FOR works the same inside FOR loopsb=int(rnd*20)printbloop

SmallBASIC

randomize' Initialize random number generatorrepeati=round(rnd*19)printi;if(i==10)thenexiti=round(rnd*19)print", ";iuntilfalse

True BASIC

RANDOMIZEDOLETi=INT(RND*19)PRINTi;"  ";IFi=10THENEXITDOENDIFLETi=INT(RND*19)PRINTi;"  ";LOOPPRINTEND


uBasic/4tH

In uBasic/4tHUNTIL<cond> is equivalent toIF<cond>THEN BREAK. You can add as manyUNTIL andWHILE as required inFOR..NEXT orDO..LOOP loops.

Don=Rnd(20)PrintnUntiln=10PrintRnd(20)Loop

ZX Spectrum Basic

On the ZX Spectrum, for loops must be terminated through the NEXT statement, otherwise a memory leak will occur. To terminate a loop prematurely, set the loop counter to the last iterative value and jump to the NEXT statement:

10FORl=1TO2020IFl=10THENLETl=20:GOTO40:REMterminatetheloop30PRINTl40NEXTl50STOP

The correct solution:

10LETa=INT(RND*20)20PRINTa30IFa=10THENSTOP40PRINTINT(RND*20)50GOTO10

Batch File

@echo off:loopset/aN=%RANDOM% %%20echo%N%if%N%==10exit /bset/aN=%RANDOM% %%20echo%N%gotoloop

BBC BASIC

Works with:BBC BASIC for Windows
REPEATnum%=RND(20)-1PRINTnum%IFnum%=10THENEXITREPEATPRINTRND(20)-1UNTILFALSE

bc

s=1/* seed of the random number generator */scale=0/* Random number from 0 to 20. */define r(){auto awhile(1){/* Formula (from POSIX) for random numbers of low quality. */s=(s*1103515245+12345)%4294967296a= s/65536/* a in [0, 65536) */if(a>=16)break/* want a >= 65536 % 20 */}return(a%20)}while(1){n= r()n/* print 1st number */if(n==10)breakr()/* print 2nd number */}quit

Befunge

>60v*2\<>?>\1-:|1+$>^7v.:%++67<>55+-#v_@>60v*2\<>?>\1-:|1+$>^7^.%++67<

C

intmain(){time_tt;inta,b;srand((unsigned)time(&t));for(;;){a=rand()%20;printf("%d\n",a);if(a==10)break;b=rand()%20;printf("%d\n",b);}return0;}

Output (example):

121828101899410

C#

classProgram{staticvoidMain(string[]args){Randomrandom=newRandom();while(true){inta=random.Next(20);Console.WriteLine(a);if(a==10)break;intb=random.Next(20)Console.WriteLine(b);}Console.ReadLine();}}

C++

#include<iostream>#include<ctime>#include<cstdlib>intmain(){srand(time(NULL));// randomize seedwhile(true){constinta=rand()%20;// biased towards lower numbers if RANDMAX % 20 > 0std::cout<<a<<std::endl;if(a==10)break;constintb=rand()%20;std::cout<<b<<std::endl;}return0;}

Chapel

useRandom;varr=newRandomStream();whiletrue{vara=floor(r.getNext()*20):int;writeln(a);ifa==10thenbreak;varb=floor(r.getNext()*20):int;writeln(b);}deleter;

Chef

"Liquify" is now depreciated in favor of "Liquefy", but my interpreter/compiler (Acme::Chef) works only with "Liquify" so that's how I'm leaving it. At least it'll work no matter which version you use.

Healthy Vita-Sauce Loop - Broken.Makes a whole lot of sauce for two people.Ingredients.0 g Vitamin A1 g Vitamin B2 g Vitamin C3 g Vitamin D4 g Vitamin E5 g Vitamin F6 g Vitamin G7 g Vitamin H8 g Vitamin I9 g Vitamin J10 g Vitamin K11 g Vitamin L12 g Vitamin M13 g Vitamin N14 g Vitamin O15 g Vitamin P16 g Vitamin Q17 g Vitamin R18 g Vitamin S19 g Vitamin T20 g Vitamin U21 g Vitamin V22 g Vitamin W32 g Vitamin X24 g Vitamin Y25 g Vitamin ZMethod.Liquify Vitamin X.Put Vitamin N into 1st mixing bowl.Fold Vitamin Y into 1st mixing bowl.Liquify Vitamin Y.Clean 1st mixing bowl.Put Vitamin K into 1st mixing bowl.Fold Vitamin Z into 1st mixing bowl.Liquify Vitamin Z.Clean 1st mixing bowl.Put Vitamin Y into 4th mixing bowl.Put Vitamin Z into 4th mixing bowl.Pour contents of the 4th mixing bowl into the 2nd baking dish.Put Vitamin A into 2nd mixing bowl. Put Vitamin B into 2nd mixing bowl. Put Vitamin C into 2nd mixing bowl. Put Vitamin D into 2nd mixing bowl. Put Vitamin E into 2nd mixing bowl. Put Vitamin F into 2nd mixing bowl. Put Vitamin G into 2nd mixing bowl. Put Vitamin H into 2nd mixing bowl. Put Vitamin I into 2nd mixing bowl. Put Vitamin J into 2nd mixing bowl. Put Vitamin K into 2nd mixing bowl. Put Vitamin L into 2nd mixing bowl. Put Vitamin M into 2nd mixing bowl. Put Vitamin N into 2nd mixing bowl. Put Vitamin O into 2nd mixing bowl. Put Vitamin P into 2nd mixing bowl. Put Vitamin Q into 2nd mixing bowl. Put Vitamin R into 2nd mixing bowl. Put Vitamin S into 2nd mixing bowl. Put Vitamin T into 2nd mixing bowl.Verb the Vitamin V.Mix the 2nd mixing bowl well.Fold Vitamin U into 2nd mixing bowl.Put Vitamin U into 3rd mixing bowl.Remove Vitamin K from 3rd mixing bowl.Fold Vitamin V into 3rd mixing bowl.Put Vitamin X into 1st mixing bowl.Put Vitamin V into 1st mixing bowl.Verb until verbed.Pour contents of the 1st mixing bowl into the 1st baking dish.Serves 2.

Clojure

(loop[[ab&more](repeatedly#(rand-int20))](printlna)(when-not(=10a)(printlnb)(recurmore)))

COBOL

Works with:OpenCOBOL
IDENTIFICATIONDIVISION.PROGRAM-ID.Random-Nums.DATADIVISION.WORKING-STORAGESECTION.01NumPIC Z9.PROCEDUREDIVISION.Main.PERFORMFOREVERPERFORMGenerate-And-Display-NumIFNum=10EXITPERFORMELSEPERFORMGenerate-And-Display-NumEND-IFEND-PERFORMGOBACK.Generate-And-Display-Num.COMPUTENum=FUNCTIONREM(FUNCTIONRANDOM*100,20)DISPLAYNum.

CoffeeScript

We can use print from the Rhino JavaScript shell as in the JavaScript example or console.log, with a result like this:

loopprinta=Math.random()*20//1breakifa==10printMath.random()*20//1

ColdFusion

<CfsetrandNum=0><cfloopcondition="randNum neq 10"><CfsetrandNum=RandRange(0,19)><Cfoutput>#randNum#</Cfoutput><CfifrandNumeq10><cfbreak></Cfif><Cfoutput>#RandRange(0, 19)#</Cfoutput><Br></cfloop>
Output:

My first two test outputs (I swear this is true)

6 0 9 6 12 3 6 0 14 10 19 12 18 14 19 8 3 2 19 1 11 12 16 9 11 15 3 19 13 8 6 4 4 4 13 17 16 9 5 12 12 6 4 14 1 10 3 7 11 15 11 8 0 16 16 14 8 14 11 10 8 8 16 11 4 7 19 10 8 2 15 11 18 10 1 2 18 9 4 9 6 6 11 8 14 6 17 15 13 2 2 0 2 17 8 17 18 13 11 5 15 18 17 8 15 3 7 17 7 13 15 14 11 9 10
10

Common Lisp

(loopfora=(random20)do(printa)until(=a10)do(print(random20)))

Using DO

(do((a(random20)(random20))); Initialize to rand and set new rand on every loop((=a10)(writea)); Break condition and last step(formatt"~a~3T~a~%"a(random20))); On every loop print formated `a' and rand `b'
Output:
19 78  1617 1019 127  165  1916 18  83  183  53  39  71  151  1014 102  413 610

D

importstd.stdio,std.random;voidmain(){while(true){intr=uniform(0,20);write(r," ");if(r==10)break;write(uniform(0,20)," ");}}
Output:
2 4 9 5 3 7 4 4 14 14 3 7 13 8 13 6 10

Dart

var seed_ = DateTime.now().microsecondsSinceEpoch;next() => seed_ = (17 * seed_ + 1) % 65521;void main() {    while(true) {        var a = next()%20;        print(a);        if(a == 10) break;        print(next()%20);    }}

dc

Translation of:bc
1 ss  [s = seed of the random number generator]sz0k    [scale = 0]sz[Function r: Push a random number from 0 to 20.]sz[ [2Q]SA [  [Formula (from POSIX) for random numbers of low quality.]sz  ls 1103515245 * 12345 + 4294967296 % d ss  [Compute next s]sz  65536 /     [it = s / 65536]sz  d 16 !>A    [Break loop if 16 <= it]sz  sz 0 0 =B   [Forget it, continue loop]sz ]SB 0 0 =B 20 %         [Push it % 20]sz LA sz LB sz  [Restore A, B]sz]sr[2Q]sA[ 0 0 =r p     [Print 1st number.]sz 10 =A        [Break if 10 == it.]sz 0 0 =r p sz  [Print 2nd number.]sz 0 0 =B       [Continue loop.]sz]sB 0 0 =B

Delphi

programProject5;{$APPTYPE CONSOLE}varnum:Integer;beginRandomize;whiletruedobeginnum:=Random(20);Writeln(num);ifnum=10thenbreak;end;end.

DuckDB

Works with:DuckDB version V1.0
#PRNinrange(0,n)createorreplacefunctionprn(n)astrunc(random()*n)::BIGINT;#Printnumbersinrange(0,n)asperthetaskdescriptioncreateorreplacefunctiontask(n)astable(withrecursivecteas(selectprn(n)asrand,falseasstopunionallselectprn(n)asrand,rand=10asstopfromctewherestop!=true)selectrandfromctewherestop=false);.printAsamplerun:fromtask(20);.printAlikelyshorterone:fromtask(11);
Output:
A sample run:┌───────┐│ rand  ││ int64 │├───────┤│     1 ││    19 ││     8 ││    13 ││    19 ││    13 ││     0 ││     1 ││    11 ││    14 ││    18 ││    18 ││     4 ││     5 ││    17 ││     1 ││    12 ││    11 ││    15 ││    10 │└───────┘A likely shorter one:┌───────┐│ rand  ││ int64 │├───────┤│     6 ││     0 ││     3 ││     1 ││     0 ││     0 ││     8 ││     7 ││    10 │└───────┘

DWScript

whileTruedobeginvarnum:=RandomInt(20);PrintLn(num);ifnum=10thenBreak;end;

E

while (true) {    def a := entropy.nextInt(20)    print(a)    if (a == 10) {        println()        break    }    println(" ", entropy.nextInt(20))}

EasyLang

repeat   a = random 20 - 1   print a   until a = 10   print random 20 - 1.

Eiffel

example-- Eiffel example codelocaln:INTEGERr:RANDOMIZERdofromcreatern:=r.random_integer_in_range(0|..|19)untiln=10loopn:=r.random_integer_in_range(0|..|19)endend
Output:

The output is superfluous and unneeded to read and understand what the Eiffel code is doing.The test code is sufficient to prove that it works.Uses randomizer library located at:https://github.com/ljr1981/randomizer

Ela

This implementation uses .NET Framework Math.Randomize function. Current ticks multiplied by an iteration index are used as a seed. As a result, an output looks almost truly random:

open datetime random monad io loop = loop' 1       where loop' n t = do                dt <- datetime.now                seed <- return <| toInt <| (ticks <| dt) * n                r <- return $ rnd seed 0 19                putStrLn (show r)                if r <> t then loop' (n + 1) t else return ()loop 10 ::: IO

Elixir

Works with:Elixir version 1.2
defmoduleLoopsdodefbreak,do:break(random)defpbreak(10),do:IO.puts10defpbreak(r)doIO.puts"#{r},\t#{random}"break(random)enddefprandom,do:Enum.random(0..19)endLoops.break
Output:
13,     712,     72,      163,      1917,     105,      1714,     07,      65,      195,      124,      28,      141,      1713,     510

Emacs Lisp

(defunwait_10()(catch'loop-break(while't(let((math(random19)))(if(=math10)(progn(message"Found value: %d"math)(throw'loop-breakmath))(message"current number is: %d"math))))))(wait_10)

EMal

for ever  int a = random(20)  write(a)  if a == 10 do break end  writeLine("," + random(20))endwriteLine()
Output:
19,1410

Erlang

%% Implemented by Arjun Sunel-module(forever).-export([main/0,for/0]).main()->for().for()->K=random:uniform(19),io:fwrite("~p ",[K]),ifK==10->ok;true->M=random:uniform(19),io:format("~p~n",[M]),for()end.

ERRE

LOOP    A=INT(RND(1)*20)    PRINT(A)    IF A=10 THEN EXIT LOOP END IF !EXIT FOR works the same inside FOR loops    PRINT(INT(RND(1)*20))END LOOP

TheRND(X) function returns a random integer from 0 to 1. X is a dummy argument.

Euphoria

integer iwhile 1 do    i = rand(20) - 1    printf(1, "%g ", {i})    if i = 10 then        exit    end if    printf(1, "%g ", {rand(20)-1})end while

Therand() function returns a random integer from 1 to the integer provided.

F#

// Loops/Break. Nigel Galloway: February 21st., 2022letn=System.Random()letrecfNg=printf"%d "g;ifg<>10thenfN(n.Next(20))fN(n.Next(20))

Factor

Usingwith-return:

[[20random[.][10=[return]when]bi20random.t]loop]with-return

Idiomatic Factor:

[20random[.][10=not]bidup[20random.]when]loop

Fantom

class ForBreak{  public static Void main ()  {    while (true)    {      a := Int.random(0..19)      echo (a)      if (a == 10) break      echo (Int.random(0..19))    }  }}

Forth

includerandom.fs:mainbegin20randomdup.10<>while20random.repeat;\ use LEAVE to break out of a counted loop:main1000doirandomdup.10=ifleavethenirandom.loop;

Fortran

Works with:Fortran version 90 and later
programExampleimplicit nonereal::rinteger::a,bdo     callrandom_number(r)a=int(r*20)write(*,*)aif(a==10)exit     callrandom_number(r)b=int(r*20)write(*,*)bend doend programExample
Works with:Fortran version 77 and later
PROGRAMLOOPBREAKINTEGERI,RNDINTCItdoesn'tmatterwhatnumberyouputhere.CALLSDRAND(123)CBecauseFORTRAN77semanticallylacksmanyloopstructures,weChavetouse GOTOstatementstodothesamething.10CONTINUECPrintarandomnumber.I=RNDINT(0,19)WRITE(*,*)ICIftherandomnumberisten,break(i.e.skiptoaftertheendCofthe"loop").IF(I.EQ.10)GOTO20COtherwise,printasecondrandomnumber.I=RNDINT(0,19)WRITE(*,*)ICThisistheendofour"loop,"meaningwejumpbacktotheCbeginningagain.GOTO1020CONTINUE        STOP      ENDCFORTRAN77doesnotcomewitharandomnumbergenerator,butitCiseasyenoughtotype"fortran 77 random number generator"intoyourCpreferredsearchengineandtocopyandpastewhatyoufind.TheCfollowingcodeisaslightly-modifiedversionof:CChttp://www.tat.physik.uni-tuebingen.de/C~kley/lehre/ftn77/tutorial/subprograms.htmlSUBROUTINESDRAND(IRSEED)COMMON/SEED/UTSEED,IRFRSTUTSEED=IRSEEDIRFRST=0RETURN      ENDINTEGERFUNCTIONRNDINT(IFROM,ITO)INTEGERIFROM,ITOPARAMETER(MPLIER=16807,MODLUS=2147483647,&&MOBYMP=127773,MOMDMP=2836)COMMON/SEED/UTSEED,IRFRSTINTEGERHVLUE,LVLUE,TESTV,NEXTNSAVENEXTNIF(IRFRST.EQ.0)THENNEXTN=UTSEEDIRFRST=1ENDIFHVLUE=NEXTN/MOBYMPLVLUE=MOD(NEXTN,MOBYMP)TESTV=MPLIER*LVLUE-MOMDMP*HVLUEIF(TESTV.GT.0)THENNEXTN=TESTVELSENEXTN=TESTV+MODLUSENDIF        IF(NEXTN.GE.0)THENRNDINT=MOD(MOD(NEXTN,MODLUS),ITO-IFROM+1)+IFROMELSERNDINT=MOD(MOD(NEXTN,MODLUS),ITO-IFROM+1)+ITO+1ENDIF        RETURN      END
Works with:Fortran version 66 and earlier

Anyone who attempts to produce random numbers via a computation is already in a state of sin, so, one might as well be hung as a goat rather than as a lamb. Here is a version using the RANDU generator, in the style of Fortran 66 as offered by the IBM1130. No logical-if statements and reliance on implicit type declarations. Sixteen-bit integers result. The standard advice is to start IX off as an odd number. Note that RANDU doesnot update IX (the "seed"); the caller must do so. Since integer overflow producing negative numbers is undone by adding 32768 (trusting that the compiler will not attempt to combine constants, thus + 32767 + 1) in the absence of an AND operation, possible values for IY are presumably zero to 32767. Since IY is divided by 32767.0 (not 32768.0 for example), the range for YFL is zero to oneinclusive, though further inspection shows that zero is not attained for proper starts - should IX be zero it will never change, thus the span is (0,1]; a more common arrangement is [0,1).

Because the upper boundis attainable, multiplying YFL by 19 and truncating the result will mean that 19 appears only as an edge event when IY = 32767. Multiplying by 20 will ensure that 19 gets its fair share along with each other integer, but, the edge event might now occasionally produce a 20. There is no MIN function available, so, explicit testing results. Rather than repeat this code with its consequent litter of labels, a helper function IR19 does the work once. These out-by-one opportunities are vexing.

The RANDU routine is so notorious that latter-day compilers can supply their own RANDU (using a better method), and further, disregard a user-supplied RANDU routine so it may have to be called RANDUU or some other name!

SUBROUTINERANDU(IX,IY,YFL)CopiedfromtheIBM1130ScientificSubroutinesPackage(1130-CM-02X):Programmer's Manual, page 60.CAUTION! This routine's32-bitvariantisreviledbyProf.Knuthandmanyothersforgoodreason!IY=IX*899IF(IY)5,6,65IY=IY+32767+16YFL=IYYFL=YFL/32767.END      FUNCTIONIR19(IX)CALLRANDU(IX,IY,YFL)IX=IYI=YFL*20IF(I-20)12,11,1111I=1912IR19=IENDIX=1Commencetheloop.10I=IR19(IX)WRITE(6,11)I11FORMAT(I3)IF(I-10)12,20,1212I=IR19(IX)WRITE(6,11)IGOTO10Cease.20CONTINUE      END

Output, converted to along the line:

 0 13  4 19  1  7  2 12  4  7 14 11  6  4  0  9  5 12 16 19 18  2  0 13  2  7 10

This source will compile with later compilers (possibly after adding INTEGER*2 declarations to not use larger integers), as well as earlier compilers. But the IBM1620's Fortran II ran on a decimal computer (and the compiler allowed an option to specify how many digits in a number) so the assumption of sixteen-bit two's-complement arithmetic would fail. There was once much more variety in computer design, not just always a power of two in word sizes.

FreeBASIC

' FB 1.05.0 Win64DimiAsIntegerRandomizeDoi=Int(Rnd*20)PrintUsing"##";i;Print"  ";Ifi=10ThenExitDoi=Int(Rnd*20)PrintUsing"##";i;Print"  ";LoopPrintSleep

Sample output

Output:
 6  12   2  16   5  19   9   6  16   1  16  10   1   4  18   3   2   9  19   019  13   0   0  12  17  13  12  18  10   8  13   9   5  14   7  10

Frink

while true{   a = random[0,19]   print["$a "]   if a == 10      break   b = random[0,19]   print["$b "]}
Output:
3 8 8 8 11 6 3 2 10

FutureBasic

include "NSLog.incl"long numdonum = rnd(20) - 1NSLog(@"%ld",num)until ( num == 10 )HandleEvents

Gambas

PublicSubForm_Open()DimiRandAsIntegerRepeatiRand=Rnd*20PrintiRandUntiliRand=10End

==Gambas ==

Click this link to run this code

PublicSubMain()DimbyNoAsByteDobyNo=Rand(0,19)PrintbyNo;;IfbyNo=10ThenBreakbyNo=Rand(0,19)PrintbyNo;;LoopEnd

Output:

0 5 12 8 1 13 16 5 4 11 5 7 15 12 16 7 9 10 13 19 4 10 2 13 16 7 0 1 16 3 17 10 0 16 14 0 0 8 6 2 1 5 9 12 2 18 15 1 1 17 9 18 8 17 19 12 6 19 9 5 15 1 2 7 2 11 18 1 15 19 10

GAP

whiletruedoa:=Random(0,19);Print(a);ifa=10thenPrint("\n");break;fi;a:=Random(0,19);Print("\t",a,"\n");od;# 11      6# 5       8# 1       4# 5       10# 1       16# 10

GDScript

Works with:Godot version 4.0.1
Translation of:11l
extendsMainLoopfunc_process(_delta:float)->bool:randomize()whiletrue:vara:int=randi_range(0,19)print(a)ifa==10:breakvarb:int=randi_range(0,19)print(b)returntrue# Exit

GML

while(1)    {    a = floor(random(19))    show_message(string(a))    if(a = 10)        break    b = floor(random(19))    show_message(string(a))    }

Go

packagemainimport"fmt"import"math/rand"import"time"funcmain(){rand.Seed(time.Now().UnixNano())for{a:=rand.Intn(20)fmt.Println(a)ifa==10{break}b:=rand.Intn(20)fmt.Println(b)}}

Golfscript

{ 20 rand .p 10= ! .{ 20 rand p }* }do

Groovy

finalrandom=newRandom()while(true){defrandom1=random.nextInt(20)printrandom1if(random1==10)breakprint'     'printlnrandom.nextInt(20)}

GW-BASIC

10NUM=020WHILENUM<>1030NUM=INT(RND*20)40PRINTNUM50WEND

Harbour

PROCEDURE Loop()LOCAL nDO WHILE.T.      ? n := hb_RandomInt( 0, 19 )IF n == 10EXITENDIF      ? hb_RandomInt( 0, 19 )ENDDORETURN

Haskell

importControl.MonadimportSystem.RandomloopBreaknk=dor<-randomRIO(0,n)printrunless(r==k)$doprint=<<randomRIO(0,n)loopBreaknk

Use:

loopBreak1910

Haxe

classProgram{staticpublicfunctionmain():Void{while(true){vara=Std.random(20);Sys.println(a);if(a==10)break;varb=Std.random(20);Sys.println(b);}}}

hexiscript

while true  let r rand 20  println r  if r = 10    break  endif  println rand 20endwhile

HicEst

1  DO i = 1, 1E20 ! "forever"     a = INT( RAN(10, 10) )     WRITE(name) a     IF( a == 10) GOTO 10     b = INT( RAN(10, 10) )     WRITE(name) b   ENDDO10 END

HolyC

U16 a, b;while (1) {  a = RandU16 % 20;  Print("%d\n", a);  if (a == 10) break;  b = RandU16 % 20;  Print("%d\n", b);}

Icon andUnicon

proceduremain()while10~=writes(?20-1)dowrite(", ",?20-1)end

Notes:

  • For any positive integer i, ?i produces a value j where 1 <= j <= i
  • Although this can be written with a break (e.g. repeat expression & break), there is no need to actually use one. (And it's ugly).
  • Programmers new to Icon/Unicon need to understand that just about everything returns values including comparison operators, I/O functions like write/writes.
  • This program will perform similarly but not identically under Icon and Unicon because the random operator ?i behaves differently. While both produce pseudo-random numbers a different generator is used. Also, the sequence produced by Icon begins with the same seed value and is repeatable whereas the sequence produced by Unicon does not. One way to force Icon to use different random sequences on each call would be to add the line
    &random:=integer(map("smhSMH","Hh:Mm:Ss",&clock))
    at the start of themain procedure to set the random number seed based on the time of day.

Insitux

(while true  (print (let x (rand-int 0 20)))  (when (= x 10) (break)))

Io

loop(a:=Randomvalue(0,20)floorwrite(a)if(a==10,writeln;break)b:=Randomvalue(0,20)floorwriteln(" ",b))

J

In recent versions of J,Z: can be used to provide early termination from afold. For example:

The task asks us to conditionally generate a second number per loop iteration, if that iteration's first number is not 10:

]F.((echo@?@20[_2Z:10&=[echo)@?@20)''3187131010

'' is customarily used as a dummy argument, since all verbs in J require an argument.

Note that, based on the given task, the output can end with two printed 10's. Both numbers are to be printed unconditionally once (and if) they're generated. The first-printed 10 was the second number generated in a given iteration, and the second-printed 10 was the first (and only) number generated in the following iteration.

It could alternately be written using Agent (@.):

]F.((echo@?@20`(_2Z:1:)@.(10&=)[echo)@?@20)''

The following implements the simpler task of generating and printing a number between 0 and 19 inclusive, and stopping upon hitting an output of 10.

]F.((_2Z:10&=[echo)@?@20)''156510]F.((_2Z:10&=[echo)@?@20)''1493819145138119210

But other mechanisms are also supported:

loopexample=:{{while.do.echok=.?20if.10=kdo.return.end.echo?20end.}}

Note thatbreak. orgoto_FOO. could have been used in place ofreturn.:

loopexample2=:verbdefinewhile.do.echok=.?20if.10=kdo.break.end.echo?20end.)
loopexample3=:{{while.do.echok=.?20if.10=kdo.goto_done.end.echo?20end.label_done.}}

Jactl

while (true) {  def x = random(20)  println x  break if x == 10  println random(20)}

Jakt

The random number generation is slightly biased, but negligible for the purpose of the task.

fn random(mut random_source: File = File::open_for_reading("/dev/urandom")) throws -> u64 {    mut buffer = [0u8; 4]    random_source.read(buffer)    mut result = 0u64    for byte in buffer {        result <<= 8        result += byte as! u64    }    return result}fn main() {    while true {        let n = random() % 20        println("{}", n)        if n == 10 {            break        }        println("{}", random() % 20)    }}

Java

importjava.util.Random;Randomrand=newRandom();while(true){inta=rand.nextInt(20);System.out.println(a);if(a==10)break;intb=rand.nextInt(20);System.out.println(b);}

JavaScript

for(;;){vara=Math.floor(Math.random()*20);print(a);if(a==10)break;a=Math.floor(Math.random()*20);print(a);}

Theprint() function is available in theRhino JavaScript shell.


If we step back for a moment from imperative assumptions about repetitive processes and their interruption, we may notice that there is actually no necessary connection between repetitive process and loops.

In a functional idiom of JavaScript, we might instead write something like:

(functionstreamTillInitialTen(){varnFirst=Math.floor(Math.random()*20);console.log(nFirst);if(nFirst===10)returntrue;console.log(Math.floor(Math.random()*20));returnstreamTillInitialTen();})();

Obtaining runs like:

181016108013321415171471080202516316671901697111710

Though returning a value composes better, and costs less IO traffic, than firing off side-effects from a moving thread:

console.log((functionstreamTillInitialTen(){varnFirst=Math.floor(Math.random()*20);if(nFirst===10)return[10];return[nFirst,Math.floor(Math.random()*20)].concat(streamTillInitialTen());})().join('\n'));

Sample result:

171434131015510

jq

With the functions defined below, the task can be accomplished using the following jq filter:

   take( rand(20); . != 10 )

Here, `rand(n)` is a pseudo-random number generator, and `take(stream; cond)` will continue taking from the stream so long as the condition is satisfied. When the condition is no longer satisfied, the PRNG is immediately terminated.

Using the built-in `foreach` construct, the above is equivalent to:

   label $done | foreach rand(20) as $n (null; $n; if . == 10 then break $done else . end)

PRNG

Currently, jq does not have a built-in random-number generator, so here we borrow one of the linear congruential generators defined athttps://rosettacode.org/wiki/Linear_congruential_generator -

# 15-bit integers generated using the same formula as rand() # from the Microsoft C Runtime.# Input: [ count, state, rand ]def next_rand_Microsoft:  .[0] as $count | .[1] as $state  | ( (214013 * $state) + 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];# Generate random integers from 0 to (n-1):def rand(n): n * (rand_Microsoft(17) / 32768) | trunc;

"take"

def take(s; cond):  label $done  | foreach s as $n (null; $n; if $n | cond | not then break $done else . end);

"count"

Since the PRNG used here is deterministic, we'll just count the number of integers generated:

def count(s): reduce s as $i (0; . + 1);

Example

   count(take(rand(20); . != 10))
Output:
   12

Julia

whiletruen=rand(0:19)@printf"%4d"nifn==10println()breakendn=rand(0:19)@printf"%4d\n"nend
Output:
   0  11  11   7   4  19   7  19   5   2   5  17  12   5  14  18   1  10  18  14  16   0  17   1  10

Koka

importstd/num/randomeffectebreakfinalctlebreak():afunmain()withfinalctlebreak()()while{True}vala=random-int()%20println(a)ifa==10thenebreak()println(random-int()%20)


Kotlin

importkotlin.random.Randomfunmain(){while(true){vala=Random.nextInt(20)println(a)if(a==10)breakprintln(Random.nextInt(20))}}

A more compact version:

funmain(){while((0..19).random().also{println(it)}!=10)println((0..19).random())}

Lambdatalk

{defloops_break{lambda{:n}{if{=:n10}then:n->endofloopelse:n{loops_break{round{*20{random}}}}}}}->loops_break{loops_break0}->0168591791811811121315110->endofloop

Lang

loop {$a = fn.randRange(20)fn.printf(%2d, $a)if($a === 10) {fn.println()con.break}$b = fn.randRange(20)fn.printf(\s- %2d%n, $b)}

Lang5

do 20 ? int dup . 10 == if break then 20 ? int . loop

langur

for {    val i = random(0..19)    write i, " "    if i == 10 { writeln(); break }}
Output:
13 18 14 8 0 5 17 13 9 13 6 5 13 16 6 9 11 18 10

Lasso

local(x=0)while(#x!=10)=>{^#x=integer_random(19,0)#x#x==10?loop_abort', '+integer_random(19,0)+'\r'^}

Liberty BASIC

The task specifies a "number".

while num<>10    num=rnd(1)*20    print num    if num=10 then exit while    print rnd(1)*20wend

If "integer" was meant, this code fulfils that requirement.

while num<>10    num=int(rnd(1)*20)    print num    if num=10 then exit while    print int(rnd(1)*20)wend

Lingo

repeat while TRUE  n = random(20)-1  put n  if n = 10 then exit repeat  put random(20)-1end repeat

Lisaac

Section Header+ name := TEST_LOOP_BREAK;Section Public- main <- (  + a, b : INTEGER;  `srand(time(NULL))`;  {    a := `rand()`:INTEGER % 20; // not exactly uniformly distributed, but doesn't matter    a.print;    '\n'.print;    a == 10  }.until_do {    b := `rand()`:INTEGER % 20; // not exactly uniformly distributed, but doesn't matter    b.print;    '\n'.print;  });

LiveCode

command loopForeverRandom    repeat forever        put random(20) - 1 into tRand        put tRand        if tRand is 10 then exit repeat        put random(20) - 1    end repeatend loopForeverRandom

Lua

repeatk=math.random(19)print(k)ifk==10thenbreakendprint(math.random(19)untilfalse

M2000 Interpreter

We use block of module to loop. Break also can be used, but breaks nested blocks (without crossing modules/functions). Using break in second Checkit module we break three blocks.

Module Checkit {      M=Random(0, 19)      Print M      If M=10 then Continue  ' because loop flag is false, continue act as Exit      Print Random(0, 19)      loop}CheckitModule Checkit {      do {            do {                  {                        M=Random(0, 19)                        Print M                        If M=10 then Break                        Print Random(0, 19)                        loop                  }                       Print "no print this"             } always            Print "no print this"      } always      Print "print ok"}Checkit

M4

define(`randSeed',141592653)dnldefine(`setRand',   `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnldefine(`rand_t',`eval(randSeed^(randSeed>>13))')dnldefine(`random',   `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')dnldnldefine(`loopbreak',`define(`a',eval(random%20))`a='aifelse(a,10,`',`define(`b',eval(random%20))`b='bloopbreak')')dnldnlloopbreak
Output:
a=17b=3a=0b=15a=10

Maple

r:=rand(0..19):don:=r();printf("%d\n",n);ifn=10thenbreakendif;printf("%d\n",r());enddo:

Mathematica /Wolfram Language

While[(Print[#];#!=10)&[RandomIntger[{0,19}]],Print[RandomInteger[{0,19}]]

Maxima

/* To exit the innermost block, use return(<value>) */block([n],do(n:random(20),ldisp(n),ifn=10thenreturn(),n:random(20),ldisp(n)))$/* To exit any level of block, use catch(...) and throw(<value>);they are not used for catching exceptions, but for non-localreturn. Use errcatch(...) for exceptions. */block([n],catch(do(n:random(20),ldisp(n),ifn=10thenthrow('done),n:random(20),ldisp(n))))$/* There is also break(<value>, ...) in Maxima. It makes Maximastop the evaluation and enter a read-eval loop where one can changevariable values, then return to the function after exit; For example */block([x:1],break(),ldisp(x));>x:2;>exit;2

MAXScript

while true do(a = random 0 19format ("A: % \n") aif a == 10 do exitb = random 0 19format ("B: % \n") b)

min

Works with:min version 0.19.6
randomize(19 random puts 10 ==) (19 random puts!) () () linrec

МК-61/52

СЧ20*П010-[x]x#018СЧ20*П1БП00ИП0С/П

Modula-3

MODULEBreakEXPORTSMain;IMPORTIO,Fmt,Random;VARa,b:INTEGER;BEGINWITHrand=NEW(Random.Default).init()DOLOOPa:=rand.integer(min:=0,max:=19);IO.Put(Fmt.Int(a)&"\n");IFa=10THENEXITEND;b:=rand.integer(min:=0,max:=19);IO.Put(Fmt.Int(b)&"\n");END;END;ENDBreak.

MOO

while(1)  a=random(20)-1;player:tell(a);if(a==10)break;endif  b=random(20)-1;player:tell(b);endwhile

MUMPS

BREAKLOOP NEW A,B SET A="" FOR  Q:A=10  DO .SET A=$RANDOM(20) .WRITE !,A .Q:A=10 .SET B=$RANDOM(20) .WRITE ?6,B KILL A,B QUIT ;A denser version that doesn't require two tests NEW A,B  FOR  SET A=$RANDOM(20) WRITE !,A QUIT:A=10  SET B=$RANDOM(20) WRITE ?6,B KILL A,B QUIT
Output:
USER>D BREAKLOOP^ROSETTA 5     39     133     129     1916    411    1718    24     1810USER>D BREAKLOOP+11^ROSETTA 6     1315    30     88     187     1315    1015    1310

Neko

/** Loops/Break in Neko Tectonics:   nekoc loops-break.neko   neko loops-break*/varrandom_new=$loader.loadprim("std@random_new",0);varrandom_int=$loader.loadprim("std@random_int",2);varrandom=random_new();whiletrue{varr=random_int(random,20);$print(r," ");ifr==10break;r=random_int(random,20);$print(r," ");}$print("\n");
Output:
prompt$ nekoc loops-break.nekoprompt$ neko loops-break0 8 17 12 4 18 7 6 19 11 13 6 12 7 6 6 6 18 14 7 18 10 15 6 9 5 4 14 10

Nemerle

Translation of:C#
usingSystem;usingSystem.Console;usingNemerle.Imperative;moduleBreak{Main():void{defrnd=Random();while(true){defa=rnd.Next(20);WriteLine(a);when(a==10)break;defb=rnd.Next(20);WriteLine(b);}}}

NetRexx

/* NetRexx */optionsreplaceformatcommentsjavacrossrefsavelogsymbolsnobinarysaysay'Loops/Break'rn=Rexxrnd=Random()looplabellbforeverrn=rnd.nextInt(19)sayrn.right(3)'\-'ifrn=10thenleavelbrn=rnd.nextInt(19)sayrn.right(3)'\-'endlbsay

NewLISP

(until(=10(println(rand20)))(println(rand20)))

Nim

Translation of:Python
importrandomwhiletrue:leta=random(19)echoaifa==10:breakletb=random(19)echob

NS-HUBASIC

10 I=RND(20)20 PRINT I30 IF I=10 THEN STOP40 PRINT RND(20)50 GOTO 10

Nu

while true {let a = random int 0..19print $aif $a == 10 {break}print (random int 0..19)}

Oberon-2

Works with oo2c Version 2

MODULELoopBreak;IMPORTRandomNumbers,Out;PROCEDUREDo();VARrn:LONGINT;BEGINLOOPrn:=RandomNumbers.RND(20);Out.LongInt(rn,0);Out.Ln;IFrn=10THENEXITEND;rn:=RandomNumbers.RND(20);Out.LongInt(rn,0);Out.LnENDENDDo;BEGINDoENDLoopBreak.

Oberon-07

Works with:Oberonc (Oberon-07 compiler for the JVM)
Translation of:Oberon-2 – Using the RandomNumbers module from theSleeping Beauty problem task.

The LOOP and EXIT statements present in Oberon-2 were removed from Oberon-07, as were LONGINT and SHORTINT.

MODULELoopsBreak;IMPORTRandomNumbers,Out;PROCEDUREDo();VARrn:INTEGER;exit:BOOLEAN;BEGINexit:=FALSE;REPEATrn:=RandomNumbers.randomInt(20);Out.Int(rn,0);Out.Ln;exit:=rn=10;IF~exitTHENrn:=RandomNumbers.randomInt(20);Out.Int(rn,0);Out.LnENDUNTILexit;ENDDo;BEGINDoENDLoopsBreak.

Objeck

while(true) {  a := (Float->Random() * 20.0)->As(Int);  a->PrintLine();  if(a = 10) {     break;  };  a := (Float->Random() * 20.0)->As(Int);  a->PrintLine();}

OCaml

#Random.self_init();;-:unit=()#whiletruedoleta=Random.int20inprint_inta;print_newline();ifa=10thenraiseExit;letb=Random.int20inprint_intb;print_newline()done;;151821310Exception:Pervasives.Exit.

Octave

while(1)a=floor(unifrnd(0,20,1));disp(a)if(a==10)breakendifb=floor(unifrnd(0,20,1));disp(b)endwhile

Oforth

while(true) [      19 rand dup print ":" print      10 == ifTrue: [ break ]      19 rand print " " print   ]

Ol

(import(otusrandom!))(call/cc(lambda(break)(letloop()(if(=(rand!20)10)(break#t))(print(rand!20))(loop))))

ooRexx

/*REXX ***************************************************************** Three Ways to leave a Loop* ooRexx added the possibility to leave an outer loop* without using a control variable* 12.05.2013 Walter Pachl**********************************************************************/doi1=1To2/* an outer loop              */Say'i1='i1/* tell where we are          */Callrandom,,123/* seed to be reproducable    */doforever/* inner loop                 */a=random(19)Sayaifa=6thenleave/* leaces the innermost loop  */endenddoi2=1To2Say'i2='i2Callrandom,,123doforevera=random(19)Sayaifa=6thenleavei2/* leaves loop with control variable i2 */endendParseVersionvSelectWhenpos('ooRexx',v)>0Thensupported=1Otherwisesupported=0EndIfsupportedThenDoSay'Leave label-name is supported in'vdoLabeli3ForeverSay'outer loop'Callrandom,,123doforevera=random(19)Sayaifa=6thenleavei3/* leaves loop with label name i3 */endendEndElseSay'Leave label-name is probably not supported in'v
Output:
i1=1141456i1=2141456i2=1141456Leave label-name is supported in REXX-ooRexx_4.1.2(MT) 6.03 28 Aug 2012outer loop141456

Oz

We can implement this either with recursion or with a special type of the for-loop. Both can be considered idiomatic.

for break:Break do   R = {OS.rand} mod 20in   {Show R}   if R == 10 then {Break}   else {Show {OS.rand} mod 20}   endend

PARI/GP

while(1,  t=random(20);  print(t);  if(t==10, break);  print(random(20)))

Pascal

See Delphi

PascalABC.NET

beginwhileTruedobeginvarx:=Random(0,19);Print(x);ifx=10thenbreak;Print(Random(0,19));end;end.


Perl

while(1){my$a=int(rand(20));print"$a\n";if($a==10){last;}my$b=int(rand(20));print"$b\n";}

Phix

Library:Phix/basics
Translation of:Euphoria

The rand() function returns a random integer from 1 to the integer provided.

integeriwhile1doi=rand(20)-1printf(1,"%g ",{i})ifi=10thenexitendifprintf(1,"%g\n",{rand(20)-1})endwhile
Output:
2 101 73 1610

Phixmonti

/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/Breakby Galileo, 11/2022 #/include ..\Utilitys.pmtdef ran rand * int enddeftrue while    20 ran    dup print "\t" print    10 == if false else 20 ran ? true endifendwhile
Output:
12      812      105       710=== Press any key to exit ===

PHP

while(true){$a=rand(0,19);echo"$a\n";if($a==10)break;$b=rand(0,19);echo"$b\n";}

PicoLisp

Literally:

(use R   (loop      (println (setq R (rand 1 19)))      (T (= 10 R))      (println (rand 1 19)) ) )

Shorter:

(until (= 10 (println (rand 1 19)))   (println (rand 1 19)) )

Pike

intmain(){while(1){inta=random(20);write(a+"\n");if(a==10){break;}intb=random(20);write(b+"\n");}}

PL/I

do forever;   k = trunc(random()*20);   put (k);   if k = 10 then leave;   k = trunc(random()*20);   put skip list (k);end;

Plain English

To run:Start up.Demonstrate breaking.Wait for the escape key.Shut down.To demonstrate breaking:Pick a number between 0 and 19.Write the number to the console.If the number is 10, break.Pick another number between 0 and 19.Write the other number to the console.Repeat.To write a number to the console:Convert the number to a string.Write the string to the console.

Pluto

while true do    local r = math.random(0, 19)    print(r)    if r == 10 then break end    print(math.random(0, 19))end
Output:

Example of a (thankfully) short run:

18161213121191371210

PostScript

realtime srand          % init RNG{    rand 20 mod         % generate number between 0 and 19    dup =               % print it    10 eq { exit } if   % exit if 10} loop

PowerShell

$r = New-Object Randomfor () {    $n = $r.Next(20)    Write-Host $n    if ($n -eq 10) {        break    }    Write-Host $r.Next(20)}

PureBasic

If OpenConsole()  Repeat    a = Random(19)    PrintN(Str(a))    If a = 10      Break    EndIf     b = Random(19)    PrintN(Str(b))    PrintN("")  ForEver  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")  Input()  CloseConsole()EndIf

Python

from random import randrangewhile True:    a = randrange(20)    print(a)    if a == 10:        break    b = randrange(20)    print(b)

QB64

CBTJD: 2020/03/14

RANDOMIZE TIMERDO    n = INT(RND * 20)    PRINT n,    IF n = 10 THEN        EXIT DO    ELSE        n = INT(RND * 20)        PRINT n    END IFLOOP UNTIL 0

Qi

(define loop -> (if (= 10 (PRINT (random 20)))                    true                    (do (PRINT (random 20))                        (loop))))(loop)

Quackery

[ 20 random  dup echo sp   10 = if done  20 random echo cr  again ]
Output:
16 99 1411 1614 1314 1716 1913 1110


R

Works with:R version 2.8.1
sample0to19 <- function() sample(0L:19L, 1,replace=TRUE)repeat{  result1 <- sample0to19()  if (result1 == 10L)  {    print(result1)    break  }  result2 <- sample0to19()  cat(result1, result2, "\n")}

Racket

#lang racket(let loop ()  (let/ec break    (define a (random 20))    (displayln a)    (when (= a 10) (break))    (displayln (random 20))    (loop)))

Raku

(formerly Perl 6)

Works with:Rakudo version #21 "Seattle"
loop {    say my $n = (0..19).pick;    last if $n == 10;    say (0..19).pick;}

Rebol

REBOL [Title: "Loop/Break"URL: http://rosettacode.org/wiki/Loop/Break]random/seed 1 ; Make repeatable.; random/seed now ; Uncomment for 'true' randomness.r20: does [(random 20) - 1]forever [prin x: r20if 10 = x [break]print rejoin [" " r20]]print ""
Output:
14 1119 156 1112 113 1410

Red

Translation of:REBOL
Red [    Title: "Loops/Break"    URL: http://rosettacode.org/wiki/Loops/Break]random/seed 2 ; Make repeatable. Delete line for 'true' randomness.r20: does [(random 20) - 1]forever [    prin x: r20    if 10 = x [break]    print rejoin [" " r20]]print ""
Output:
2 150 01 116 144 1410

Retro

doc{A couple of helper functions to make the rest of thecode more readable.}doc: rand  ( -n )  random 20 mod ;: .  ( n- )  putn space ;doc{One approach is to use a simple repeat/again loop, anda conditional exit. For instance:}doc: foo   ( - )  repeat rand dup . 10 = if; rand . again ;doc{The other approach uses a structured while loop with thesecond printing handled by a conditional clause.}doc[ rand dup . 10 <> [ [ rand . ] ifTrue ] sip ] while

REXX

/*REXX program demonstrates a    FOREVER   DO  loop  with a test to    LEAVE   (break). */                                                 /*REXX's RANDOM BIF returns an integer.*/    do forever                                   /*perform loop until da cows come home.*/    a=random(19)                                 /*same as:    random(0, 19)            */    call charout , right(a, 5)                   /*show   A   right─justified, column 1.*/    if a==10  then leave                         /*is random #=10?  Then cows came home.*/    b=random(19)                                 /*same as:    random(0, 19)            */    say right(b, 5)                              /*show   B   right─justified, column 2.*/    end   /*forever*/                            /* [↑]  CHAROUT , xxx   writes to term.*/                                                 /*stick a fork in it,  we're all done. */
output:

(A long run was chosen)

    1    0   16    3    8   15   11    8   12   14   15    4    0    0    6   11   15    5   14    0   18   16   15    0   14    5    3    5    9    4    4    4   17    6    4   10    6    2    9   13   12    6   14   16   17    0    8    6    9    2    0    6    9    9   12    8   11    3   11    4    7    1    3   13    4    8   14   14   14   13   12    7    1    0   16   15    8   19   12    7   18    9    7   18   19   13    6    2    6    7    2    1    8    2    9    7    6   13   19   15   10

Ring

while true      a = random(20)      see a + nl      if a = 10 exit okend

RPL

RPL does not have anyBREAK command. Flags are of great help to exit loops:

≪ 1 CFWHILE 1 FC?REPEAT      RAND 20 * IP      DUP 1 DISPIF 10 ==THEN 1 SFELSE          RAND 20 * IP          2 DISPENDEND

The error handling mechanism provides another way to break a loop:

IFERRWHILE 1REPEAT         RAND 20 * IP DUP 1 DISPIF 10 ==THEN 0 DUP /END          RAND 20 * IP 2 DISPENDTHEN DROP2END

Ruby

loop do  a = rand(20)  print a  if a == 10    puts    break  end  b = rand(20)  puts "\t#{b}"end

or

loop do  print a = rand(20)  puts or break if a == 10  puts "\t#{rand(20)}"end
Output:
0       411      08       212      133       06       92       812      108       1712      610

Rust

Library:rand
// cargo-deps: randextern crate rand;use rand::{thread_rng, Rng}; fn main() {    let mut rng = thread_rng();    loop {        let num = rng.gen_range(0, 20);        if num == 10 {            println!("{}", num);            break;        }        println!("{}", rng.gen_range(0, 20));    }}

SAS

data _null_;do while(1);   n=floor(uniform(0)*20);   put n;   if n=10 then leave;    /* 'leave' to break a loop */end;run;

Sather

-- help class for random number sequenceclass RANDOM is  attr seed:INT;  create(seed:INT):SAME is    res:RANDOM := new;    res.seed := seed;    return res;  end;  -- this code is taken from rand's man (C)  next:INT is    seed := seed * 1103515245 + 12345;    return (seed/65536) % 32768;  end;end;class MAIN is  main is    a, b :INT;    rnd:RANDOM := #(1);    loop      a := rnd.next % 20;      #OUT + a + "\n";      if a = 10 then break!; end; -- here we break      b := rnd.next % 20;      #OUT + b + "\n";    end;   end;end;

S-BASIC

S-BASIC lacks an explicit BREAK statement, but thesame effect can be achieved (at some loss of elegance)using a GOTO to jump out of the loop. It helps thatS-BASIC allows alphanumeric labels as the target of GOTO and GOSUB statements, though the first character must be a digit.

var n = integerwhile (1 = 1) do  begin    n = int(rnd(1) * 20)    print n;    if n = 10 then goto 0_done    n = int(rnd(1) * 20)    print n  end0_done print " That's all!"end

A more idiomatic approach (avoiding the GOTO, at the expenseof a repeated test) is to invert the BREAK condition and use the result both to fence off the remaining portion of the loopand to supply the terminating condition.

var n = integerrepeat  begin    n = int(rnd(1) * 20)    print n;    if n <> 10 then         print int(rnd(1) * 20)  enduntil n = 10print " That's all!"end
Output:

Same for both approaches

0 16 190 00 14 145 1715 910 That's all!

Scala

scala> import util.control.Breaks.{breakable, break}import util.control.Breaks.{breakable, break}scala> import util.Randomimport util.Randomscala> breakable {     |   while(true) {     |     val a = Random.nextInt(20)     |     println(a)     |     if(a == 10)     |       break     |     val b = Random.nextInt(20)     |     println(b)     |   }     | }5410

Scheme

(let loop ((first (random 20)))  (print first)  (if (not (= first 10))      (begin        (print (random 20))        (loop (random 20)))))

Or by using call/cc to break out:

(call/cc  (lambda (break)   (let loop ((first (random 20)))     (print first)     (if (= first 10)         (break))     (print (random 20))     (loop (random 20)))))

Scilab

Works with:Scilab version 5.5.1
while %T    a=int(rand()*20)  // [0..19]     printf("%2d ",a)    if a==10 then break; end    b=int(rand()*20)    printf("%2d\n",b)endprintf("\n")
Output:
 4 15 0  613 1216 1317  111 1314  310

Seed7

Seed7 has no goto statement and hidden gotos like break- and continue-statements are also omitted.But this is not a problem. All programs with break-statements can be rewritten as structured programs without break.Usually structured programs have better readability. If you are used to it writing programs without goto (and break) is easy.The example below shows how easy a break can be avoided in this exercise. The loop ends, if the first random numberis 10. The second random number does never terminate the loop.

$ include "seed7_05.s7i";const proc: main is func  local    var integer: number is 0;  begin    repeat      number := rand(0, 19);      writeln(number);      if number <> 10 then        writeln(rand(0, 19));      end if;    until number = 10;  end func;

Sidef

var lim = 20;loop {    say (var n = lim.rand.int);    n == 10 && break;    say lim.rand.int;}

Simula

Works with:SIMULA-67
! Loops/Break - simula67 - 08/03/2017;begin  integer num,seed;  seed:=0;  while true do  begin    num:=randint(1,20,seed);    outint(num,2); outimage;    if num=10 then goto lab;  end;lab:end
Output:
 1 9 810

Smalltalk

Works with:Smalltalk/X
[    |first second done|    first := Random nextIntegerBetween:0 and:19.    Stdout print:first; cr.    (done := (first == 10)) ifFalse:[        second := Random nextIntegerBetween:0 and:19.        Stdout print:' '; print:second; cr.    ].    done] whileFalse

alternative:

[:exit |    |first|    Stdout printCR: (first := Random nextIntegerBetween:0 and:19).    first == 10 ifTrue:[ exit value:nil ].    Stdout print:' '; printCR: (Random nextIntegerBetween:0 and:19).] loopWithExit.

or shorter (becauseifTrue: sends #value to its arg):

[:exit |    |first|    Stdout printCR: (first := Random nextIntegerBetween:0 and:19).    first == 10 ifTrue:exit.    Stdout print:' '; printCR: (Random nextIntegerBetween:0 and:19).] loopWithExit.

Snabel

Uses a ranged random generator as iterator.

let: rnd 19 random;@rnd {  $ str say  10 = &break when  @rnd pop str say} for

SNOBOL4

Most Snobols lack a built-in rand( ) function. Kludgy "Linux-only" implementation:

input(.random,io_findunit(),1,"/dev/urandom")while&ALPHABET random @randoutput = rand = rand - (rand / 20) * 20 eq(rand,10) :f(while)end

Or using a library function:

* rand(n) -> real x | 0 <= x < n-include 'random.sno'loop    ne(output = convert(rand(20)'integer'),10) :s(loop)end

Spin

Works with:BST/BSTC
Works with:FastSpin/FlexSpin
Works with:HomeSpun
Works with:OpenSpin
con  _clkmode = xtal1 + pll16x  _clkfreq = 80_000_000obj  ser : "FullDuplexSerial.spin"pub main | r, s  ser.start(31, 30, 0, 115200)  s := 1337 ' PRNG seed  repeat    r := ||?s // 20    ser.dec(r)    ser.tx(32)    if r == 10      quit    r := ||?s // 20    ser.dec(r)    ser.tx(32)  waitcnt(_clkfreq + cnt)  ser.stop  cogstop(0)
Output:
8 13 1 7 19 1 15 16 9 6 5 9 1 15 5 0 6 3 9 19 8 9 10

SparForte

As a structured script.

#!/usr/local/bin/sparpragma annotate( summary, "loopsbreak" )              @( description, "Show a loop which prints random numbers (each number newly" )              @( description, "generated each loop) from 0 to 19 (inclusive). If a number is" )              @( description, "10, stop the loop after printing it, and do not generate any" )              @( description, "further numbers. Otherwise, generate and print a second random" )              @( description, "number before restarting the loop. If the number 10 is never" )              @( description, "generated as the first number in a loop, loop forever. " )              @( category, "tutorials" )              @( author, "Ken O. Burtch" )              @( see_also, "http://rosettacode.org/wiki/Loops/Break" );pragma license( unrestricted );pragma software_model( nonstandard );pragma restriction( no_external_commands );procedure arraysloop is  a : positive;  b : positive;begin  loop    a := numerics.rnd( 20 );    put_line( strings.image( a ) );    exit when a = 10;    b := numerics.rnd( 20 );    put_line( strings.image( b ) );  end loop;end arraysloop;

SPL

Direct approach:

>  n = #.rnd(20)  #.output(n)  << n=10  n = #.rnd(20)  #.output(n)<

With reusable code:

>  :1  n = #.rnd(20)  #.output(n)  <-  << n=10  1 <-><

SQL PL

Works with:Db2 LUW

version 9.7 or higher.

With SQL PL:

--#SET TERMINATOR @SET SERVEROUTPUT ON@BEGIN DECLARE VAL INTEGER; LOOP: WHILE (TRUE = TRUE) DO  SET VAL = INTEGER(RAND() * 20);  CALL DBMS_OUTPUT.PUT_LINE(VAL);  IF (VAL = 10) THEN   LEAVE LOOP;  END IF;  SET VAL = INTEGER(RAND() * 20);  CALL DBMS_OUTPUT.PUT_LINE(VAL); END WHILE LOOP;END @

Output:

db2 -td@db2 => SET SERVEROUTPUT ON@DB20000I  The SET SERVEROUTPUT command completed successfully.db2 => BEGIN...db2 (cont.) => END @DB20000I  The SQL command completed successfully.4169110

Since V11.1, the builtin module can be used instead of RAND, like this:

SET VAL = CALL DBMS_RANDOM.VALUE(0,20);

Stata

while 1 {local n=runiformint(0,19)display `n'if `n'==10 continue, breakdisplay runiformint(0,19)}

Mata

for (; 1; ) {printf("%f\n",n=runiformint(1,1,0,19))if (n==10) breakprintf("%f\n",runiformint(1,1,0,19))}

Suneido

forever    {    Print(i = Random(20))    if i is 10        break    Print(i = Random(20))    }

Swift

while true{  let a = Int(arc4random()) % (20)  print("a: \(a)",terminator: "   ")  if (a == 10)  {    break  }  let b = Int(arc4random()) % (20)  print("b: \(b)")}
Output:
a: 2   b: 7a: 16   b: 13a: 18   b: 16a: 10

TAV

As this is not about the quality of random numbers, random seed is not used.

  ?*                                  \ if no expression, forever    a =: random next integer %% 20    print a    ? a = 10      print random next integer %% 20      ?>                              \ exit loop    print random next integer %% 20

In publication (C) syntax, the source reads:

  while true    a = random next integer %% 20    print a    if a == 10      print random next integer %% 20      break    print random next integer %% 20
Output:
361715131561291271019

Tcl

while true {    set a [expr int(20*rand())]    puts $a    if {$a == 10} {        break    }    set b [expr int(20*rand())]    puts $b}

TI-89 BASIC

Local xLoop  rand(20)-1 → x  Disp x                     © new line and text  If x = 10 Then    Exit  EndIf  Output 64, 50, rand(20)-1  © paint text to the right on same lineEndLoop

TorqueScript

for(%a = 0; %a > -1; %a++){    %number = getRandom(0, 19);    if(%number == 10)        break;}

Transact-SQL

DECLARE @i INT;WHILE 1=1BEGIN    SET @i = ABS(CHECKSUM(NewId())) % 20;    PRINT @i;    IF @i=10 BREAK;    PRINT ABS(CHECKSUM(NewId())) % 20;END;

TUSCRIPT

$$ MODE TUSCRIPTLOOPa=RANDOM_NUMBERS (0,19,1)IF (10==a) THEN PRINT "a=",a STOPELSE b=RANDOM_NUMBERS (0,19,1) PRINT "a=",a," b=",bENDIFIF (10==a,b) STOPENDLOOP
Output:
a=0 b=17a=11 b=13a=3 b=16a=17 b=13a=8 b=11a=8 b=0a=6 b=2a=10

uBasic/4tH

Do  n = RND(20)  Print n  Until n = 10  Print RND(20)Loop

Uiua

Rnd ← (⌊×20⚂)po ⍢ (  ⊸&pRnd◌  ⍥(&pRnd)⊸≠10|≠10) 0

Recursive

Translation of:Haskell
Rnd ← (⌊×20⚂)Loop ←|0.0 (  ≠10 ⊸&pRnd  ⍥ (Loop &p Rnd))Loop

Using ⍣ try and ° pattern matching

To simulate a break, use a failing pattern match in a surrounding try function.

⍣(⍢(&p$"\t_"⚂₂₀⍥(°0 1)=₁₀⊸&pf⚂₂₀|1)|&p"\nended")
Output:
3101017110ended

UNIX Shell

This script gets random numbers from jot(1). If there is any error with jot(1), the script exits.

Works with:Bourne Shell
Library:jot
while true; doa=`jot -w %d -r 1 0 20` || exit $?echo $atest 10 -eq $a && breakb=`jot -w %d -r 1 0 20` || exit $?echo $bdone

Korn Shells have a RANDOM parameter.

Works with:Bash
Works with:pdksh version 5.2.14
while true; do  echo $((a=RANDOM%20))  [ $a -eq 10 ] && break  echo $((b=RANDOM%20))done

Ursa

Translation of:Python
decl ursa.util.random rdecl int a bwhile true        set a (r.getint 19)        out a endl console        if (= a 10)                break        end while        set b (r.getint 19)        out b endl consoleend while

Ursalang

use js.Mathlet f = fn() {   Math.floor(Math.random() * 20)}loop {  let n = f()  print(n)  if n == 10 { break }   print(f())}

Uxntal

%newline { [ LIT2 0a -Console/write ] DEO }%tab { [ LIT2 09 -Console/write ] DEO }%MOD ( a b -- a%b ) { DIVk MUL SUB }|18 @Console/write|c0 @DateTime/year $2 &month $1 &day $1 &hour $1 &minute $1 &second $1|100 rand/init&looprand/0:13 DUP print/dec tab#0a NEQ ?{newline !&break }rand/0:13 print/dec newline!&loop &breakBRK@print/dec ( dec -- )DUP #64 DIV /numDUP #0a DIV /num( >> )@print/num_ ( num -- )#0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEOJMP2r@print/num ( num -- )DUP ?&num_POP JMP2r@rand/init ( -- )[ LIT2 00 -DateTime/second ] DEI[ LIT2 00 -DateTime/minute ] DEI #60 SFT2 EOR2[ LIT2 00 -DateTime/hour ] DEI #c0 SFT2 EOR2 ,&x STR2[ LIT2 00 -DateTime/hour ] DEI #04 SFT2[ LIT2 00 -DateTime/day ] DEI #10 SFT2 EOR2[ LIT2 00 -DateTime/month ] DEI #60 SFT2 EOR2.DateTime/year DEI2 #a0 SFT2 EOR2 ,&y STR2JMP2r@rand/short ( -- number* )[ LIT2 &x $2 ]DUP2 #50 SFT2 EOR2DUP2 #03 SFT2 EOR2[ LIT2 &y $2 ] DUP2 ,&x STR2DUP2 #01 SFT2 EOR2 EOR2,&y STR2k POPJMP2r@rand/byte ( -- number )/short ANDJMP2r@rand/0:13 ( -- U[0,13] )/byte #14 MODJMP2r
Output:
13      165       128       140       117      25       210

VBA

Public Sub LoopsBreak()    Dim value As Integer    Randomize    Do While True        value = Int(20 * Rnd)        Debug.Print value        If value = 10 Then Exit Do        Debug.Print Int(20 * Rnd)    LoopEnd Sub

VBScript

Based on BASIC version. Demonstrates breaking out of Do/Loop and For/Next (Exit is good for getting out of functions and subs as well).

Dim a, b, iDo    a = Int(Rnd * 20)    WScript.StdOut.Write a     If a = 10 Then Exit Do    b = Int(Rnd * 20)    WScript.Echo vbNullString, bLoopFor i = 1 To 100000    a = Int(Rnd * 20)    WScript.StdOut.Write a     If a = 10 Then Exit For    b = Int(Rnd * 20)    WScript.Echo vbNullString, bNext

Visual Basic .NET

Translation of:C#
Module Program    Sub Main()        ' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).        Dim rand As New Random(0)        Do            Dim first = rand.Next(20) ' Upper bound is exclusive.            Console.Write(first & " ")            If first = 10 Then Exit Do            Dim second = rand.Next(20)            Console.Write(second & " ")        Loop    End SubEnd Module
Output:
14 16 15 11 4 11 18 8 19 5 5 9 12 9 19 0 17 19 13 6 16 16 19 0 13 10 18 13 10

V (Vlang)

import randimport rand.seedfn main() {    rand.seed(seed.time_seed_array(2))    for {        a := rand.intn(20)!        println(a)        if a == 10 {            break        }        b := rand.intn(20)!        println(b)    }}

Wren

import "random" for Randomvar r = Random.new()while (true) {    var n = r.int(20)    System.print(n)    if (n == 10) break    System.print(r.int(20))}
Output:

A (mercifully short) sample run:

1013162010

XBasic

Works with:Windows XBasic
PROGRAM "loopbreak"IMPORT "xst" ' for XstGetSystemTimeDECLARE FUNCTION Entry()' Pseudo-random number generator' Based on the rand, srand functions from Kernighan & Ritchie's book' 'The C Programming Language'DECLARE FUNCTION Rand()DECLARE FUNCTION SRand(seed%%)FUNCTION Entry()  XstGetSystemTime (@msec)  SRand(INT(msec) MOD 32768)  DO    a%% = Rand() MOD 20    PRINT FORMAT$("##", a%%);    IF a%% = 10 THEN EXIT DO    b%% = Rand() MOD 20    PRINT FORMAT$(" ##", b%%)  LOOP  PRINTEND FUNCTION' Return pseudo-random integer on 0..32767FUNCTION Rand()  #next&& = #next&& * 1103515245 + 12345END FUNCTION USHORT(#next&& / 65536) MOD 32768' Set seed for Rand()FUNCTION SRand(seed%%)  #next&& = seed%%END FUNCTIONEND PROGRAM
Output:
17  3 3  8 9  718  5 4  0 9 16 0 19 5 1812 16 1  110

XBS

while(true){set n:number = math.random(0,19);log(`first: {n}`);if(n==10){stop}n = math.random(0,19);log(`second: {n}`);}
Output:
first: 0second: 13first: 11second: 10first: 16second: 3first: 8second: 19first: 7second: 10first: 10

XPL0

include c:\cxpl\codes;int N;loop    [N:= Ran(20);        IntOut(0, N);        if N=10 then quit;        ChOut(0, 9\tab\);        IntOut(0, Ran(20));        CrLf(0);        ]
Output:
7       1713      22       100       42       915      1514      1910


Yabasic

doi = int(ran(19))print i using "##";print "  ";if i = 10 then break : fii = int(ran(19))print i using "##", "  ";loopprintend

Zig

const std = @import("std");pub fn main() !void {    const RndGen = std.rand.DefaultPrng;    var rnd = RndGen.init(42);    // possible improvement: make rng fair    var rand_num1: u5 = undefined;    var rand_num2: u5 = undefined;    while (true) {        rand_num1 = rnd.random().int(u5) % 20;        try std.io.getStdOut().writer().print("{d}\n", .{rand_num1});        if (rand_num1 == 10)            break;        rand_num2 = rnd.random().int(u5) % 20;        try std.io.getStdOut().writer().print("{d}\n", .{rand_num2});    }}

Works with: 0.14.x, 0.15.0-dev.849+36499c251

const std = @import("std");pub fn main() !void {    const stdout = std.io.getStdOut().writer();    var prng = std.Random.DefaultPrng.init(blk: {        var seed: u64 = undefined;        try std.posix.getrandom(std.mem.asBytes(&seed));        break :blk seed;    });    const rand = prng.random();    while (true) {        const n1 = rand.intRangeAtMost(u8, 0, 19);        try stdout.print("{d:2}  ", .{n1});        if (n1 == 10) {            break;        }        const n2 = rand.intRangeAtMost(u8, 0, 19);        try stdout.print("{d:2}\n", .{n2});    }    try stdout.print("\n", .{});}
Output:
15  1415  1217  12 3   119  17 6   2 4   0 6  1210

zkl

while(1){n:=(0).random(20); n.print("  ");    if (n==10){ println(); break; } (0).random().println();}
Output:
7  21393410794  321733492318  20503572112  206136100010
Retrieved from "https://rosettacode.org/wiki/Loops/Break?oldid=392962"
Categories:
Hidden category:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

[8]ページ先頭

©2009-2026 Movatter.jp