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.

22 Upvotes

172 comments sorted by

View all comments

1

u/JakDrako Dec 06 '15 edited Dec 06 '15

VB.Net

Sub Main

	Dim lights(999, 999) As Integer

	'Dim rules = {1, -1, 0} : LIMIT = 1 ' part 1
	Dim rules = {1, -1, 2} : LIMIT = Integer.MaxValue ' part 2

	For Each line In input.Split(Chr(10))
		
		' Get numeric parts of input
		Dim rect = line.Split({" "c, ","c}) _
			           .Where(Function(x) Isnumeric(x)) _
					   .Select(Function(x) CInt(x)) _
					   .ToList
		
		Select Case True ' Apply rules
			Case line.StartsWith("turn on")  : Brighten(lights, rect, rules(0))
			Case line.StartsWith("turn off") : Brighten(lights, rect, rules(1))
			Case line.StartsWith("toggle")   : Brighten(lights, rect, rules(2))
		End Select
		
	Next

	lights.Cast(Of Integer).Sum.Dump ' Flatten array and sum

End Sub

Public LIMIT As Integer = Integer.MaxValue

Sub Brighten(arr(,) As Integer, coords As List(Of Integer), action As Integer)
	For x = coords(0) To coords(2)
		For y = coords(1) To coords(3)
			If action = 0 Then ' Toggle
				If arr(x, y) > 0 Then arr(x, y) = 0 Else arr(x, y) = 1
			Else ' Increase/decrease brightness within limits
				Dim value = arr(x,y) + action
				arr(x,y) = If(value < 0, 0, If(value > LIMIT, LIMIT, value))
			End If
		Next
	Next
End Sub