Calculate the characters from a combination

84 Views Asked by At

Given a table with position - 2 character combination pairs like this:

1. aa
2. ab
3. ac
4. ad
...
27. ba
28. bb
29. bc
30. bd

Assuming there are unique combinations with two characters from the alphabet following the same pattern.

How do I calculate what is the first and second character of the combination, if I know the position. That is, how do I find position 28 holds bb?


EDIT:

The answer that also describes how to do the reverse, i.e find the position of a combination based on the pair is going to be the most useful answer.

2

There are 2 best solutions below

12
On BEST ANSWER

Assuming you have an alphabet A = ['a','b',...'z'] and a permutation list L = ['aa', 'ab', ..., 'az', 'ba', ... , 'zz'], with the first index starting from 1. (BTW the arithmetic would be much cleaner if you start indexing from $0$, like in the C language, for example.)

Then, the permutations come in groups of $26$, so if you are given an index $k$, then

  • the second letter is given by the offset of $k$ in the current 26-long block, so it is $A[(k-1)\pmod{26} + 1]$ and
  • the first letter is given by $A\left[\lfloor(k-1)/26\rfloor+1\right]$.

If you were to number starting with $0$, the formulae become

  • the second letter is given by $A[k \pmod{26}]$ and
  • the first letter is given by $A\left[\lfloor k/26\rfloor\right]$.

Another free update you get with C, for example, is that if you declare int k, d = 26; then k/d computes $\lfloor k/d \rfloor$ automatically, no extra flooring is needed.


UPDATE

The inversion is simple. If first letter has index $F$ and last has index $L$, the offset is given by

  • $26F + L$ for $0$-based indexing (like C)
  • $26(F+1) + (L+1) = 26F + L + 27$ for $1$-based indexing
2
On

For the index $n$, the $(\lfloor \frac{n-1}{26}\rfloor+1)^{th}$ letter of the alphabet is the first character, $(n\mod26)^{th}$ letter of the alphabet is the second character.