adventofcode/2017/day02/day02.go

96 lines
1.5 KiB
Go
Raw Normal View History

2017-12-02 05:34:33 +00:00
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
func main() {
inp := StdinToStrings()
part1(inp)
part2(inp)
}
func part1(inp []string) {
fmt.Println("= Part 1 =")
var chk int
for i := range inp {
cells := strings.Split(inp[i], "\t")
max, min := -1, -1
for j := range cells {
tst := Atoi(cells[j])
if tst > max {
max = tst
}
if min < 0 || tst < min {
min = tst
}
}
chk += (max - min)
}
fmt.Println("Checksum: ", chk)
fmt.Println("")
}
func part2(inp []string) {
fmt.Println("= Part 2 =")
var chk int
for i := range inp {
cells := strings.Split(inp[i], "\t")
var foundIt bool
for j := range cells {
for k := j; k < len(cells); k++ {
jVal, kVal := Atoi(cells[j]), Atoi(cells[k])
if isThePair(jVal, kVal) {
foundIt = true
chk += getResult(jVal, kVal)
break
}
}
if foundIt {
break
}
}
}
fmt.Println("Checksum: ", chk)
fmt.Println("")
}
func isThePair(k, j int) bool {
if k == j {
return false
}
jVal, kVal := float64(j), float64(k)
return math.Mod(jVal, kVal) == 0 || math.Mod(kVal, jVal) == 0
}
func getResult(k, j int) int {
if k > j {
return k / j
}
return j / k
}
func StdinToStrings() []string {
var input []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input = append(input, scanner.Text())
}
return input
}
func Atoi(i string) int {
var ret int
var err error
if ret, err = strconv.Atoi(i); err != nil {
log.Fatal("Invalid Atoi")
}
return ret
}