From d4eb4a757c15d8be20a0e6a6a09bc77fcc47ac9e Mon Sep 17 00:00:00 2001 From: Pierre Jeanjean Date: Thu, 1 Dec 2022 07:10:11 +0100 Subject: [PATCH] Day 1 --- .gitignore | 1 + 01/1.go | 21 +++++++++++++++++++++ 01/2.go | 30 ++++++++++++++++++++++++++++++ 01/parser.go | 41 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+) create mode 100644 .gitignore create mode 100644 01/1.go create mode 100644 01/2.go create mode 100644 01/parser.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..06c798b --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +input.txt diff --git a/01/1.go b/01/1.go new file mode 100644 index 0000000..dddc457 --- /dev/null +++ b/01/1.go @@ -0,0 +1,21 @@ +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + inventories := parse(*bufio.NewScanner(os.Stdin)) + + largestInventoryTotal := 0 + for _, inventory := range inventories { + currentTotal := inventory.getTotal() + if currentTotal > largestInventoryTotal { + largestInventoryTotal = currentTotal + } + } + + fmt.Println(largestInventoryTotal) +} diff --git a/01/2.go b/01/2.go new file mode 100644 index 0000000..ffb6131 --- /dev/null +++ b/01/2.go @@ -0,0 +1,30 @@ +package main + +import ( + "bufio" + "fmt" + "os" +) + +func main() { + inventories := parse(*bufio.NewScanner(os.Stdin)) + + largestInventoriesTotal := []int{0, 0, 0} + largestInventoriesIndex := []int{-1, -1, -1} + for i := 0; i < 3; i++ { + for index, inventory := range inventories { + currentTotal := inventory.getTotal() + if currentTotal > largestInventoriesTotal[i] && index != largestInventoriesIndex[0] && index != largestInventoriesIndex[1] { + largestInventoriesTotal[i] = currentTotal + largestInventoriesIndex[i] = index + } + } + } + + sum := 0 + for _, inventoryTotal := range largestInventoriesTotal { + sum += inventoryTotal + } + + fmt.Println(sum) +} diff --git a/01/parser.go b/01/parser.go new file mode 100644 index 0000000..c9ab6f4 --- /dev/null +++ b/01/parser.go @@ -0,0 +1,41 @@ +package main + +import ( + "bufio" + "strconv" +) + +type Inventory struct { + rations []int +} + +func (inventory *Inventory) addRation(ration int) { + inventory.rations = append(inventory.rations, ration) +} + +func (inventory Inventory) getTotal() int { + total := 0 + for _, ration := range inventory.rations { + total += ration + } + return total +} + +func parse(scanner bufio.Scanner) []Inventory { + inventories := []Inventory{} + currentInventory := Inventory{} + + for scanner.Scan() { + line := scanner.Text() + if line == "" { + inventories = append(inventories, currentInventory) + currentInventory = Inventory{[]int{}} + } else { + ration, _ := strconv.Atoi(line) + currentInventory.addRation(ration) + } + } + inventories = append(inventories, currentInventory) + + return inventories +}