100 doors: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
m →{{header|FutureBasic}}: removed 'needs attention' Tag: Manual revert |
||
(133 intermediate revisions by 56 users not shown) | |||
Line 25:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V doors = [0B] * 100
L(i) 100
L(j) (i .< 100).step(i + 1)
Line 32:
=={{header|360 Assembly}}==
<syntaxhighlight lang="360asm">* 100 doors 13/08/2015
HUNDOOR CSECT
USING HUNDOOR,R12
Line 75:
=={{header|4DOS Batch}}==
<syntaxhighlight lang=
@echo off
set doors=%@repeat[C,100]
Line 86:
The SET line consists of three functions:
<syntaxhighlight lang="text">
%@left[n,string] ^: Return n leftmost chars in string
%@right[n,string] ^: Return n rightmost chars in string
Line 98:
'''unoptimized'''
Based on BASIC QB64 unoptimized version
<syntaxhighlight lang="6502asm">; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html
; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.
; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC
Line 153:
Largely inspired by the optimized C implementation - makes use of the fact that finally only the doors whose numbers are squares of integers are open, as well as the fact that
<math>n^2 = 1 + 3 + 5 + \ldots + (2n-1)</math>.
<syntaxhighlight lang="6502asm"> ;assumes memory at $02xx is initially set to 0 and stack pointer is initialized
;the 1 to 100 door byte array will be at $0200-$0263 (decimal 512 to 611)
;Zero-page location $01 will hold delta
Line 175:
{{works with|http://www.easy68k.com/ EASy68K v5.13.00}}
Some of the macro code is derived from the examples included with EASy68K.
<syntaxhighlight lang="68000devpac">*-----------------------------------------------------------
* Title : 100Doors.X68
* Written by : G. A. Tippery
Line 290:
=={{header|8080 Assembly}}==
<syntaxhighlight lang="8080asm">page: equ 2 ; Store doors in page 2
doors: equ 100 ; 100 doors
puts: equ 9 ; CP/M string output
Line 335:
=={{header|8th}}==
<syntaxhighlight lang="forth">
\ Array of doors; init to empty; accessing a non-extant member will return
\ 'null', which is treated as 'false', so we don't need to initialize it:
Line 373:
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
'''unoptimized'''
<syntaxhighlight lang=
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program 100doors64.s */
Line 455:
</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang=
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program 100doors64_1.s */
Line 516:
=={{header|ABAP}}==
'''unoptimized'''
<syntaxhighlight lang=
data: lv_door type i,
lv_count type i value 1.
Line 548:
'''unoptimized / functional'''
<syntaxhighlight lang=
cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab
aux TYPE i
Line 564:
Using <math>\sum_{i=1}^n (2i-1) = n^2</math>
<syntaxhighlight lang=
data: lv_square type i value 1,
lv_inc type i value 3.
Line 581:
'''ultra-optimized / imperative'''
<syntaxhighlight lang=
DO 10 TIMES.
DATA(val) = sy-index * sy-index.
Line 589:
'''ultra-optimized / functional'''
<syntaxhighlight lang=
cl_demo_output=>display( REDUCE stringtab( INIT list TYPE stringtab
FOR i = 1 WHILE i <= 10
NEXT list = VALUE #( BASE list ( i * i ) ) ) ).
</syntaxhighlight>
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO INITIALIZE:
SHARE doors
PUT {} IN doors
FOR door IN {1..100}:
PUT 0 IN doors[door]
HOW TO TOGGLE door:
SHARE doors
PUT 1-doors[door] IN doors[door]
HOW TO WALK step:
SHARE doors
PUT step IN door
WHILE door <= 100:
TOGGLE door
PUT door+step IN door
HOW TO DISPLAY OPEN DOORS:
SHARE doors
FOR door IN {1..100}:
IF doors[door] = 1:
WRITE "Door", door, "is open"/
INITIALIZE
FOR pass IN {1..100}: WALK pass
DISPLAY OPEN DOORS</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|ACL2}}==
<syntaxhighlight lang="lisp">(defun rep (n x)
(if (zp n)
nil
Line 620 ⟶ 659:
=={{header|Action!}}==
<syntaxhighlight lang=
PROC Main()
Line 653 ⟶ 692:
{{works with|ActionScript|3.0}}
'''unoptimized'''
<syntaxhighlight lang="actionscript">package {
import flash.display.Sprite;
Line 679 ⟶ 718:
Using #HASH-OFF, OPTION OICC ="^" , CICC ="^"
</pre>
<syntaxhighlight lang="acurity architect">
VAR sStatus: SHORT
VAR sArray: SHORT
Line 823 ⟶ 862:
=={{header|Ada}}==
'''unoptimized'''
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
procedure Doors is
Line 847 ⟶ 886:
'''optimized'''
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 866 ⟶ 905:
=={{header|Agena}}==
Translation of Algol W. Tested with Agena 2.9.5 Win32
<syntaxhighlight lang="agena"># find the first few squares via the unoptimised door flipping method
scope
Line 887 ⟶ 926:
=={{header|Aikido}}==
<syntaxhighlight lang="aikido">
var doors = new int [100]
Line 905 ⟶ 944:
=={{header|ALGOL 60}}==
{{works with|A60}}
'''begin'''
''comment - 100 doors problem in ALGOL-60;''
'''boolean''' '''array''' doors[1:100];
'''integer''' i, j;
'''boolean''' open, closed;
open := '''true''';
closed := '''not''' '''true''';
outstring(1,"100 Doors Problem\n");
''comment - all doors are initially closed;''
'''for''' i := 1 '''step''' 1 '''until''' 100 '''do'''
doors[i] := closed;
''comment''
'' cycle through at increasing intervals''
'' and flip each door encountered;''
'''for''' i := 1 '''step''' 1 '''until''' 100 '''do'''
'''for''' j := i '''step''' i '''until''' 100 '''do'''
doors[j] := '''not''' doors[j];
''comment - show which doors are open;''
outstring(1,"The open doors are:");
'''for''' i := 1 '''step''' 1 '''until''' 100 '''do'''
'''if''' doors[i] '''then'''
outinteger(1,i);
'''end'''
{{out}}
<pre>
Line 946 ⟶ 984:
=={{header|ALGOL 68}}==
'''unoptimized'''
'''PROC''' doors = ('''INT''' limit)'''VOID''':
(
'''MODE''' '''DOORSTATE''' = '''BOOL''';
'''BOOL''' closed = '''FALSE''';
'''BOOL''' open = '''NOT''' closed;
'''MODE''' '''DOORLIST''' = [limit]'''DOORSTATE''';
'''DOORLIST''' the doors;
'''FOR''' i '''FROM''' '''LWB''' the doors '''TO''' '''UPB''' the doors '''DO''' the doors[i]:=closed '''OD''';
'''FOR''' i '''FROM''' '''LWB''' the doors '''TO''' '''UPB''' the doors '''DO'''
'''FOR''' j '''FROM''' '''LWB''' the doors '''BY''' i '''TO''' '''UPB''' the doors '''DO'''
the doors[j] := '''NOT''' the doors[j]
'''OD'''
'''OD''';
'''FOR''' i '''FROM''' '''LWB''' the doors '''TO''' '''UPB''' the doors '''DO'''
print((whole(i,-12)," is ",(the doors[i]|"opened"|"closed"),newline))
'''OD'''
);
doors(100)
'''optimized'''
'''PROC''' doors optimised = ( '''INT''' limit )'''VOID''':
'''FOR''' i '''TO''' limit '''DO'''
'''REAL''' num := sqrt(i);
print((whole(i,0)," is ",('''ENTIER''' num = num |"opened"|"closed"),newline))
'''OD'''
;
doors optimised(100)
=={{header|ALGOL W}}==
'''begin'''
'''integer''' doorMax;
doorMax := 100;
'''begin'''
''% need to start a new block so the array can have variable bounds %''
''% array of doors - door( i ) is true if open, false if closed %''
'''logical''' '''array''' door( 1 :: doorMax );
''% set all doors to closed %''
'''for''' i := 1 '''until''' doorMax '''do''' door( i ) := '''false''';
''% repeatedly flip the doors %''
'''for''' i := 1 '''until''' doorMax
'''do''' '''begin'''
'''for''' j := i '''step''' i '''until''' doorMax
'''do''' '''begin'''
door( j ) := '''not''' door( j )
'''end'''
'''end''';
''% display the results %''
i_w := 1; ''% set integer field width %''
s_w := 1; ''% and separator width %''
'''for''' i := 1 '''until''' doorMax '''do''' '''if''' door( i ) '''then''' writeon( i )
'''end'''
'''end'''.
{{out}}
<pre>
Line 1,019 ⟶ 1,056:
=={{header|ALGOL-M}}==
<syntaxhighlight lang=
BEGIN
Line 1,060 ⟶ 1,097:
=={{header|AmigaE}}==
<syntaxhighlight lang="amigae">PROC main()
DEF t[100]: ARRAY,
pass, door
Line 1,078 ⟶ 1,115:
{{works with|GNU APL}}
<syntaxhighlight lang=
≠⌿⊃doors¨ ⍳100</syntaxhighlight>
'''optimized'''
Line 1,095 ⟶ 1,126:
{{works with|Dyalog APL}}
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
≠⌿0=(⍳100)∘.|⍳100</syntaxhighlight>
Each of the above solutions produces the same output:
{{out}}
<pre>
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1</pre>
However the result is obtained, applying the ⍸ function (which has been in Dyalog since 16.0 and was added to GNU APL in SVN r1368, 2020-12-03) will transform the Boolean array into a list of the indices of the true values (open doors):
<syntaxhighlight lang="apl">⍸≠⌿0=(⍳100)∘.|⍳100</syntaxhighlight>
{{out}}
<pre>1 4 9 16 25 36 49 64 81 100</pre>
=={{header|AppleScript}}==
Line 1,108 ⟶ 1,147:
===Iteration===
<syntaxhighlight lang=
repeat 100 times
set end of is_open to false
Line 1,126 ⟶ 1,165:
display dialog "Open doors: " & open_doors</syntaxhighlight>
----
This is similar to the above, but makes use of the fact that the final status of the first door in each pass is known as it's about to be set and the door number can thus be logged at that point if needed. It makes a separate checking repeat at the end unnecessary, the toggled status boolean doesn't need to be put back into the list, and the door number can be stored in the redundant list slot instead of a separate results list having to be built. It would be satisfying if the first pass, opening all the doors, could be combined with the initial creation of the doors list, but the task description does say "all initially closed"!
<syntaxhighlight lang="applescript">on _100doors()
script o
property doors : {}
end script
repeat 100 times
set end of o's doors to false -- false = "not open".
end repeat
repeat with pass from 1 to 100
if (not item pass of o's doors) then set item pass of o's doors to pass
repeat with d from (pass + pass) to 100 by pass
set item d of o's doors to (not item d of o's doors)
end repeat
end repeat
return o's doors's integers
end _100doors
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
return "Open doors:
" & join(_100doors(), ", ")
</syntaxhighlight>
{{output}}
<syntaxhighlight lang="applescript">"Open doors:
1, 4, 9, 16, 25, 36, 49, 64, 81, 100"</syntaxhighlight>
----
===Functional composition===
<syntaxhighlight lang=
-- finalDoors :: Int -> [(Int, Bool)]
Line 1,278 ⟶ 1,353:
end zip</syntaxhighlight>
{{Out}}
<syntaxhighlight lang=
===Odd numbers of integer factors===
Line 1,284 ⟶ 1,359:
The question of which doors are flipped an odd number of times reduces to the question of which numbers in the range have an odd number of integer factors (for an AppleScript implementation of integerFactors(n) see Factors of An Integer). Using '''map''' from the functional composition example above:
<syntaxhighlight lang=
on factorCountMod2(n)
Line 1,292 ⟶ 1,367:
This, on inspection, and further reflection, then collapses to the even simpler question of which numbers are perfect squares, since all other numbers have an even number of integer factors (n factors below the square root, plus n paired cofactors above the square root). Using '''map''' and '''enumFromTo''' from the functional composition example above:
<syntaxhighlight lang=
on perfectSquaresUpTo(n)
script squared
Line 1,314 ⟶ 1,389:
end run</syntaxhighlight>
{{Out}}
<syntaxhighlight lang=
=={{header|Arbre}}==
<syntaxhighlight lang=
openshut(n):
for x in [1..n]
Line 1,333 ⟶ 1,408:
=={{header|Argile}}==
<syntaxhighlight lang=
close all doors
Line 1,354 ⟶ 1,429:
'''unoptimized'''
<syntaxhighlight lang=
/* ARM assembly Raspberry PI */
Line 1,512 ⟶ 1,587:
</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang=
/*********************************************/
/* optimized version */
Line 1,652 ⟶ 1,727:
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">isOpen: map 1..101 => false
loop 1..100 'pass ->
Line 1,678 ⟶ 1,753:
=={{header|Astro}}==
<syntaxhighlight lang="python">var doors = falses(100)
for a in 1..100: for b in a..a..100:
Line 1,688 ⟶ 1,763:
=={{header|Asymptote}}==
<syntaxhighlight lang=
if (i % i^2 < 11) {
write("Door ", i^2, suffix=none);
Line 1,696 ⟶ 1,771:
=={{header|ATS}}==
<syntaxhighlight lang=
#include "share/atspre_staload.hats"
Line 1,742 ⟶ 1,817:
=={{header|AutoHotkey}}==
=== Standard Approach ===
<syntaxhighlight lang="autohotkey">Loop, 100
Door%A_Index% := "closed"
Line 1,774 ⟶ 1,849:
<math>\sum_{i=1}^n (2i-1) = n^2</math>
<syntaxhighlight lang="autohotkey">increment := 3, square := 1
Loop, 100
If (A_Index = square)
Line 1,781 ⟶ 1,856:
MsgBox,, Succesfull, % SubStr(outstring, 2)</syntaxhighlight>
=== Optimized ===
<syntaxhighlight lang="autohotkey">While (Door := A_Index ** 2) <= 100
Result .= "Door " Door " is open`n"
MsgBox, %Result%</syntaxhighlight>
=={{header|AutoIt}}==
<syntaxhighlight lang=
#include <array.au3>
$doors = 100
Line 1,808 ⟶ 1,883:
=={{header|AWK}}==
'''unoptimized'''
<syntaxhighlight lang="awk">BEGIN {
for(i=1; i <= 100; i++)
{
Line 1,826 ⟶ 1,901:
}</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang="awk">BEGIN {
for(i=1; i <= 100; i++) {
doors[i] = 0 # close the doors
Line 1,842 ⟶ 1,917:
=={{header|Axiom}}==
Unoptimized:<syntaxhighlight lang=
doors := bits(100,closed);
for i in 1..#doors repeat
Line 1,848 ⟶ 1,923:
doors.j := change doors.j
[i for i in 1..#doors | open? doors.i]
</syntaxhighlight>Optimized:<syntaxhighlight lang=
[i^2 for i in 1..sqrt(100)::Integer]</syntaxhighlight>
=={{header|B}}==
{{works with|The Amsterdam Compiler Kit - B|V6.1pre1}}
<syntaxhighlight lang=
{
auto doors[100]; /* != 0 means open */
Line 1,882 ⟶ 1,957:
return(0);
}</syntaxhighlight>
=={{header|BabyCobol}}==
<syntaxhighlight lang="cobol">
* NB: the implementation is rather vanilla
* besides using the idiomatic buffer overrun.
* LOOP is what PERFORM in COBOL is, with defaults.
* MOVE in this language acts like OVE CORRESPONDING,
* which is actually good here.
IDENTIFICATION DIVISION.
PROGRAM-ID. ONE HUNDRED DOORS.
DATA DIVISION.
01 I PICTURE IS 9(3).
01 J LIKE I.
01 DOOR PICTURE IS 9 OCCURS 100 TIMES.
01 STOP LIKE DOOR.
PROCEDURE DIVISION.
* Initialise the data
MOVE HIGH-VALUES TO STOP
MOVE SPACES TO DOOR.
* Do the main algorithm
LOOP VARYING I UNTIL DOOR(I) = 9
LOOP VARYING J FROM I TO 100 BY I
SUBTRACT DOOR (J) FROM 1 GIVING DOOR (J)
END
END.
* Print the results
LOOP VARYING I UNTIL DOOR(I) = 9
DISPLAY "Door" I "is" WITH NO ADVANCING
IF DOOR (I) = 1
THEN DISPLAY "open"
ELSE DISPLAY "closed".
END.
</syntaxhighlight>
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">
OPTION BASE 1
Line 1,911 ⟶ 2,020:
81
100
</pre>
=={{header|Bait}}==
<syntaxhighlight lang="bait">
const NUM_DOORS := 100
fun main() {
// All doors are closed by default (`false`)
mut is_open := []bool{length = NUM_DOORS}
// Make 100 passes by the doors
for pass := 0; pass < 100; pass += 1 {
// Only visit every `pass + 1`th door
for door := pass; door < NUM_DOORS; door += pass + 1 {
is_open[door] = not is_open[door]
}
}
// Print the doors that are open
for i, open in is_open {
if open {
println("Door #${i + 1} is open.")
}
}
}
</syntaxhighlight>
{{out}}
<pre>
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.
</pre>
Line 1,916 ⟶ 2,064:
==={{header|Applesoft BASIC}}===
Based on the Sinclair ZX81 BASIC implementation.
<syntaxhighlight lang="basic">
100 :
110 REM 100 DOORS PROBLEM
Line 1,935 ⟶ 2,083:
==={{header|BASIC256}}===
<syntaxhighlight lang=
dim d(100)
Line 1,972 ⟶ 2,120:
'''ultra optimizado''': portado desde la versión Julia<br>
<syntaxhighlight lang="basic">
for i = 1 to 10 : if i % i^2 < 11 then print "La puerta "; int(i^2); " esta abierta" : end if : next i : end
</syntaxhighlight>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|Applesoft BASIC}}
{{works with|QBasic}}
{{works with|GW-BASIC}}
Based on the Sinclair ZX81 BASIC implementation.
<syntaxhighlight lang="qbasic">100 CLS : REM 10 HOME for Applesoft BASIC
110 DIM D(100)
120 FOR P = 1 TO 100
130 FOR T = P TO 100 STEP P
140 D(T) = NOT D(T)
150 NEXT T
160 NEXT P
170 ' Print "opened" doors
180 FOR I = 1 TO 100
190 IF D(I) THEN PRINT I;" ";
200 NEXT I
210 END</syntaxhighlight>
{{out}}
<pre>>RUN
1 4 9 16 25 36 49 64 81 100 ></pre>
==={{header|Commodore BASIC}}===
Based on the Sinclair ZX81 BASIC implementation.
<syntaxhighlight lang="gwbasic">10 DIM D(100)
20 FOR I=1 TO 100
30 FOR J=I TO 100 STEP I
Line 1,988 ⟶ 2,157:
80 IF D(I) THEN PRINT I,
90 NEXT I</syntaxhighlight>
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|QBasic}}
Based on the Sinclair ZX81 BASIC implementation.
<syntaxhighlight lang="qbasic">100 CLS : REM 10 HOME for Applesoft BASIC
110 DIM D(100)
120 FOR P = 1 TO 100
130 FOR T = P TO 100 STEP P
140 D(T) = NOT D(T)
150 NEXT T
160 NEXT P
170 ' Print "opened" doors
180 FOR I = 1 TO 100
190 IF D(I) THEN PRINT I;" ";
200 NEXT I
210 END</syntaxhighlight>
{{out}}
<pre> 1 4 9 16 25 36 49 64 81 100</pre>
==={{header|IS-BASIC}}===
<syntaxhighlight lang=
110 NUMERIC D(1 TO 100)
120 FOR I=1 TO 100
Line 2,004 ⟶ 2,193:
220 NEXT</syntaxhighlight>
Optimized:
<syntaxhighlight lang=
110 LET NR=1:LET D=3
120 DO
Line 2,010 ⟶ 2,199:
140 LET NR=NR+D:LET D=D+2
150 LOOP WHILE NR<=100</syntaxhighlight>
==={{header|Minimal BASIC}}===
{{works with|IS-BASIC}}
<syntaxhighlight lang="qbasic">10 PRINT "FOLLOWING DOORS ARE OPEN:"
20 LET I = 0
30 REM LOOP
40 LET I = I + 1
50 PRINT I * I; " ";
60 IF I * I < 100 THEN 30
70 END</syntaxhighlight>
==={{header|MSX Basic}}===
Based on the Sinclair ZX81 BASIC implementation.
<syntaxhighlight lang="basic">
10 DIM D(100)
20 FOR I=1 TO 100
30 FOR J=i TO 100 STEP I
40 D(J)=NOT D(J)
50 NEXT J
60 NEXT I
70 FOR I=1 TO 100
80 IF D(I) THEN PRINT I;
90 NEXT I
100 END
</syntaxhighlight>
{{out}}
<pre>
]RUN
1 4 9 16 25 36 49 64 81 100</pre>
===QBasic===
{{works with|QBASIC, QB64}}
'''unoptimized'''
<syntaxhighlight lang="qbasic">REM "100 Doors" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler.
REM Author: G. A. Tippery
REM Date: 12-Feb-2014
Line 2,041 ⟶ 2,258:
'''unoptimized'''
<syntaxhighlight lang="qbasic">DIM doors(0 TO 99)
FOR pass = 0 TO 99
FOR door = pass TO 99 STEP pass + 1
Line 2,058 ⟶ 2,275:
NEXT i</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang="qbasic">DIM doors(0 TO 99)
FOR door = 0 TO 99
IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1
Line 2,070 ⟶ 2,287:
END IF
NEXT i</syntaxhighlight>
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">100 ARRAY D
110 FOR P = 1 TO 100
120 FOR T = P TO 100 STEP P
130 LET D[T] = (D[T] <> 1)
140 NEXT T
150 NEXT P
160 FOR I = 1 TO 100
170 IF D[I] THEN PRINT I;" ";
180 NEXT I
190 END</syntaxhighlight>
==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="tiny basic"> PRINT "Open doors are:"
LET I = 1
10 IF I = 100 THEN END
rem funcion SQR
LET B = I*I
rem funcion MODULO
LET A = I - (I / B) * B
IF A < 11 THEN PRINT B
LET I = I + 1
GOTO 10</syntaxhighlight>
==={{header|Sinclair ZX81 BASIC}}===
Works with only 1k of RAM, although it doesn't leave too much to play with.
<syntaxhighlight lang="basic">10 DIM D(100)
20 FOR I=1 TO 100
30 FOR J=I TO 100 STEP I
Line 2,082 ⟶ 2,324:
80 IF D(I) THEN PRINT I,
90 NEXT I</syntaxhighlight>
=={{header|Batch File}}==
'''unoptimized'''
<syntaxhighlight lang="dos">
@echo off
setlocal enableDelayedExpansion
Line 2,119 ⟶ 2,342:
'''optimized'''
<syntaxhighlight lang="dos">
@echo off
setlocal enableDelayedExpansion
Line 2,132 ⟶ 2,355:
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic">DIM doors%(100)
FOR pass% = 1 TO 100
FOR door% = pass% TO 100 STEP pass%
Line 2,143 ⟶ 2,366:
=={{header|bc}}==
<syntaxhighlight lang="bc">/* 0 means door is closed, 1 means door is open */
for (i = 0; i < 100; i++) {
for (j = i; j < 100; j += (i + 1)) {
Line 2,157 ⟶ 2,380:
=={{header|BCPL}}==
<syntaxhighlight lang=
let start() be
Line 2,196 ⟶ 2,419:
====Unoptimized====
Requires an interpreter with working read-write memory support. Padding the code page with extra blank lines can sometimes help.
<syntaxhighlight lang="befunge">>"d">:00p1-:>:::9%\9/9+g2%!\:9v
$.v_^#!$::$_^#`"c":+g00p+9/9\%<
::<_@#`$:\*:+55:+1p27g1g+9/9\%9
Line 2,202 ⟶ 2,425:
====Optimized====
Just calculates the first 10 perfect squares.
<syntaxhighlight lang="befunge">1+:::*.9`#@_
</syntaxhighlight>
===Befunge-98===
{{works with|CCBI|2.1}}
<syntaxhighlight lang="befunge">108p0>:18p;;>:9g!18g9p08g]
*`!0\|+relet|-1`*aap81::+]
;::+1<r]!g9;>$08g1+:08paa[
*`#@_^._aa</syntaxhighlight>
=={{header|Binary Lambda Calculus}}==
This computes the characteristic sequence of squares by flipping every i'th door in round i, for infinitely many rounds i. But since it's computed lazily and the prefix stabilizes, we can still take the first 100 bits and print them! See corresponding source code at https://github.com/tromp/AIT/blob/master/characteristic_sequences/squares.lam
<pre>0001000100010101000110100000010110000011001110110010100011010000000000101111111000000101111101011001011001000110100001111100110100101111101111000000001011111111110110011001111111011100000000101111110000001011111010110011011100101011000000101111011001011110011110011110110100000000001011011100111011110000000001000000111001110100000000101101110110</pre>
Output
<pre>1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001</pre>
=={{header|Blade}}==
===Unoptimized version===
<syntaxhighlight lang="blade">var doors = [false] * 100
for i in 0..100 {
iter var j = i; j < 100; j += i + 1 {
Line 2,224 ⟶ 2,457:
===Optimized version===
<syntaxhighlight lang="blade">for i in 1..101 {
echo 'Door ${i} is ${i ** 0.5 % 1 > 0 ? "closed" : "open"}'
}</syntaxhighlight>
===Ultra-optimized version===
<syntaxhighlight lang="blade">for i in 1..11 echo 'Door ${i**2} is open'</syntaxhighlight>
=={{header|BlitzMax}}==
Line 2,235 ⟶ 2,468:
'''optimized'''
<syntaxhighlight lang=
i=1
While ((i*i)<=100)
Line 2,248 ⟶ 2,481:
=={{header|BlooP}}==
The currently available BlooP interpreters don't really allow iterating over cells with any level of ease, so instead I loop over each door in turn, running it through all 100 cycles and toggling it when it is a multiple of the step number.
<syntaxhighlight lang=
DEFINE PROCEDURE ''DIVIDE'' [A,B]:
BLOCK 0: BEGIN
Line 2,350 ⟶ 2,583:
Solution 1. Use an indexable array. Local variables are stored in stacks. Each stack corresponds to one variable name and vice versa. Stacks can also be used as arrays, but because of how local variables are implemented, arrays cannot be declared as local variables.
<syntaxhighlight lang="bracmat">( 100doors-tbl
= door step
. tbl$(doors.101) { Create an array. Indexing is 0-based. Add one extra for addressing element nr. 100 }
Line 2,378 ⟶ 2,611:
Solution 2. Use one variable for each door. In Bracmat, a variable name can be any non-empty string, even a number, so we use the numbers 1 .. 100 as variable names, but also as door numbers. When used as variable an extra level of indirection is needed. See the occurrences of <code>?!</code> and <code>!!</code> in the following code.
<syntaxhighlight lang="bracmat">( 100doors-var
= step door
. 0:?door
Line 2,410 ⟶ 2,643:
Solution 3. Use a list and a dedicated positioning pattern to address the right door in the list. Create a new list by concatenating the skipped elements with the toggled elements. This solution is computationally unfavourable because of the many concatenations.
<syntaxhighlight lang="bracmat">( 100doors-list
= doors door doorIndex step
. :?doors
Line 2,437 ⟶ 2,670:
Solution 4. Use a list of objects. Each object can be changed without the need to re-create the whole list.
<syntaxhighlight lang="bracmat">( 100doors-obj
= doors door doorIndex step
. :?doors
Line 2,461 ⟶ 2,694:
These four functions are called in the following way:
<syntaxhighlight lang="bracmat">100doors-tbl$
& 100doors-var$
& 100doors-list$
Line 2,470 ⟶ 2,703:
Version using square numbers:
<syntaxhighlight lang="burlesque">
blsq ) 10ro2?^
{1 4 9 16 25 36 49 64 81 100}
Line 2,476 ⟶ 2,709:
=={{header|BQN}}==
<syntaxhighlight lang=
¯1↓∾{𝕩∾@+10}¨•Fmt¨⟨swch,/swch⟩</syntaxhighlight>
<syntaxhighlight lang="bqn">"⟨ 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ⟩
⟨ 0 3 8 15 24 35 48 63 80 99 ⟩"</syntaxhighlight>
<
The second line then formats the boolean array and the truthy indices into a string for display.
Line 2,489 ⟶ 2,722:
===unoptimized===
{{uses from|Library|C Runtime|component1=printf}}
<syntaxhighlight lang="c">#include <stdio.h>
int main()
Line 2,510 ⟶ 2,743:
Using defensive programming, pointers, sentinel values and some other standard programming practices,
{{uses from|Library|C Runtime|component1=printf}}
<syntaxhighlight lang="c">#include <stdio.h>
#define NUM_DOORS 100
Line 2,537 ⟶ 2,770:
{{uses from|Library|C Runtime|component1=printf}}
<syntaxhighlight lang="c">#include <stdio.h>
int main()
Line 2,559 ⟶ 2,792:
The following ultra-short optimized version demonstrates the flexibility of C loops, but isn't really considered good C style:
<syntaxhighlight lang="c">#include <stdio.h>
int main()
Line 2,569 ⟶ 2,802:
}</syntaxhighlight>
Or really optimize it -- square of an integer is, well, computable:<syntaxhighlight lang=
int main()
Line 2,583 ⟶ 2,816:
===Unoptimized with Modulus % Operator===
<syntaxhighlight lang="csharp">namespace ConsoleApplication1
{
using System;
Line 2,628 ⟶ 2,861:
===Optimized for Orthogonality===
(This version demonstrates a different thought pattern during development, where operation and presentation are separated. It could easily be refactored so that the operations to determine which doors are opened and to display the list of doors would be in separate methods, at which point it would become simple to extract them to separate classes and employ a DI pattern to switch the algorithm or display mechanism being used. It also keeps the calculation clear and concise.)
<syntaxhighlight lang="csharp">namespace ConsoleApplication1
{
using System;
Line 2,651 ⟶ 2,884:
===Unoptimized but Concise===
<syntaxhighlight lang="csharp">namespace ConsoleApplication1
{
using System;
Line 2,672 ⟶ 2,905:
===Optimized for brevity===
<syntaxhighlight lang="csharp">namespace ConsoleApplication1
{
using System;
Line 2,691 ⟶ 2,924:
===Optimized for Flexibility===
This version supports altering the number of doors through console commands. Its main intent is to be flexible and easy to use.
<syntaxhighlight lang="csharp">
using System;
using System.IO;
Line 2,794 ⟶ 3,027:
'''unoptimized '''
<syntaxhighlight lang="cpp">#include <iostream>
int main()
Line 2,814 ⟶ 3,047:
This optimized version makes use of the fact that finally only the doors with square index are open, as well as the fact that <math>(n+1)^2 = 1 + 3 + 5 + \ldots + (2n+1)</math>.
<syntaxhighlight lang="cpp">#include <iostream>
int main()
Line 2,835 ⟶ 3,068:
The only calculation that's really needed:
<syntaxhighlight lang="cpp">#include <iostream> //compiled with "Dev-C++" , from RaptorOne
int main()
Line 2,844 ⟶ 3,077:
Compile time computation using C++17 to produce fastest runtime.
<syntaxhighlight lang="cpp">#include <iostream> // compiled with clang (tags/RELEASE_600/final)
#include <type_traits> // or g++ (GCC) 7.3.1 20180406 -- from hare1039
namespace functional_list // basic building block for template meta programming
Line 2,971 ⟶ 3,204:
=={{header|C1R}}==
<syntaxhighlight lang="c">100_doors</syntaxhighlight>
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="text">
for i=1:1:100 {
set doors(i) = 0
Line 2,989 ⟶ 3,222:
</syntaxhighlight>
Output:
<syntaxhighlight lang="text">
1: open
4: open
Line 3,003 ⟶ 3,236:
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">shared void run() {
print("Open doors (naive): ``naive()``
Open doors (optimized): ``optimized()``");
Line 3,032 ⟶ 3,265:
=={{header|Clarion}}==
<syntaxhighlight lang="clarion">
program
Line 3,076 ⟶ 3,309:
'''Unoptimized'''
<syntaxhighlight lang="clio">fn visit-doors doors step:
if step > 100: doors
else:
Line 3,094 ⟶ 3,327:
'''Optimized'''
<syntaxhighlight lang="clio">[1:100] -> * (@eager) fn i:
i ^ 0.5
-> eq @ (transform i: floor)
Line 3,105 ⟶ 3,338:
'''Unoptimized'''
<syntaxhighlight lang="clips">(deffacts initial-state
(door-count 100)
)
Line 3,172 ⟶ 3,405:
'''Optimized'''
<syntaxhighlight lang="clips">(deffacts initial-state
(door-count 100)
)
Line 3,195 ⟶ 3,428:
=={{header|Clojure}}==
'''Unoptimized / mutable array'''
<syntaxhighlight lang="clojure">(defn doors []
(let [doors (into-array (repeat 100 false))]
(doseq [pass (range 1 101)
Line 3,210 ⟶ 3,443:
'''Unoptimized / functional '''
<syntaxhighlight lang="clojure">(defn doors []
(reduce (fn [doors toggle-idx] (update-in doors [toggle-idx] not))
(into [] (repeat 100 false))
Line 3,225 ⟶ 3,458:
'''Alternative Unoptimized / functional '''
<syntaxhighlight lang="clojure">(defn open-doors []
(->> (for [step (range 1 101), occ (range step 101 step)] occ)
frequencies
Line 3,238 ⟶ 3,471:
'''Optimized / functional'''
<syntaxhighlight lang="clojure">(defn doors []
(reduce (fn [doors idx] (assoc doors idx true))
(into [] (repeat 100 false))
Line 3,252 ⟶ 3,485:
'''Alternative Optimized / functional'''
<syntaxhighlight lang="clojure">(defn open-doors [] (->> (iterate inc 1) (map #(* % %)) (take-while #(<= % 100))))
(defn print-open-doors []
Line 3,260 ⟶ 3,493:
=={{header|CLU}}==
<syntaxhighlight lang="clu">start_up = proc ()
max = 100
po: stream := stream$primary_output()
Line 3,290 ⟶ 3,523:
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. 100Doors.
Line 3,328 ⟶ 3,561:
We use the naive algorithm.
<syntaxhighlight lang="coco">doors = [false] * 100
for pass til doors.length
Line 3,339 ⟶ 3,572:
=={{header|CoffeeScript}}==
'''unoptimized''':
<syntaxhighlight lang="coffeescript">doors = []
for pass in [1..100]
Line 3,353 ⟶ 3,586:
'''optimized''':
<syntaxhighlight lang="coffeescript">isInteger = (i) -> Math.floor(i) == i
console.log door for door in [1..100] when isInteger Math.sqrt door</syntaxhighlight>
'''ultra-optimized''':
<syntaxhighlight lang="coffeescript">console.log Math.pow(i,2) for i in [1..10]</syntaxhighlight>
=={{header|ColdFusion}}==
'''Basic Solution: Returns List of 100 values: 1=open 0=closed'''
<syntaxhighlight lang="coldfusion">
doorCount = 1;
doorList = "";
Line 3,391 ⟶ 3,624:
'''Squares of Integers Solution: Returns List of 100 values: 1=open 0=closed'''
<syntaxhighlight lang="coldfusion">
doorCount = 1;
doorList = "";
Line 3,406 ⟶ 3,639:
'''Display only'''
<syntaxhighlight lang="cfm">// Display all doors
<cfloop from="1" to="100" index="x">
Door #x# Open: #YesNoFormat(ListGetAt(doorList,x))#<br />
Line 3,419 ⟶ 3,652:
'''Another Route'''
<syntaxhighlight lang="cfm"><Cfparam name="doorlist" default="">
<cfloop from="1" to="100" index="i">
<Cfset doorlist = doorlist & 'c,'>
Line 3,435 ⟶ 3,668:
=={{header|Comal}}==
<syntaxhighlight lang="comal">0010 DIM doors#(100)
0020 FOR pass#:=1 TO 100 DO
0030 FOR door#:=pass# TO 100 STEP pass# DO doors#(door#):=NOT doors#(door#)
Line 3,456 ⟶ 3,689:
=={{header|Commodore BASIC}}==
<syntaxhighlight lang="basic">
10 D=100: DIMD(D): P=1
20 PRINT CHR$(147);"PASS: ";P
Line 3,474 ⟶ 3,707:
It emphasizes the functional way of solving this problem.
<syntaxhighlight lang="lisp">(defun visit-door (doors doornum value1 value2)
"visits a door, swapping the value1 to value2 or vice-versa"
(let ((d (copy-list doors))
Line 3,516 ⟶ 3,749:
This is a version that closely follows the problem description and is still quite short. Of all the presented solutions it might be closest to "idiomatic Common Lisp".
<syntaxhighlight lang="lisp">(define-modify-macro toggle () not)
(defun 100-doors ()
Line 3,527 ⟶ 3,760:
'''Unoptimized, ''' n-doors.
<syntaxhighlight lang="lisp">(defun doors (z &optional (w (make-list z)) (n 1))
(if (> n z) w (doors z (toggle w n z) (1+ n))))
Line 3,542 ⟶ 3,775:
'''Optimized, ''' n-doors.
<syntaxhighlight lang="lisp">(defun doors (n)
(loop for a from 1 to n collect
(zerop (mod (sqrt a) 1))))
Line 3,556 ⟶ 3,789:
This is an optimized version, using the perfect square algorithm.
<syntaxhighlight lang="lisp">(defun 100-doors ()
(let ((doors (make-array 100)))
(dotimes (i 10)
Line 3,566 ⟶ 3,799:
Another optimized version, with finer granular separation of functionality (might be a bit excessive).
<syntaxhighlight lang="lisp">(defun perfect-square-list (n)
"Generates a list of perfect squares from 0 up to n"
(loop for i from 1 to (isqrt n) collect (expt i 2)))
Line 3,593 ⟶ 3,826:
This version displays a much more functional solution through the use of MAPCAR.
<syntaxhighlight lang="lisp">(let ((i 0))
(mapcar (lambda (x)
(if (zerop (mod (sqrt (incf i)) 1))
Line 3,601 ⟶ 3,834:
=={{header|Component Pascal}}==
BlackBox Component Builder
<syntaxhighlight lang="oberon2">
MODULE Doors100;
IMPORT StdLog;
Line 3,647 ⟶ 3,880:
=={{header|Coq}}==
Basic solution:
<syntaxhighlight lang="coq">Require Import List.
Fixpoint rep {A} (a : A) n :=
Line 3,675 ⟶ 3,908:
Optimized version ((n+1)^2 = n^2 + 2n + 1):
<syntaxhighlight lang="coq">Require Import List.
Fixpoint prisoo' nd n k accu :=
Line 3,690 ⟶ 3,923:
Unit test:
<syntaxhighlight lang="coq">Goal prison 100 = prisoo 100. compute. reflexivity. Qed.</syntaxhighlight>
Full proof at [https://github.com/spanjel/rosetta github]:
<syntaxhighlight lang="coq">Goal forall n, prison n = prisoo n. Abort.</syntaxhighlight>
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
var doors: uint8[101]; # one extra so we can start at 1
Line 3,737 ⟶ 3,970:
100 is open</pre>
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">do
let i = i + 1
print i * i, " ",
loop i * i < 100</syntaxhighlight>
{{out| Output}}
<pre>1 4 9 16 25 36 49 64 81 100 </pre>
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">doors = Array.new(100, false)
1.upto(100) do |i|
Line 3,753 ⟶ 3,995:
=={{header|D}}==
===Unoptimized===
<syntaxhighlight lang="d">import std.stdio;
const N = 101; // #doors + 1
void main() {
Line 3,770 ⟶ 4,012:
This optimized version prints these squares using an alternative algorithm based on <math>\sum_{i=1}^n (2i-1) = n^2</math>
<syntaxhighlight lang="d">import std.stdio;
const N = 101; // #doors + 1
void main() {
Line 3,780 ⟶ 4,022:
===Other proposals===
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
enum DoorState : bool { closed, open }
Line 3,817 ⟶ 4,059:
'''Unoptimized. Demonstrates very basic language syntax/features.
Program output allows to see what the code is doing:'''
<syntaxhighlight lang="d">
import std.stdio;
Line 3,847 ⟶ 4,089:
The InitializeDoors function demonstrates some of Dafny's advanced features.
<syntaxhighlight lang="dafny">
datatype Door = Closed | Open
Line 3,900 ⟶ 4,142:
=={{header|Dart}}==
'''unoptimized'''
<syntaxhighlight lang="dart">main() {
for (var k = 1, x = new List(101); k <= 100; k++) {
for (int i = k; i <= 100; i += k)
Line 3,909 ⟶ 4,151:
'''optimized version''' (including generating squares without multiplication)
<syntaxhighlight lang="dart">main() {
for(int i=1,s=3;i<=100;i+=s,s+=2)
print("door $i is open");
Line 3,915 ⟶ 4,157:
'''comprehensible (not "code golf") version for a pedestrian language'''
<syntaxhighlight lang="dart">import 'dart:io';
final numDoors = 100;
Line 4,048 ⟶ 4,290:
'''Unoptimized''':
{{works with|GNU dc|1.3.95}}
<syntaxhighlight lang=
## NB: This code uses the dc command "r" via register "r".
## You may comment out the unwanted version.
Line 4,138 ⟶ 4,380:
=={{header|DCL}}==
'''Adapted from optimized Batch example'''
<syntaxhighlight lang=
$! doors.com
$! Excecute by running @doors at prompt.
Line 4,161 ⟶ 4,403:
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec main() void:
byte DOORS = 100;
[DOORS+1] bool door_open;
Line 4,196 ⟶ 4,438:
=={{header|DUP}}==
<syntaxhighlight lang="dup">100[$][0^:1-]# {initialize doors}
%
[s;[$101<][$$;~\:s;+]#%]d: {function d, switch door state function}
Line 4,204 ⟶ 4,446:
Result:
<syntaxhighlight lang="dup">1 open
2 closed
3 closed
Line 4,229 ⟶ 4,471:
=={{header|DWScript}}==
'''Unoptimized'''
<syntaxhighlight lang="delphi">var doors : array [1..100] of Boolean;
var i, j : Integer;
Line 4,244 ⟶ 4,486:
Outputs only open doors to save up space:
<syntaxhighlight lang=
for p in 0..99 {
Line 4,273 ⟶ 4,515:
=={{header|Dylan}}==
'''Unoptimized'''
<syntaxhighlight lang="dylan">define
let
let doors = make(<vector>, size: n, fill: #f);
for (y from x below n by x + 1)
doors[y] := ~doors[y]
end
end;
format-out("open: ");
if (doors[x])
format-out("%d ", x + 1)
end
end
end function;
</syntaxhighlight>
'''Result:'''
open: 1 4 9 16 25 36 49 64 81 100
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">local :open-doors [ rep 101 false ]
for i range 1 100:
Line 4,309 ⟶ 4,558:
This version animates the changes of the doors (as checkboxes).
<syntaxhighlight lang="e">#!/usr/bin/env rune
var toggles := []
Line 4,356 ⟶ 4,605:
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
len d[] 100
for p = 1 to 100
i = p
while i <= 100
d[i] = 1 - d[i]
i += p
.
.
for i = 1 to 100
if d[i] = 1
print i
.
.
</syntaxhighlight>
=={{header|EchoLisp}}==
The result is obviously the same in we run the process backwards. So, we check the state of each door during the 100-th step (opening/closing every door)
<syntaxhighlight lang="lisp">
; initial state = closed = #f
(define doors (make-vector 101 #f))
Line 4,399 ⟶ 4,650:
'''optimized version'''
<syntaxhighlight lang=
Doors := RECORD
UNSIGNED1 DoorNumber;
Line 4,419 ⟶ 4,670:
'''unoptimized version - demonstrating LOOP'''
<syntaxhighlight lang=
Doors := RECORD
UNSIGNED1 DoorNumber;
Line 4,456 ⟶ 4,707:
This is a bit more efficient than the LOOP version
<syntaxhighlight lang=
DoorSet := DATASET(100,TRANSFORM({UNSIGNED1 DoorState},SELF.DoorState := 1));
SetDoors := SET(DoorSet,DoorState);
Line 4,481 ⟶ 4,732:
PROJECT(Res,TRANSFORM({STRING20 txt},SELF.Txt := 'Door ' + COUNTER + ' is ' + IF(LEFT.DoorState=1,'Open','Closed')));
</syntaxhighlight>
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module OneHundredDoors {
void run() {
Boolean[] doors = new Boolean[100];
for (Int pass : 0 ..< 100) {
for (Int door = pass; door < 100; door += 1+pass) {
doors[door] = !doors[door];
}
}
@Inject Console console;
console.print($|open doors: {doors.mapIndexed((d, i) -> d ? i+1 : 0)
| .filter(i -> i > 0)}
);
}
}</syntaxhighlight>
{{out}}
<pre>
open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
</pre>
=={{header|EDSAC order code}}==
Line 4,490 ⟶ 4,764:
orders (instructions). This would be considered bad practice today,
but was quite usual on the EDSAC.
<syntaxhighlight lang="edsac">
[Hundred doors problem from Rosetta Code website]
[EDSAC program, Initial Orders 2]
Line 4,623 ⟶ 4,897:
=={{header|Eero}}==
<syntaxhighlight lang="objc">
#import <Foundation/Foundation.h>
Line 4,644 ⟶ 4,918:
=={{header|Egel}}==
<syntaxhighlight lang=
import "prelude.eg"
Line 4,676 ⟶ 4,950:
=={{header|EGL}}==
<syntaxhighlight lang=
program OneHundredDoors
Line 4,720 ⟶ 4,994:
'''file: application.e'''
<syntaxhighlight lang="eiffel">note
description: "100 Doors problem"
date: "08-JUL-2015"
Line 4,814 ⟶ 5,088:
'''file: door.e'''
<syntaxhighlight lang="eiffel">note
description: "A door with an address and an open or closed state."
date: "08-JUL-2015"
Line 4,895 ⟶ 5,169:
'''Standard Approach'''
<syntaxhighlight lang="ela">open generic
type Door = Open | Closed
Line 4,908 ⟶ 5,182:
'''Alternate Approach'''
<syntaxhighlight lang="ela">open list
run n = takeWhile (<n) [& k*k \\ k <- [1..]]</syntaxhighlight>
=={{header|Elena}}==
ELENA
<syntaxhighlight lang="elena">import system'routines;
import extensions;
public program()
{
var Doors := Array.allocate(100).populate::(n=>false);
for(int i := 0
{
for(int j := i
{
Doors[j] := Doors[j].Inverted
Line 4,927 ⟶ 5,201:
};
for(int i := 0
{
console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed"))
Line 4,936 ⟶ 5,210:
=={{header|Elixir}}==
<syntaxhighlight lang=
def doors(n \\ 100) do
List.duplicate(false, n)
Line 4,972 ⟶ 5,246:
=={{header|Elm}}==
<syntaxhighlight lang=
import List exposing (indexedMap, foldl, repeat, range)
import Html exposing (text)
Line 4,995 ⟶ 5,269:
'''Unoptimized'''
<syntaxhighlight lang="lisp">(defun create-doors ()
"Returns a list of closed doors
Line 5,078 ⟶ 5,352:
;; Print the final solution on the buffer
(print-doors (main-program))</syntaxhighlight>
=={{header|EMal}}==
<syntaxhighlight lang="emal">
type Door:State
enum do int CLOSED, OPEN end
type Door
model
int id
Door:State state
new by int =id, Door:State =state do end
fun toggle ← <|me.state ← when(me.state æ Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED)
fun asText ← <|"Door #" + me.id + " is " + when(me.state æ Door:State.CLOSED, "closed", "open")
end
type Main
^|There are 100 doors in a row that are all initially closed.|^
List doors ← Door[].with(100, <int i|Door(i + 1, Door:State.CLOSED))
^|You make 100 passes by the doors.|^
for int pass ← 0; pass < 100; ++pass
for int i ← pass; i < 100; i += pass + 1
doors[i].toggle()
end
end
^|Which are open, which are closed?|^
for each Door door in doors
if door.state æ Door:State.CLOSED do continue end
writeLine(door)
end
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|Erlang}}==
'''non-optimized'''
<syntaxhighlight lang="erlang">
-module(hundoors).
Line 5,100 ⟶ 5,415:
</syntaxhighlight>
using an array is faster (around 2 time faster for 100 doors but already 25 faster for 10 000 doors)
<syntaxhighlight lang="erlang">
array_go() -> go(array:new([101, fixed, {default, closed}]), 1, 1).
go(Array, Big, Inc) when Big > 100, Inc =< 100 ->
go(Array, Inc + 1, Inc + 1);
go(Array, Index, Inc) when Inc < 101 ->
go(array:set(Index, toggle(Array, Index), Array), Index + Inc, Inc);
go(Array, _, _) -> array:sparse_to_orddict(Array).
toggle(Array, Index) -> toggle(array:get(Index, Array)).
</syntaxhighlight>
and, as an added benefit, the output is nicer :)
{{out}}
<pre>
task_100_doors:array_go().
[{1,open},
{4,open},
{9,open},
{16,open},
{25,open},
{36,open},
{49,open},
{64,open},
{81,open},
{100,open}]
</pre>
'''optimized'''
<syntaxhighlight lang="erlang">doors() ->
F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end,
Out = fun(X, true) -> io:format("Door ~p: open~n",[X]);
Line 5,110 ⟶ 5,455:
=={{header|ERRE}}==
<syntaxhighlight lang=
! "100 Doors" program for ERRE LANGUAGE
! Author: Claudio Larini
Line 5,141 ⟶ 5,486:
END PROGRAM
</syntaxhighlight>
=={{header|Euler}}==
In Euler, all variables have the value <code>undefined</code> until assigned another value. <code>isu x</code> returns <code>true</code> if x is currently undefined and the and/or operators short-circuit.
'''begin''' '''new''' doors; '''new''' i; '''label''' doorLoop; '''label''' outDoors;
doors <- '''list''' 100;
i <- 0;
doorLoop: '''if''' [ i <- i + 1 ] <= '''length''' doors '''then''' '''begin'''
'''new''' j; '''label''' flipLoop;
j <- 0;
flipLoop: '''if''' [ j <- J + i ] <= '''length''' doors '''then''' '''begin'''
doors[ j ] <- '''isu''' doors[ j ] '''or''' '''not''' doors[ j ];
'''goto''' flipLoop
'''end''' '''else''' 0;
'''goto''' doorLoop
'''end''' '''else''' 0;
i <- 0;
outDoors: '''if''' [ i <- i + 1 ] <= '''length''' doors '''then''' '''begin'''
'''if''' doors[ i ] '''then''' '''out''' i '''else''' 0;
'''goto''' outDoors
'''end''' '''else''' 0
'''end''' $
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang=
>function Doors () ...
$ doors:=zeros(1,100);
Line 5,159 ⟶ 5,525:
=={{header|Euphoria}}==
unoptimised
<syntaxhighlight lang=
include std/console.e
sequence doors
Line 5,192 ⟶ 5,558:
Cell C2:
<syntaxhighlight lang=
=IF($A2/C$1=INT($A2/C$1),IF(B2=0,1,IF(B2=1,0)),B2)
</syntaxhighlight>
Cell C3:
<syntaxhighlight lang=
=IF($A3/C$1=INT($A3/C$1),IF(B3=0,1,IF(B3=1,0)),B3)
</syntaxhighlight>
Cell D2:
<syntaxhighlight lang=
=IF($A2/D$1=INT($A2/D$1),IF(C2=0,1,IF(C2=1,0)),C2)
</syntaxhighlight>
Line 5,207 ⟶ 5,573:
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
type doorState=Open|Closed
let flip=function Open->Closed |_->Open
let Doors=Array.create 100 Closed
for n in 1..100 do
Doors|>Array.iteri(fun n g->if g=Open then printf "%d " (n+1)); printfn ""
</syntaxhighlight>
{{out}}
<pre>
1 4 9 16 25 36 49 64 81 100
</pre>
Following is the solution using perfect squares. The coercions in PerfectSquare are, I believe, slightly different in versions prior to 2010 beta and, again, #light is required in those versions.
<syntaxhighlight lang="fsharp">open System
let answer2 =
let PerfectSquare n =
Line 5,258 ⟶ 5,593:
Simple single line solution using nothing but List
<syntaxhighlight lang="fsharp">
[1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1) % pass)=0 then not x else x) doors) (List.init 100 (fun _->false))
</syntaxhighlight>
Line 5,264 ⟶ 5,599:
=={{header|Factor}}==
'''Unoptimized'''
<syntaxhighlight lang=
sequences ;
IN: rosetta.doors
Line 5,291 ⟶ 5,626:
'''Optimized'''
<syntaxhighlight lang=
USING:
formatting
Line 5,304 ⟶ 5,639:
=={{header|Falcon}}==
'''Unoptimized code'''
<syntaxhighlight lang="falcon">doors = arrayBuffer( 101, false )
for pass in [ 0 : doors.len() ]
Line 5,317 ⟶ 5,652:
</syntaxhighlight>
'''Optimized code'''
<syntaxhighlight lang="falcon">
for door in [ 1 : 101 ]: > "Door ", $door, " is: ", fract( door ** 0.5 ) ? "closed" : "open"</syntaxhighlight>
=={{header|FALSE}}==
<syntaxhighlight lang="false">100[$][0 1ø:1-]# {initialize doors}
%
[s;[$101\>][$$;~\:s;+]#%]d: {function d, switch door state function}
Line 5,331 ⟶ 5,666:
Result:
<syntaxhighlight lang="dup">1 open
2 closed
3 closed
Line 5,350 ⟶ 5,685:
=={{header|Fantom}}==
'''Unoptimized'''
<syntaxhighlight lang="fantom">
states := (1..100).toList
100.times |i| {
Line 5,358 ⟶ 5,693:
</syntaxhighlight>
'''Optimized'''
<syntaxhighlight lang="fantom">
echo("Open doors are " + (1..100).toList.findAll { it.toFloat.pow(0.5f).toInt.pow(2) == it})
</syntaxhighlight>
Line 5,364 ⟶ 5,699:
=={{header|FBSL}}==
'''Unoptimised'''
<syntaxhighlight lang="qbasic">#AppType Console
Dim doors[], n As Integer = 100
Line 5,380 ⟶ 5,715:
Pause</syntaxhighlight>
'''Optimised''' (by ML)
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
DIM i = 0, j = 0, door = 1
Line 5,392 ⟶ 5,727:
PAUSE</syntaxhighlight>
=={{header|Fe}}==
<syntaxhighlight lang="clojure">
; macro for finite loop
(= repeat (mac (i n . body)
(list 'do
(list 'let i 0)
(list 'while (list '< i n)
(list '= i (list '+ i 1))
(cons 'do body)))))
; function to get n-th element of list
(= nth (fn (i lst)
(while (< 0 i)
(= i (- i 1))
(= lst (cdr lst)))
lst))
; make list of 100 nils
(repeat i 100 (= doors (cons nil doors)))
; do algorithm iterations
(repeat i 100
(let pos (nth (- i 1) doors))
(while pos
(setcar pos (not (car pos)))
(= pos (nth i pos))))
(print doors)
</syntaxhighlight>
Algorithm iterations can be simplified to:
<syntaxhighlight lang="clojure">
; do algorithm iterations sqrt(100) = 10 times
(repeat i 10 (setcar (nth (- (* i i) 1) doors) 't))
</syntaxhighlight>
=={{header|Fhidwfe}}==
unoptomized
<syntaxhighlight lang=
doors = malloc$ 100u
for uint [0u, sizeof$ doors) with l1 {
Line 5,425 ⟶ 5,795:
'''Unoptimized'''
<syntaxhighlight lang="fish">1001-p01.
>0101-p02.
>101-g001-g+:::aa*)?v101-p03.
Line 5,437 ⟶ 5,807:
=={{header|FOCAL}}==
<syntaxhighlight lang=
1.2 F M=1,100;F N=M,M,100;S D(N)=1-D(N)
1.3 F N=1,100;D 2.0
Line 5,460 ⟶ 5,830:
'''Unoptimized'''
<syntaxhighlight lang="forth">: toggle ( c-addr -- ) \ toggle the byte at c-addr
dup c@ 1 xor swap c! ;
Line 5,480 ⟶ 5,850:
'''Optimized'''
<syntaxhighlight lang="forth">: squared ( n -- n' ) dup * ;
: doors ( n -- )
1 begin 2dup squared >= while
Line 5,492 ⟶ 5,862:
'''unoptimized'''
<syntaxhighlight lang="fortran">program doors
implicit none
integer, allocatable :: door(:)
Line 5,510 ⟶ 5,880:
'''optimized'''
<syntaxhighlight lang="fortran">PROGRAM DOORS
INTEGER, PARAMETER :: n = 100 ! Number of doors
Line 5,532 ⟶ 5,902:
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">
program OneHundredIsOpen;
Line 5,571 ⟶ 5,941:
=={{header|FreeBASIC}}==
===Toggle===
<syntaxhighlight lang="freebasic">' version 27-10-2016
' compile with: fbc -s console
Line 5,608 ⟶ 5,978:
There are 10 doors open</pre>
===Count===
<syntaxhighlight lang="freebasic">' version 27-10-2016
' compile with: fbc -s console
Line 5,643 ⟶ 6,013:
Output is the same as the first version.
=== Optimized===
<syntaxhighlight lang="freebasic">' version 27-10-2016
' compile with: fbc -s console
Line 5,667 ⟶ 6,037:
===Ultra optimizado===
<syntaxhighlight lang="freebasic">' version 16-06-2021
' portado desde Julia
Line 5,679 ⟶ 6,049:
'''Unoptimized'''
<syntaxhighlight lang="fishshell"># Set doors to empty list
set doors
Line 5,708 ⟶ 6,078:
'''Optimized'''
<syntaxhighlight lang="fishshell"># Set doors to empty list
set doors
Line 5,722 ⟶ 6,092:
=={{header|Frink}}==
<syntaxhighlight lang="frink">
doors = new array[[101], false]
for pass=1 to 100
Line 5,733 ⟶ 6,103:
print["$door "]
</syntaxhighlight>
=={{header|FTCBASIC}}==
<syntaxhighlight lang="basic">define i = 0, d = 0
do
let i = i + 1
let d = i * i
print d
loop d < 100
pause
end</syntaxhighlight>
=={{header|FunL}}==
=== Unoptimized ===
<syntaxhighlight lang="funl">for i <- 1..100
r = foldl1( \a, b -> a xor b, [(a|i) | a <- 1..100] )
println( i + ' ' + (if r then 'open' else 'closed') )</syntaxhighlight>
=== Optimized ===
<syntaxhighlight lang="funl">import math.sqrt
for i <- 1..100
Line 5,749 ⟶ 6,133:
<syntaxhighlight lang=
let main(n: i32): [n]bool =
loop is_open = replicate n false for i < n do
Line 5,762 ⟶ 6,146:
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
Line 5,780 ⟶ 6,164:
Output:
<pre style="height:20ex;">
Door 1 is open.
Door 2 is closed.
Line 5,884 ⟶ 6,268:
=={{header|FUZE BASIC}}==
<syntaxhighlight lang="qbasic">READ x,y,z
PRINT "Open doors: ";x;" ";
CYCLE
Line 5,897 ⟶ 6,281:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/100_doors}}
'''Solution'''
The solution consists in having a 100 element array, initialized with FALSE values. In each of the 100 rounds (controlled by a simple FOR-FROM-TO cycle), the values are flipped using a FOR-FROM-TO-STEP cycle. Finally the array is shown, using green colors for open doors, and red for closed ones. The resulting matrix is transposed in order to be shown horizontally.
[[File:Fōrmulæ - 100 doors 01.png]]
The result of calling the function is:
[[File:Fōrmulæ - 100 doors 06.png]]
[[File:Fōrmulæ - 100 doors 02.png]]
'''Improvements. Graphic output, in order to show evolution in time, and an arbitrary number of doors'''
[[File:Fōrmulæ - 100 doors 03.png]]
100 doors, each door is 3x3 pixel:
[[File:Fōrmulæ - 100 doors 04.png]]
[[File:Fōrmulæ - 100 doors 05.png]]
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=10f109e90581b04b9cbc30fdaf49892b Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim bDoor As New Boolean[101]
Dim siCount1, siCount2, siStart As Short
Line 5,927 ⟶ 6,329:
=={{header|GAP}}==
<syntaxhighlight lang="gap">doors := function(n)
local a,j,s;
a := [ ];
Line 5,947 ⟶ 6,349:
=={{header|GDScript}}==
<syntaxhighlight lang=
var doors : Array
doors.resize(door_count)
Line 5,979 ⟶ 6,381:
=={{header|Genie}}==
<syntaxhighlight lang="genie">
// 100 doors problem
// Author: Sinuhe masan (2019)
Line 6,005 ⟶ 6,407:
=={{header|Glee}}==
<syntaxhighlight lang="glee">100` *=0=>d $$ create vector 1..100, create bit pattern d, marking all equal to 0
:for (1..100[.s]){ $$ loop s from 1 to 100
d^(100` %s *=0 )=>d;} $$ d = d xor (bit pattern of vector 1..100 % s)
Line 6,013 ⟶ 6,415:
The resulting output is the bit pattern showing the state of the 100 doors:
<syntaxhighlight lang="glee">Result:
10010000 10000001 00000000 10000000 00010000 00000000 10000000 00000001 00000000 00000000 10000000 00000000 0001</syntaxhighlight>
=={{header|GML}}==
<syntaxhighlight lang="gml">var doors,a,i;
//Sets up the array for all of the doors.
for (i = 1; i<=100; i += 1)
Line 6,050 ⟶ 6,452:
=={{header|Go}}==
'''unoptimized'''
<syntaxhighlight lang="go">package main
import "fmt"
Line 6,094 ⟶ 6,496:
</pre>
'''optimized'''
<syntaxhighlight lang="go">package main
import "fmt"
Line 6,116 ⟶ 6,518:
'''optimized 2'''
<syntaxhighlight lang="go">// 100 (optimized) doors in Go
package main
Line 6,142 ⟶ 6,544:
=={{header|Golfscript}}==
<syntaxhighlight lang="golfscript">100:c;[{0}c*]:d;
c,{.c,>\)%{.d<\.d=1^\)d>++:d;}/}/
[c,{)"door "\+" is"+}%d{{"open"}{"closed"}if}%]zip
Line 6,151 ⟶ 6,553:
added easily; the code was tested using a work-in-progress C interpreter
for a language compatible enough with Golfscript)
<syntaxhighlight lang="golfscript">100,{)}%
{:d.sqrt 2?=
{"open"}{"close"}if"door "d+" is "+\+puts}/</syntaxhighlight>
'''optimized without sqrt'''
<syntaxhighlight lang="golfscript">[{"close"}100*]:d;
10,{)2?(.d<\["open"]\)d>++:d;}/
[100,{)"door "\+" is"+}%d]zip
Line 6,163 ⟶ 6,565:
=={{header|Gosu}}==
'''unoptimized'''
<syntaxhighlight lang="scala">
uses java.util.Arrays
Line 6,184 ⟶ 6,586:
'''optimized'''
<syntaxhighlight lang="scala">
var door = 1
var delta = 0
Line 6,201 ⟶ 6,603:
=={{header|Groovy}}==
'''unoptimized'''
<syntaxhighlight lang="groovy">doors = [false] * 100
(0..99).each {
it.step(100, it + 1) {
Line 6,214 ⟶ 6,616:
Using square roots
<syntaxhighlight lang="groovy">(1..100).each {
println("Door #${it} is ${Math.sqrt(it).with{it==(int)it} ? 'open' : 'closed'}.")
}</syntaxhighlight>
Line 6,220 ⟶ 6,622:
'''optimized b'''
Without using square roots
<syntaxhighlight lang="groovy">doors = ['closed'] * 100
(1..10).each { doors[it**2 - 1] = 'open' }
(0..99).each {
Line 6,227 ⟶ 6,629:
=={{header|GW-BASIC}}==
<syntaxhighlight lang="qbasic">10 DIM A(100)
20 FOR OFFSET = 1 TO 100
30 FOR I = 0 TO 100 STEP OFFSET
Line 6,253 ⟶ 6,655:
'''Unoptimized code:'''
<syntaxhighlight lang="visualfoxpro">#define ARRAY_ELEMENTS 100
PROCEDURE Main()
LOCAL aDoors := Array( ARRAY_ELEMENTS )
Line 6,268 ⟶ 6,670:
'''Optimized code'''
<syntaxhighlight lang="visualfoxpro">#define ARRAY_ELEMENTS 100
PROCEDURE Main()
LOCAL aDoors := Array( ARRAY_ELEMENTS )
Line 6,299 ⟶ 6,701:
=={{header|Haskell}}==
=== Unoptimized ===
<syntaxhighlight lang="haskell">data Door
= Open
| Closed
Line 6,324 ⟶ 6,726:
<pre>[(1,Open),(4,Open),(9,Open),(16,Open),(25,Open),(36,Open),(49,Open),(64,Open),(81,Open),(100,Open)]</pre>
==== One liner (unoptimized) ====
<syntaxhighlight lang="haskell">
run n = findIndices odd $ foldr toggleEvery (replicate n 0) [0..n] where toggleEvery k = zipWith (+) $ cycle $ 1 : replicate k 0
</syntaxhighlight>
=== Optimized ===
(without using square roots)
<syntaxhighlight lang="haskell">gate :: Eq a => [a] -> [a] -> [Door]
gate (x:xs) (y:ys) | x == y = Open : gate xs ys
gate (x:xs) ys = Closed : gate xs ys
Line 6,334 ⟶ 6,739:
run n = gate [1..n] [k*k | k <- [1..]]</syntaxhighlight>
==== One liner (optimized) ====
Alternatively, returning a list of all open gates, it's a one-liner:
<syntaxhighlight lang="haskell">run n = takeWhile (< n) [k*k | k <- [1..]]</syntaxhighlight>
=={{header|Haxe}}==
===Unoptimised===
<syntaxhighlight lang="haxe">
class Main
{
static public function main()
{
findOpenDoors( 100 );
}
static function findOpenDoors( n : Int )
{
var door = [];
for( i in 0...n + 1 ){ door[ i ] = false; }
for( i in 1...n + 1 ){
var j = i;
while( j <= n ){
door[ j ] = ! door[ j ];
j += i;
}
}
for( i in 1...n + 1 ){
if( door[ i ] ){ Sys.print( ' $i' ); }
}
}
}</syntaxhighlight>
{{out}}
<pre>
1 4 9 16 25 36 49 64 81 100
</pre>
===Optimised===
<syntaxhighlight lang="haxe">class RosettaDemo
{
static public function main()
Line 6,352 ⟶ 6,791:
while((i*i) <= n)
{
Sys.
i++;
}
Line 6,360 ⟶ 6,799:
=={{header|HicEst}}==
Unoptimized
<syntaxhighlight lang="hicest">REAL :: n=100, open=1, door(n)
door = 1 - open ! = closed
Line 6,370 ⟶ 6,809:
DLG(Text=door, TItle=SUM(door)//" doors open") </syntaxhighlight>
Optimized
<syntaxhighlight lang="hicest">door = 1 - open ! = closed
DO i = 1, n^0.5
door(i*i) = open
Line 6,378 ⟶ 6,817:
=={{header|HolyC}}==
{{trans|C}}
<syntaxhighlight lang="holyc">U8 is_open[100];
U8 pass = 0, door = 0;
Line 6,395 ⟶ 6,834:
=={{header|Hoon}}==
<syntaxhighlight lang="hoon">|^
=/ doors=(list ?) (reap 100 %.n)
=/ passes=(list (list ?)) (turn (gulf 1 100) pass-n)
Line 6,413 ⟶ 6,852:
=={{header|Huginn}}==
<syntaxhighlight lang="huginn">#! /bin/sh
exec huginn --no-argv -E "${0}"
#! huginn
Line 6,444 ⟶ 6,883:
{{trans|Coco}}
<syntaxhighlight lang="lisp">(setv doors (* [False] 100))
(for [pass (range (len doors))]
Line 6,456 ⟶ 6,895:
=={{header|I}}==
<syntaxhighlight lang="i">software {
var doors = len(100)
Line 6,479 ⟶ 6,918:
'''Unoptimized solution.'''
<syntaxhighlight lang="icon">
procedure main()
door := table(0) # default value of entries is 0
Line 6,490 ⟶ 6,929:
'''Optimized solution.'''
<syntaxhighlight lang="icon">
procedure main()
every write("Door ", i := 1 to 100, " is ", if integer(sqrt(i)) = sqrt(i) then "open" else "closed")
Line 6,498 ⟶ 6,937:
or
<syntaxhighlight lang="icon">procedure main(args)
dMap := table("closed")
every dMap[(1 to sqrt(100))^2] := "open"
Line 6,505 ⟶ 6,944:
=={{header|Idris}}==
<syntaxhighlight lang="idris">import Data.Vect
-- Creates list from 0 to n (not including n)
Line 6,544 ⟶ 6,983:
{{works with|Z-machine|8}}
{{works with|Glulx virtual machine}}
<syntaxhighlight lang="inform7">Hallway is a room.
A toggle door is a kind of thing.
Line 6,575 ⟶ 7,014:
=={{header|Informix 4GL}}==
<syntaxhighlight lang=
MAIN
DEFINE
Line 6,599 ⟶ 7,038:
END MAIN
</syntaxhighlight>
=={{Header|Insitux}}==
<syntaxhighlight lang="insitux">
(var doors (times 100 false))
(for i (range 1 101)
i2 (range (dec i) 100 i)
(var! doors (set-at [i2] (! (i2 doors))))
(continue))
(-> (xmap vec doors)
(filter 1)
(map (comp 0 inc))
(join ", ")
@(str "open doors: "))
</syntaxhighlight>
{{out}}
<pre>
open doors: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
</pre>
=={{header|Io}}==
simple boolean list solution:
<syntaxhighlight lang="io">doors := List clone
100 repeat(doors append(false))
for(i,1,100,
Line 6,609 ⟶ 7,071:
doors foreach(i, x, if(x, "Door #{i + 1} is open" interpolate println))</syntaxhighlight>
Optimized solution:
<syntaxhighlight lang="io">(Range 1 to(10) asList) foreach(v, "Door #{v ** 2} is open." interpolate println)</syntaxhighlight>
Sample output:<pre>Door 1 is open.
Door 4 is open.
Line 6,623 ⟶ 7,085:
=={{header|Ioke}}==
'''Unoptimized Object Oriented solution.'''
<syntaxhighlight lang="ioke">NDoors = Origin mimic
NDoors Toggle = Origin mimic do(
Line 6,646 ⟶ 7,108:
=={{header|Isabelle}}==
<syntaxhighlight lang=
imports Main
begin
Line 6,846 ⟶ 7,308:
=={{header|J}}==
'''unoptimized'''
<syntaxhighlight lang="j"> ~:/ (100 $ - {. 1:)"0 >:i.100
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...
~:/ 0=|/~ >:i.100 NB. alternative
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...
(*/"1)2|>:_ q:>:i.100 NB. alternative
</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang="j"> (e. *:) 1+i.100
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 ...
1 (<:*:i.10)} 100$0 NB. alternative
Line 6,857 ⟶ 7,321:
'''with formatting'''
<syntaxhighlight lang="j"> 'these doors are open: ',": I. (i.101) e. *: 1+i.10
these doors are open: 1 4 9 16 25 36 49 64 81 100
</syntaxhighlight>
Line 6,863 ⟶ 7,327:
=={{header|Janet}}==
<syntaxhighlight lang="janet">
(def doors (seq [_ :range [0 100]] false))
Line 6,880 ⟶ 7,344:
=={{header|Java}}==
=== With an array of boolean ===
<syntaxhighlight lang="java">class HundredDoors {
public static void main(String[] args) {
boolean[] doors = new boolean[101];
Line 6,899 ⟶ 7,363:
=== With a BitSet ===
<syntaxhighlight lang="java">import java.util.BitSet;
public class HundredDoors {
Line 6,916 ⟶ 7,380:
=== Only print the result ===
<syntaxhighlight lang="java">class HundredDoors {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++)
Line 6,936 ⟶ 7,400:
'''If only printing the result is required, using streams.'''
<syntaxhighlight lang="java">import java.util.stream.Collectors;
import java.util.stream.IntStream;
Line 6,958 ⟶ 7,422:
=== ES5 ===
==== Iterative ====
<syntaxhighlight lang="javascript">var doors=[];
for (var i=0;i<100;i++)
doors[i]=false;
for (var i=1;i<=100;i++)
for (var i2=i-1
doors[i2]=!doors[i2];
for (var i=1;i<=100;i++)
console.log("Door %d is %s",i,doors[i-1]?"open":"closed")</syntaxhighlight>
====Functional Composition====
Naive search
<syntaxhighlight lang=
"use strict";
function finalDoors(n) {
Line 7,027 ⟶ 7,492:
})(100);</syntaxhighlight>
==== Optimized (iterative)====
<syntaxhighlight lang="javascript">for (var door = 1; door <= 100; door++) {
var sqrt = Math.sqrt(door);
if (sqrt === (sqrt | 0)) {
Line 7,034 ⟶ 7,499:
}</syntaxhighlight>
Simple for loop. Optimizing the optimized?
<syntaxhighlight lang="javascript">for(var door=1;i<10/*Math.sqrt(100)*/;i++){
console.log("Door %d is open",i*i);
}</syntaxhighlight>
Line 7,040 ⟶ 7,505:
The question of which doors are flipped an odd number of times reduces to the question of which numbers have an odd number of integer factors.
We can simply search for these:
<syntaxhighlight lang=
"use strict";
return range(1, 100)
Line 7,074 ⟶ 7,539:
})(100);</syntaxhighlight>
Or we can note, on inspection and further reflection, that only perfect squares have odd numbers of integer factors - all other numbers have only matched pairs of factors - low factors below the non-integer square root, and the corresponding quotients above the square root. In the case of perfect squares, the additional integer square root (not paired with any other factor than itself) makes the total number of distinct factors odd.
<syntaxhighlight lang=
"use strict";
return perfectSquaresUpTo(100);
Line 7,099 ⟶ 7,564:
=== ES6 ===
<syntaxhighlight lang="javascript">
Array.apply(null, { length: 100 })
.map((v, i) => i + 1)
Line 7,109 ⟶ 7,574:
}
});</syntaxhighlight>
{{works with|SpiderMonkey}}(Firefox) But not most (if any) other JavaScript engines. Array comprehension (<code>[ for... ]</code>) is non-standard.
<syntaxhighlight lang="javascript">// Array comprehension style
[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => {
var door = i + 1
Line 7,117 ⟶ 7,581:
if (sqrt === (sqrt | 0)) {
console.log("Door
}
});</syntaxhighlight>
Line 7,135 ⟶ 7,599:
Or using a more general function for listing perfect squares:
<syntaxhighlight lang=
Line 7,167 ⟶ 7,631:
{{Out}}
<syntaxhighlight lang=
Line 7,174 ⟶ 7,638:
{{works with|JavaScript|Node.js 16.13.0 (LTS)}}
<syntaxhighlight lang=
// Doors can be open or closed.
Line 7,217 ⟶ 7,681:
=={{header|jq}}==
jq arrays have 0 as their index origin, but in the following, the 100 doors are numbered from 1 to 100.
<br>'''Solution by simulation'''<syntaxhighlight lang="jq"># Solution for n doors:
def doors(n):
Line 7,232 ⟶ 7,696:
</syntaxhighlight>
'''Analytical solution'''<syntaxhighlight lang="jq"># Solution for 100 doors:
def solution:
range(1;11) | "Door \(. * .) is open";
Line 7,243 ⟶ 7,707:
* string concatenation by '*'.
<br>
<syntaxhighlight lang="julia">doors = falses(100)
for a in 1:100, b in a:a:100
doors[b] = !doors[b]
Line 7,252 ⟶ 7,716:
'''Gimmicky-optimized''':
<syntaxhighlight lang="julia">for i in 1:10 println("Door $(i^2) is open.") end</syntaxhighlight>
=={{header|K}}==
===K3===
{{works with|Kona}}
Converted from [[#Q|Q]]:
<syntaxhighlight lang="k"> doors:{`closed`open![;2]@#:'1_=,/&:'0=t!\:/:t:!101}</syntaxhighlight>
Optimized 1-based indices:
<syntaxhighlight lang="k"> (1+!10)^2
1 4 9 16 25 36 49 64 81 100</syntaxhighlight>
Indices as a parameterized function:
<syntaxhighlight lang="k"> {(1+!_ x^%2)^2}100
1 4 9 16 25 36 49 64 81 100 </syntaxhighlight>
=={{header|Klingphix}}==
<syntaxhighlight lang=
%n 100 !n
Line 7,282 ⟶ 7,748:
=={{header|Klong}}==
===unoptimized===
<syntaxhighlight lang=
flip::{,/{(1-*x),1_x}'x:#y}
i::0;(100{i::i+1;flip(i;x)}:*100:^0)?1
Line 7,288 ⟶ 7,754:
===optimized===
<syntaxhighlight lang=
(1+!9)^2
</syntaxhighlight>
=={{header|Koka}}==
Iterative version
<syntaxhighlight lang="koka">
type state
Open
Closed
fun toggle(self: state): state
match self
Open -> Closed
Closed -> Open
inline extern unsafe-assign : forall<a> ( v : vector<a>, i : ssize_t, x : a ) -> total ()
c "kk_vector_unsafe_assign"
fun main()
val doors = vector(100, Closed)
for(0,99) fn(pass)
var door := pass
while { door < 99 }
doors.unsafe-assign(door.ssize_t, doors[door].toggle)
door := door + (pass+1)
doors.foreach-indexed fn(idx, it)
match it
Open -> println("door " ++ (idx + 1).show ++ " is open")
Closed -> println("door " ++ (idx + 1).show ++ " is closed")
</syntaxhighlight>
Functional Version (Same definitions as above with different main)
<syntaxhighlight lang="koka">
fun main()
val doors = list(0,99,1,fn(i) Closed)
val transformed = list(1,99).foldl(doors) fn(drs, pass)
drs.map-indexed fn(i, door)
if ((i + 1) % pass) == 0 then door.toggle else door
transformed.foreach-indexed fn(idx, it)
match it
Open -> println("door " ++ (idx + 1).show ++ " is open")
Closed -> println("door " ++ (idx + 1).show ++ " is closed")
</syntaxhighlight>
=={{header|Kotlin}}==
<syntaxhighlight lang=
fun oneHundredDoors(): List<Int> {
repeat(doors.size) { i ->
for (j in i until doors.size step (i + 1)) {
doors[j] = !doors[j]
}
}
return doors
.
if (door) acc + (i + 1) else acc
}
</syntaxhighlight>
=={{header|KQL}}==
<syntaxhighlight lang=
| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)
| mvexpand DoorVisited=DoorsVisited to typeof(int)
Line 7,318 ⟶ 7,831:
{{VI solution|LabVIEW_100_doors.png}}
=={{header|
Translation from Python
<syntaxhighlight lang=
1) unoptimized version
Line 7,359 ⟶ 7,872:
-> 1 4 9 16 25 36 49 64 81 100
</syntaxhighlight>
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&doors = fn.arrayGenerateFrom(fn.inc, 100)
fp.mapper = ($i) -> {
$n
$open = 0
repeat($[n], 100) {
$open $= $i % +|$n?!$open:$open
}
return $open
}
fn.arrayMap(&doors, fp.mapper)
fn.print(Open doors:)
$i
repeat($[i], @&doors) {
if(&doors[$i]) {
fn.printf(\s%03d, parser.op(+|$i))
}
}
fn.println()
</syntaxhighlight>
{{out}}
<pre>
Open doors: 001 004 009 016 025 036 049 064 081 100
</pre>
=={{header|langur}}==
=== not optimized ===
<syntaxhighlight lang="langur">var doors = [false] * 100
for
for
}
}
writeln for[=[]]
</syntaxhighlight>
Or, we could use the foldfrom() function to produce the output.
<syntaxhighlight lang="langur">writeln foldfrom(
</syntaxhighlight>
=== optimized ===
<syntaxhighlight lang="langur">writeln map(
</syntaxhighlight>
{{out}}
Line 7,387 ⟶ 7,927:
=={{header|Lasso}}==
=== Loop ===
<syntaxhighlight lang=
local(root = math_sqrt(loop_count))
local(state = (#root == math_ceil(#root) ? '<strong>open</strong>' | 'closed'))
Line 7,405 ⟶ 7,945:
=={{header|Latitude}}==
<syntaxhighlight lang="latitude">use 'format importAllSigils.
doors := Object clone.
Line 7,428 ⟶ 7,968:
This implementation defines 100 variables, named "1 through "100, rather than using a list. Thanks to Pavel Boytchev, the author of Lhogho, for help with the code.
<syntaxhighlight lang=
;Problem 100 Doors
;Lhogho
Line 7,460 ⟶ 8,000:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">dim doors(100)
for pass = 1 to 100
for door = pass to 100 step pass
Line 7,472 ⟶ 8,012:
=={{header|Lily}}==
<syntaxhighlight lang=
for i in 0...99:
Line 7,492 ⟶ 8,032:
=={{header|xTalk}}==
{{works with|HyperCard}} {{works with|LiveCode}}
<syntaxhighlight lang="lb">
on mouseUp
repeat with tStep = 1 to 100
Line 7,507 ⟶ 8,047:
<syntaxhighlight lang=
;Problem 100 Doors
;FMSLogo
Line 7,523 ⟶ 8,063:
=={{header|LOLCODE}}==
<syntaxhighlight lang=
I HAS A doors ITZ A BUKKIT
Line 7,552 ⟶ 8,092:
=={{header|Lua}}==
<syntaxhighlight lang="lua">local is_open = {}
for pass = 1,100 do
Line 7,573 ⟶ 8,113:
<syntaxhighlight lang=
Module Doors100 {
Dim Doors(1 to 100)
Line 7,601 ⟶ 8,141:
=={{header|M4}}==
<syntaxhighlight lang="m4">define(`_set', `define(`$1[$2]', `$3')')dnl
define(`_get', `defn(`$1[$2]')')dnl
define(`for',`ifelse($#,0,``$0'',`ifelse(eval($2<=$3),1,
Line 7,611 ⟶ 8,151:
for(`x',`1',upper,`1',`door x is _get(`door',x)
')dnl</syntaxhighlight>
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE DOORS
.MCALL .TTYOUT,.EXIT
NDOORS = ^D100
DOORS::
; CLOSE ALL DOORS
MOV #DOORBF+1,R0
CLOSE: CLR (R0)+
CMP R0,#BUFTOP
BLT CLOSE
; VISIT DOORS
MOV #1,R1 ; R1 = PASS
PASS: MOV R1,R2 ; R2 = DOOR
DOOR: COMB DOORBF(R2) ; VISIT DOOR
ADD R1,R2
CMP R2,#NDOORS ; NEXT DOOR
BLE DOOR
INC R1
CMP R1,R2 ; NEXT PASS
BLE PASS
; DISPLAY DOORS AS ASCII 0 OR 1
MOV #DOORBF+1,R1
DISP: MOVB (R1)+,R0
BICB #^C1,R0
BISB #^D48,R0
.TTYOUT
CMP R1,#BUFTOP
BLT DISP
.EXIT
DOORBF: .BLKB NDOORS+1
BUFTOP = .
.END DOORS</syntaxhighlight>
{{out}}
<pre>1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001</pre>
=={{header|MAD}}==
<syntaxhighlight lang=
DIMENSION OPEN(100)
PRINT COMMENT $ $
Line 7,647 ⟶ 8,225:
DOOR 100 IS OPEN.</pre>
=={{header|make}}==
Make does not have any built-in arithmetic. It does have easy access to the shell and plug-ins for other languages but using them would be 'cheating' because the real work would not be done by make. Instead of doing arithmetic with numbers, the number of passes is encoded as the number of X's in $(pass). The door to toggle is encoded as the number of X's in $(count) and toggling a door is achieved by adding a dependency to the door number. To prevent $(count) from containing a huge number of X's the 'if' in $(loop) short circuits the inner loop.
<syntaxhighlight lang="make">.DEFAULT_GOAL:=100
digit=1 2 3 4 5 6 7 8 9
doors:=$(digit) $(foreach i,$(digit),$(foreach j,0 $(digit),$i$j)) 100
$(doors):;@: $(if $(filter %1 %3 %5 %7 %9,$(words $^)),$(info $@))
$(foreach i,$(doors),$(eval $i: $(word $i,0 $(doors))))
0 $(addprefix pass,$(doors)):
pass:=X
dep=$(eval count+=$(pass))$(eval $(words $(count)):pass$(words $(pass)))
loop=$(foreach inner,$(doors),$(if $(word 101,$(count)),,$(dep)))
$(foreach outer,$(doors),$(eval pass+=X)$(eval count:=)$(loop))
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang=
NDoors := proc( N :: posint )
# Initialise, using 0 to represent "closed"
Line 7,669 ⟶ 8,262:
</syntaxhighlight>
To solve the problem, call it with 100 as argument (output not shown here).
<syntaxhighlight lang=
> NDoors( 100 );
</syntaxhighlight>
Here is the optimised version, which outputs only the open doors.
<syntaxhighlight lang=
> seq( i^2, i = 1 .. isqrt( 100 ) );
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
</syntaxhighlight>
Alternatively,
<syntaxhighlight lang=
> [seq]( 1 .. 10 )^~2;
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Line 7,685 ⟶ 8,278:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
'''unoptimized 1'''
<syntaxhighlight lang="mathematica">n=100;
tmp=ConstantArray[-1,n];
Do[tmp[[i;;;;i]]*=-1;,{i,n}];
Line 7,691 ⟶ 8,284:
'''unoptimized 2'''
<syntaxhighlight lang="mathematica">f[n_] = "Closed";
Do[Do[If[f[n] == "Closed", f[n] = "Open", f[n] = "Closed"], {n, k, 100, k}], {k, 1, 100}];
Table[f[n], {n, 1, 100}]</syntaxhighlight>
Line 7,698 ⟶ 8,291:
Mathematica also supports immutable data paradigms, like so:
<syntaxhighlight lang=
Fold[
ReplacePart[#1, (i_ /; Mod[i, #2] == 0) :> (-#1[[i]])] &,
Line 7,708 ⟶ 8,301:
'''optimized 1'''
<syntaxhighlight lang="mathematica">Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}]</syntaxhighlight>
'''optimized 2'''
<syntaxhighlight lang="mathematica">n=100;
a=Range[1,Sqrt[n]]^2
Do[Print["door ",i," is ",If[MemberQ[a,i],"open","closed"]],{i,100}]</syntaxhighlight>
'''optimized 3'''
<syntaxhighlight lang="mathematica">n=100
nn=1
a=0
Line 7,731 ⟶ 8,324:
These will only give the indices for the open doors:
'''unoptimized 2'''
<syntaxhighlight lang="mathematica">Pick[Range[100], Xor@@@Array[Divisible[#1,#2]&, {100,100}]]</syntaxhighlight>
'''optimized 4'''
<syntaxhighlight lang="mathematica">Range[Sqrt[100]]^2</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
Line 7,740 ⟶ 8,333:
===Iterative Method===
'''Unoptimized'''
<syntaxhighlight lang=
for b=1:100
for i = b:b:100
Line 7,749 ⟶ 8,342:
</syntaxhighlight>
'''Optimized'''
<syntaxhighlight lang=
for x=1:100;
if sqrt(x) == floor(sqrt(x))
Line 7,756 ⟶ 8,349:
end
a
</syntaxhighlight>
'''Optimized - Alternative'''
<syntaxhighlight lang="matlab">
doors = zeros(1,100); // 0: closed 1: open
for i = 1:100
doors(i:i:100) = 1-doors(i:i:100)
end
doors
</syntaxhighlight>
'''More Optimized'''
<syntaxhighlight lang=
a = zeros(100,1);
for counter = 1:sqrt(100);
Line 7,767 ⟶ 8,368:
===Vectorized Method===
<syntaxhighlight lang=
%Initialize the doors, make them booleans for easy vectorization
Line 7,784 ⟶ 8,385:
===Known-Result Method===
<syntaxhighlight lang=
doors((1:10).^2) = 1;
Line 7,791 ⟶ 8,392:
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">doors(n) := block([v], local(v),
v: makelist(true, n),
for i: 2 thru n do
Line 7,797 ⟶ 8,398:
sublist_indices(v, 'identity));</syntaxhighlight>
Usage:
<syntaxhighlight lang="maxima">doors(100);
/* [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] */</syntaxhighlight>
=={{header|MAXScript}}==
'''unoptimized'''
<syntaxhighlight lang="maxscript">doorsOpen = for i in 1 to 100 collect false
for pass in 1 to 100 do
Line 7,817 ⟶ 8,418:
)</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang="maxscript">for i in 1 to 100 do
(
root = pow i 0.5
Line 7,824 ⟶ 8,425:
=={{header|Mercury}}==
<syntaxhighlight lang=
:- interface.
:- import_module io.
Line 7,865 ⟶ 8,466:
=={{header|Metafont}}==
<syntaxhighlight lang="metafont">boolean doors[];
for i = 1 upto 100: doors[i] := false; endfor
for i = 1 upto 100:
Line 7,879 ⟶ 8,480:
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
<syntaxhighlight lang="microsoftsmallbasic">
For offset = 1 To 100
For i = 0 To 100 Step offset
Line 7,908 ⟶ 8,509:
Using a map to hold the set of open doors:
<syntaxhighlight lang=
for p in range(1, 100)
for t in range(p, 100, p)
Line 7,921 ⟶ 8,522:
Using an array of boolean values to keep track of door state, and a separate list of indexes of the open doors:
<syntaxhighlight lang=
open = []
for p in range(1, 100)
Line 7,935 ⟶ 8,536:
=={{header|MIPS Assembly}}==
<syntaxhighlight lang="mips">.data
doors: .space 100
num_str: .asciiz "Number "
Line 8,002 ⟶ 8,603:
=={{header|Mirah}}==
<syntaxhighlight lang=
class Door
Line 8,047 ⟶ 8,648:
end
</syntaxhighlight>
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (show (openDoors 100)),
Stdout "\n"]
openDoors :: num->[num]
openDoors doors =
map snd (filter fst (zip2 (doorStates doors) [1..]))
doorStates :: num->[bool]
doorStates doors =
take doors (foldr (zipWith (~=)) (repeat False) (map pass [1..doors]))
pass :: num->[bool]
pass n = tl (concat (repeat (take n (True:repeat False))))
zipWith f x y = map f' (zip2 x y)
where f' (x,y) = f x y </syntaxhighlight>
{{out}}
<pre>[1,4,9,16,25,36,49,64,81,100]</pre>
=={{header|mIRC Scripting Language}}==
<syntaxhighlight lang="mirc">var %d = $str(0 $+ $chr(32),100), %m = 1
while (%m <= 100) {
var %n = 1
Line 8,067 ⟶ 8,689:
=={{header|ML/I}}==
<syntaxhighlight lang=
"" 100 doors
MCINS %.
Line 8,114 ⟶ 8,736:
=={{header|Modula-2}}==
'''unoptimized'''
<syntaxhighlight lang="modula2">MODULE Doors;
IMPORT InOut;
Line 8,152 ⟶ 8,774:
'''optimized'''
<syntaxhighlight lang="modula2">MODULE DoorsOpt;
IMPORT InOut;
Line 8,181 ⟶ 8,803:
=={{header|Modula-3}}==
'''unoptimized'''
<syntaxhighlight lang="modula3">MODULE Doors EXPORTS Main;
IMPORT IO, Fmt;
Line 8,215 ⟶ 8,837:
'''optimized'''
<syntaxhighlight lang="modula3">MODULE DoorsOpt EXPORTS Main;
IMPORT IO, Fmt;
Line 8,240 ⟶ 8,862:
=={{header|MontiLang}}==
<syntaxhighlight lang=
for l 0 endfor
Line 8,269 ⟶ 8,891:
=={{header|MOO}}==
<syntaxhighlight lang="moo">is_open = make(100);
for pass in [1..100]
for door in [pass..100]
Line 8,285 ⟶ 8,907:
=={{header|MoonScript}}==
<syntaxhighlight lang=
for pass = 1,100
Line 8,295 ⟶ 8,917:
=={{header|MUMPS}}==
<syntaxhighlight lang=
For door=1:1:100 Set door(door)=0
For pass=1:1:100 For door=pass:pass:100 Set door(door)='door(door)
Line 8,315 ⟶ 8,937:
=={{header|Myrddin}}==
<syntaxhighlight lang="myrddin">
use std
Line 8,352 ⟶ 8,974:
=={{header|MySQL}}==
<syntaxhighlight lang="mysql">
DROP PROCEDURE IF EXISTS one_hundred_doors;
Line 8,413 ⟶ 9,035:
=={{header|Nanoquery}}==
<syntaxhighlight lang=
// we need 101 since there will technically be a door 0
doors = {false} * 101
Line 8,436 ⟶ 9,058:
=={{header|NetRexx}}==
'''unoptimized'''
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
Line 8,459 ⟶ 9,081:
'''optimized''' (Based on the Java 'optimized' version)
{{trans|Java}}
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
Line 8,480 ⟶ 9,102:
'''optimized 2''' (Based on the Java 'optimized 2' version)
{{trans|Java}}
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
Line 8,492 ⟶ 9,114:
'''optimized 3'''
<syntaxhighlight lang="netrexx">/* NetRexx */
loop i = 1 to 10
Line 8,499 ⟶ 9,121:
=={{header|newLISP}}==
<syntaxhighlight lang=
(let ((x (int (sqrt door-num))))
(if
Line 8,510 ⟶ 9,132:
Not optimized:
<syntaxhighlight lang=
(set 'Doors (array 100)) ;; Default value: nil (Closed)
Line 8,541 ⟶ 9,163:
Output of the boolean array showing the status of the doors. Truth values in Nial arrays are shown as <code>l</code>(true) and <code>o</code>(false):
<syntaxhighlight lang="nial"> n:=100;reduce xor (count n eachright mod count n eachall<1)
looloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo
Line 8,548 ⟶ 9,170:
Indices of the open doors:
<syntaxhighlight lang="nial"> true findall (n:=100;reduce xor (count n eachright mod count n eachall<1))+1
1 4 9 16 25 36 49 64 81 100</syntaxhighlight>
optimized solution:
<syntaxhighlight lang="nial"> count 10 power 2
1 4 9 16 25 36 49 64 81 100</syntaxhighlight>
=={{header|Nim}}==
unoptimized:
<syntaxhighlight lang=
const numDoors = 100
Line 8,572 ⟶ 9,194:
Challenging C++'s compile time computation: https://rosettacode.org/wiki/100_doors#C.2B.2B <br>''outputString'' is evaluated at compile time. Check the resulting binary in case of doubt.
<syntaxhighlight lang=
const numDoors = 100
Line 8,588 ⟶ 9,210:
echo outputString</syntaxhighlight>
=={{header|Oberon-07}}==
[http://oberon07.com/ Oberon-07], by [http://people.inf.ethz.ch/wirth/index.html Niklaus Wirth].
'''IMPORT''' Out;
'''PROCEDURE''' Do*; ''(* In Oberon an asterisk after an identifier is an export mark *)''
'''CONST''' N = 100; len = N + 1;
'''VAR''' i, j: INTEGER;
closed: '''ARRAY''' len '''OF''' BOOLEAN; ''(* Arrays in Oberon always start with index 0; closed[0] is not used *)''
'''BEGIN'''
'''FOR''' i := 1 '''TO''' N '''DO''' closed[i] := '''TRUE''' '''END''';
'''FOR''' i := 1 '''TO''' N '''DO'''
j := 1;
'''WHILE''' j
'''IF''' j '''MOD''' i = 0 '''THEN''' closed[j] := ~closed[j] '''END'''; INC(j) ''(* ~ = NOT *)''
'''END'''
'''END''';
''(* Print a state diagram of all doors *)''
'''FOR''' i := 1 '''TO''' N '''DO'''
'''IF''' (i - 1) '''MOD''' 10 = 0 '''THEN''' Out.Ln '''END''';
'''IF''' closed[i] '''THEN''' Out.String("- ") '''ELSE''' Out.String("+ ") '''END'''
'''END'''; Out.Ln;
''(* Print the numbers of the open doors *)''
'''FOR''' i := 1 '''TO''' N '''DO'''
'''IF''' ~closed[i] '''THEN''' Out.Int(i, 0); Out.Char(" ") '''END'''
'''END'''; Out.Ln
'''END''' Do;
'''END''' Doors.
Execute: Doors.Do<br/>
{{out}}
Line 8,635 ⟶ 9,258:
=={{header|Objeck}}==
'''optimized'''
<syntaxhighlight lang="objeck">
bundle Default {
class Doors {
Line 8,665 ⟶ 9,288:
It uses modern Objective-C syntax such as literals, blocks, and a compiler module import statement.
<syntaxhighlight lang=
@import Foundation;
Line 8,707 ⟶ 9,330:
In a real world program classes are normally separated into different files.
<syntaxhighlight lang=
@import Foundation;
Line 8,780 ⟶ 9,403:
=={{header|OCaml}}==
'''unoptimized'''
<syntaxhighlight lang="ocaml">let max_doors = 100
let show_doors =
Line 8,801 ⟶ 9,424:
'''optimized'''
<syntaxhighlight lang="ocaml">let optimised_flip_doors doors =
for i = 1 to int_of_float (sqrt (float_of_int max_doors)) do
doors.(i*i - 1) <- true
Line 8,811 ⟶ 9,434:
This variant is more '''functional style''' (loops are recursions), unoptimized, and we do rather 100 passes on first element, then 100 * second, to avoid mutable data structures and many intermediate lists.
<syntaxhighlight lang="ocaml">type door = Open | Closed (* human readable code *)
let flipdoor = function Open -> Closed | Closed -> Open
Line 8,837 ⟶ 9,460:
=={{header|Octave}}==
<syntaxhighlight lang="octave">doors = false(100,1);
for i = 1:100
for j = i:i:100
Line 8,856 ⟶ 9,479:
=={{header|Oforth}}==
<syntaxhighlight lang=
| i j l |
100 false Array newWith dup ->l
Line 8,866 ⟶ 9,489:
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define (flip doors every)
(map (lambda (door num)
Line 8,885 ⟶ 9,508:
<pre>
100th doors: (1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
</pre>
=={{header|OmniMark}}==
<syntaxhighlight lang="omnimark">
process
local switch doors size 100 ; all initialised ('1st pass' to false)
repeat over doors
repeat for integer door from #item to 100 by #item
do when doors[door] = false
activate doors[door] ; illustrating alternative to set ... to
else
set doors[door] to false
done
again
again
repeat over doors
do when doors = true
put #error '%d(#item)%n'
done
again
</syntaxhighlight>
{{out}}
<pre>
1
4
9
16
25
36
49
64
81
100
</pre>
'''Optimised version.'''
<syntaxhighlight lang="omnimark">
process
local integer door initial {1}
local integer step initial {3}
repeat
output "Door %d(door) is open%n"
increment door by step
increment step by 2
exit when door > 100
again
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|Onyx}}==
<syntaxhighlight lang=
1 1 100 {Door exch false put} for
$Toggle {dup Door exch get not Door up put} def
Line 9,002 ⟶ 9,691:
=={{header|ooRexx}}==
<syntaxhighlight lang=
do i = 1 to doors~size -- initialize with a collection of closed doors
doors[i] = .door~new(i)
Line 9,047 ⟶ 9,736:
=={{header|OpenEdge/Progress}}==
<syntaxhighlight lang=
DEFINE VARIABLE idoor AS INTEGER NO-UNDO.
DEFINE VARIABLE ipass AS INTEGER NO-UNDO.
Line 9,093 ⟶ 9,782:
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
NumDoors = 100
NumPasses = 100
Line 9,144 ⟶ 9,833:
=={{header|PARI/GP}}==
'''Unoptimized version.'''
<syntaxhighlight lang="parigp">
v=vector(d=100);/*set 100 closed doors*/
for(i=1,d,forstep(j=i,d,i,v[j]=1-v[j]));
Line 9,150 ⟶ 9,839:
</syntaxhighlight>
'''Optimized version.'''
<syntaxhighlight lang="parigp">for(n=1,sqrt(100),print("Door ",n^2," is open."))</syntaxhighlight>
'''Unoptimized version.'''
<syntaxhighlight lang="pari/gp">
doors =vector(100);
print("open doors are : ");
Line 9,164 ⟶ 9,853:
=={{header|Pascal}}==
<syntaxhighlight lang="pascal">Program OneHundredDoors;
var
Line 9,191 ⟶ 9,880:
'''Optimized version.'''
<syntaxhighlight lang="pascal">program OneHundredDoors;
{$APPTYPE CONSOLE}
Line 9,215 ⟶ 9,904:
WriteLn('Close doors: ' + ACloseDoors);
end. </syntaxhighlight>
=={{header|PascalABC.NET}}==
{{trans|F#}}
<syntaxhighlight lang="pascal">
// 100 doors. Nigel Galloway: January 11th., 2023
type doorState=(Open,Closed);
function flip(n:doorState):doorState:=if n=Open then Closed else Open;
var Doors:Array of doorState:=ArrFill(100,Closed);
begin
for var n:=1 to 100 do for var g:=n-1 to 99 step n do Doors[g]:=flip(Doors[g]);
for var n:=0 to 99 do if Doors[n]=Open then write(n+1,' '); writeLn
end.
</syntaxhighlight>
{{out}}
<pre>
1 4 9 16 25 36 49 64 81 100
</pre>
=={{header|Pebble}}==
<syntaxhighlight lang="pebble">;100 doors example program for x86 DOS
;Compiles with Pebble to 95 bytes com executable
program examples\100doors
data
int i[0]
int d[0]
begin
label loop
+1 [i]
[d] = [i] * [i]
echo [d]
crlf
if [d] < 100 then loop
pause
kill
end</syntaxhighlight>
=={{header|Perl}}==
'''unoptimized'''
{{works with|Perl|5.x}}
<syntaxhighlight lang="perl">my @doors;
for my $pass (1 .. 100) {
for (1 .. 100) {
Line 9,233 ⟶ 9,966:
{{works with|Perl|5.x}}
This version flips doors, but doesn't visit (iterate over) doors that aren't toggled. Note: I represent open doors as 0 and closed as 1 just for preference. (When I print it as a bit vector, 0 looks more like an open door to me.)
<syntaxhighlight lang="perl">
#!/usr/bin/perl
use strict;
Line 9,248 ⟶ 9,981:
'''optimized'''
{{works with|Perl|5.x}}
<syntaxhighlight lang="perl">print "Door $_ is open\n" for map $_**2, 1 .. 10;</syntaxhighlight>
<syntaxhighlight lang="perl">print "Door $_ is ", qw"closed open"[int sqrt == sqrt], "\n" for 1..100;</syntaxhighlight>
<syntaxhighlight lang="perl">while( ++$i <= 100 )
{
$root = sqrt($i);
Line 9,264 ⟶ 9,997:
=={{header|Perl5i}}==
<syntaxhighlight lang=
use perl5i::2;
Line 9,348 ⟶ 10,081:
=={{header|Phix}}==
===unoptimised===
<!--<syntaxhighlight lang=
<span style="color: #004080;">sequence</span> <span style="color: #000000;">doors</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat<span style="color: #0000FF;">(<span style="color: #004600;">false<span style="color: #0000FF;">,<span style="color: #000000;">100<span style="color: #0000FF;">)</span>
Line 9,378 ⟶ 10,111:
===optimised===
<!--<syntaxhighlight lang=
<span style="color: #008080;">function</span> <span style="color: #000000;">doors<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">n<span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- returns the perfect squares<=n</span>
Line 9,399 ⟶ 10,132:
=={{header|Phixmonti}}==
<syntaxhighlight lang=
0 l repeat
Line 9,419 ⟶ 10,152:
endfor</syntaxhighlight>
Another way
<syntaxhighlight lang=
0 n repeat /# Make the doors #/
Line 9,433 ⟶ 10,166:
endfor</syntaxhighlight>
Optimized
<syntaxhighlight lang=
=={{header|PHL}}==
Line 9,439 ⟶ 10,172:
===unoptimized===
<syntaxhighlight lang="phl">module doors;
extern printf;
Line 9,466 ⟶ 10,199:
{{trans|C#}}
<syntaxhighlight lang="phl">module var;
extern printf;
Line 9,496 ⟶ 10,229:
See: [http://www.thomporter.com/100doors.php Demo]
'''optimized'''
<syntaxhighlight lang="php"><?php
for ($i = 1; $i <= 100; $i++) {
$root = sqrt($i);
Line 9,505 ⟶ 10,238:
'''unoptimized'''
<syntaxhighlight lang="php"><?php
$doors = array_fill(1, 100, false);
for ($pass = 1; $pass <= 100; ++$pass) {
Line 9,520 ⟶ 10,253:
=={{header|Picat}}==
Non-optimized:
<syntaxhighlight lang=
Doors = new_array(N),
foreach(I in 1..N) Doors[I] := 0 end,
Line 9,539 ⟶ 10,272:
optimized version 1:
<syntaxhighlight lang=
foreach(I in 1..N)
Root = sqrt(I),
Line 9,548 ⟶ 10,281:
optimized version 2:
<syntaxhighlight lang=
println([I**2 : I in 1..N, I**2 <= N]).
</syntaxhighlight>
Line 9,554 ⟶ 10,287:
=={{header|PicoLisp}}==
unoptimized
<syntaxhighlight lang=
(for I 100
(for (D (nth Doors I) D (cdr (nth D I)))
Line 9,560 ⟶ 10,293:
(println Doors) )</syntaxhighlight>
optimized
<syntaxhighlight lang=
(for I (sqrt 100)
(set (nth Doors (* I I)) T) )
Line 9,572 ⟶ 10,305:
With formatting:
<syntaxhighlight lang=
(for I (sqrt 100)
(set (nth Doors (* I I)) T) )
Line 9,585 ⟶ 10,318:
=={{header|Pike}}==
<syntaxhighlight lang="pike">array onehundreddoors()
{
array doors = allocate(100);
Line 9,594 ⟶ 10,327:
}</syntaxhighlight>
optimized version:
<syntaxhighlight lang="pike">array doors = map(enumerate(100,1,1), lambda(int x)
{
return sqrt((float)x)%1 == 0.0;
});</syntaxhighlight>
<syntaxhighlight lang="pike">write("%{%d %d %d %d %d %d %d %d %d %d\n%}\n", doors/10)</syntaxhighlight>
output:
1 0 0 1 0 0 0 0 1 0
Line 9,613 ⟶ 10,346:
=={{header|PL/I}}==
<syntaxhighlight lang="pli">
declare door(100) bit (1) aligned;
declare closed bit (1) static initial ('0'b),
Line 9,638 ⟶ 10,371:
==={{header|PL/I-80}}===
<syntaxhighlight lang="pli">
/* Solution to the 100 doors problem in PLI-80 */
Line 9,683 ⟶ 10,416:
=={{header|PL/M}}==
{{Trans|ALGOL W}}
<syntaxhighlight lang="pli">100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */
/* BDOS SYSTEM CALL */
Line 9,749 ⟶ 10,482:
'''Unoptimized'''
<syntaxhighlight lang="plsql">
DECLARE
TYPE doorsarray IS VARRAY(100) OF BOOLEAN;
Line 9,782 ⟶ 10,515:
END;
</syntaxhighlight>
=={{header|Plain English}}==
{{libheader|Plain English-output}}
{{libheader|Plain English-things}}
<syntaxhighlight lang="text">
To create some doors given a count:
Loop.
If a counter is past the count, exit.
Allocate memory for a door.
Clear the door's flag.
Append the door to the doors.
Repeat.
A door is a flag thing.
To go through some doors given a number and some passes:
Put 0 into a counter.
Loop.
Add the number to the counter.
If the counter is greater than the passes, exit.
Pick a door from the doors given the number.
Invert the door's flag.
Repeat.
To output the states of some doors:
Loop.
Bump a counter.
Get a door from the doors.
If the door is nil, exit.
If the door's flag is set, write "Door " then the counter then " is open" to the output; repeat.
Write "Door " then the counter then " is closed" to the output.
Repeat.
To pass doors given a count and some passes:
Create some doors given the count.
Loop.
If a counter is past the passes, break.
Go through the doors given the counter and the passes.
Repeat.
Output the states of the doors.
Destroy the doors.
A pass is a number.
To pick a door from some doors given a number:
Loop.
If a counter is past the number, exit.
Get the door from the doors.
If the door is nil, exit.
Repeat.
To run:
Start up.
Pass doors given 100 and 100 passes.
Wait for the escape key.
Shut down.
</syntaxhighlight>
{{out}}
<pre>
Door 1 is open
Door 2 is closed
Door 3 is closed
Door 4 is open
Door 5 is closed
Door 6 is closed
Door 7 is closed
Door 8 is closed
Door 9 is open
Door 10 is closed
Door 11 is closed
Door 12 is closed
Door 13 is closed
Door 14 is closed
Door 15 is closed
Door 16 is open
Door 17 is closed
Door 18 is closed
Door 19 is closed
Door 20 is closed
Door 21 is closed
Door 22 is closed
Door 23 is closed
Door 24 is closed
Door 25 is open
Door 26 is closed
Door 27 is closed
Door 28 is closed
Door 29 is closed
Door 30 is closed
Door 31 is closed
Door 32 is closed
Door 33 is closed
Door 34 is closed
Door 35 is closed
Door 36 is open
Door 37 is closed
Door 38 is closed
Door 39 is closed
Door 40 is closed
Door 41 is closed
Door 42 is closed
Door 43 is closed
Door 44 is closed
Door 45 is closed
Door 46 is closed
Door 47 is closed
Door 48 is closed
Door 49 is open
Door 50 is closed
Door 51 is closed
Door 52 is closed
Door 53 is closed
Door 54 is closed
Door 55 is closed
Door 56 is closed
Door 57 is closed
Door 58 is closed
Door 59 is closed
Door 60 is closed
Door 61 is closed
Door 62 is closed
Door 63 is closed
Door 64 is open
Door 65 is closed
Door 66 is closed
Door 67 is closed
Door 68 is closed
Door 69 is closed
Door 70 is closed
Door 71 is closed
Door 72 is closed
Door 73 is closed
Door 74 is closed
Door 75 is closed
Door 76 is closed
Door 77 is closed
Door 78 is closed
Door 79 is closed
Door 80 is closed
Door 81 is open
Door 82 is closed
Door 83 is closed
Door 84 is closed
Door 85 is closed
Door 86 is closed
Door 87 is closed
Door 88 is closed
Door 89 is closed
Door 90 is closed
Door 91 is closed
Door 92 is closed
Door 93 is closed
Door 94 is closed
Door 95 is closed
Door 96 is closed
Door 97 is closed
Door 98 is closed
Door 99 is closed
Door 100 is open
</pre>
=={{header|Pointless}}==
<syntaxhighlight lang="pointless">output =
range(1, 100)
|> map(visit(100))
Line 9,814 ⟶ 10,707:
The PL/I include file "pg.inc" can be found on the [[Polyglot:PL/I and PL/M]] page.
Note the use of text in column 81 onwards to hide the PL/I specifics from the PL/M compiler.
<syntaxhighlight lang="pli">/* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */
doors_100H: procedure options (main);
Line 9,892 ⟶ 10,785:
Probably also rather pointless in its use of actors, but, after all, they're cheap.
<syntaxhighlight lang="pony">
actor Toggler
let doors:Array[Bool]
Line 10,011 ⟶ 10,904:
=={{header|Pop11}}==
'''unoptimized'''
<syntaxhighlight lang="pop11">lvars i;
lvars doors = {% for i from 1 to 100 do false endfor %};
for i from 1 to 100 do
Line 10,025 ⟶ 10,918:
'''optimized'''
<syntaxhighlight lang="pop11">for i to 100 do
lvars root = sqrt(i);
i; if root = round(root) then ' open' ><; else ' closed' ><; endif; =>
Line 10,031 ⟶ 10,924:
=={{header|PostScript}}==
Bruteforce:<syntaxhighlight lang=
1 1 100 { dup 1 sub exch 99 {
dup doors exch get not doors 3 1 roll put
} for } for
doors pstack</syntaxhighlight>Shows: <syntaxhighlight lang="text">[true false false true false false false false true false ...<90 doors later>... true]</syntaxhighlight>
=={{header|Potion}}==
<syntaxhighlight lang=
1 to 100(door):
if (door == square):
Line 10,049 ⟶ 10,942:
=={{header|PowerShell}}==
===unoptimized===
<syntaxhighlight lang="powershell">$doors = @(0..99)
for($i=0; $i -lt 100; $i++) {
$doors[$i] = 0 # start with all doors closed
Line 10,064 ⟶ 10,957:
}</syntaxhighlight>
===Alternative Method===
<syntaxhighlight lang="powershell">function Get-DoorState($NumberOfDoors)
{
begin
Line 10,102 ⟶ 10,995:
}</syntaxhighlight>
===unoptimized Pipeline===
<syntaxhighlight lang="powershell">$doors = 1..100 | ForEach-Object {0}
1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } }
</syntaxhighlight>
===unoptimized Pipeline 2===
<syntaxhighlight lang="powershell">$doors = 1..100 | ForEach-Object {0}
$visited = 1..100
1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } }
</syntaxhighlight>
===unoptimized Pipeline 3 (dynamically build pipeline)===
<syntaxhighlight lang="powershell">1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""}
filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_}
invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host"
Line 10,117 ⟶ 11,010:
===Using Powershell Workflow for Parallelism===
<syntaxhighlight lang="powershell">
Workflow Calc-Doors {
Line 10,129 ⟶ 11,022:
=== optimized ===
<syntaxhighlight lang="powershell">
1..10|%{"Door "+ $_*$_ + " is open"}
</syntaxhighlight>
Line 10,135 ⟶ 11,028:
=={{header|Processing}}==
'''Unoptimized:'''
<syntaxhighlight lang="processing">boolean[] doors = new boolean[100];
void setup() {
Line 10,169 ⟶ 11,062:
==={{header|Processing.R}}===
'''Unoptimized:'''
<syntaxhighlight lang="r">setup <- function() {
for(door in doors(100, 100)) {
stdout$print(paste(door, ""))
Line 10,189 ⟶ 11,082:
=={{header|ProDOS}}==
Uses math module.
<syntaxhighlight lang=
enabledelayedexpansion
editvar /newvar /value=0 /title=closed
Line 10,208 ⟶ 11,101:
Declarative:
<syntaxhighlight lang=
forall(between(1,100,Door), ignore(display(Door))).
Line 10,233 ⟶ 11,126:
Doors as a list:
<syntaxhighlight lang=
length(L, N),
maplist(init, L),
Line 10,271 ⟶ 11,164:
Using dynamic-rules. Tried to be ISO:
<syntaxhighlight lang="prolog">doors(Num, Passes) :-
forall(( everyNth(1,Passes,1,Pass)
, forall((everyNth(Pass,Num,Pass,Door), toggle(Door)))
Line 10,304 ⟶ 11,197:
===optimized===
<syntaxhighlight lang=
Max is floor(sqrt(N)),
forall(between(1, Max, I),
( J is I*I,format('Door ~w is open.~n',[J]))).
</syntaxhighlight>
=={{header|PROMAL}}==
<syntaxhighlight lang="promal">
;;; find the first few squares via the unoptimised door flipping method
PROGRAM hundredDoors
INCLUDE LIBRARY
CON INT doorMax = 100
BYTE door [ doorMax + 1 ] ; door( i ) is true if open, false if closed
WORD i
BYTE j
BEGIN
FOR i = 0 TO doorMax ; set all doors to closed
door[ i ] = false
FOR i = 1 TO doorMax ; repeatedly flip the doors
j = i:<
WHILE j <= doorMax
door[ j ] = not door[ j ]
j = j + i:<
FOR i = 1 TO doorMax ; display the results
IF door[ i ]
OUTPUT " #W", i
OUTPUT "#C"
END
</syntaxhighlight>
=={{header|Pure}}==
<syntaxhighlight lang=
// initialize doors as pairs: number, status where 0 means open
Line 10,349 ⟶ 11,266:
=={{header|Pure Data}}==
<syntaxhighlight lang=
#N canvas 241 375 414 447 10;
Line 10,431 ⟶ 11,348:
=={{header|PureBasic}}==
'''unoptimized'''
<syntaxhighlight lang="purebasic">Dim doors.i(100)
For x = 1 To 100
Line 10,451 ⟶ 11,368:
'''optimized'''
<syntaxhighlight lang=
PrintN("Following Doors are open:")
For i = 1 To 100
Line 10,467 ⟶ 11,384:
=={{header|Pyret}}==
<syntaxhighlight lang="pyret">
data Door:
| open
Line 10,543 ⟶ 11,460:
{{works with|Python|2.5+}}
'''unoptimized'''
<syntaxhighlight lang="python">
doors = [False] * 100
for i in range(100):
Line 10,555 ⟶ 11,472:
A version that only visits each door once:
<syntaxhighlight lang="python">for i in xrange(1, 101):
root = i ** 0.5
print "Door %d:" % i, 'open' if root == int(root) else 'close'</syntaxhighlight>
Line 10,561 ⟶ 11,478:
One liner using a list comprehension, item lookup, and is_integer
<syntaxhighlight lang="python">print '\n'.join(['Door %s is %s' % (i, ('closed', 'open')[(i**0.5).is_integer()]) for i in xrange(1, 101)])</syntaxhighlight>
One liner using a generator expression, ternary operator, and modulo
<syntaxhighlight lang="python">print '\n'.join('Door %s is %s' % (i, 'closed' if i**0.5 % 1 else 'open') for i in range(1, 101))</syntaxhighlight>
{{works with|Python|3.x}}
<syntaxhighlight lang="python">
for i in range(1, 101):
if i**0.5 % 1:
Line 10,578 ⟶ 11,495:
'''ultra-optimized''': ported from Julia version<br>
<syntaxhighlight lang="python">for i in range(1,
=={{header|Q}}==
'''unoptimized'''
<syntaxhighlight lang="q">`closed`open(100#0b){@[x;where y;not]}/100#'(til[100]#'0b),'1b</syntaxhighlight>
Binary function <code>{@[x;where y;not]}</code> is applied using [https://code.kx.com/q/ref/accumulators/#binary-application Over]. The initial state is <code>100#0b</code> and the right argument is a list of 100 boolean masks. The boolean vector result is used to index the pair of states.
Line 10,589 ⟶ 11,506:
'''optimized'''
<syntaxhighlight lang="q">`closed`open (1+til 100) in {x*x} 1+til 10</syntaxhighlight>
'''alternative'''
<syntaxhighlight lang="q">@[100#`closed; -1+{x*x}1+til 10; :; `open]</syntaxhighlight>
=={{header|QB64}}==
<syntaxhighlight lang=
Const Opened = -1, Closed = 0
Dim Doors(1 To 100) As Integer, Passes As Integer, Index As Integer
Line 10,635 ⟶ 11,552:
=={{header|Quackery}}==
'''unoptimized'''
<syntaxhighlight lang=
...
... [ 0
Line 10,661 ⟶ 11,578:
=={{header|R}}==
'''Using a loop'''
<syntaxhighlight lang="rsplus">doors_puzzle <- function(ndoors, passes = ndoors) {
doors <- logical(ndoors)
for (ii in seq(passes)) {
Line 10,674 ⟶ 11,591:
'''optimized'''
<syntaxhighlight lang="rsplus">x <- rep(1, 100)
for (i in 1:100-1) {
x <- xor(x, rep(c(rep(0,i),1), length.out=100))
Line 10,681 ⟶ 11,598:
'''Using a **ply function'''
<syntaxhighlight lang="rsplus">doors_puzzle <- function(ndoors=100,passes=100) {
names(which(table(unlist(sapply(1:passes, function(X) seq(0, ndoors, by=X)))) %% 2 == 1))
}
Line 10,690 ⟶ 11,607:
===Using Reduce===
<syntaxhighlight lang=
f=rep(F,H)
which(Reduce(function(d,n) xor(replace(f,seq(n,H,n),T),d), 1:H, f))</syntaxhighlight>
Line 10,700 ⟶ 11,617:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 10,721 ⟶ 11,638:
Optimized:
<syntaxhighlight lang="racket">
#lang racket
(for ([x (in-range 1 101)] #:when (exact-integer? (sqrt x)))
Line 10,728 ⟶ 11,645:
Unoptimized imperative, with graphic rendering:
<syntaxhighlight lang="racket">
#lang slideshow
(define-syntax-rule (vector-neg! vec pos)
Line 10,755 ⟶ 11,672:
===unoptimized===
{{works with|Rakudo|2015.09"}}
<syntaxhighlight lang=
(.=not for @doors[0, $_ ... 100]) for 1..100;
Line 10,763 ⟶ 11,680:
===optimized===
<syntaxhighlight lang=
===probably the most compact idiom===
<syntaxhighlight lang=
===Here's a version using the cross meta-operator instead of a map:===
<syntaxhighlight lang=
This one prints both opened and closed doors:
<syntaxhighlight lang=
===verbose version, but uses ordinary components===
{{works with|Rakudo|2016.07 Tom Legrady}}
<syntaxhighlight lang=
sub output( @arr, $max ) {
my $output = 1;
Line 10,816 ⟶ 11,733:
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
dim x as integer, y as integer
dim door(1 to 100) as byte
Line 10,854 ⟶ 11,771:
===Unoptimized===
<syntaxhighlight lang="rebol">doors: array/initial 100 'closed
repeat i 100 [
door: at doors i
Line 10,861 ⟶ 11,778:
===Optimized===
<syntaxhighlight lang="rebol">doors: array/initial 100 'closed
repeat i 10 [doors/(i * i): 'open]
</syntaxhighlight>
Line 10,868 ⟶ 11,785:
===Unoptimized===
<syntaxhighlight lang=
Purpose: "100 Doors Problem (Perfect Squares)"
Author: "Barry Arthur"
Line 10,890 ⟶ 11,807:
</syntaxhighlight>
===Using bitset! type===
<syntaxhighlight lang=
doors: make bitset! len: 100
Line 10,901 ⟶ 11,818:
repeat n len [if doors/:n [print n]]
</syntaxhighlight>
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <Show 1 <Walk 1 <Doors>>>;
};
NDoors { = 100; };
Doors { = <Repeat <NDoors> Closed>; };
Repeat {
0 s.val = ;
s.N s.val = s.val <Repeat <- s.N 1> s.val> ;
};
Toggle {
1 Closed e.rest = Open e.rest;
1 Open e.rest = Closed e.rest;
s.N s.door e.rest = s.door <Toggle <- s.N 1> e.rest>;
};
Pass {
s.pass s.door e.doors, <Compare s.door <NDoors>>: '+'
= e.doors;
s.pass s.door e.doors
= <Pass s.pass <+ s.pass s.door> <Toggle s.door e.doors>>;
};
Walk {
s.pass e.doors, <Compare s.pass <NDoors>>: '+'
= e.doors;
s.pass e.doors
= <Walk <+ s.pass 1> <Pass s.pass s.pass e.doors>>;
};
Show {
s.N Open e.rest = <Prout Door s.N is open>
<Show <+ s.N 1> e.rest>;
s.N Closed e.rest = <Show <+ s.N 1> e.rest>;
s.N = ;
};</syntaxhighlight>
{{out}}
<pre>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</pre>
=={{header|Relation}}==
<syntaxhighlight lang=
relation door, state
set i = 1
Line 10,944 ⟶ 11,912:
=={{header|Retro}}==
<syntaxhighlight lang=
#100 doors</syntaxhighlight>
=={{header|REXX}}==
===the idiomatic way===
<syntaxhighlight lang="rexx">/*REXX pgm solves the 100 doors puzzle, doing it the hard way by opening/closing doors.*/
parse arg doors . /*obtain the optional argument from CL.*/
if doors=='' | doors=="," then doors=100 /*not specified? Then assume 100 doors*/
Line 10,983 ⟶ 11,951:
===the shortcut way===
<syntaxhighlight lang="rexx">/*REXX pgm solves the 100 doors puzzle, doing it the easy way by calculating squares.*/
parse arg doors . /*obtain the optional argument from CL.*/
if doors=='' | doors=="," then doors=100 /*not specified? Then assume 100 doors*/
Line 10,997 ⟶ 11,965:
'''Unoptimized'''
<syntaxhighlight lang="ring">doors = list(100)
for i = 1 to 100
doors[i] = false
Line 11,016 ⟶ 11,984:
'''Optimized'''
<syntaxhighlight lang="ring">doors = list(100)
for i = 1 to 100
doors[i] = false
Line 11,030 ⟶ 11,998:
see nl
Next</syntaxhighlight>
=={{header|RPL}}==
{{trans|Python}}
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ { }
{ 100 } 0 CON
1 100 '''FOR''' ii
ii 100 '''FOR''' j
DUP j GET NOT j SWAP PUT ii '''STEP'''
'''IF''' DUP ii GET '''THEN''' SWAP ii + SWAP '''END'''
'''NEXT''' DROP
≫ ''''DOORS'''' STO
|
'''DOORS''' ''( -- { open_doors } )''
doors = [False] * 100
for i in range(100):
for j in range(i, 100, i+1):
doors[j] = not doors[j]
if doors[i} then print(i)
// clean stack
|}
{{out}}
<pre>
1: { 1 4 9 16 25 36 49 64 81 100 }
</pre>
===Optimized===
≪ { } 1 100 '''FOR''' ii '''IF''' ii √ FP NOT '''THEN''' ii + '''END NEXT''' ≫
Run time on standard HP-28S:
* unoptimized: 45 seconds
* optimized: 3 seconds
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">doors = Array.new(101,0)
print "Open doors "
(1..100).step(){ |i|
Line 11,045 ⟶ 12,049:
'''unoptimized; Ruby-way'''
<syntaxhighlight lang="ruby">class Door
attr_reader :state
Line 11,088 ⟶ 12,092:
'''unoptimized'''
<syntaxhighlight lang="ruby">n = 100
Open = "open"
Closed = "closed"
Line 11,109 ⟶ 12,113:
'''optimized'''
<syntaxhighlight lang="ruby">n = 100
(1..n).each do |i|
puts "Door #{i} is #{i**0.5 == (i**0.5).round ? "open" : "closed"}"
Line 11,116 ⟶ 12,120:
'''generic true/false, with another way of handling the inner loop demonstrating Range#step'''
<syntaxhighlight lang="ruby">doors = [false] * 100
100.times do |i|
(i ... doors.length).step(i + 1) do |j|
Line 11,229 ⟶ 12,233:
=={{header|Run BASIC}}==
<syntaxhighlight lang=
print "Open doors ";
for i = 1 to 100
Line 11,240 ⟶ 12,244:
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn main() {
let mut door_open = [false; 100];
for pass in 1..101 {
Line 11,250 ⟶ 12,254:
}
for (i, &is_open) in door_open.iter().enumerate() {
println!(
"Door {} is {}.",
i + 1,
if is_open { "open" } else { "closed" }
);
}
}</syntaxhighlight>
Declarative version of above: <br>
<syntaxhighlight lang="rust">fn main() {
let doors = vec![false; 100]
.iter_mut()
.enumerate()
.map(|(door, door_state)| {
(1..100)
.into_iter()
.filter(|pass| (door + 1) % pass == 0)
.map(|_| {
*door_state = !*door_state;
*door_state
})
.last()
.unwrap()
})
.collect::<Vec<_>>();
println!("{:?}", doors);
Line 11,268 ⟶ 12,286:
Optimized version: <br>
(In this case the printing is the bottleneck so this version is not faster than the above one.)
<syntaxhighlight lang="rust">fn main() {
let squares: Vec<_> = (1..11).map(|n| n * n).collect();
let is_square = |num| squares.binary_search(&num).is_ok();
for i in 1..101 {
let state = if is_square(i) { "open" } else { "closed" };
println!("Door {} is {}", i, state);
}
Line 11,279 ⟶ 12,297:
ultra-optimized: ported from Julia version
<syntaxhighlight lang="rust">fn main() {
for i in 1u32..11u32 {
println!("Door {} is open", i.pow(2));
}
Line 11,286 ⟶ 12,304:
=={{header|S-BASIC}}==
<syntaxhighlight lang=
$constant DOOR_OPEN = 1
$constant DOOR_CLOSED = 0
Line 11,321 ⟶ 12,339:
=={{header|S-lang}}==
<syntaxhighlight lang="s-lang">variable door,
isOpen = Char_Type [101],
pass;
Line 11,345 ⟶ 12,363:
=={{header|Salmon}}==
Here's an unoptimized version:
<syntaxhighlight lang=
for (pass; 1; pass <= 100)
for (door_num; pass; door_num <= 100; pass)
Line 11,355 ⟶ 12,373:
And here's an optimized one-line version:
<syntaxhighlight lang=
And a shorter optimized one-line version:
<syntaxhighlight lang=
=={{header|SAS}}==
<syntaxhighlight lang="sas">data _null_;
open=1;
close=0;
Line 11,378 ⟶ 12,396:
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
main is
doors :ARRAY{BOOL} := #(100);
Line 11,395 ⟶ 12,413:
=={{header|Scala}}==
<syntaxhighlight lang="scala">for { i <- 1 to 100
r = 1 to 100 map (i % _ == 0) reduceLeft (_^_)
} println (i +" "+ (if (r) "open" else "closed"))</syntaxhighlight>
Line 11,407 ⟶ 12,425:
I made a version that optional accepts an argument for the number of doors. It is also a little more a ‘classical’ solution:
<syntaxhighlight lang="scala">
def openDoors(length : Int = 100) = {
var isDoorOpen = new Array[Boolean](length)
Line 11,433 ⟶ 12,451:
"Optimized" version:
<syntaxhighlight lang="scala">val o = 1 to 10 map (i => i * i)
println("open: " + o)
println("closed: " + (1 to 100 filterNot o.contains))</syntaxhighlight>
Line 11,439 ⟶ 12,457:
=={{header|Scheme}}==
'''unoptimized'''
<syntaxhighlight lang="scheme">(define *max-doors* 100)
(define (show-doors doors)
Line 11,467 ⟶ 12,485:
'''optimized'''
<syntaxhighlight lang="scheme">(define (optimised-flip-doors doors)
(define (flip-all i)
(cond ((> i (floor (sqrt *max-doors*))) doors)
Line 11,478 ⟶ 12,496:
'''the 3rd version'''
<syntaxhighlight lang="scheme">(define (N_doors N)
(define (init)
(define (str n)
Line 11,504 ⟶ 12,522:
=={{header|Scilab}}==
{{trans|Octave}}
<syntaxhighlight lang="text">doors=zeros(1,100);
for i = 1:100
for j = i:i:100
Line 11,630 ⟶ 12,648:
=={{header|Seed7}}==
'''unoptimized'''
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
Line 11,655 ⟶ 12,673:
'''optimized'''
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
Line 11,697 ⟶ 12,715:
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">
put false repeated 100 times as a list into Doors100
Line 11,715 ⟶ 12,733:
=={{header|SequenceL}}==
'''Unoptimized'''
<syntaxhighlight lang="sequencel">
import <Utilities/Sequence.sl>;
Line 11,733 ⟶ 12,751:
'''Optimized'''
<syntaxhighlight lang="sequencel">
main := flipDoors([1], 2);
Line 11,742 ⟶ 12,760:
=={{header|SETL}}==
'''Unoptimized'''
<syntaxhighlight lang="setl">program hundred_doors;
const toggle := {['open', 'closed'], ['closed', 'open']};
Line 11,764 ⟶ 12,782:
'''Optimized'''
Exploits the fact that squares are separated by successive odd numbers. Use array replication to insert the correct number of closed doors in between the open ones.
<syntaxhighlight lang="setl">program hundred_doors;
doorStates := (+/ [['closed'] * oddNum with 'open': oddNum in [1,3..17]]);
Line 11,775 ⟶ 12,793:
=={{header|SheerPower 4GL}}==
<syntaxhighlight lang="sp4gl">
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! I n i t i a l i z a t i o n
Line 11,824 ⟶ 12,842:
'''Unoptimized'''
<syntaxhighlight lang="ruby">var doors = []
{ |pass|
Line 11,839 ⟶ 12,857:
'''Optimized'''
<syntaxhighlight lang="ruby">{ |i|
"Door %3d is %s\n".printf(i, <closed open>[i.is_sqr])
} << 1..100</syntaxhighlight>
=={{header|Simula}}==
<syntaxhighlight lang="modula2">BEGIN
INTEGER LIMIT = 100, door, stride;
BOOLEAN ARRAY DOORS(1:LIMIT);
Line 11,865 ⟶ 12,883:
=={{header|Slate}}==
'''Unoptimized'''
<syntaxhighlight lang="slate">define: #a -> (Array newSize: 100).
a infect: [| :_ | False].
Line 11,876 ⟶ 12,894:
'''Optimized'''
<syntaxhighlight lang="slate">define: #a -> (Array newSize: 100).
a infect: [| :_ | False].
Line 11,886 ⟶ 12,904:
{{works with|GNU Smalltalk}}
'''Unoptimized'''
<syntaxhighlight lang="smalltalk">|a|
a := Array new: 100 .
1 to: 100 do: [ :i | a at: i put: false ].
Line 11,903 ⟶ 12,921:
'''Optimized'''
<syntaxhighlight lang="smalltalk">|a|
a := (1 to: 100) collect: [ :x | false ].
1 to: 10 do: [ :i | a at: (i squared) put: true ].
Line 11,915 ⟶ 12,933:
{{works with|Squeak Smalltalk}}
'''Unoptimized, using Morphs'''
<syntaxhighlight lang="smalltalk">
| m w h smh smw delay closedDoor border subMorphList |
Line 11,948 ⟶ 12,966:
=={{header|smart BASIC}}==
<syntaxhighlight lang="qbasic">x=1!y=3!z=0
PRINT "Open doors: ";x;" ";
DO
Line 11,961 ⟶ 12,979:
'''unoptimized'''
<syntaxhighlight lang="snobol4">
DEFINE('PASS(A,I),O') :(PASS.END)
PASS O = 0
Line 12,002 ⟶ 13,020:
'''optimized'''
<syntaxhighlight lang="snobol4">
MAIN D = ARRAY(100,0)
I = 1
Line 12,018 ⟶ 13,036:
The output of this version is almost identical to the above.
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "doors" )
@( description, "Problem: You have 100 doors in a row that are all initially closed. You" )
@( description, "make 100 passes by the doors. The first time through, you visit every door" )
@( description, "and toggle the door (if the door is closed, you open it; if it is open, you" )
@( description, "close it). The second time you only visit every 2nd door (door #2, #4, #6," )
@( description, "...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you" )
@( description, "only visit the 100th door." )
@( description, "Question: What state are the doors in after the last pass? Which are open," )
@( description, "which are closed?" )
@( see_also, "http://rosettacode.org/wiki/100_doors" )
@( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure Doors is
type Door_State is (Closed, Open);
type Door_List is array(1..100) of Door_State;
The_Doors : Door_List;
begin
for I in 1..100 loop
The_Doors(I) := Closed;
end loop;
for I in 1..100 loop
for J in arrays.first(The_Doors)..arrays.last(The_Doors) loop
if J mod I = 0 then
if The_Doors(J) = Closed then
The_Doors(J) := Open;
else
The_Doors(J) := Closed;
end if;
end if;
end loop;
end loop;
for I in arrays.first(The_Doors)..arrays.last(The_Doors) loop
put (I) @ (" is ") @ (The_Doors(I));
new_line;
end loop;
end Doors;</syntaxhighlight>
=={{header|Sparkling}}==
Line 12,023 ⟶ 13,084:
'''unoptimized'''
<syntaxhighlight lang=
var isOpen = {};
var pass, door;
Line 12,047 ⟶ 13,108:
'''optimized'''
<syntaxhighlight lang=
var door_sqrt = 1;
var door;
Line 12,066 ⟶ 13,127:
{{works with|HomeSpun}}
{{works with|OpenSpin}}
<syntaxhighlight lang=
_clkmode = xtal1+pll16x
_clkfreq = 80_000_000
Line 12,107 ⟶ 13,168:
=={{header|SQL}}==
'''optimized'''
<syntaxhighlight lang=
DECLARE @sqr int,
@i int,
Line 12,132 ⟶ 13,193:
</syntaxhighlight>
'''A postgres version, in one request'''
principle: the number of passes per door is counted, if this is odd, the door is open.
<syntaxhighlight lang="sql">
with numbers as (
select generate_series(1, 100) as n
),
passes as (
select passes.n pass, doors.n door
from numbers doors
cross join numbers passes
where doors.n % passes.n = 0 -- modulo
),
counting as (
select door, count(pass) pass_number
from passes
group by door
)
select door from counting
where pass_number % 2 = 1
order by door
</syntaxhighlight>
'''A Oracle version, in one request'''
<syntaxhighlight lang="sql">
with numbers as (
select rownum as n from dual connect by level <= 100
),
passes as (
select doors.n door, count(passes.n) pass_number
from numbers doors
cross join numbers passes
where MOD(doors.n, passes.n) = 0 -- modulo
group by doors.n
)
select door from passes
where MOD(pass_number, 2) = 1
order by door
</syntaxhighlight>
{{out}}
<pre>
door|
----+
1|
4|
9|
...
</pre>
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
With SQL only:
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
Line 12,293 ⟶ 13,406:
=={{header|Standard ML}}==
<syntaxhighlight lang=
datatype Door = Closed | Opened
Line 12,327 ⟶ 13,440:
=={{header|Stata}}==
<syntaxhighlight lang="stata">clear
set obs 100
gen doors=0
Line 12,349 ⟶ 13,462:
| 100 |
+-------+</syntaxhighlight>
=={{header|Stringle}}==
<syntaxhighlight lang="stringle">d "."
#d
i d
#i
p "door" #i
*p *p "."
i d f "oc"
i d #@f #*p
i d .\f "o" $ #i
i i d
#i +101 i ""
#i
d d "."
#d +101 d ""
#d</syntaxhighlight>
{{out}}
<pre>1
4
9
16
25
36
49
64
81
100</pre>
=={{header|SuperCollider}}==
<syntaxhighlight lang=
var n = 100, doors = false ! n;
var pass = { |j| (0, j .. n-1).do { |i| doors[i] = doors[i].not } };
Line 12,362 ⟶ 13,503:
'''unoptimized'''
<syntaxhighlight lang=
enum DoorState : String {
case Opened = "Opened"
Line 12,386 ⟶ 13,527:
'''optimized'''
<syntaxhighlight lang=
enum DoorState : String {
case Opened = "Opened"
Line 12,406 ⟶ 13,547:
println("Door \(index+1) is \(item.rawValue)")
}</syntaxhighlight>
===One-liner===
<syntaxhighlight lang="swift">
var arr: [Bool] = Array(1...100).map{ remquo(exp(log(Float($0))/2.0),1).0 == 0 }
</syntaxhighlight>
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
source hundredDoors
@: [ 1..100 -> 0 ];
Line 12,430 ⟶ 13,575:
'''unoptimized'''
<syntaxhighlight lang="tcl">package require Tcl 8.5
set n 100
set doors [concat - [lrepeat $n 0]]
Line 12,444 ⟶ 13,589:
'''optimized'''
<syntaxhighlight lang="tcl">package require Tcl 8.5
set doors [lrepeat [expr {$n + 1}] closed]
for {set i 1} {$i <= sqrt($n)} {incr i} {
Line 12,457 ⟶ 13,602:
{{libheader|Tk}}
Inspired by the E solution, here's a visual representation
<syntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
Line 12,516 ⟶ 13,661:
=={{header|TI-89 BASIC}}==
<syntaxhighlight lang="ti89b">Define doors(fast) = Func
Local doors,i,j
seq(false,x,1,100) ? doors
Line 12,534 ⟶ 13,679:
=={{header|TorqueScript}}==
<syntaxhighlight lang=
for(%current = %steps; %current <= 100; %current += %steps)
%door[%current] = !%door[%current];
Line 12,541 ⟶ 13,686:
=={{header|Transact-SQL}}==
<syntaxhighlight lang="sql">
WITH OneToTen (N)
AS ( SELECT N
Line 12,588 ⟶ 13,733:
{{works with|Transact-SQL|SQL Server 2017}}
<syntaxhighlight lang=
-- Doors can be open or closed.
Line 12,685 ⟶ 13,830:
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
MainModule: {
Line 12,705 ⟶ 13,850:
=={{header|True BASIC}}==
<syntaxhighlight lang="basic">
! Optimized solution with True BASIC
Line 12,724 ⟶ 13,869:
=={{header|TSE SAL}}==
<syntaxhighlight lang=
// library: math: get: task: door: open: close100 <description></description> <version control></version control> <version>1.0.0.0.11</version> <version control></version control> (filenamemacro=getmaocl.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 22:03:16]
Line 12,815 ⟶ 13,960:
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
DICT doors create
Line 12,945 ⟶ 14,090:
100 = open
</pre>
=={{header|TypeScript}}==
<syntaxhighlight lang="typescript">
interface Door {
id: number;
Line 12,986 ⟶ 14,118:
=={{header|TXR}}==
<syntaxhighlight lang="txrlisp">(defun hyaku-mai-tobira ()
(let ((doors (vector 100)))
(each ((i (range 0 99)))
Line 13,000 ⟶ 14,132:
{{trans|BBC BASIC}}
Deliberately unoptimized.
<syntaxhighlight lang="ubasic/4th">FOR p = 1 TO 100
FOR d = p TO 100 STEP p
@(d) = @(d) = 0
Line 13,009 ⟶ 14,141:
IF @(d) PRINT "Door ";d;" is open"
NEXT d</syntaxhighlight>
=={{header|Uiua}}==
<pre>
◿2/+=0⊞◿.+1⇡100
+1⇡100 # 1-100
⊞◿. # Mod each with 1-100
=0 # Find where mod = 0, aka the divisors
/+ # Sum to get num of divisors
◿2 # Num divisors is odd
</pre>
{{out}}
<pre>[1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1]</pre>
=={{header|Uniface}}==
Line 13,014 ⟶ 14,158:
{{works with|Uniface 9.6}}
<syntaxhighlight lang=
entry LP_DO_IT
Line 13,087 ⟶ 14,231:
=={{header|Unison}}==
<syntaxhighlight lang=
hundredDoors =
toggleEachNth : Nat -> [Boolean] -> [Boolean]
Line 13,106 ⟶ 14,250:
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<syntaxhighlight lang="bash">#! /bin/bash
declare -a doors
Line 13,130 ⟶ 14,274:
Optimised version
<syntaxhighlight lang="bash">#!/bin/bash
for i in {1..100}; do
Line 13,138 ⟶ 14,282:
=={{header|Ursa}}==
<syntaxhighlight lang="text">
#
# 100 doors
Line 13,174 ⟶ 14,318:
The doors are represented as a list of 100 booleans initialized to false. The pass function takes a number and a door list to a door list with doors toggled at indices that are multiples of the number. The main program folds the pass function (to the right) over the list of pass numbers from 100 down to 1, numbers the result, and filters out the numbers of the open doors.
<syntaxhighlight lang=
#import nat
Line 13,185 ⟶ 14,329:
main = ~&rFlS num pass=>doors nrange(100,1)</syntaxhighlight>
optimized version:
<syntaxhighlight lang=
#cast %nL
Line 13,196 ⟶ 14,340:
=={{header|UTFool}}==
<syntaxhighlight lang=
···
http://rosettacode.org/wiki/100_doors
Line 13,221 ⟶ 14,365:
=={{header|Vala}}==
'''Unoptimized'''
<syntaxhighlight lang="vala">int main() {
bool doors_open[101];
for(int i = 1; i < doors_open.length; i++) {
Line 13,245 ⟶ 14,389:
...</pre>
'''Optimized'''
<syntaxhighlight lang="vala">int main() {
int i = 1;
while(i*i <= 100) {
Line 13,267 ⟶ 14,411:
=={{header|VAX Assembly}}==
<syntaxhighlight lang=
00000064 0000 1 n = 100
0000 0000 2 .entry doors, ^m<>
Line 13,299 ⟶ 14,443:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Sub Rosetta_100Doors()
Dim Door(100) As Boolean, i As Integer, j As Integer
Line 13,358 ⟶ 14,502:
{{works with|Windows Script Host|5.7}}
'''Unoptimized'''
<syntaxhighlight lang=
For currentDoor = 0 To 99
Line 13,384 ⟶ 14,528:
This implementation uses a free edit buffer as data array and for displaying the results.<br>
A closed door is represented by a character <tt>'-'</tt> and an open door by character <tt>'O'</tt>.
<syntaxhighlight lang="vedit">Buf_Switch(Buf_Free)
Ins_Char('-', COUNT, 100) // All doors closed
for (#1 = 1; #1 <= 100; #1++) {
Line 13,394 ⟶ 14,538:
'''Optimized'''
<syntaxhighlight lang="vedit">Buf_Switch(Buf_Free)
Ins_Char('-', COUNT, 100)
for (#1=1; #1 <= 10; #1++) {
Line 13,408 ⟶ 14,552:
=={{header|Verilog}}==
<syntaxhighlight lang=
module main;
integer i;
Line 13,423 ⟶ 14,567:
=={{header|VHDL}}==
'''unoptimized'''
<syntaxhighlight lang="vhdl">library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
Line 13,454 ⟶ 14,598:
'''unoptimized and synthesizable'''
<syntaxhighlight lang=
USE ieee.std_logic_1164.all;
Line 13,491 ⟶ 14,635:
=={{header|Visual Basic}}==
<syntaxhighlight lang="vb">
Public Sub Doors100()
' the state of a door is represented by the data type boolean (false = door closed, true = door opened)
Line 13,527 ⟶ 14,671:
{{works with|Visual Basic .NET|9.0+}}
'''unoptimized'''
<syntaxhighlight lang="vbnet">Module Module1
Sub Main()
Line 13,547 ⟶ 14,691:
End Module</syntaxhighlight>
'''optimized'''
<syntaxhighlight lang="vbnet">Module Module1
Sub Main()
Line 13,565 ⟶ 14,709:
End Module</syntaxhighlight>
=={{header|V (Vlang)}}==
===Unoptimized===
<syntaxhighlight lang="go">const number_doors = 101
fn main() {
Line 13,597 ⟶ 14,741:
</pre>
===Optimized Optimised GO Inspired===
<syntaxhighlight lang="go">const door_number = 100
fn main(){
Line 13,611 ⟶ 14,755:
increment++
door_nbr += 2 * increment + 1
print('O')
} else {
print('=')
}
}
println('')
}
Line 13,622 ⟶ 14,765:
Output:<pre>
O==O====O======O========O==========O============O==============O================O==================O
</pre>
===Optimized +===
<syntaxhighlight lang="go">fn main() {
for i in 1..11 {
print ( " Door ${i*i} is open.\n" )
}
}
</syntaxhighlight>
Output:<pre>
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.
</pre>
=={{header|VTL-2}}==
<syntaxhighlight lang=
20 :D)=0
30 D=D+1
Line 13,658 ⟶ 14,821:
=={{header|Wart}}==
<syntaxhighlight lang="python">def (doors n)
let door (table)
for step 1 (step <= n) ++step
Line 13,670 ⟶ 14,833:
=={{header|WDTE}}==
<syntaxhighlight lang=
let s => import 'stream';
let io => import 'io';
Line 13,702 ⟶ 14,865:
=={{header|Wortel}}==
{{trans|JavaScript}}
<syntaxhighlight lang="wortel">; unoptimized
+^[
@var doors []
Line 13,719 ⟶ 14,882:
=={{header|Wrapl}}==
'''Unoptimized'''
<syntaxhighlight lang="wrapl">MOD Doors;
IMP Agg.Table;
Line 13,735 ⟶ 14,898:
END Doors.</syntaxhighlight>
'''Optimized'''
<syntaxhighlight lang="wrapl">MOD Doors;
IMP IO.Terminal USE Out;
Line 13,749 ⟶ 14,912:
=={{header|Wren}}==
'''Unoptimized'''
<syntaxhighlight lang=
for (i in 1..100) {
var j = i
Line 13,764 ⟶ 14,927:
'''Optimized'''
<syntaxhighlight lang=
var increment = 3
while (door <= 100) {
Line 13,782 ⟶ 14,945:
{{works with|MASM 6+}}
<syntaxhighlight lang=
.NOLIST
Line 13,856 ⟶ 15,019:
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "100doors"
VERSION "0.0001"
Line 13,887 ⟶ 15,050:
=={{header|Xojo}}==
<syntaxhighlight lang="vb">
// True=Open; False=Closed
Dim doors(100) As Boolean // Booleans default to false
Line 13,898 ⟶ 15,061:
=={{header|XPL0}}==
<syntaxhighlight lang=
int Door(100); \You have 100 doors in a row
define Open, Closed;
Line 13,939 ⟶ 15,102:
With input document ...
<syntaxhighlight lang="xml"><hallway>
<door number="1">closed</door>
<door number="2">closed</door>
Line 13,950 ⟶ 15,113:
... visually representing the initial state of the hallway, apply the following XSLT 1.0 style-sheet...
<syntaxhighlight lang="xml"><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
Line 13,990 ⟶ 15,153:
This XSLT 2.0 style-sheet does not use the input document.
<syntaxhighlight lang="xml"><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
Line 14,010 ⟶ 15,173:
=={{header|Yabasic}}==
<syntaxhighlight lang=
ppa = 1 // next open door
p2 = 1
Line 14,024 ⟶ 15,187:
end if
next</syntaxhighlight>
Optimized
<syntaxhighlight lang="yabasic">for i = 1 to sqrt(100) : print "Door ", i**2, " is open" : next</syntaxhighlight>
=={{header|YAMLScript}}==
<syntaxhighlight lang="yaml">
!yamlscript/v0
defn main():
say: |-
Open doors after 100 passes:
$(apply str interpose(', ' open-doors()))
defn open-doors():
for [[d n] map(vector doors() iterate(inc 1)) :when d]:
n
defn doors():
reduce:
fn(doors idx): assoc(doors idx true)
into []: repeat(100 false)
map \(dec (%1 * %1)): 1 .. 10
</syntaxhighlight>
{{out}}
<pre>
$ ys 100-doors.ys
Open doors after 100 passes: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
</pre>
=={{header|Yorick}}==
'''Unoptimized, iterative'''
<syntaxhighlight lang="yorick">doors = array(0, 100);
for(i = 1; i <= 100; i++)
for(j = i; j <= 100; j += i)
Line 14,035 ⟶ 15,227:
'''Unoptimized, vectorized'''
<syntaxhighlight lang="yorick">doors = array(0, 100);
for(i = 1; i <= 100; i++)
doors(i::i) ~= 1;
Line 14,041 ⟶ 15,233:
'''Optimized'''
<syntaxhighlight lang="yorick">print, indgen(1:long(sqrt(100)))^2</syntaxhighlight>
All of the above output:
Line 14,049 ⟶ 15,241:
=={{header|Zig}}==
===Unoptimized===
<syntaxhighlight lang="zig">pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
Line 14,062 ⟶ 15,256:
}
for (doors, 0..) |open, num|
if (open)
try stdout.print("Door {d} is open.\n", .{num});
}</syntaxhighlight>
===Optimized===
<syntaxhighlight lang="zig">pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
var square: u8 = 1;
var increment: u8 = 3;
var door: u8 = 1;
while (door <= 100) : (door += 1) {
if (door == square) {
try stdout.print("Door {d} is open\n", .{door});
square += increment;
increment += 2;
}
}
}</syntaxhighlight>
===Optimized with new for-loop (since Zig 0.11)===
<syntaxhighlight lang="zig">
pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
var square: u8 = 1;
var increment: u8 = 3;
for (1..101) |door| {
if (door == square) {
try stdout.print("Door {d} is open\n", .{door});
square += increment;
increment += 2;
}
}
}
</syntaxhighlight>
===Really Optimized===
<syntaxhighlight lang="zig">
pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
var door: u8 = 1;
while (door * door <= 100) : (door += 1) {
try stdout.print("Door {d} is open\n", .{door * door});
}
}
</syntaxhighlight>{{out}}
<pre>Door 1 is open.
Door 4 is open.
Line 14,077 ⟶ 15,315:
Door 81 is open.
Door 100 is open.</pre>
=={{header|zkl}}==
Pure brute force.
<syntaxhighlight lang="zkl">doors:=List.createLong(100,False); // list of 100 Falses
foreach n,m in (100,[n..99,n+1]){ doors[m]=(not doors[m]); } //foreach{ foreach{} }
doors.filterNs().apply('+(1)).println();</syntaxhighlight>
The filterNs method returns the index of each item that passes the filter.
{{out}}<pre>L(1,4,9,16,25,36,49,64,81,100)</pre>
=={{header|ZX Spectrum Basic}}==
|