Code for day1, 2 in golang

This commit is contained in:
Template Pony 2022-12-03 18:56:12 +08:00
commit c8f7b64102
2 changed files with 170 additions and 0 deletions

83
go/1/main.go Normal file
View File

@ -0,0 +1,83 @@
package main
import (
"bufio"
"fmt"
"github.com/emirpasic/gods/trees/binaryheap"
"os"
"path/filepath"
"strconv"
)
var (
f = "../../1.input.txt"
)
func must(e error) {
if e != nil {
panic(e)
}
}
func min(a, b interface{}) int {
c1 := a.(int)
c2 := b.(int)
switch {
case c1 < c2:
return 1
case c2 > c1:
return -1
default:
return 0
}
}
func main() {
fp, err:= filepath.Abs(f)
must(err)
rf, err := os.Open(fp)
must(err)
s := bufio.NewScanner(rf)
s.Split(bufio.ScanLines)
max := 0
mh := binaryheap.NewWith(min)
b := []string{}
for s.Scan() {
l := s.Text()
switch l {
case "":
sum := 0
for _, a := range b {
i, err := strconv.Atoi(a)
must(err)
sum = sum + i
}
mh.Push(sum)
if max < sum {
max = sum
}
b = []string{}
default:
b = append(b, l)
}
}
fmt.Println("max:", max)
lastN := []int{}
sum3 := 0
for range []int{1,2,3} {
e, _ := mh.Pop()
value := (e).(int)
lastN = append(lastN, value)
sum3 = sum3 + value
}
fmt.Println("last 3:", lastN, sum3)
}

87
go/2/main.go Normal file
View File

@ -0,0 +1,87 @@
package main
import (
"bufio"
"os"
"path/filepath"
"strings"
)
var (
f = "../../2.input.txt"
RPS = map[string] int {
"X":1,
"Y":2,
"Z":3,
"A":1,
"B":2,
"C":3,
}
outcome = map[string] int {
"A X":3,
"A Y":6,
"A Z":0,
"B X":0,
"B Y":3,
"B Z":6,
"C X":6,
"C Y":0,
"C Z":3,
}
// A:Rock B:Paper C:Scissor
// X:lose Y:draw Z:win
rRPS = map[string] string {
"A X":"C",
"A Y":"A",
"A Z":"B",
"B X":"A",
"B Y":"B",
"B Z":"C",
"C X":"B",
"C Y":"C",
"C Z":"A",
}
rOutcome = map[string] int {
"X":0,
"Y":3,
"Z":6,
}
)
func must(e error) {
if e != nil {
panic(e)
}
}
func Score(line string) int {
sp := strings.Split(line, " ")
return RPS[sp[1]] + outcome[line]
}
func RealScore(line string) int {
sp := strings.Split(line, " ")
throw := rRPS[line]
return RPS[throw] + rOutcome[sp[1]]
}
func main() {
fp, err:= filepath.Abs(f)
must(err)
rf, err := os.Open(fp)
must(err)
s := bufio.NewScanner(rf)
s.Split(bufio.ScanLines)
totScore := 0
totRealScore := 0
for s.Scan() {
l := s.Text()
totScore = Score(l) + totScore
totRealScore = RealScore(l) + totRealScore
}
println("part 1 score:", totScore)
println("part 2 score:", totRealScore)
}