Happy hacking indeed!

Your code made playing with this problem a lot more fun:
http://mathschallenge.net/index.php?section=project&ref=problems&id=4

Regards,
-Harold

On 2/4/06, Christian Neukirchen <chneukirchen / gmail.com> wrote:
> Christian Neukirchen <chneukirchen / gmail.com> writes:
>
> > Also, you may want to extend it to be like APL's "encode" (tack), so you
> > can do stuff like:
>
> For fun, an implementation of encode/decode.
>
>
> class Integer
>   def encode(restbase, *bases)
>     mybases = bases.dup
>     result = []
>     n = self
>
>     while base = mybases.pop || restbase
>       break  if n < base
>       break  if base.zero?
>       result << n % base
>       n = n / base
>     end
>
>     result << n
>
>     if (missing = bases.size - result.size + 1) > 0
>       result.concat [0] * missing
>     end
>
>     result.reverse!
>   end
> end
>
> class Array
>   def decode(restbase, *bases)
>     bases = bases.dup
>     result = 0
>     factor = 1
>
>     self.reverse_each { |a|
>       base = bases.pop || restbase
>       result += a * factor
>       factor *= base
>     }
>
>     result
>   end
> end
>
> p 01776.encode(8)                # => [1, 0, 2, 2]  (octal -> decimal)
> p [1, 7, 7, 6].decode(8)         # => 1022
>
> p 105246.encode(0, 1760, 3, 12)  # => [1,     1163,  1,    6]
>                                  #    [miles, yards, feet, inches]
>
> p [14,   12,    20,      57].decode(0, 24, 60, 60)  # => 1254057
> # [days, hours, minutes, seconds]
>
> duration = 324477
> p "Runtime: %d days %02d:%02d:%02d" % duration.encode(0, 24, 60, 60)
>
>
> Happy hacking,
> --
> Christian Neukirchen  <chneukirchen / gmail.com>  http://chneukirchen.org
>
>