Home > Back-end >  Finding the formula for an alphanumeric code
Finding the formula for an alphanumeric code

Time:09-18

A script I am making scans a 5-character code and assigns it a number based on the contents of characters within the code. The code is a randomly-generated number/letter combination. For example 7D3B5 or HH42B where any position can be any one of (26 10) characters.

Now, the issue I am having is I would like to figure out the number from 1-(36^5) based on the code. For example:

00000 = 0

00001 = 1

00002 = 2

0000A = 10

0000B = 11

0000Z = 36

00010 = 37

00011 = 38

So on and so forth until the final possible code which is:

ZZZZZ = 60466176 (36^5)

What I need to work out is a formula to figure out, let's say G47DU in its number form, using the examples below.

CodePudding user response:

Something like this?

function getCount(s){
  if (!isNaN(s))
    return Number(s);

  return s.charCodeAt(0) - 55;
}

function f(str){
  let result = 0;
  
  for (let i=0; i<str.length; i  )
    result  = Math.pow(36, str.length - i - 1) * getCount(str[i]);
  
  return result;
}


var strs = [
  '00000',
  '00001',
  '00002',
  '0000A',
  '0000B',
  '0000Z',
  '00010',
  '00011',
  'ZZZZZ'
];


for (str of strs)
  console.log(str, f(str));

CodePudding user response:

You are trying to create a base 36 numeric system. Since there are 5 'digits' each digit being 0 to Z, the value can go from 0 to 36^5. (If we are comparing this with hexadecimal system, in hexadecimal each 'digit' goes from 0 to F). Now to convert this to decimal, you could try use the same method used to convert from hex or binary etc... system to the decimal system.

It will be something like d4 * (36 ^ 4) d3 * (36 ^ 3) d2 * (36 ^ 2) d1 * (36 ^ 1) d0 * (36 ^ 0) Note: Here 36 is the total number of symbols.

d0, d1, d2, d3, d4 can range from 0 to 35 in decimal (Important: Not 0 to 36).

Also, you can extend this for any number of digits or symbols and you can implement operations like addition, subtraction etc in this system itself as well. (It will be fun to implement that. :) ) But it will be easier to convert it to decimal do the operations and convert it back though.

  • Related