I was hanging out with a friend and his new GF the other day, enjoying a couple of drinks. She asked me what my birthday was and I told her - she did some quick math and decided that I wasn't 'lucky'. Both her and my friend were; in that the sum of their birthday's month, date and year added up to 100 ex. 3/22/75.
I pointed out that it should really be 2000 and that this was one of the stupidest idea I had heard - determining luck based on numbers. Anyhow, the problem of determining this intrigued me. I had picked up a Ruby book earlier that week and in the course of a couple hours wrote this script that does exactly that - finds all dates that add up to a given number.
Here is the code:
Code:
#!/usr/bin/env ruby -wKU
require 'date'
start_time = Time.now
if ARGV.length != 1
puts 'please provide the target number (and only the target number)'
else
target = ARGV[0].to_i # this is a String initially
start_year = target - 12 - 31 # maximum month and date for start year for target
end_year = target - 1 - 1 # minimum month and date for end year for target
n = 0 # just a counter
(start_year..end_year).each do |year|
test_date = Date.new(year, 1, 1) # start with lowest possible value
last_of_the_year = Date.new(year, 12, 31) # don't move up through to the next year
hit_dates = Array.new
while (last_of_the_year >= test_date) do
if ( (test_date.year + test_date.month + test_date.day) == target )
hit_dates << test_date
n = n + 1
end
test_date = (test_date + 1)
end
dates = hit_dates.collect { |d| d.month.to_s + '/' + d.day.to_s }
dates = dates.join ', '
puts hit_dates[0].year.to_s + ' ' + dates.to_s + ' (n:' + hit_dates.length.to_s + ')' unless hit_dates.empty?
end
puts n.to_s + ' total dates which add up to ' + target.to_s
end
puts (Time.now - start_time).to_s + ' seconds'
And it's run from the command line:
As this is one of the first Ruby scripts I've written, I wanted to see what people thought of it - where I could 'optimize' my code, see if there were any ruby tricks that I could use, better code design, etc. in order to learn from the exercise.