From b03c50fcfb59818e10147a03cb5644877c82b071 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Fri, 4 Dec 2020 23:56:25 +0100 Subject: [PATCH] 3 in go --- solutions/3/go/main.go | 66 ++++++++++++++++++++++++++++++++ solutions/3/{ => python}/main.py | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 solutions/3/go/main.go rename solutions/3/{ => python}/main.py (96%) diff --git a/solutions/3/go/main.go b/solutions/3/go/main.go new file mode 100644 index 0000000..3c9282e --- /dev/null +++ b/solutions/3/go/main.go @@ -0,0 +1,66 @@ +package main + +import ( + "fmt" + "io/ioutil" + "strings" +) + +const high = rune('#') + +type sForest struct { + data [][]bool + height int + width int +} + +func (f sForest) at(y, x int) bool { + if y >= f.height { + return false + } + return f.data[y][x%f.width] +} + +func (f sForest) traverse(y, x int) int { + trees := 0 + for dy := 0; dy <= f.height; dy++ { + tree := f.at(dy*y, dy*x) + if tree { + trees++ + } + } + return trees +} + +func main() { + data, _ := ioutil.ReadFile("./solutions/3/data.txt") + + rows := strings.Split(strings.TrimSpace(string(data)), "\n") + height, width := len(rows), len(rows[0]) + d := make([][]bool, height) + + for y, row := range rows { + d[y] = make([]bool, width) + for x, char := range []rune(row) { + d[y][x] = char == high + } + } + + forest := sForest{ + data: d, + height: height, + width: width, + } + + fmt.Println("Simple: ", forest.traverse(1, 3)) + + trees11 := forest.traverse(1, 1) + trees13 := forest.traverse(1, 3) + trees15 := forest.traverse(1, 5) + trees17 := forest.traverse(1, 7) + trees21 := forest.traverse(2, 1) + + fmt.Println(trees11, trees13, trees15, trees17, trees21) + fmt.Println(trees11 * trees13 * trees15 * trees17 * trees21) + +} diff --git a/solutions/3/main.py b/solutions/3/python/main.py similarity index 96% rename from solutions/3/main.py rename to solutions/3/python/main.py index e118aaa..e1e333d 100644 --- a/solutions/3/main.py +++ b/solutions/3/python/main.py @@ -19,7 +19,7 @@ class Forest(): return row[x % len(row)] == '#' -data = join(dirname(__file__), 'data.txt') +data = join(dirname(__file__), '../data.txt') with open(data) as f: forest = Forest(f.read())