-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday22.go
More file actions
109 lines (90 loc) · 2.34 KB
/
day22.go
File metadata and controls
109 lines (90 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
"strconv"
)
func buildQueue(puzzleInput []string, sectionBreak string) (resultQueue []int) {
var sectionProcessed bool = false
var tmpCard int
resultQueue = make([]int, 0)
for _, line := range puzzleInput {
if len(line) == 0 {
// We've reached the break. Have we seen section break? If so quit
if sectionProcessed {
return resultQueue
}
}
if line == sectionBreak {
sectionProcessed = true
} else if sectionProcessed {
tmpCard, _ = strconv.Atoi(line)
resultQueue = append(resultQueue, tmpCard)
}
}
return resultQueue
}
/* HOW TO USE A SLICE AS A QUEUE
queue := make([]int, 0)
// Push to the queue
queue = append(queue, 1)
// Top (just get next element, don't remove it)
x = queue[0]
// Discard top element
queue = queue[1:]
// Is empty ?
if len(queue) == 0 {
fmt.Println("Queue is empty !")
}
*/
func playCombat(player1Hand []int, player2Hand []int) []int {
for len(player1Hand) > 0 && len(player2Hand) > 0 {
if player1Hand[0] > player2Hand[0] {
player1Hand = append(player1Hand, player1Hand[0])
player1Hand = append(player1Hand, player2Hand[0])
player1Hand = player1Hand[1:]
player2Hand = player2Hand[1:]
} else if player2Hand[0] > player1Hand[0] {
player2Hand = append(player2Hand, player2Hand[0])
player2Hand = append(player2Hand, player1Hand[0])
player1Hand = player1Hand[1:]
player2Hand = player2Hand[1:]
} else {
fmt.Println("ERROR: Draw!")
}
}
if len(player1Hand) > 1 {
return player1Hand
}
return player2Hand
}
// part a
func calcWinningScore(filename string, part byte, debug bool) int {
var result int
puzzleInput, _ := readFile(filename)
player1Hand := buildQueue(puzzleInput, "Player 1:")
player2Hand := buildQueue(puzzleInput, "Player 2:")
if debug {
fmt.Println("player1Hand:", player1Hand)
fmt.Println("player2Hand:", player2Hand)
}
winningDeck := playCombat(player1Hand, player2Hand)
posScore := len(winningDeck)
for _, card := range winningDeck {
result += card * posScore
posScore--
}
return result
}
// Main routine
func main() {
filenamePtr, execPart, debug, test := catchUserInput()
if test {
return
}
if execPart == 'z' {
fmt.Println("Bad part choice. Available choices are 'a' and 'b'")
} else if execPart == 'a' {
fmt.Println("Winning Score:", calcWinningScore(filenamePtr, execPart, debug))
} else {
}
}