How to resolve the algorithm 100 doors step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm 100 doors step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

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.

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   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 100 doors step by step in the UNIX Shell programming language

Source code in the unix programming language

#! /bin/bash

declare -a doors
for((i=1; i <= 100; i++)); do
    doors[$i]=0
done

for((i=1; i <= 100; i++)); do
    for((j=i; j <= 100; j += i)); do
	echo $i $j
	doors[$j]=$(( doors[j] ^ 1 ))
    done
done

for((i=1; i <= 100; i++)); do
    if [[ ${doors[$i]} -eq 0 ]]; then
	op="closed"
    else
	op="open"
    fi
    echo $i $op
done

#!/bin/bash

for i in {1..100}; do
  door[$i*$i]=1
  [ -z ${door[$i]} ] && echo "$i closed" || echo "$i open"
done

  

You may also check:How to resolve the algorithm Magic squares of doubly even order step by step in the ALGOL 60 programming language
You may also check:How to resolve the algorithm Compare a list of strings step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Color of a screen pixel step by step in the Wren programming language
You may also check:How to resolve the algorithm Abstract type step by step in the Pascal and Object Pascal programming language
You may also check:How to resolve the algorithm Time a function step by step in the Java programming language