User590254
User590254

Reputation: 132

How to generate unique string from number which lies in range of quantity of characters ' permutations in this string?

Suppose I could have a string with length 8 bytes, each byte is a character from one of the next ranges: 0-9,a-z,A-Z, totally 62 variants. Total number of permutations of this string is 62 to the power of 8 = 218340105584896. I need to write a function which will accept number in range
0-218340105584896 and return unique string. Under the unique I mean that function cannot return the same string for two different numbers in this range. Any code examples and hints will be appreciated.

Upvotes: 0

Views: 325

Answers (2)

yoyoyango
yoyoyango

Reputation: 140

You could treat the number as a base 62 number, and fill in the string "digits" (base-62 bits) accordingly.

Let's see how we do this with the decimal number 1234 in different bases. note that division below is always integer division (fractional parts are chopped off).

Base 10 (decimal): 0-9

1234 / 10^3 = 1, 1234 mod 10^3 = 234
234 / 10^2 = 2, 234 mod 10^2 = 34
34 / 10^1 = 3, 34 mod 10^1 = 4
4 / 10^0 = 4, 4 mod 10^0 = 0
Thus we represent this number in base-10 as "1234"

Base 16 (hexadecimal): 0-9,a-f (where a=10, b=11, ...)

1234 / 16^2 = 4, 1234 mod 16^2 = 210
210 / 16^1 = d, 210 mod 16^1 = 2
2 / 16^0 = 2, 2 mod 16^0 = 0
Thus we represent this number in base-16 as "4d2"

This could extend to any base, including base-62: 0-9,a-z,A-Z

1234 / 62^1 = j, 1234 mod 62^1 = 56
56 / 62^0 = U, 56 mod 62^0 = 0
Thus we represent this number in base-62 as "jU"

I didn't bother doing leading 0's, but you could see that 1234 / 62^2 = 0, and 1234 mod 62^2 = 1234, so in base-62 you can have "000000jU".


Note that you could only do this for numbers in the range [0, 218340105584896), so it wouldn't be possible to represent 218340105584896.

Upvotes: 4

SergGr
SergGr

Reputation: 23788

If I understand your question correctly, then just yesterday I put a JavaScript code that answers it to another question Get offset in combinations without generating all possible combinations The method you are interested in is indexToPermutation. Note that JS has some limitations on number types so it will not work for your range but if you translate it into some other language that supports 64-bit long integer type, it should work. Unfortunately you didn't put any language tag so I can't do a translation myself.

Upvotes: 2

Related Questions