Unable to load image

Advent of code day 4 :marseysad:

This is the advent of code day 4 thread for bragging about your solution and bullying people who haven't gotten it yet :marseyill:

35
Jump in the discussion.

No email address required.

yes I stole the intersection function, no I don't care


package four

import (
	"bufio"
	"os"
	"strconv"
	"strings"
)

func grabRange(line string) (map[string]int, map[string]int) {
	a := make(map[string]int)
	b := make(map[string]int)

	pair := strings.Split(line, ",")

	left := strings.Split(pair[0], "-")
	right := strings.Split(pair[1], "-")

	a["min"], _ = strconv.Atoi(left[0])
	a["max"], _ = strconv.Atoi(left[1])

	b["min"], _ = strconv.Atoi(right[0])
	b["max"], _ = strconv.Atoi(right[1])

	return a, b
}

func One() int {
	var deliver int

	fp, _ := os.Open("four.txt")
	defer fp.Close()

	rd := bufio.NewScanner(fp)

	for rd.Scan() {
		left, right := grabRange(rd.Text())

		if (left["min"] <= right["min"] && right["max"] <= left["max"]) ||
			(left["min"] >= right["min"] && right["max"] >= left["max"]) {
			deliver++
		}
	}

	return deliver
}

func Two() int {
	var deliver int

	fp, _ := os.Open("four.txt")
	defer fp.Close()

	rd := bufio.NewScanner(fp)

	for rd.Scan() {
		var a, b []int
		left, right := grabRange(rd.Text())

		for i := left["min"]; ; i++ {
			a = append(a, i)

			if i >= left["max"] {
				break
			}
		}

		for i := right["min"]; ; i++ {
			b = append(b, i)

			if i >= right["max"] {
				break
			}
		}

		intersection := func(a, b []int) bool {
			var c []int
			m := make(map[int]bool)

			for _, item := range a {
				m[item] = true
			}

			for _, item := range b {
				if _, ok := m[item]; ok {
					c = append(c, item)
				}
			}
			return (len(c) > 0)
		}

		if intersection(a, b) {
			deliver++
		}

		a = nil
		b = nil
	}

	return deliver
Jump in the discussion.

No email address required.

I don't know what you said, because I've seen another human naked.

Jump in the discussion.

No email address required.



Now playing: Funky's Fugue (DKC).mp3

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.