Add tasks for all the new languages

This commit is contained in:
Tina Müller 2016-12-05 23:44:36 +01:00
parent 9dc3c2bb62
commit bba7bfd280
13208 changed files with 134745 additions and 0 deletions

View file

@ -0,0 +1,110 @@
*-----------------------------------------------------------
* Title : 100Doors.X68
* Written by : G. A. Tippery
* Date : 2014-01-17
* Description: Solves "100 Doors" problem, see: http://rosettacode.org/wiki/100_doors
* Notes : Translated from C "Unoptimized" version, http://rosettacode.org/wiki/100_doors#unoptimized
* : No optimizations done relative to C version; "for("-equivalent loops could be optimized.
*-----------------------------------------------------------
*
* System-specific general console I/O macros (Sim68K, in this case)
*
PUTS MACRO
** Print a null-terminated string w/o CRLF **
** Usage: PUTS stringaddress
** Returns with D0, A1 modified
MOVEQ #14,D0 ; task number 14 (display null string)
LEA \1,A1 ; address of string
TRAP #15 ; display it
ENDM
*
PRINTN MACRO
** Print decimal integer from number in register
** Usage: PRINTN register
** Returns with D0,D1 modified
IFNC '\1','D1' ;if some register other than D1
MOVE.L \1,D1 ;put number to display in D1
ENDC
MOVE.B #3,D0
TRAP #15 ;display number in D1
*
* Generic constants
*
CR EQU 13 ;ASCII Carriage Return
LF EQU 10 ;ASCII Line Feed
*
* Definitions specific to this program
*
* Register usage:
* D3 == pass (index)
* D4 == door (index)
* A2 == Doors array pointer
*
SIZE EQU 100 ;Define a symbolic constant for # of doors
ORG $1000 ;Specify load address for program -- actual address system-specific
START: ; Execution starts here
LEA Doors,A2 ; make A2 point to Doors byte array
MOVEQ #0,D3
PassLoop:
CMP #SIZE,D3
BCC ExitPassLoop ; Branch on Carry Clear - being used as Branch on Higher or Equal
MOVE D3,D4
DoorLoop:
CMP #SIZE,D4
BCC ExitDoorLoop
NOT.B 0(A2,D4)
ADD D3,D4
ADDQ #1,D4
BRA DoorLoop
ExitDoorLoop:
ADDQ #1,D3
BRA PassLoop
ExitPassLoop:
* $28 = 40. bytes of code to this point. 32626 cycles so far.
* At this point, the result exists as the 100 bytes starting at address Doors.
* To get output, we must use methods specific to the particular hardware, OS, or
* emulator system that the code is running on. I use macros to "hide" some of the
* system-specific details; equivalent macros would be written for another system.
MOVEQ #0,D4
PrintLoop:
CMP #SIZE,D4
BCC ExitPrintLoop
PUTS DoorMsg1
MOVE D4,D1
ADDQ #1,D1 ; Convert index to 1-based instead of 0-based
PRINTN D1
PUTS DoorMsg2
TST.B 0(A2,D4) ; Is this door open (!= 0)?
BNE ItsOpen
PUTS DoorMsgC
BRA Next
ItsOpen:
PUTS DoorMsgO
Next:
ADDQ #1,D4
BRA PrintLoop
ExitPrintLoop:
* What to do at end of program is also system-specific
SIMHALT ;Halt simulator
*
* $78 = 120. bytes of code to this point, but this will depend on how the I/O macros are actually written.
* Cycle count is nearly meaningless, as the I/O hardware and routines will dominate the timing.
*
* Data memory usage
*
ORG $2000
Doors DCB.B SIZE,0 ;Reserve 100 bytes, prefilled with zeros
DoorMsg1 DC.B 'Door ',0
DoorMsg2 DC.B ' is ',0
DoorMsgC DC.B 'closed',CR,LF,0
DoorMsgO DC.B 'open',CR,LF,0
END START ;last line of source

View file

@ -0,0 +1,31 @@
\ 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:
[] var, doors
\ given a door number, get the value and toggle it:
: toggle-door \ n --
doors @ over a:@
not rot swap a:! drop ;
\ print which doors are open:
: .doors
(
doors @ over a:@ nip
if . space else drop then
) 1 100 loop ;
\ iterate over the doors, skipping 'n':
: main-pass \ n --
0
true
repeat
drop
dup toggle-door
over n:+
dup 101 <
while 2drop drop ;
\ calculate the first 100 doors:
' main-pass 1 100 loop
\ print the results:
.doors cr bye

View file

@ -0,0 +1,23 @@
shared void run() {
print("Open doors (naive): ``naive()``
Open doors (optimized): ``optimized()``");
}
shared {Integer*} naive(Integer count = 100) {
variable value doors = [ for (_ in 1..count) closed ];
for (step in 1..count) {
doors = [for (i->door in doors.indexed) let (index = i+1) if (step == 1 || step.divides(index)) then door.toggle() else door ];
}
return doors.indexesWhere((door) => door == opened).map(1.plusInteger);
}
shared {Integer*} optimized(Integer count = 100) =>
{ for (i in 1..count) i*i }.takeWhile(count.notSmallerThan);
shared abstract class Door(shared actual String string) of opened | closed {
shared formal Door toggle();
}
object opened extends Door("opened") { toggle() => closed; }
object closed extends Door("closed") { toggle() => opened; }

View file

@ -0,0 +1,37 @@
program
map
end
MAX_DOOR_NUMBER equate(100)
CRLF equate('<13,10>')
Doors byte,dim(MAX_DOOR_NUMBER)
Pass byte
DoorNumber byte
DisplayString cstring(2000)
ResultWindow window('Result'),at(,,133,291),center,double,auto
prompt('Door states:'),at(8,4),use(?PromptTitle)
text,at(8,16,116,266),use(DisplayString),boxed,vscroll,font('Courier New',,,,CHARSET:ANSI),readonly
end
code
Doors :=: false
loop Pass = 1 to MAX_DOOR_NUMBER
loop DoorNumber = Pass to MAX_DOOR_NUMBER by Pass
Doors[DoorNumber] = choose(Doors[DoorNumber], false, true)
end
end
clear(DisplayString)
loop DoorNumber = 1 to MAX_DOOR_NUMBER
DisplayString = DisplayString & format(DoorNumber, @n3) & ' is ' & choose(Doors[DoorNumber], 'opened', 'closed') & CRLF
end
open(ResultWindow)
accept
end
close(ResultWindow)
return

View file

@ -0,0 +1,8 @@
doors = [false] * 100
for pass til doors.length
for i from pass til doors.length by pass + 1
! = doors[i]
for i til doors.length
console.log 'Door %d is %s.', i + 1, if doors[i] then 'open' else 'closed'

View file

@ -0,0 +1,8 @@
10 D=100: DIMD(D): P=1
20 PRINT CHR$(147);"PASS: ";P
22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT
30 IF P=100 THEN 40
32 P=P+1: GOTO20
40 PRINT: PRINT"THE FOLLOWING DOORS ARE OPEN: "
42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI;
44 NEXT

View file

@ -0,0 +1,11 @@
doors = Array.new(100, false)
1.upto(100) do |i|
i.step(by: i, limit: 100) do |j|
doors[j - 1] = !doors[j - 1]
end
end
doors.each_with_index do |open, i|
puts "Door #{i + 1} is #{open ? "open" : "closed"}"
end

View file

@ -0,0 +1,15 @@
Doors := RECORD
UNSIGNED1 DoorNumber;
STRING6 State;
END;
AllDoors := DATASET([{0,0}],Doors);
Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM
SELF.DoorNumber := Cnt;
SELF.State := IF((CNT * 10) % (SQRT(CNT)*10)<>0,'Closed','Opened');
END;
OpenDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));
OpenDoors;

View file

@ -0,0 +1,30 @@
Doors := RECORD
UNSIGNED1 DoorNumber;
STRING6 State;
END;
AllDoors := DATASET([{0,'0'}],Doors);
//first build the 100 doors
Doors OpenThem(AllDoors L,INTEGER Cnt) := TRANSFORM
SELF.DoorNumber := Cnt;
SELF.State := 'Closed';
END;
ClosedDoors := NORMALIZE(AllDoors,100,OpenThem(LEFT,COUNTER));
//now iterate through them and use door logic
loopBody(DATASET(Doors) ds, UNSIGNED4 c) :=
PROJECT(ds, //ds=original input
TRANSFORM(Doors,
SELF.State := CASE((COUNTER % c) * 100,
0 => IF(LEFT.STATE = 'Opened','Closed','Opened')
,LEFT.STATE);
SELF.DoorNumber := COUNTER; //PROJECT COUNTER
));
g1 := LOOP(ClosedDoors,100,loopBody(ROWS(LEFT),COUNTER));
OUTPUT(g1);

View file

@ -0,0 +1,23 @@
DoorSet := DATASET(100,TRANSFORM({UNSIGNED1 DoorState},SELF.DoorState := 1));
SetDoors := SET(DoorSet,DoorState);
Doors := RECORD
UNSIGNED1 Pass;
SET OF UNSIGNED1 DoorSet;
END;
StartDoors := DATASET(100,TRANSFORM(Doors,SELF.Pass := COUNTER,SELF.DoorSet := SetDoors));
Doors XF(Doors L, Doors R) := TRANSFORM
ds := DATASET(L.DoorSet,{UNSIGNED1 DoorState});
NextDoorSet := PROJECT(ds,
TRANSFORM({UNSIGNED1 DoorState},
SELF.DoorState := CASE((COUNTER % R.Pass) * 100,
0 => IF(LEFT.DoorState = 1,0,1),
LEFT.DoorState)));
SELF.DoorSet := IF(L.Pass=0,R.DoorSet,SET(NextDoorSet,DoorState));
SELF.Pass := R.Pass
END;
Res := DATASET(ITERATE(StartDoors,XF(LEFT,RIGHT))[100].DoorSet,{UNSIGNED1 DoorState});
PROJECT(Res,TRANSFORM({STRING20 txt},SELF.Txt := 'Door ' + COUNTER + ' is ' + IF(LEFT.DoorState=1,'Open','Closed')));

View file

@ -0,0 +1,29 @@
! "100 Doors" program for ERRE LANGUAGE
! Author: Claudio Larini
! Date: 21-Nov-2014
!
! PC Unoptimized version translated from a QB version
PROGRAM 100DOORS
!$INTEGER
CONST N=100
DIM DOOR[N]
BEGIN
FOR STRIDE=1 TO N DO
FOR INDEX=STRIDE TO N STEP STRIDE DO
DOOR[INDEX]=NOT(DOOR[INDEX])
END FOR
END FOR
PRINT("Open doors:";)
FOR INDEX=1 TO N DO
IF DOOR[INDEX] THEN PRINT(INDEX;) END IF
END FOR
PRINT
END PROGRAM

View file

@ -0,0 +1,21 @@
; initial state = closed = #f
(define doors (make-vector 101 #f))
; run pass 100 to 1
(for*
((pass (in-range 100 0 -1))
(door (in-range 0 101 pass)))
(when (and
(vector-set! doors door (not (vector-ref doors door)))
(= pass 1))
(writeln door "is open")))
1 "is open"
4 "is open"
9 "is open"
16 "is open"
25 "is open"
36 "is open"
49 "is open"
64 "is open"
81 "is open"
100 "is open"

View file

@ -0,0 +1,16 @@
#import <Foundation/Foundation.h>
int main()
square := 1, increment = 3
for int door in 1 .. 100
printf("door #%d", door)
if door == square
puts(" is open.")
square += increment
increment += 2
else
puts(" is closed.")
return 0

View file

@ -0,0 +1,10 @@
READ x,y,z
PRINT "Open doors: ";x;" ";
CYCLE
z=x+y
PRINT z;" ";
x=z
y=y+2
REPEAT UNTIL z>=100
DATA 1,3,0
END

View file

@ -0,0 +1,32 @@
' version 27-10-2016
' compile with: fbc -s console
#Define max_doors 100
Dim As ULong c, n, n1, door(1 To max_doors)
' toggle, at start all doors are closed (0)
' 0 = door closed, 1 = door open
For n = 1 To max_doors
For n1 = n To max_doors Step n
door(n1) = 1 - door(n1)
Next
Next
' count the doors that are open (1)
Print "doors that are open nr: ";
For n = 1 To max_doors
If door(n) = 1 Then
Print n; " ";
c = c + 1
End If
Next
Print : Print
Print "There are " + Str(c) + " doors open"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,33 @@
' version 27-10-2016
' compile with: fbc -s console
#Define max_doors 100
Dim As ULong c, n, n1, door(1 To max_doors)
' at start all doors are closed
' simple add 1 each time we open or close a door
' doors with odd numbers are open
' doors with even numbers are closed
For n = 1 To max_doors
For n1 = n To max_doors Step n
door(n1) += 1
Next
Next
Print "doors that are open nr: ";
For n = 1 To max_doors
If door(n) And 1 Then
Print n; " ";
c = c + 1
End If
Next
Print : Print
Print "There are " + Str(c) + " doors open"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,21 @@
' version 27-10-2016
' compile with: fbc -s console
#Define max_doors 100
Dim As ULong c, n
Print "doors that are open nr: ";
For n = 1 To 10
Print n * n; " ";
c = c + 1
Next
Print : Print
Print "There are " + Str(c) + " doors open"
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,3 @@
for i <- 1..100
r = foldl1( \a, b -> a xor b, [(a|i) | a <- 1..100] )
println( i + ' ' + (if r then 'open' else 'closed') )

View file

@ -0,0 +1,4 @@
import math.sqrt
for i <- 1..100
println( i + ' ' + (if sqrt(i) is Integer then 'open' else 'closed') )

View file

@ -0,0 +1,11 @@
fun main(n: int): [n]bool =
let is_open = replicate n False
loop (is_open) = for i < n do
let js = map (*i+1) (iota n)
let flips = map (fn j =>
if j < n
then unsafe !is_open[j]
else True -- Doesn't matter.
) js
in write js flips is_open
in is_open

View file

@ -0,0 +1,14 @@
include "ConsoleWindow"
dim as short door, square : square = 1
dim as short increment : increment = 3
for door = 1 to 100
if (door == square)
print "Door"; door; " is open."
square += increment
increment += 2
else
print "Door"; door; " is closed."
end if
next

View file

@ -0,0 +1,34 @@
'
' 100 doors problem
'
DIM doors!(101) ! use indices 1 to 100
@close_doors
@do_passes
@show_doors
'
PROCEDURE close_doors
ARRAYFILL doors!(),FALSE
RETURN
'
PROCEDURE do_passes
LOCAL i%,j%
FOR i%=1 TO 100
FOR j%=i% TO 100 STEP i%
doors!(j%)=NOT doors!(j%)
NEXT j%
NEXT i%
RETURN
'
PROCEDURE show_doors
LOCAL i%
OPENW 1
CLEARW 1
FOR i%=1 TO 100
IF doors!(i%)
PRINT "Door ";i%;" is open"
ENDIF
NEXT i%
PRINT "(press a key to end program)"
~INP(2)
CLOSEW 1
RETURN

View file

@ -0,0 +1,13 @@
#define ARRAY_ELEMENTS 100
PROCEDURE Main()
LOCAL aDoors := Array( ARRAY_ELEMENTS )
LOCAL i, j
AFill( aDoors, .F. )
FOR i := 1 TO ARRAY_ELEMENTS
FOR j := i TO ARRAY_ELEMENTS STEP i
aDoors[ j ] = ! aDoors[ j ]
NEXT
NEXT
AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL) } )
RETURN

View file

@ -0,0 +1,8 @@
#define ARRAY_ELEMENTS 100
PROCEDURE Main()
LOCAL aDoors := Array( ARRAY_ELEMENTS )
AFill( aDoors, .F. )
AEval( aDoors, {|e, n| aDoors[n] := e := Iif( Int(Sqrt(n))==Sqrt(n), .T., .F. ) } )
AEval( aDoors, {|e, n| QQout( Padl(n,3) + " is " + Iif(aDoors[n], "*open*", "closed" ) + "|" ), Iif( n%5 == 0, Qout(), e:=NIL )} )
RETURN

View file

@ -0,0 +1,10 @@
(def doors (* [False] 100))
(for [pass (range (len doors))]
(for [i (range pass (len doors) (inc pass))]
(assoc doors i (not (get doors i)))))
(for [i (range (len doors))]
(print (.format "Door {} is {}."
(inc i)
(if (get doors i) "open" "closed"))))

View file

@ -0,0 +1,18 @@
software {
var doors = len(100)
for pass over [1, 100]
var door = pass - 1
loop door < len(doors) {
doors[door] = doors[door]/0
door += pass
}
end
for door,isopen in doors
if isopen
print("Door ",door+1,": open")
end
end
print("All other doors are closed")
}

View file

@ -0,0 +1,35 @@
import Data.Vect
-- Creates list from 0 to n (not including n)
upTo : (m : Nat) -> Vect m (Fin m)
upTo Z = []
upTo (S n) = 0 :: (map FS (upTo n))
data DoorState = DoorOpen | DoorClosed
toggleDoor : DoorState -> DoorState
toggleDoor DoorOpen = DoorClosed
toggleDoor DoorClosed = DoorOpen
isOpen : DoorState -> Bool
isOpen DoorOpen = True
isOpen DoorClosed = False
initialDoors : Vect 100 DoorState
initialDoors = fromList $ map (\_ => DoorClosed) [1..100]
iterate : (n : Fin m) -> Vect m DoorState -> Vect m DoorState
iterate n doors {m} =
map (\(idx, doorState) =>
if ((S (finToNat idx)) `mod` (S (finToNat n))) == Z
then toggleDoor doorState
else doorState)
(zip (upTo m) doors)
-- Returns all doors left open at the end
solveDoors : List (Fin 100)
solveDoors =
findIndices isOpen $ foldl (\doors,val => iterate val doors) initialDoors (upTo 100)
main : IO ()
main = print $ map (\n => S (finToNat n)) solveDoors

View file

@ -0,0 +1,5 @@
loop(100) => {^
local(root = math_sqrt(loop_count))
local(state = (#root == math_ceil(#root) ? '<strong>open</strong>' | 'closed'))
#state != 'closed' ? 'Door ' + loop_count + ': ' + #state + '<br>'
^}

View file

@ -0,0 +1,15 @@
var doors = List.fill(100, false)
for i in 0...99:
for j in i...99 by i + 1:
doors[j] = !doors[j]
# The type must be specified since the list starts off empty.
var open_doors: List[Integer] = []
doors.each_index{|i|
if doors[i]:
open_doors.push(i + 1)
}
print($"Open doors: ^(open_doors)")

View file

@ -0,0 +1,9 @@
on mouseUp
repeat with tStep = 1 to 100
repeat with tDoor = tStep to 100 step tStep
put not tDoors[tDoor] into tDoors[tDoor]
end repeat
if tDoors[tStep] then put "Door " & tStep & " is open" & cr after tList
end repeat
set the text of field "Doors" to tList
end mouseUp

View file

@ -0,0 +1,8 @@
is_open = [false for door = 1,100]
for pass = 1,100
for door = pass,100,pass
is_open[door] = not is_open[door]
for i,v in ipairs is_open
print "Door #{i}: " .. if v then 'open' else 'closed'

View file

@ -0,0 +1,16 @@
from strutils import format
proc check_doors() =
const n = 100
var is_open : array[1..n, bool] # auto-initialized to false
# pass over the doors n times
for pass in 1..n:
var i = pass
while i <= n:
is_open[i] = not is_open[i]
i += pass
# print the result
for door in 1..n:
echo format("door $1 is $2.", door, (if is_open[door]: "open" else: "closed"))
check_doors()

View file

@ -0,0 +1,9 @@
var isOpen: array[1..100, bool]
for pass in countup(1, 100):
for door in countup(pass,100,pass):
isOpen[door] = not isOpen[door]
for i in countup(1, 100):
if isOpen[i]:
echo("Door ",i," is open.")

View file

@ -0,0 +1,7 @@
: doors
| i j l |
ListBuffer initValue(100, false) ->l
100 loop: i [
i 100 i step: j [ l put(j, l at(j) not) ]
]
l println ;

View file

@ -0,0 +1,22 @@
module doors;
extern printf;
@Integer main [
@Array<@Boolean> doors = new @Array<@Boolean>.init(100);
var i = 1;
while (i <= 100) {
var j = i-1;
while (j < 100) {
doors.set(j, doors.get(j)::not);
j = j + i;
}
i = i::inc;
}
i = 0;
while (i < 100) {
printf("%i %s\n", i+1, iif(doors.get(i), "open", "closed"));
i = i::inc;
}
return 0;
]

View file

@ -0,0 +1,26 @@
module var;
extern printf;
@Integer main [
var door = 1;
var incrementer = 0;
var current = 1;
while (current <= 100)
{
printf("Door %i ", current);
if (current == door)
{
printf("open\n");
incrementer = incrementer::inc;
door = door + 2 * incrementer + 1;
}
else
printf("closed\n");
current = current + 1;
}
return 0;
]

View file

@ -0,0 +1,79 @@
use perl5i::2;
package doors {
use perl5i::2;
use Const::Fast;
const my $OPEN => 1;
const my $CLOSED => 0;
# ----------------------------------------
# Constructor: door->new( @args );
# input: N - how many doors?
# returns: door object
#
method new($class: @args ) {
my $self = bless {}, $class;
$self->_init( @args );
return $self;
}
# ----------------------------------------
# class initializer.
# input: how many doors?
# sets N, creates N+1 doors ( door zero is not used ).
#
method _init( $N ) {
$self->{N} = $N;
$self->{doors} = [ ($CLOSED) x ($N+1) ];
}
# ----------------------------------------
# $self->toggle( $door_number );
# input: number of door to toggle.
# OPEN a CLOSED door; CLOSE an OPEN door.
#
method toggle( $which ) {
$self->{doors}[$which] = ( $self->{doors}[$which] == $OPEN
? $CLOSED
: $OPEN
);
}
# ----------------------------------------
# $self->toggle_n( $cycle );
# input: number.
# Toggle doors 0, $cycle, 2 * $cycle, 3 * $cycle, .. $self->{N}
#
method toggle_n( $n ) {
$self->toggle($_)
for map { $n * $_ }
( 1 .. int( $self->{N} / $n) );
}
# ----------------------------------------
# $self->toggle_all();
# Toggle every door, then every other door, every third door, ...
#
method toggle_all() {
$self->toggle_n( $_ ) for ( 1 .. $self->{N} );
}
# ----------------------------------------
# $self->print_open();
# Print list of which doors are open.
#
method print_open() {
say join ', ', grep { $self->{doors}[$_] == $OPEN } ( 1 ... $self->{N} );
}
}
# ----------------------------------------------------------------------
# Main Thread
#
my $doors = doors->new(100);
$doors->toggle_all();
$doors->print_open();

View file

@ -0,0 +1,13 @@
sequence doors = repeat(false,100)
for i=1 to 100 do
for j=i to 100 by i do
doors[j] = not doors[j]
end for
end for
for i=1 to 100 do
if doors[i] == true then
printf(1,"Door #%d is open.\n", i)
end if
end for

View file

@ -0,0 +1,13 @@
function doors(integer n)
-- returns the perfect squares<=n
integer door = 1, step = 1
sequence res = {}
while door<=n do
res &= door
step += 2
door += step
end while
return res
end function
?doors(100)

View file

@ -0,0 +1,7 @@
square=1, i=3
1 to 100(door):
if (door == square):
("door", door, "is open") say
square += i
i += 2.
.

View file

@ -0,0 +1,69 @@
data Door:
| open
| closed
end
fun flip-door(d :: Door) -> Door:
cases(Door) d:
| open => closed
| closed => open
end
end
fun flip-doors(doors :: List<Door>) -> List<Door>:
doc:```Given a list of door positions, repeatedly switch the positions of
every nth door for every nth pass, and return the final list of door
positions```
for fold(flipped-doors from doors, n from range(1, doors.length() + 1)):
for map_n(m from 1, d from flipped-doors):
if num-modulo(m, n) == 0:
flip-door(d)
else:
d
end
end
end
where:
flip-doors([list: closed, closed, closed]) is
[list: open, closed, closed]
flip-doors([list: closed, closed, closed, closed]) is
[list: open, closed, closed, open]
flip-doors([list: closed, closed, closed, closed, closed, closed]) is
[list: open, closed, closed, open, closed, closed]
closed-100 = for map(_ from range(1, 101)): closed end
answer-100 = for map(n from range(1, 101)):
if num-is-integer(num-sqrt(n)): open
else: closed
end
end
flip-doors(closed-100) is answer-100
end
fun find-indices<A>(pred :: (A -> Boolean), xs :: List<A>) -> List<Number>:
doc:```Given a list and a predicate function, produce a list of index
positions where there's a match on the predicate```
ps = map_n(lam(n,e): if pred(e): n else: -1 end end, 1, xs)
ps.filter(lam(x): x >= 0 end)
where:
find-indices((lam(i): i == true end), [list: true,false,true]) is [list:1,3]
end
fun run(n):
doc:```Given a list of doors that are closed, make repeated passes
over the list, switching the positions of every nth door for
each nth pass. Return a list of positions in the list where the
door is Open.```
doors = repeat(n, closed)
ys = flip-doors(doors)
find-indices((lam(y): y == open end), ys)
where:
run(4) is [list: 1,4]
end
run(100)

View file

@ -0,0 +1,20 @@
Red [
Purpose: "100 Doors Problem (Perfect Squares)"
Author: "Barry Arthur"
Date: "07-Oct-2016"
]
doors: make vector! [char! 8 100]
repeat i 100 [change at doors i #"."]
repeat i 100 [
j: i
while [j <= 100] [
door: at doors j
change door either #"O" = first door [#"."] [#"O"]
j: j + i
]
]
repeat i 10 [
print copy/part at doors (i - 1 * 10 + 1) 10
]

View file

@ -0,0 +1,17 @@
doors = list(100)
for i = 1 to 100
doors[i] = false
next
For pass = 1 To 100
For door = pass To 100
if doors[door] doors[door] = false else doors[door] = true ok
door += pass-1
Next
Next
For door = 1 To 100
see "Door (" + door + ") is "
If doors[door] see "Open" else see "Closed" ok
see nl
Next

View file

@ -0,0 +1,14 @@
doors = list(100)
for i = 1 to 100
doors[i] = false
next
For p = 1 To 10
doors[pow(p,2)] = True
Next
For door = 1 To 100
see "Door (" + door + ") is "
If doors[door] see "Open" else see "Closed" ok
see nl
Next

View file

@ -0,0 +1,14 @@
import <Utilities/Sequence.sl>;
main:=
let
doors := flipDoors(duplicate(false, 100), 1);
open[i] := i when doors[i];
in
open;
flipDoors(doors(1), count) :=
let
newDoors[i] := not doors[i] when i mod count = 0 else doors[i];
in
doors when count >= 100 else flipDoors(newDoors, count + 1);

View file

@ -0,0 +1,4 @@
main := flipDoors([1], 2);
flipDoors(openDoors(1), i) :=
openDoors when i * i >= 100 else flipDoors(openDoors ++ [i * i], i + 1);

View file

@ -0,0 +1,13 @@
var doors = []
100.times { |pass|
100.times { |i|
if (i % pass == 0) {
doors[i] := false -> not!
}
}
}
100.times { |i|
"Door %3d is %s\n".printf(i, doors[i] ? 'open' : 'closed')
}

View file

@ -0,0 +1,3 @@
{ |i|
"Door %3d is %s\n".printf(i, ["closed", "open"][i.is_sqr])
} * 100

View file

@ -0,0 +1,21 @@
/* declare the variables */
var isOpen = {};
var pass, door;
/* initialize the doors */
for door = 0; door < 100; door++ {
isOpen[door] = true;
}
/* do the 99 remaining passes */
for pass = 1; pass < 100; ++pass {
for door = pass; door < 100; door += pass+1 {
isOpen[door] = !isOpen[door];
}
}
/* print the results */
var states = { true: "open", false: "closed" };
for door = 0; door < 100; door++ {
printf("Door #%d is %s.\n", door+1, states[isOpen[door]]);
}

View file

@ -0,0 +1,13 @@
/* declare the variables */
var door_sqrt = 1;
var door;
/* print the perfect square doors as open */
for door = 0; door < 100; door++ {
if (door_sqrt*door_sqrt == door+1) {
printf("Door #%d is open.\n", door+1);
door_sqrt ++;
} else {
printf("Door #%d is closed.\n", door+1);
}
}

View file

@ -0,0 +1,21 @@
/* declare enum to identify the state of a door */
enum DoorState : String {
case Opened = "Opened"
case Closed = "Closed"
}
/* declare list of doors state and initialize them */
var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)
/* do the 100 passes */
for i in 1...100 {
/* map on a strideTo instance to only visit the needed doors on each iteration */
map(stride(from: i - 1, to: 100, by: i)) {
doorsStateList[$0] = doorsStateList[$0] == .Opened ? .Closed : .Opened
}
}
/* print the results */
for (index, item) in enumerate(doorsStateList) {
println("Door \(index+1) is \(item.rawValue)")
}

View file

@ -0,0 +1,20 @@
/* declare enum to identify the state of a door */
enum DoorState : String {
case Opened = "Opened"
case Closed = "Closed"
}
/* declare list of doors state and initialize them */
var doorsStateList = [DoorState](count: 100, repeatedValue: DoorState.Closed)
/* set i^2 doors to opened */
var i = 1
do {
doorsStateList[(i*i)-1] = DoorState.Opened
++i
} while (i*i) <= doorsStateList.count
/* print the results */
for (index, item) in enumerate(doorsStateList) {
println("Door \(index+1) is \(item.rawValue)")
}

View file

@ -0,0 +1,53 @@
entry LP_DO_IT
variables
string V_DOORS
boolean V_DOOR_STATE
string V_DOOR_STATE_S
numeric V_IDX
numeric V_TOTAL_DOORS
string V_DOOR_STATE_LIST
numeric V_LOOP_COUNT
endvariables
V_TOTAL_DOORS = 100
putitem V_DOORS, V_TOTAL_DOORS, 0
V_DOORS = $replace (V_DOORS, 1, "·;", "·;0", -1)
putitem/id V_DOOR_STATE_LIST, "1", "Open"
putitem/id V_DOOR_STATE_LIST, "0", "Close"
V_LOOP_COUNT = 1
while (V_LOOP_COUNT <= V_TOTAL_DOORS)
V_IDX = 0
V_IDX = V_IDX + V_LOOP_COUNT
getitem V_DOOR_STATE, V_DOORS, V_IDX
while (V_IDX <= V_TOTAL_DOORS)
V_DOOR_STATE = !V_DOOR_STATE
getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
putitem V_DOORS, V_IDX, V_DOOR_STATE
V_IDX = V_IDX + V_LOOP_COUNT
getitem V_DOOR_STATE, V_DOORS, V_IDX
endwhile
V_LOOP_COUNT = V_LOOP_COUNT + 1
endwhile
V_IDX = 1
getitem V_DOOR_STATE, V_DOORS, V_IDX
while (V_IDX <= V_TOTAL_DOORS)
getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
if (V_DOOR_STATE)
putmess "Door %%V_IDX%%% is finally %%V_DOOR_STATE_S%%%"
endif
V_IDX = V_IDX + 1
getitem V_DOOR_STATE, V_DOORS, V_IDX
endwhile
end ; LP_DO_IT

View file

@ -0,0 +1,30 @@
#
# 100 doors
#
decl int i j
decl boolean<> doors
# append 101 boolean values to doors stream
for (set i 0) (or (< i 100) (= i 100)) (inc i)
append false doors
end for
# loop through, opening and closing doors
for (set i 1) (or (< i 100) (= i 100)) (inc i)
for (set j i) (or (< j 100) (= j 100)) (inc j)
if (= (mod j i) 0)
set doors<j> (not doors<j>)
end if
end for
end for
# loop through and output which doors are open
for (set i 1) (or (< i 100) (= i 100)) (inc i)
out "Door " i ": " console
if doors<i>
out "open" endl console
else
out "closed" endl console
end if
end if

View file

@ -0,0 +1,10 @@
def (doors n)
let door (table)
for step 1 (step <= n) ++step
for j 0 (j < n) (j <- j+step)
zap! not door.j
for j 0 (j < n) ++j
when door.j
pr j
pr " "

View file

@ -0,0 +1,14 @@
; unoptimized
+^[
@var doors []
@for i rangei [1 100]
@for j rangei [i 100 i]
:!@not `j doors
@for i rangei [1 100]
@if `i doors
!console.log "door {i} is open"
]
; optimized, map square over 1 to 10
!*^@sq @to 10

View file

@ -0,0 +1,12 @@
var doors = [true] * 100
for (i in 1..100) {
var j = i
while(j < 100) {
doors[j] = !doors[j]
j = j + i + 1
}
}
for (i in 0...100) {
if (doors[i]) System.print(i + 1)
}

View file

@ -0,0 +1,7 @@
var door = 1
var increment = 3
while(door <= 100) {
System.print(door)
door = door + increment
increment = increment + 2
}

View file

@ -0,0 +1,13 @@
# Solution for n doors:
def doors(n):
def print:
. as $doors
| range(1; length+1)
| if $doors[.] then "Door \(.) is open" else empty end;
([][n+1] = null) as $doors
| reduce range(1; n+1) as $run
( $doors; reduce range($run; n+1; $run ) as $door
( .; .[$door] = (.[$door] | not) ) )
| print ;

View file

@ -0,0 +1,3 @@
# Solution for 100 doors:
def solution:
range(1;11) | "Door \(. * .) is open";