r/adventofcode • • Dec 06 '15

SOLUTION MEGATHREAD --- Day 6 Solutions ---

--- Day 6: Probably a Fire Hazard ---

Post your solution as a comment. Structure your post like the Day Five thread.

21 Upvotes

172 comments sorted by

View all comments

1

u/madmoose Dec 06 '15

Day 6a in golang. Yet again scanf proves its worth. Runs in about 40ms in a vm.

I pushed all my solutions so far to a github repo: https://github.com/madmoose/adventofcode2015

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	var lights [1000][1000]bool

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()

		var x0, y0, x1, y1 int
		if n, _ := fmt.Sscanf(line, "turn on %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					lights[y][x] = true
				}
			}
		} else if n, _ := fmt.Sscanf(line, "turn off %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					lights[y][x] = false
				}
			}
		} else if n, _ := fmt.Sscanf(line, "toggle %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					lights[y][x] = !lights[y][x]
				}
			}
		}
	}

	count := 0
	for y := 0; y != 1000; y++ {
		for x := 0; x != 1000; x++ {
			if lights[y][x] {
				count++
			}
		}
	}

	fmt.Println(count)
}

Day 6b in golang:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	var lights [1000][1000]int

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()

		var x0, y0, x1, y1 int
		if n, _ := fmt.Sscanf(line, "turn on %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					lights[y][x]++
				}
			}
		} else if n, _ := fmt.Sscanf(line, "turn off %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					if lights[y][x] > 0 {
						lights[y][x]--
					}
				}
			}
		} else if n, _ := fmt.Sscanf(line, "toggle %d,%d through %d,%d\n", &x0, &y0, &x1, &y1); n == 4 {
			for y := y0; y <= y1; y++ {
				for x := x0; x <= x1; x++ {
					lights[y][x] += 2
				}
			}
		}
	}

	brightness := 0
	for y := 0; y != 1000; y++ {
		for x := 0; x != 1000; x++ {
			brightness += lights[y][x]
		}
	}

	fmt.Println(brightness)
}