I need an algorithm that will map a string of length four to a four digit number. The problem is it has to maintain lexicographical order. It doesn't need to not have collisions, it's just that if S <= T, F(S) <= F(T). The only additional constraint is that it should be surjective: all numbers must be mapped to by some string.
Asked
Active
Viewed 946 times
1
-
4Surely F(S) = 9999 is not what you're looking for, yet it satisfies the constraints. – David Eisenstat Oct 16 '14 at 19:48
-
@DavidEisenstat Good catch. The other constraint was that it's surjective: all numbers can be produced. – Alex Beals Oct 16 '14 at 21:12
-
Ah. What exactly is the domain of F, then? (e.g., strings of length exactly four, comprised entirely of characters in the class `[A-Za-z]`) – David Eisenstat Oct 16 '14 at 21:16
-
Assuming characters are integers between MIN and MAX inclusively: `y[i]=(x[i]-MIN)*10/(MAX-MIN+1)` (not tested) – n. m. could be an AI Oct 16 '14 at 21:43
1 Answers
1
Can't you just map letters to digits directly, grouping a few at a time to handle the fact that there are more letters than digits? {a, b, c} => 1, {d, e, f} => 2
etc.

MattPutnam
- 2,927
- 2
- 17
- 23