I
ishamid
[progrmming novice]
Hi,
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)."
MY SOLUTION (tested for the different scenarios):
===============
puts 'Type initial year:'
leapi = gets.chomp.to_i
puts 'Type final year:'
leapf = gets.chomp.to_i
puts ''
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.
Best
Idris
Hi,
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)."
MY SOLUTION (tested for the different scenarios):
===============
puts 'Type initial year:'
leapi = gets.chomp.to_i
puts 'Type final year:'
leapf = gets.chomp.to_i
puts ''
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.
Best
Idris