From 1cccb7132d9a02aba8c57b46043716a79080bf17 Mon Sep 17 00:00:00 2001 From: Karl Spickermann Date: Tue, 15 Dec 2020 16:43:32 +0100 Subject: [PATCH] Day15 --- .idea/workspace.xml | 38 ++++++++++++++++++----------- day15/day15.go | 59 +++++++++++++++++++++++++++++++++++++++++++++ helper/helper.go | 9 +++++++ 3 files changed, 92 insertions(+), 14 deletions(-) create mode 100644 day15/day15.go diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 0bb4675..4b832ec 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -11,10 +11,9 @@ - - - + + - + @@ -106,6 +105,15 @@ + + + + + + + + + @@ -224,9 +232,11 @@ + + @@ -261,26 +271,26 @@ - + - - + + - - + + - - + + - + @@ -301,9 +311,9 @@ - + - + \ No newline at end of file diff --git a/day15/day15.go b/day15/day15.go new file mode 100644 index 0000000..b18853a --- /dev/null +++ b/day15/day15.go @@ -0,0 +1,59 @@ +package main + +import "fmt" + +func main() { + fmt.Println(run([]int{5,1,9,18,13,8,0}, 2020)) + fmt.Println(runPart2([]int{5,1,9,18,13,8,0}, 30000000)) +} + +func run(startingNumber []int, length int) int{ + var band []int + band = append(band, startingNumber...) + for i := len(startingNumber); i < length; i++ { + currentNumber := band[i-1] + index := findIndex(currentNumber,band) + if index == -1 { + band = append(band, 0) + }else { + band = append(band, i-1-index) + } + } + return band[len(band)-1] +} + +func runPart2(startingNumber []int, length int) int{ + var band = make (map[int][]int) + for i, val := range startingNumber { + band[val] = []int{i,i} + } + lastNumber := startingNumber[len(startingNumber)-1] + for i := len(startingNumber); i < length; i++ { + currentNumber := lastNumber + indexes := band[currentNumber] + diffIndexes := indexes[1]-indexes[0] + if diffIndexes == 0 { + lastNumber = 0 + band[0] = []int{band[0][1],i} + }else { + lastNumber = diffIndexes + if len(band[diffIndexes]) != 0 { + band[diffIndexes] = []int{band[diffIndexes][1],i} + }else { + band[diffIndexes] = []int{i,i} + } + } + } + return lastNumber +} + +func findIndex(number int, band []int) int{ + for i := len(band)-2; i >= 0; i-- { + if band[i] == number { + return i + } + } + return -1 +} + + diff --git a/helper/helper.go b/helper/helper.go index 35ce7a4..0e2eee0 100644 --- a/helper/helper.go +++ b/helper/helper.go @@ -56,3 +56,12 @@ func FindAddendsForSum (possibleAddends []int, sum int) (int, int, error) { } return 0,0,errors.New("No fitting Addends found") } + +func SliceIndex(limit int, predicate func(i int) bool) int { + for i := 0; i < limit; i++ { + if predicate(i) { + return i + } + } + return -1 +} \ No newline at end of file