I came across the following problem while preparing for an exam:
Imagine an alphabet of words. Example:
a ==> 1
b ==> 2
c ==> 3
...
z ==> 26
ab ==> 27
ac ==> 28
...
az ==> 51
bc ==> 52
and so on.
The sequence of characters needs to be in ascending order only (i.e. 'ab' is valid but 'ba' is not).
Question: Given any word, print its index if valid and 0 if not.
Input Output
ab 27
ba 0
aez 441
Any pointers on how to solve this would be appreciated.
Let me give you a few hints:
k
?k
, and a letter l
. How many word of length k
starting with l
are they ?Hint: Pascal triangle. If you need some more hint, http://en.wikipedia.org/wiki/Combinadic can help. If you need some implementation, you can get inspiration from the rank function defined in (Python language) https://github.com/sagemath/sagelib/blob/master/sage/combinat/choose_nk.py
To be fair, I have not mentioned an algorithm on how to calculate the index value, just the exit case. But it gives you a start in the right direction and calculating the index will follow the same framework.
More Info:
Start counting upwards on first letter. When you hit 'z', reset to next valid string and keep counting -> "aa" fails don't count it. Add to next which here is "ab". Once you hit "az", try "ba" - fail, keep adding letters until you get a valid string "bc" and start counting again. It's like an odometer that counts upwards.
Dang slow, but it should work as it is what you do manually to get the answer.
BTW, there is a much more elegant solution hinted at by @hivert that would be nearly instant to calculate...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With