Last active
January 5, 2016 06:34
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(:+) |
@real=20.326836811
@real=10.053620170998329
(roughly same on parts 1 and 2)
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
@real=301.809517362
@real=271.768964734
@real=104.395315207 # Latest