Started 2022 with go

This commit is contained in:
Karma Riuk
2023-08-02 11:50:29 +02:00
parent 567c8487b5
commit 7098b525f0
26 changed files with 6810 additions and 0 deletions

91
2022/go/02/answer.go Normal file
View File

@ -0,0 +1,91 @@
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
const (
ROCK int = iota
PAPER
SCISSOR
)
const (
LOSS int = 3 * iota
DRAW
WIN
)
type Turn struct {
them int
me int
}
type Input struct {
turns []Turn
}
var str_to_RPS = map[string]int{
"A": ROCK,
"B": PAPER,
"C": SCISSOR,
"X": ROCK,
"Y": PAPER,
"Z": SCISSOR,
}
func input(filename string) *Input {
file, err := os.Open(filename)
check(err)
defer file.Close()
input := &Input{
turns: []Turn{},
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
hands := strings.Split(line, " ")
input.turns = append(input.turns, Turn{str_to_RPS[hands[0]], str_to_RPS[hands[1]]})
}
return input
}
func result(inp *Input, part int8) string {
var res string
score := 0
for _, turn := range inp.turns {
score += turn.me + 1
if turn.me == (turn.them+1)%3 {
score += WIN
} else if turn.me == turn.them {
score += DRAW
}
}
res = fmt.Sprint(score)
return res
}
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
result := result(input("sample1"), 1)
log.SetFlags(log.Lshortfile)
log.Println(result)
fmt.Println(result)
}

44
2022/go/02/answer_test.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"reflect"
"testing"
)
func TestInputSample1(t *testing.T) {
filename := "sample1"
expected := &Input{
turns: []Turn{
{ROCK, PAPER},
{PAPER, ROCK},
{SCISSOR, SCISSOR},
},
}
var got *Input = input(filename)
if !reflect.DeepEqual(expected, got) {
t.Errorf("input(%q) = %v, want %v", filename, got, expected)
}
}
func TestResult(t *testing.T) {
tests := []struct {
part int8
filename string
expected string
}{
{1, "sample1", "15"},
{1, "input", "12855"},
// {2, "sample1", ""},
// {2, "input", ""},
}
for _, test := range tests {
var got string = result(input(test.filename), test.part)
if got != test.expected {
t.Errorf("result = %q, want %q", got, test.expected)
}
}
}

3
2022/go/02/go.mod Normal file
View File

@ -0,0 +1,3 @@
module aoc/2
go 1.20

0
2022/go/02/go.sum Normal file
View File

2500
2022/go/02/input Normal file

File diff suppressed because it is too large Load Diff

3
2022/go/02/sample1 Normal file
View File

@ -0,0 +1,3 @@
A Y
B X
C Z