From 40f7ca289def02dc1944a2d098d3089bf8e271d9 Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Wed, 6 Dec 2017 00:52:36 -0500 Subject: [PATCH] day 6 solution --- day6/Makefile | 8 ++++++++ day6/day6.erl | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 day6/Makefile create mode 100644 day6/day6.erl diff --git a/day6/Makefile b/day6/Makefile new file mode 100644 index 0000000..8bcb478 --- /dev/null +++ b/day6/Makefile @@ -0,0 +1,8 @@ +all: day6.beam + erl -noshell -s day6 start -s init stop + +day6.beam: + erlc day6.erl + +clean: + rm -f day6.beam diff --git a/day6/day6.erl b/day6/day6.erl new file mode 100644 index 0000000..49f2118 --- /dev/null +++ b/day6/day6.erl @@ -0,0 +1,39 @@ +-module(day6). +-export([start/0]). + +index_of(Item, List) -> index_of(Item, List, 1). + +index_of(_, [], _) -> not_found; +index_of(Item, [Item|_], Index) -> Index; +index_of(Item, [_|Tl], Index) -> index_of(Item, Tl, Index+1). + +redistribute_banks(BankConfiguration) + -> Max = lists:max(BankConfiguration), + Index = index_of(Max, BankConfiguration) - 1, + %io:fwrite("max ~B index ~B~n", [Max, Index]), + RawArray = array:from_list(BankConfiguration), + redistribute_banks(array:set(Index, 0, RawArray), Index, Max, length(BankConfiguration)). + +redistribute_banks(Array, _Index, RemainingBanks, _MaxSize) + when RemainingBanks == 0 -> array:to_list(Array); +redistribute_banks(Array, Index, RemainingBanks, MaxSize) + -> Target = (Index + 1) rem MaxSize, + OldBankValue = array:get(Target, Array), + %io:fwrite("target ~B oldbankvalue ~B~n", [Target, OldBankValue]), + redistribute_banks(array:set(Target, OldBankValue + 1, Array), Target, RemainingBanks - 1, MaxSize). + +steps_until_repeated(Input) + -> steps_until_repeated(Input, [], []). +steps_until_repeated(Input, Visited, UniqList) + when length(Visited) > 0, length(UniqList) /= length(Visited) -> [_|PriorVisits] = Visited, + InputIndex = index_of(Input, PriorVisits), + VisitedLength = length(Visited), + {VisitedLength,Input,InputIndex}; +steps_until_repeated(Input, Visited, _UniqList) + -> NewConfiguration = redistribute_banks(Input), + NewVisited = [NewConfiguration|Visited], + steps_until_repeated(NewConfiguration, NewVisited, lists:usort(NewVisited)). + +start() + -> io:fwrite("~p~n", [steps_until_repeated([0,2,7,0])]), + io:fwrite("~p~n", [steps_until_repeated([4,1,15,12,0,9,9,5,5,8,7,3,14,5,12,3])]).