Loops/Nested: Difference between revisions
< Loops
Content added Content deleted
(added java) |
(add Ruby) |
||
Line 55: | Line 55: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|Ruby}}== |
|||
The break command only jumps out of the innermost loop. |
|||
<lang ruby>srand |
|||
ary = (1..20).to_a.shuffle.each_slice(4).to_a |
|||
p ary |
|||
catch :found_it do |
|||
for row in ary |
|||
for element in row |
|||
print "%2d " % element |
|||
throw :found_it if element == 20 |
|||
end |
|||
puts "," |
|||
end |
|||
end |
|||
puts "done"</lang> |
|||
<pre>[[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]] |
|||
2 12 10 4 , |
|||
18 11 9 3 , |
|||
14 15 7 17 , |
|||
6 19 8 13 , |
|||
1 20 done</pre> |
Revision as of 18:44, 11 June 2009
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Show a nested loop which searches two-dimensional array filled with random number uniformly distributed on [1..20]. The loops iterate rows and columns of the array printing the iterated elements of, until the value 20 is met.
Ada
<lang ada> 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; </lang> Sample output:
16 3 1 17 13 5 4 2 19 1 5 5 17 15 17 2 5 5 17 13 16 10 10 20
Java
<lang java>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; } System.out.println(); } System.out.println(); }
}</lang>
Ruby
The break command only jumps out of the innermost loop. <lang ruby>srand ary = (1..20).to_a.shuffle.each_slice(4).to_a p ary
catch :found_it do
for row in ary for element in row print "%2d " % element throw :found_it if element == 20 end puts "," end
end
puts "done"</lang>
[[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, 20, 16, 5]] 2 12 10 4 , 18 11 9 3 , 14 15 7 17 , 6 19 8 13 , 1 20 done