Skip to content

Instantly share code, notes, and snippets.

@rthbound
Last active January 5, 2016 06:34
Show Gist options
  • Save rthbound/789d8d5469eb4808b22b to your computer and use it in GitHub Desktop.
Save rthbound/789d8d5469eb4808b22b to your computer and use it in GitHub Desktop.
http://adventofcode.com/day/6 solution in ruby... roughly 10 seconds to finish running (per part)
def run_commands(commands)
commands.each { |command|
command_set = command.match(/(\w*)\s(\d*,\d*)\s\w*\s(\d*,\d*)/).to_a[1..-1]
s = command_set[1].split(",").map(&:to_i)
e = command_set[-1].split(",").map(&:to_i)
s[0].upto(e[0]) do |x|
s[1].upto(e[1]) do |y|
@lights[x * 1000 + y] = @instructions[command_set[0].to_sym].call(@lights[x * 1000 + y])
end
end
};nil
end
# Part 1
@instructions = {
on: Proc.new {|x| x | true },
off: Proc.new {|x| x & false },
toggle: Proc.new {|x| x ^ true }
}
@lights = []
run_commands(commands)
@lights.select { |x| x }.count
# Part 2
@instructions = {
on: Proc.new { |x| x and (x + 1) or 1 },
off: Proc.new { |x| x && x > 0 and (x - 1) or 0 },
toggle: Proc.new { |x| x and (x + 2) or 2 }
}
@lights = []
run_commands(commands)
@lights.compact.inject(:+)
@rthbound
Copy link
Author

rthbound commented Dec 6, 2015

@real=301.809517362
@real=271.768964734
@real=104.395315207 # Latest

@rthbound
Copy link
Author

rthbound commented Dec 6, 2015

@real=20.326836811

@rthbound
Copy link
Author

rthbound commented Dec 6, 2015

@real=10.053620170998329

(roughly same on parts 1 and 2)

@rthbound
Copy link
Author

rthbound commented Dec 6, 2015

A different instruction set along with prefilling the @lights array seems to give a little speed boost to number 2:

@instructions = {
  on:     Proc.new { |x| x + 1 },
  off:    Proc.new { |x| x > 0 ? x - 1 : 0 },
  toggle: Proc.new { |x| x + 2 }
}
@lights = [0] * 1e6; nil
run_commands(commands)
@lights.inject(:+)

10.02s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment