adventofcode/2017/day01/day01.go

64 lines
1020 B
Go
Raw Normal View History

2017-12-01 12:41:19 +00:00
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
"strconv"
)
func main() {
inp := StdinToString()
part1(inp)
part2(inp)
}
func part1(inp string) {
sum := 0
for k := range inp {
2017-12-01 14:04:46 +00:00
tstIdx := getCompareIndex(k, 1, len(inp))
2017-12-01 12:41:19 +00:00
sum += getCompareResult(inp[k], inp[tstIdx])
}
fmt.Println("Part 1:", sum)
}
func part2(inp string) {
sum := 0
for k := range inp {
tstIdx := getCompareIndex(k, (len(inp) / 2), len(inp))
sum += getCompareResult(inp[k], inp[tstIdx])
}
fmt.Println("Part 2:", sum)
}
func getCompareIndex(curr, add, max int) int {
return int(math.Mod(float64(curr+add), float64(max)))
}
func getCompareResult(c1, c2 byte) int {
if c1 != c2 {
return 0
}
return Atoi(string(c1))
}
func StdinToString() string {
var input string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
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
}