advent-of-code

advent of code (partial solutions)
Log | Files | Refs | README

commit cc9e8162c26e44717aa9af7ee6e503d367349350
parent ec87d8e08bc4f6b4d78d74bc9420741b2e2b0847
Author: alex wennerberg <alex@alexwennerberg.com>
Date:   Fri,  3 Dec 2021 19:20:34 -0800

AOC 2021 1.1 in go templates

Diffstat:
A2021/aoc01-templ.go | 32++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+), 0 deletions(-)

diff --git a/2021/aoc01-templ.go b/2021/aoc01-templ.go @@ -0,0 +1,32 @@ +package main + +// Advent of Code day 1 part 1 in Go templates. reads input from stdin + +import ( + "bufio" + "os" + "strconv" + "text/template" +) + +const templ = `{{$x := -1}}{{$last := 0}}{{range $n, $element := .Input}}{{if gt $element $last}}{{$x = addone $x }}{{end}}{{$last = $element}}{{end}}{{$x}} +` + +func main() { + scanner := bufio.NewScanner(os.Stdin) + var lines []int + for scanner.Scan() { + d, _ := strconv.Atoi(scanner.Text()) + lines = append(lines, d) + } + tmpl := template.New("aoc") + tmpl = tmpl.Funcs(template.FuncMap{"addone": func(i int) int { return i + 1 }}) + tmpl, err := tmpl.Parse(templ) + if err != nil { + panic(err) + } + err = tmpl.Execute(os.Stdout, struct{ Input []int }{lines}) + if err != nil { + panic(err) + } +}