The following solution appears to work, but I would like to make it
more efficient and "Rubyish" (still trying to figure out what that
means...).
PROBLEM (from Chris Pine -- Learn to Program): "Write a program which
will ask for a starting year and an ending year, and then puts all of
the leap years between them (and including them, if they are also leap
years). Leap years are years divisible by four (like 1984 and 2004).
However, years divisible by 100 are not leap years (such as 1800 and
1900) unless they are divisible by 400 (like 1600 and 2000, which were
in fact leap years)."
if leapi%4 == 0 && (leapi%400 == 0 || leapi%100 != 0)
puts leapi
else
end
while (leapi + (4 - leapi%4)) <= leapf
leapi = (leapi + (4 - leapi%4))
if leapi%4 == 0 && (leapi%400 == 0 || leapi%100 != 0)
puts leapi
else
end
end
Is there a nicer way to do this? I can't but feel that the first
conditional is superflous and that I should be able to do it all within
a single "while" loop.
The following solution appears to work, but I would like to make it
more efficient and "Rubyish" (still trying to figure out what that
means...).
PROBLEM (from Chris Pine -- Learn to Program): "Write a program which
will ask for a starting year and an ending year, and then puts all of
the leap years between them (and including them, if they are also leap
years). Leap years are years divisible by four (like 1984 and 2004).
However, years divisible by 100 are not leap years (such as 1800 and
1900) unless they are divisible by 400 (like 1600 and 2000, which were
in fact leap years)."
I am only as far as this problem in the book, and this was my solution
(after I saw a few ways to clean it up after looking at yours ).
···
On Nov 30, 4:46 pm, "ishamid" <isha...@colostate.edu> wrote:
[progrmming novice]
Is there a nicer way to do this? I can't but feel that the first
conditional is superflous and that I should be able to do it all within
a single "while" loop.
Best
Idris
---------------------------------------
puts 'Start year:'
ly = gets.chomp.to_i
puts 'End year:'
lye = gets.chomp.to_i
puts ''
puts 'Leap years between and including ' + ly.to_s + ' and ' + lye.to_s
+ ':'
puts '-----------------------------------------------'
puts ''
while ly <= lye
if ly%4 == 0 && (ly%100 != 0 || ly%400 == 0)
puts ly
ly = (ly + 1).to_i
else
ly = (ly + 1).to_i
end
end
-----------------------------------------
Hope that helps. I was looking around for help originally and all the
postings I had seen used coding that was more advanced than this
chapter of the book, so they weren't much help to check/refine my
answer. This is a great book so far, tho, I'm really enjoying it.