Answer the question
In order to leave comments, you need to log in
How to correctly generate a unique code from the alphabet?
The alphabet from which the code can consist is given:
var lang = ['A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0',
'1','2','3','4','5','6','7','8','9'];
function codeGen(id) {
var lang = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
var code= '';
while(id !==0){
if(id<=lang.length){
code = code + lang[id-1];
id =0;
} else{
var del = Math.floor(id / lang.length);
var ost = id-del*lang.length;
id = del;
code = code + lang[ost-1];
}
}
return code;
}
Answer the question
In order to leave comments, you need to log in
id.toString(36)
Isn't that what you're looking for?
demo: https://jsfiddle.net/xjzL2L3u/
function codeGen( number ) {
var base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split( '' );
var result = '', quotient, remainder;
do {
quotient = Math.floor( number / base.length );
remainder = number % base.length;
number = quotient - 1;
result = base[ remainder ] + result;
} while ( quotient > 0 );
return result;
}
In principle, "correct" - there is no such thing, and there is not enough data to determine the "correctness" of the algorithm. I would add 1-2 "checksum" characters to the generated code, or a single-character error correction code, so that in case of errors during transmission or interpretation of the code, it could be restored, and it would not be so easy to organize a brute-force attack on the code in order to extract unknown resources.
Option 1. Generate code, check for uniqueness, if not unique, start over.
Option 2. Describe a unique display (serial number <=> code), generate code by number.
Judging by the description, the most "interesting" option will be mixing: we swap randomly selected positions ... and so many times. The number of elements of the alphabet does not change, but their order does.
In the old days, they played around like this with a vga video buffer in text mode
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question