Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
[QUIZ] Happy Numbers (#93)
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Ken Bloom, post: 4525656"] Since the order of digits in the number doesn't matter, here's code to generate digits whose numbers are in nondecreasing order. This makes the "happiest number" test finish almost instantly when the numbers are generated this way: #generates all numbers in the given range whose digits are in #nondecreasing order. the order in which the numbers are generated is #undefined, so it's possible for 123 to appear before 23, for #example. def nondec_digits(range,&b) yield 0 if range.first<=0 (1..9).each { |x| noninc_digits_internal(x,x,range,&b) } end def nondec_digits_internal(last,accum,range,&b) (last..9).each do |x| iaccum=accum*10+x b.call(iaccum) if range.include?(iaccum) noninc_digits_internal(x,iaccum,range,&b) if iaccum<=range.last end end [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
[QUIZ] Happy Numbers (#93)
Top