עוד גירסא הפעם בשפת אליקסיר (וכוללת גם הדפסה של הלוח בסוף).
defmodule Game do
defstruct matrix: %{}, pos: {0, 0}, head: { 1, 0 }
end
defmodule Day22 do
@directions [{1, 0}, {0, 1}, {-1, 0}, {0, -1}]
def next("#"), do: "."
def next("."), do: "#"
def next(nil), do: "#"
def pp(game, size) do
matrix = game.matrix
pos = game.pos
for i <- 0..size-1 do
for j <- 0..size-1 do
val = Map.get(matrix, { i - div(size, 2), j - div(size, 2) })
if val do
if pos == { i - div(size, 2), j - div(size, 2) } do
"[#{val}]"
else
" #{val} "
end
else
if pos == { i - div(size, 2), j - div(size, 2) } do
"[.]"
else
" . "
end
end
end
|> Enum.join("")
end
|> Enum.join("\n")
end
def flip(matrix, { row, col }) do
{ _, next } = matrix
|> Map.get_and_update(
{ row, col },
fn current_value -> { current_value, next(current_value) }
end
)
next
end
def right(direction) do
idx = Enum.find_index(@directions, fn x -> x == direction end)
Enum.at(@directions, rem(idx + 1, length(@directions)))
end
def left(direction) do
idx = Enum.find_index(@directions, fn x -> x == direction end)
Enum.at(@directions, rem(idx - 1, length(@directions)))
end
def move({ dr, dc }, { row, col }), do: { row + dr, col + dc }
def step(game) do
next_direction = case Map.get(game.matrix, game.pos, ".") do
"." -> left(game.head)
"#" -> right(game.head)
end
Map.merge(
game,
%{
head: next_direction,
matrix: flip(game.matrix, game.pos),
pos: move(next_direction, game.pos)
}
)
end
def play(game, 0) do
game
end
def play(game, n) do
play(step(game), n - 1)
end
def main do
iterations = System.argv() |> Enum.at(0) |> String.to_integer
game = %Game{}
s1 = play(game, iterations)
s1
|> pp(20)
|> IO.puts
Enum.count(s1.matrix, fn {_, v} -> v == "#" end)
|> IO.puts
end
end
Day22.main
וככה זה נראה כשמריצים:
localhost:aoc2017 ynonperek$ elixir day22_b.elxrs 100000
# # . . # . . . . . . # . . # . . # . .
# . # # . . . . . . . # . . . # . . # .
. # # # # # # # # . # . . . . # . . # .
# . # . # # . # # . . . . # . # . # . #
. . . . # . . . # . # # . . . # # . . #
. # . . # # # # . . . # . . # . . . # #
. . # # . # # # # # . . # . # # # # . .
. . . # . # . . # # . # # # # # . # # .
# . # . . . . . # # # # # . # . # # # #
. . . # . # . # # . # . # # . # # # # #
. # # # . # # # . # # . # # . . . # # .
# # # # # # # # # . . # # . . # # # # .
# . . # . # # # # # # # # # # # . . # #
# # # . . . . . . . # # . . . # . # # .
# # . . . . . . # # . # . # . # # # . #
# . # # # # # . . # # . . # # . # . # #
. . . . . . # . . # # # . # . . # . . .
# # . # . . # # . # # # # . # . # . . #
. . . . # . . # # # . . . # # . # # . .
. # . . . . . # # . . # . . # # # . # #
11108
הבא בתור בפייתון?