User Tools

Site Tools


java_100_doors

Java 100 Doors

Return to 100 Doors

There are 100 doors in a row that are all initially closed.

You make 100 passes by the doors.

The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it).

The second time, only visit every 2nd door   (door #2, #4, #6, …),   and toggle it.

The third time, visit every 3rd door   (door #3, #6, #9, …), etc,   until you only visit the 100th door.

;Task: Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed?

Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares.

Opening only those doors is an &nbsp; optimization &nbsp; that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages. <br><br>

{{header|Java}}

With an array of boolean

<syntaxhighlight lang=“java”>class HundredDoors {

   public static void main(String[] args) {
       boolean[] doors = new boolean[101];
       for (int i = 1; i < doors.length; i++) {
           for (int j = i; j < doors.length; j += i) {
               doors[j] = !doors[j];
           }
       }
       for (int i = 1; i < doors.length; i++) {
           if (doors[i]) {
               System.out.printf("Door %d is open.%n", i);
           }
       }
   }
}</syntaxhighlight>

With a BitSet

<syntaxhighlight lang=“java”>import java.util.BitSet;

public class HundredDoors {

   public static void main(String[] args) {
       final int n = 100;
       var a = new BitSet(n);
       for (int i = 1; i <= n; i++) {
           for (int j = i - 1; j < n; j += i) {
               a.flip(j);
           }
       }
       a.stream().map(i -> i + 1).forEachOrdered(System.out::println);
   }
}</syntaxhighlight>

Only print the result

<syntaxhighlight lang=“java”>class HundredDoors {

   public static void main(String[] args) {
       for (int i = 1; i <= 10; i++)
           System.out.printf("Door %d is open.%n", i * i);
   }
}</syntaxhighlight>

Output:

Door 1 is open.
Door 4 is open.
Door 9 is open.
Door 16 is open.
Door 25 is open.
Door 36 is open.
Door 49 is open.
Door 64 is open.
Door 81 is open.
Door 100 is open.

If only printing the result is required, using streams. <syntaxhighlight lang=“java”>import java.util.stream.Collectors; import java.util.stream.IntStream;

class HundredDoors {

   public static void main(String args[]) {
       String openDoors = IntStream.rangeClosed(1, 100)
               .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i)
               .mapToObj(Integer::toString)
               .collect(Collectors.joining(", "));
       System.out.printf("Open doors: %s%n", openDoors);
   }
} </syntaxhighlight>

Output:

Open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
java_100_doors.txt · Last modified: 2024/04/28 03:45 (external edit)