Palindromic gapful numbers
Inspired from the C++ and Perl 6 entries.
class PalindromeGenerator (digit, base=10) {
has power = base
has after = (digit*power - 1)
has even = false
method next {
if (++after == power*(digit+1)) {
power *= base if even
after = digit*power
even.not!
}
even ? (after*power*base + reverse(after, base))
: (after*power + reverse(after/base, base))
}
}
var task = [
"(Required) First 20 gapful palindromes:", { .first(20) }, 7,
,"\n(Required) 86th through 100th:", { .first(1e2).last(15) }, 8,
,"\n(Optional) 991st through 1,000th:", { .first(1e3).last(10) }, 10,
,"\n(Extra stretchy) 9,995th through 10,000th:", { .first(1e4).last(6) }, 12,
]
task.each_slice(3, {|title, f, w|
say title
for d in (1..9) {
var k = 11*d
var iter = PalindromeGenerator(d)
var arr = f(^Inf->lazy.map { iter.next }.grep {|n| k `divides` n })
say ("#{d}: ", arr.map{ "%*s" % (w, _) }.join(' '))
}
})