Search code examples
while-loopf#mutable

is it possible to loop though 2 values using only 1 loop?


I have mutable variables x and y, and I can only use a while (something) loop. I want to loop through 0 .. 9 and 0 .. 9. I have made many attempts using different if statements and in different orders. Here's what I have so far.

open System

let mutable x = 0
let mutable y = 0

let n = 9

while x <> n && y <> n do
    Console.SetCursorPosition(x, y)
    printf "."

    // ...

Console.Read() |> ignore

Solution

  • The normal way of doing this would be to use two nested loops - if you're iterating over a known number of items (rather than unboundedly, until some condition holds), then for loop is easier:

    for x in 0 .. 9 do
      for y in 0 .. 9 do
        Console.SetCursorPosition(x, y)
        printf "."
    

    The nested loop iterates 10 times and the outer loop runs the nested one 10 times, so you get 100 executions of the nested body.

    You could do this with just one loop if you iterate over 100 values, i.e. 0 .. 10*10-1 which is 0 .. 99. If you have numbers from 0 to 99, you can then calculate x and y by taking x=n/10 and y=n%10:

    for n in 0 .. 10 * 10 - 1 do
      let x = n / 10
      let y = n % 10
      Console.SetCursorPosition(20+x, y)
      printf "."