2
$\begingroup$

I'm searching for an algorithm but struggle to find anything, as I'm not sure how to formulate it correctly. I created a simple survey app in Angular with 24 questions and each has 2-5 answers. When the user answered all the questions I'd like to give him a token (as short as possible) on the result page that he can note down, so the next time he can enter the token instead of having to answer all the questions again.

My thought process so far:

  • I can store the information in an array with 24 entries [1, 4, 2, ..., 2, 3]
  • As all values have 1 digit I can remove everything but the numbers 142...23

This still leaves me with a 24 digits long number. Nothing one would like to note down and type out by hand. So next I tried to convert this number (with ().toString(2)) to a binary with the goal to turned that binary into a human readable string with String.fromCharCode. But all I got was the rather not so human readable æ\u000f\u0000³KH\u0000\u0000\u0000 for my test input.

I could break down the number into digit pairs (e.g. 120422... -> [12, 04, 22, ...]) and map each of these to a character (00 -> A, 01 -> B, ...), but I think there must be something more elegant and efficient, as it would only half the original size. Although using 3 digits for mapping would result in 125 combinations which is rather hard to map to the alphabet, even with upper/lowercases and special characters. But I'd be very happy to hear your ideas. Many thanks in advance!

$\endgroup$
3
$\begingroup$

I think you should try converting your 24-digits (in base 10) number, in another base, which would reduce a lot the length of your token, while keeping the same information.

You should try experimenting with this website for example, which convert in base 36 (10 number + 26 letters):

http://www.unitconversion.org/numbers/base-10-to-base-36-conversion.html

Here, the number 986541236547896541258745 becomes 4GNE5T9XUQO08CKK

I'm sure you can devise an algorithm in base 62 (10 number, 26 lower cases letters, 26 upper cases letters), or event more if you use other characters, such as +-*&"# ... etc

EDIT:

found this website that allows you to convert from and to any bases between 2 and 62: https://www.dcode.fr/base-n-convert

Here, the number 986541236547896541258745 becomes 4VMCgFPOG10DLH

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you very much Adrien, base-n conversion is exactly what I was looking for. $\endgroup$ – Johannes Stadler Jul 10 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.