Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@iiska
Created December 4, 2012 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iiska/4205163 to your computer and use it in GitHub Desktop.
Save iiska/4205163 to your computer and use it in GitHub Desktop.
Candle puzzle encountered in IRC
#! /usr/bin/env ruby
# Finds answer to following puzzle
#
# There are one thousand candles on the altar and one thousand priests
# in the temple. Their god asks the first priest to go and light all
# the candles. Then he has the second priest go to every second candle
# and put it out."
#
# The third goes to every third candle and, if it is not burning, he
# lights it, and if it is lit, he puts it out."
#
# The fourth priest does this to every fourth candle, and so on. After
# the process is completed with the thousandth priest, how many
# candles are not lit?"
candles = []
(1..1000).each do |priest|
(0...1000).step(priest) do |candle|
candles[candle] = !candles[candle]
end
end
puts "#{candles.select{|c|c}.count} candles lit"
puts "#{candles.select{|c|!c}.count} candles unlit"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment