Skip to content

Instantly share code, notes, and snippets.

@DeedleFake
Created August 2, 2023 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeedleFake/2e18b0f8eddd3707c95eae9032f5e3fa to your computer and use it in GitHub Desktop.
Save DeedleFake/2e18b0f8eddd3707c95eae9032f5e3fa to your computer and use it in GitHub Desktop.
Advent of Code, 2022, Day 4
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
type Iter[T any] func(func(T) bool) bool
func ScanText(s *bufio.Scanner) Iter[string] {
return func(yield func(string) bool) bool {
for s.Scan() {
if !yield(s.Text()) {
break
}
}
return false
}
}
func Lines(r io.Reader, err *error) Iter[string] {
s := bufio.NewScanner(r)
return func(yield func(string) bool) bool {
ScanText(s)(yield)
*err = s.Err()
return false
}
}
func parse(str string) (start, end int) {
s, e, _ := strings.Cut(str, "-")
sn, _ := strconv.ParseInt(s, 10, 0)
en, _ := strconv.ParseInt(e, 10, 0)
return int(sn), int(en)
}
func check(line string) bool {
left, right, _ := strings.Cut(line, ",")
l1, l2 := parse(left)
r1, r2 := parse(right)
return ((l1 >= r1) && (l2 <= r2)) || ((r1 >= l1) && (r2 <= l2))
}
func main() {
file, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer file.Close()
var total int
for line := range Lines(file, &err) {
if check(line) {
total++
}
}
if err != nil {
panic(err)
}
fmt.Println(total)
}
module advent04
go 1.21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment