Skip to content

Instantly share code, notes, and snippets.

@de-sh
Last active October 19, 2022 12:48
Show Gist options
  • Save de-sh/a690fdfeac976c7764d1f8ab15af539b to your computer and use it in GitHub Desktop.
Save de-sh/a690fdfeac976c7764d1f8ab15af539b to your computer and use it in GitHub Desktop.
A rusty loop based solution to a problem found in the wild

Consider the following problem statement:

There are a 100 monkeys, each has a key that can open or close 100 doors. The monkeys come in sequence from 1 to 100 and open or close doors with numbers from their respective sequence number's multiplication table. i.e. monkey #2 can open all even numbered doors while monkey #50 can open only the doors numbered 50 and 100.

What are the doors left opened after all monkeys have done their monkey business?

Solution: Idea: Door i will be open if the number of factors to i are odd, else it will be closed. Since there are only 100 doors to check and we have to check all doors, a nested loop will be a very effective solution:

let mut doors = [false; 100];
for i in 1..=100 { // iterate through monkeys
  for j in 1..=100/i { // iterate through multiplication table for each monkey, numbers <100
    doors[(i*j) - 1] = !doors[(i*j) - 1]; // arrays are 0 indexed, so subtract 1
  }
}

println!("{:?}", doors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment