Integer encoding challenge

D

David Balmain

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
 
Y

Yohanes Santoso

David Balmain said:
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.
 
D

David Balmain

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,209
Messages
2,571,085
Members
47,683
Latest member
AustinFairchild

Latest Threads

Top