1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
require "ext"
local cave = {}
local lowest = 0
for line in io.lines() do
print("line:",line)
local cursor = nil
for pair in line:gmatch("([0-9,]+)") do
local col,row = pair:match("(%d+),(%d+)")
col,row = tonumber(col),tonumber(row)
if cursor then
for rown = math.min(cursor[1],row), math.max(cursor[1],row) do
for coln = math.min(cursor[2],col), math.max(cursor[2],col) do
cave[rown] = cave[rown] or {}
printf("Setting %d %d to true",rown,coln)
cave[rown][coln] = true
end
end
end
lowest = math.max(row,lowest)
cursor = {row,col}
end
end
local sand = {}
function print_puzzle()
for row = 0, 500 do
for col = 0,100 do
local data = cave[row] and cave[row][col]
if data == "s" then
io.write("O")
elseif data then
io.write("#")
else
io.write(".")
end
end
io.write("\n")
end
for _,row in pairs(cave) do
for _,col in pairs(row) do
end
end
end
print_puzzle()
print("lowest:",lowest)
local floor = lowest + 2
local sandpoint = {0,500}
local movement = {
{1,0},
{1,-1},
{1,1}
}
local x = 0
while true do
for k,v in pairs(sandpoint) do
sand[k] = v
end
local could_move = false
repeat
could_move = false
for _,move in ipairs(movement) do
local drow, dcol = sand[1] + move[1], sand[2] + move[2]
if not cave[drow] or cave[drow][dcol] == nil then
could_move = true
sand[1] = drow
sand[2] = dcol
break
end
end
until not could_move or sand[1] = floor
if not could_move then
cave[sand[1]] = cave[sand[1]] or {}
cave[sand[1]][sand[2]] = "s"
end
if sand[1] == 500 then
print("sand stopped falling")
break
end
x = x + 1
end
print_puzzle()
print(x)
|