Skip to content

Instantly share code, notes, and snippets.

@mmmries
Created January 17, 2020 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmmries/9ec5dfecaf8f6b5048ed2c98305d3335 to your computer and use it in GitHub Desktop.
Save mmmries/9ec5dfecaf8f6b5048ed2c98305d3335 to your computer and use it in GitHub Desktop.
A solution for how to encode a list of "on" cell locations into a game-of-life encoding
defmodule GOL do
def encode(list) do
encode(nil, list)
end
# Figure out the starting condition, whether we start "on" or "blank"
def encode(nil, [1 | rest]), do: encode({:on, 1, 1}, rest)
def encode(nil, rest), do: encode({:blank, 1}, rest)
# If we have a sequence of "on" cells we need to know when it started and whether we are consecutive
# with the last cell
def encode({:on, since, last}, [next | rest]) when next == last + 1 do
encode({:on, since, next}, rest)
end
# If we observed some "on" cells, but are no longer sequential, then we need to switch to "blank"
def encode({:on, since, last}, [next | rest]) do
encode_chunk("o", last - since + 1) <> encode({:blank, last + 1}, [next | rest])
end
# Blanks are already collapsed in the sequence, so we just need to know when things went blank
def encode({:blank, since}, [next | rest]) do
encode_chunk("b", next - since) <> encode({:on, next, next}, rest)
end
def encode({:on, since, last}, []) do
encode_chunk("o", last - since + 1) <> "$"
end
# Handle the special case of an empty list
def encode({:blank, 1}, []), do: "$"
def encode_chunk(char, 0), do: ""
def encode_chunk(char, 1), do: char
def encode_chunk(char, n), do: "#{n}#{char}"
end
IO.puts "1, 2, 3 => #{GOL.encode([1, 2, 3])}"
IO.puts "\tShould be 3o$"
IO.puts "4 => #{GOL.encode([4])}"
IO.puts "\tShould be 3bo$"
IO.puts "4 8 9 10 14 => #{GOL.encode([4, 8, 9, 10, 14])}"
IO.puts "\tShould be 3bo3b3o3bo$"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment