From: Levin Alexander Date: 2006-02-05T03:43:15+09:00 Subject: Re: Fixnum#to_a ------=_Part_18062_33073521.1139078580616 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: base64 Content-Disposition: inline T24gMi80LzA2LCBDaHJpc3RpYW4gTmV1a2lyY2hlbiA8Y2huZXVraXJjaGVuQGdtYWlsLmNvbT4g d3JvdGU6Cj4gQ2hyaXN0aWFuIE5ldWtpcmNoZW4gPGNobmV1a2lyY2hlbkBnbWFpbC5jb20+IHdy aXRlczoKPgo+ID4gQWxzbywgeW91IG1heSB3YW50IHRvIGV4dGVuZCBpdCB0byBiZSBsaWtlIEFQ TCdzICJlbmNvZGUiICh0YWNrKSwgc28geW91Cj4gPiBjYW4gZG8gc3R1ZmYgbGlrZToKPgo+IEZv ciBmdW4sIGFuIGltcGxlbWVudGF0aW9uIG9mIGVuY29kZS9kZWNvZGUuCgpJIHBsYXllZCB3aXRo IHlvdXIgY29kZSBhIGJpdCBtb3JlLCByZXZlcnNlZCB0aGUgb3JkZXIgb2YgdGhlIGNyZWF0ZWQK YXJyYXkgYW5kIGFkZGVkIHNvbWUgdGVzdCBjYXNlcy4gIFdoYXQgSSBoYXZlIG5vdyBpcyBhdHRh Y2hlZC4KCklNSE8sIHNvbWV0aGluZyBsaWtlIHRoYXQgd291bGQgYmUgbmljZSB0byBoYXZlIGlu IHRoZSBzdGFuZGFyZCBsaWJyYXJ5LgoKR3LDvMOfZSwKTGV2aW4K ------=_Part_18062_33073521.1139078580616 Content-Type: application/octet-stream; name=encode.rb Content-Transfer-Encoding: 7bit X-Attachment-Id: f_eja9vxnm Content-Disposition: attachment; filename="encode.rb" class Integer def encode(restbase = 2, *bases) mybases = bases.dup n = self result = [] begin base = mybases.pop || restbase base = n+1 if base < 2 n, val = n.divmod(base) result << val end until (n == 0) || (n == -1) if (missing = bases.size - result.size + 1) > 0 result.concat [0] * missing end result end end class Array def decode(restbase=2, *bases) bases = bases.dup result = 0 factor = 1 self.each { |a| base = bases.pop || restbase result += a*factor factor *= base } result end end if __FILE__ == $0 require 'test/unit' class TestEncodeDecode < Test::Unit::TestCase def test_encode assert_equal [0], 0.encode assert_equal [1], 1.encode assert_equal [123], 123.encode(0) assert_equal [0,1,0,1], 10.encode assert_equal [5,4,3,2,1], 12345.encode(10) assert_equal [6,1,1163,1], 105246.encode(0,1760,3,12) assert_equal [0,0,23,0], 82800.encode(0,24,60,60) assert_equal [1], -1.encode(2) # ??? assert_equal [6,6,7,8], -1234.encode(10) # ??? assert_equal [456], 456.encode(1) # invalid base end def test_decode assert_equal 0, [0].decode assert_equal 1, [1].decode assert_equal 12345, [5,4,3,2,1].decode(10) assert_equal 82800, [0,0,23,0].decode(0,24,60,60) assert_equal 105246, [6,1,1163,1].decode(0,1760,3,12) end end end ------=_Part_18062_33073521.1139078580616--