Crystal 0.34
This code will compile and run.
def palindromegen(digit, count)
nums = [] of UInt64
nn = digit * 11
num = 0.to_u64
(2..).each do |pow|
base = 10_u64**(pow >> 1)
n1 = base * digit
n2 = base * (digit + 1)
n1.step(to: n2 - 1, by: 10) do |n1|
ns = (n1 // 10).to_s
(n1..n1 + 9).each_with_index do |pal, i|
num = (pal.to_s + pal.to_s.reverse).to_u64 if pow.odd?
num = (ns + "0" + ns.reverse).to_u64 + base * i if pow.even?
nums << num if num % nn == 0
return nums if nums.size == count
end
end
end
end
count = 20
puts "First 20 palindromic gapful numbers 100 ending with:"
(1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count)}\n" }
But when I add another print statement it fails to compile, because of the statement ...last(15)
def palindromegen(digit, count)
nums = [] of UInt64
nn = digit * 11
num = 0.to_u64
(2..).each do |pow|
base = 10_u64**(pow >> 1)
n1 = base * digit
n2 = base * (digit + 1)
n1.step(to: n2 - 1, by: 10) do |n1|
ns = (n1 // 10).to_s
(n1..n1 + 9).each_with_index do |pal, i|
num = (pal.to_s + pal.to_s.reverse).to_u64 if pow.odd?
num = (ns + "0" + ns.reverse).to_u64 + base * i if pow.even?
nums << num if num % nn == 0
return nums if nums.size == count
end
end
end
end
count = 20
puts "First 20 palindromic gapful numbers 100 ending with:"
(1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count)}\n" }
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count).last(15)}\n"
------------------------------------------------------------------
âžś rosettacode crystal build pal2b.cr --release
Showing last frame. Use --error-trace for full trace.
In pal2b.cr:27:71
27 | (1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count).last(15)}\n" }
^---
Error: undefined method 'last' for Nil (compile-time type is (Array(UInt64) | Nil))
The simplest way I got it to compile was to add the line nums
at the end of the method.
def palindromegen(digit, count)
nums = [] of UInt64
nn = digit * 11
num = 0.to_u64
(2..).each do |pow|
base = 10_u64**(pow >> 1)
n1 = base * digit
n2 = base * (digit + 1)
n1.step(to: n2 - 1, by: 10) do |n1|
ns = (n1 // 10).to_s
(n1..n1 + 9).each_with_index do |pal, i|
num = (pal.to_s + pal.to_s.reverse).to_u64 if pow.odd?
num = (ns + "0" + ns.reverse).to_u64 + base * i if pow.even?
nums << num if num % nn == 0
return nums if nums.size == count
end
end
end
nums # <- need to add this for it to compile for all outputs
end
count = 20
puts "First 20 palindromic gapful numbers 100 ending with:"
(1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count)}\n" }
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{palindromegen(digit, count).last(15)}\n" }
This is a total hack, that should be unnecessary, because I consider this a compiler bug.
At the very least, the error message should be more detailed and suggest how to fix it.