adventofcode/2018/day24/army.go

81 lines
1.7 KiB
Go

package main
type Army struct {
tp int
units int
hp int
immunities []string
weaknesses []string
damageType string
strength int
init int
}
func NewArmy(inp string, tp int) *Army {
a := new(Army)
a.tp = tp
// Pull the parenthetical out, if one is there
var prnth, other string
var inPrnth bool
var ptsOfOther int
for _, v := range strings.Fields(inp) {
if len(v) > 0 && v[len(v)-1] == ')' {
prnth = prnth + " " + v
inPrnth = false
continue
} else if len(v) > 0 && v[0] == '(' {
inPrnth = true
prnth = v
continue
}
if inPrnth {
prnth = prnth + " " + v
} else {
if len(other) > 0 {
other = other + " "
}
other = other + v
ptsOfOther++
}
}
_, err := fmt.Sscanf(other, "%d units each with %d hit points with an attack that does %d %s damage at initiative %d", &a.units, &a.hp, &a.strength, &a.damageType, &a.init)
if err != nil {
panic(err)
}
// Now parse out immunities and weaknesses
if len(prnth) > 3 {
prnth = prnth[1:len(prnth)-1]
var inImmune bool
for _, v := range strings.Fields(prnth) {
if v == "immune" {
inImmune = true
} else if v == "weak" {
inImmune = false
}
if v == "to" {
continue
}
if v[len(v)-1] == ';' || v[len(v)-1] == ',' {
v = v[:len(v)-1]
}
if inImmune {
a.immunities = append(a.immunities, v)
} else {
a.weaknesses = append(a.weaknesses, v)
}
}
}
return a
}
func (a *Army) Power() int {
return a.units * a.strength
}
// Army Sorting
type ByPower []Army
func (b ByPower) Len() int { return len(b) }
func (b ByPower) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
func (b ByPower) Less(i, j int) { b[i].Power() < b[j].Power() }