commit c8f7b64102ae0d3e660a209879a1373fd5766d5e Author: Template Pony Date: Sat Dec 3 18:56:12 2022 +0800 Code for day1, 2 in golang diff --git a/go/1/main.go b/go/1/main.go new file mode 100644 index 0000000..536ab28 --- /dev/null +++ b/go/1/main.go @@ -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) + +} \ No newline at end of file diff --git a/go/2/main.go b/go/2/main.go new file mode 100644 index 0000000..ba9597b --- /dev/null +++ b/go/2/main.go @@ -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) +} \ No newline at end of file