Lucky and even lucky numbers: Difference between revisions
Content added Content deleted
(→{{header|Tcl}}: Added output) |
(Added Ruby) |
||
Line 407: | Line 407: | ||
<pre> |
<pre> |
||
evenLucky number: 10000 ───► 111842 |
evenLucky number: 10000 ───► 111842 |
||
</pre> |
|||
=={{header|Ruby}}== |
|||
{{trans|Python}} |
|||
<lang ruby>def generator(even=false, nmax=1000000) |
|||
start = even ? 2 : 1 |
|||
Enumerator.new do |y| |
|||
n = 1 |
|||
ary = [0] + (start..nmax).step(2).to_a # adds [0] to revise the 0 beginnings. |
|||
y << ary[n] |
|||
while (m = ary[n+=1]) < ary.size |
|||
y << m |
|||
(m...ary.size).step(m){|i| ary[i]=nil} |
|||
ary.compact! # remove nil |
|||
end |
|||
# drain |
|||
ary[n..-1].each{|i| y << i} |
|||
raise StopIteration |
|||
end |
|||
end |
|||
def lucky(argv) |
|||
j, k = argv[0].to_i, argv[1].to_i |
|||
mode = /even/i=~argv[2] ? :'even lucky' : :lucky |
|||
seq = generator(mode == :'even lucky') |
|||
ord = ->(n){"#{n}#{(n%100).between?(11,19) ? 'th' : %w[th st nd rd th th th th th th][n%10]}"} |
|||
if k.zero? |
|||
puts "#{ord[j]} #{mode} number: #{seq.take(j).last}" |
|||
elsif 0 < k |
|||
puts "#{ord[j]} through #{ord[k]} (inclusive) #{mode} numbers", |
|||
" #{seq.take(k)[j-1..-1]}" |
|||
else |
|||
k = -k |
|||
ary = [] |
|||
loop do |
|||
case num=seq.next |
|||
when 1...j |
|||
when j..k then ary << num |
|||
else break |
|||
end |
|||
end |
|||
puts "all #{mode} numbers in the range #{j}..#{k}", |
|||
" #{ary}" |
|||
end |
|||
end |
|||
if __FILE__ == $0 |
|||
lucky(ARGV) |
|||
end</lang> |
|||
{{out}} |
|||
<pre> |
|||
C:\>ruby lucky.rb 1 20 |
|||
1st through 20th (inclusive) lucky numbers |
|||
[1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79] |
|||
C:\>ruby lucky.rb 1 20 evenLucky |
|||
1st through 20th (inclusive) even lucky numbers |
|||
[2, 4, 6, 10, 12, 18, 20, 22, 26, 34, 36, 42, 44, 50, 52, 54, 58, 68, 70, 76] |
|||
C:\>ruby lucky.rb 6000 -6100 Lucky |
|||
all lucky numbers in the range 6000..6100 |
|||
[6009, 6019, 6031, 6049, 6055, 6061, 6079, 6093] |
|||
C:\>ruby lucky.rb 6000 -6100 evenLucky |
|||
all even lucky numbers in the range 6000..6100 |
|||
[6018, 6020, 6022, 6026, 6036, 6038, 6050, 6058, 6074, 6090, 6092] |
|||
C:\>ruby lucky.rb 10000 |
|||
10000th lucky number: 115591 |
|||
C:\>ruby lucky.rb 10000 , EVENLUCKY |
|||
10000th even lucky number: 111842 |
|||
</pre> |
</pre> |
||