create a unique key from 3 Alphabet

Viewed 78

I'm trying to create a unique key using the alphabets; I've managed to work it out but I don't really like the approach I took. and I believe someone out there might be able to help me get a better way to do this code. Please let me know if you think of a better idea? or whatever your idea to compare with mine? I think this might be a good way to share knowledge .. Thanks in advance

let string = 'ABE';
let ar1 = ["A", "B", "C", "D", "E"];
string = string.split('');

if (string[2] !=='E') {
  for (let i = 0; i < 5; i++) {
        if (string[2] === ar1[i]) {
          i = i+1;
          string[2] = ar1[i]
        }
    }
    string = string.toString().replace(/,/g, '');
    console.log("case 1", string);

} else if (string[1] !=='E' && string[2] ==='E') { 
    string[2] ='A';
    for (let i = 0; i < 5; i++) {
        if (string[1] === ar1[i]) {
          i = i+1;
          let newString = ar1[i];
          console.log(ar1[i]);
          string[1] = newString;
        }
    }
      string = string.toString().replace(/,/g, '');
      console.log("case 2", string);
} else if (string[1] ==='E' && string[2] ==='E') { 
    string[1] ='A';
    string[2] ='A';
    for (let i = 0; i < 5; i++) {
        if (string[0] === ar1[i]) {
          i = i+1;
          string[0] = ar1[i];
        }
    }
    string = string.toString().replace(/,/g, '');
    console.log("case 3", string);
}

Results would be like:

if string = "AAA" Then the result "AAB"

if string = "AAE" Then result will be "ABA"

if string = "AEE" Then result will be "BAA"

2 Answers

You could encode the value to a numerical value, like this palce value

36  6  1
 C  B  A 
 2  1  0   78

and encode an incremented value with the wanted characters and length.

function decode(value, characters) {
    const
        values = Object.fromEntries(Array.from(characters, (v, i) => [v, i]));
        
    return value
        .split('')
        .reduce((s, v) => s * characters.length + values[v], 0);
}

function encode(value, characters, length = 0) {
    let result = '';

    do {
        result = characters[value % characters.length] + result;
        value = Math.floor(value / characters.length);
    } while (value);
    
    return result.padStart(length, characters[0]);
}

console.log(decode('AAA', 'ABCDEF')); //   0
console.log(encode(0, 'ABCDEF', 3));  // AAA
console.log(encode(1, 'ABCDEF', 3));  // AAB

console.log(decode('CBA', 'ABCDEF')); //  78
console.log(encode(78, 'ABCDEF', 3)); // CBA
console.log(encode(79, 'ABCDEF', 3)); // CBB

This approach rotates each character by a fixed amount (which could be improved upon), ignoring the other characters.

let ar1 = ["A", "B", "C", "D", "E"];
function scramble(str) {
   let rotation=3;
   let s = str.split('');
   for (let i=0; i<s.length; i++) {
      s[i]=ar1[(parseInt(s[i],16)+rotation) % ar1.length];
   }
   return s.toString().replace(/,/g, '');
}
Related