Tamás Pap
Tamás Pap

Reputation: 18273

Convert numbers to another one in the same range, and back

I'm looking for a solution to convert all numbers in a given range to another number in the same range, and later convert that number back.

More concrete, let's say I have the numbers 1..100.

The easiest way to convert all numbers to another one in the same range is to use: b = 99 -a; later get the original with a = 99 - b;.

My problem is that I want to simulate some randomness.

I want to implement this in PHP, but the coding language doesn't matter.

WHY?

You maybe say why? Good question :)

I am generating some easy to read short code string based on id-s, and because the id's are incremented one by one, my consecutive short codes are too similar. Later I need to "decode" the short codes, to get the id.

What my algorithm is doing now is:

0000001 -> ababac, 0000002 -> ababad, 0000003 -> ababaf, etc.

later

ababac -> 0000001, ababad -> 0000002, ababaf -> 0000003, etc.

So before I actually generate the short code I want to "randomize" the number as much as possible.

Upvotes: 0

Views: 192

Answers (2)

Tamás Pap
Tamás Pap

Reputation: 18273

Finally I found a solution based on module operator, on the math forum. The solution can be found here:

https://math.stackexchange.com/questions/259891/function-to-convert-each-number-in-a-m-n-to-another-number-in-the-same-range

Upvotes: 0

Laurence
Laurence

Reputation: 60038

Option 1: Why dont you just have a database of conversion? i.e each record has a "real" id, and a "random md5" string or something

Option 2: Use a rainbow table - maybe even a MD5 lookup table for the range 0 - 10,000 or whatever. Then just do a hashtable lookup

Upvotes: 1

Related Questions