/*
100 doors problem in Picat.
From Rosetta code:
http://rosettacode.org/wiki/100_doors
"""
Problem:
You have 100 doors in a row that are all initially closed. You make 100 passes by
the doors. The first time through, you visit every door and toggle the door
(if the door is closed, you open it; if it is open, you close it). The second time
you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door
(door #3, #6, #9, ...), etc, until you only visit the 100th door.
Question: What state are the doors in after the last pass? Which are open, which
are closed? [1]
Alternate: As noted in this page's discussion page, the only doors that remain open are
whose numbers are perfect squares of integers. Opening only those doors is an
optimization that may also be expressed.
"""
This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com
See also my Picat page: http://www.hakank.org/picat/
*/
% import util.
% import cp.
main => go.
go =>
doors(10),
doors(100),
doors_opt(100),
doors_opt2(100),
nl.
% non-optimized
doors(N) =>
Doors = new_array(N),
foreach(I in 1..N) Doors[I] := 0 end,
foreach(I in 1..N)
foreach(J in I..I..N)
Doors[J] := 1^Doors[J]
end,
if N <= 10 then
print_open(Doors)
end
end,
writeln(Doors),
print_open(Doors),
nl.
print_open(Doors) => writeln([I : I in 1..Doors.length, Doors[I] == 1]).
% optimized version 1
doors_opt(N) =>
foreach(I in 1..N)
Root = sqrt(I),
writeln([I, cond(Root == 1.0*round(Root), open, closed)])
end,
nl.
% optimized version 2
doors_opt2(N) =>
writeln([I**2 : I in 1..N, I**2 <= N]).