Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over 



[
1
,
…
,
20
]


{\displaystyle [1,\ldots ,20]}

.

The loops iterate rows and columns of the array printing the elements until the value 



20


{\displaystyle 20}

 is met.

Specifically, this task also shows how to break out of nested loops.



Related tasks

   Loop over multiple arrays simultaneously
   Loops/Break
   Loops/Continue
   Loops/Do-while
   Loops/Downward for
   Loops/For
   Loops/For with a specified step
   Loops/Foreach
   Loops/Increment loop index within loop body
   Loops/Infinite
   Loops/N plus one half
   Loops/Nested
   Loops/While
   Loops/with multiple ranges
   Loops/Wrong ranges


 
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
 