Integer encoding challenge

Hey all,

I need to come up with a way to encode an integer as a string so that
it will sort correctly lexicographically. This is pretty easy when you
have a fixed integer range but how do you do it with Ruby’s BigNums?
Any ideas?

Cheers,
Dave

“David B.” [email protected] writes:

Hey all,

I need to come up with a way to encode an integer as a string so that
it will sort correctly lexicographically. This is pretty easy when you
have a fixed integer range but how do you do it with Ruby’s BigNums?
Any ideas?

Cheers,
Dave

def encode_integer(num)
“x”*num
end

Do I win something?

YS.

On 7/19/06, Yohanes S. [email protected]
wrote:

Dave

def encode_integer(num)
“x”*num
end

Do I win something?

YS.

Nice idea :stuck_out_tongue:
But how about negative numbers.

“David B.” [email protected] writes:

Cheers,
Nice idea :stuck_out_tongue:
But how about negative numbers.

Same technique, but put them in different namespace.

YS.

On 7/19/06, Yohanes S. [email protected]
wrote:

Any ideas?
YS.

Nice idea :stuck_out_tongue:
But how about negative numbers.

Same technique, but put them in different namespace.

YS.

I need to be able to compare positive integers with negative so I
would need to add a bit to this technique, (not to mention a couple of
terabytes of memory to handle even moderately large numbers :))

def encode_integer(int)
if (int > 0)
“z” * int
else
“x” * -int + “y”
end
end

Anyway, here is a better solution using only only digits 0-9. I’ll
extend it myself to use the full ascii alphabet;

def encode_int(int)
if (int > 0)
int_str = int.to_s
(“3%04d” % int_str.size) + int_str
elsif (int < 0)
int_str = (-int).to_s
(“1%04d” % (9999 - int_str.size)) + (10 ** (int_str.size + 1) +
int).to_s
else
“2”
end
end

Cheers,
Dave

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs