Saturday, September 02, 2006

Ruby Quiz #93

The happiest number between 1 and 1 million seems to be 15,999, with a happiness index of 20*. For base 10, the code is as follows:

    Integer>>happyDerivation

      self = 0 ifTrue: [^0].
      ^(self // 10) happyDerivation
        + (self \\ 10) squared

    Integer>>happyDerivations

      ^self addHappyDerivationsTo: Set new

    Integer>>addHappyDerivationsTo: aSet

      (aSet includes: self) ifTrue: [^aSet].
      aSet add: self.
      ^self happyDerivation addHappyDerivationsTo: aSet

    Integer>>happiness

      ^self happyDerivations size


This is easily extensible by adding the base as an argument.

I have a feeling all bases are happy, although I can't quite muster a proof right now. Is there a counterexample?

* The problem statement seems to indicate the only unhappy numbers are those in which the procedure above never ends, and this is what I assumed. Also, I assumed that since 1^2 = 1, 1 is happy, and its happiness index is 1 because starting at 1 one finds that the number 1 is happy.

But if the statement meant that unhappy numbers are the ones that do not reach 1 instead, then we just need isHappy to answer ^self happyDerivations includes: 1.

1 comment:

Andres said...

I found about the 2 day no spoiler period a while ago. I was too selective and just went through the quizzes at the website last night! Sorry :(