pain-by-number

This commit is contained in:
2023-12-19 09:38:41 -05:00
parent 3001618707
commit 9d03ff01dc
12 changed files with 699 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
# You can ignore this file if you're solving this exercise in the web editor,
# or on your own computer if you have Elixir version 1.12 or higher.
# You can check which Elixir version you have by running `elixir -v` in your terminal.
defmodule Math do
import Bitwise
# copied from https://github.com/elixir-lang/elixir/blob/v1.12.0/lib/elixir/lib/integer.ex#L103-L114
def pow(base, exponent) when is_integer(base) and is_integer(exponent) do
if exponent < 0, do: raise("exponent cannot be negative")
guarded_pow(base, exponent)
end
# https://en.wikipedia.org/wiki/Exponentiation_by_squaring
defp guarded_pow(_, 0), do: 1
defp guarded_pow(b, 1), do: b
defp guarded_pow(b, e) when (e &&& 1) == 0, do: guarded_pow(b * b, e >>> 1)
defp guarded_pow(b, e), do: b * guarded_pow(b * b, e >>> 1)
end

View File

@@ -0,0 +1,41 @@
defmodule PaintByNumber do
def palette_bit_size(color_count, pow \\ 1) do
if color_count <= 2 ** pow do
pow
else
palette_bit_size(color_count, pow + 1)
end
end
def empty_picture() do
<<>>
end
def test_picture() do
<<0::2, 1::2, 2::2, 3::2>>
end
def prepend_pixel(picture, color_count, pixel_color_index) do
size = palette_bit_size(color_count)
pixel = <<pixel_color_index::size(size)>>
<<pixel::bitstring, picture::bitstring>>
end
def get_first_pixel(<<>>, _color_count), do: nil
def get_first_pixel(picture, color_count) do
size = palette_bit_size(color_count)
<<value::size(size), _rest::bitstring>> = picture
value
end
def drop_first_pixel(<<>>, _color_count), do: <<>>
def drop_first_pixel(picture, color_count) do
size = palette_bit_size(color_count)
<<_value::size(size), rest::bitstring>> = picture
rest
end
def concat_pictures(picture1, picture2) do
<<picture1::bitstring, picture2::bitstring>>
end
end