Skip to content

Commit

Permalink
use util in d1
Browse files Browse the repository at this point in the history
  • Loading branch information
krystiangryczon committed Dec 9, 2023
1 parent f393e33 commit e301312
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 21 deletions.
14 changes: 3 additions & 11 deletions lib/code/day1_1.ex
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
defmodule Advent.Code1_1 do
def is_num(x) do
case Integer.parse(x, 10) do
{num, _} -> num
:error -> false
end
end

@spec get_left(str: String.t()) :: integer()
def get_left(""), do: 0

def get_left(str) do
if String.length(str) > 0 do
[h | t] = String.split(str, "", trim: true)

if !!is_num(h) do
is_num(h)
if is_number(My.Utils.string_to_num_or_false(h)) do
My.Utils.string_to_num_or_false(h)
else
get_left(Enum.join(t))
end
Expand All @@ -30,6 +22,6 @@ defmodule Advent.Code1_1 do
end

def sum_list(str_list) do
Enum.reduce([0 | str_list], fn el, acc -> acc + is_num(sum(el)) end)
Enum.reduce([0 | str_list], fn el, acc -> acc + My.Utils.string_to_num_or_false(sum(el)) end)
end
end
13 changes: 3 additions & 10 deletions lib/code/day1_2.ex
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
defmodule Advent.Code1_2 do
def is_num(x) do
case Integer.parse(x, 10) do
{num, _} -> num
:error -> false
end
end

def combine(str) do
Integer.to_string(digit_from_left(str)) <> Integer.to_string(digit_from_right(str))
end
Expand Down Expand Up @@ -38,7 +31,7 @@ defmodule Advent.Code1_2 do

digit =
String.graphemes(from_start_to_smallest)
|> Enum.map(fn x -> is_num(x) end)
|> Enum.map(fn x -> My.Utils.string_to_num_or_false(x) end)
|> Enum.filter(fn x -> x != false end)

cond do
Expand All @@ -63,7 +56,7 @@ defmodule Advent.Code1_2 do

digit =
String.graphemes(from_biggest_to_end)
|> Enum.map(fn x -> is_num(x) end)
|> Enum.map(fn x -> My.Utils.string_to_num_or_false(x) end)
|> Enum.filter(fn x -> x != false end)

cond do
Expand All @@ -74,7 +67,7 @@ defmodule Advent.Code1_2 do

def sum_list(str_list) do
Enum.reduce([0 | str_list], fn el, acc ->
acc + is_num(combine(el))
acc + My.Utils.string_to_num_or_false(combine(el))
end)
end
end

0 comments on commit e301312

Please sign in to comment.