YoungLearnsToCoding YoungLearnsToCoding -4 years ago 71
Javascript Question

Good algorithm for generating A-Z by given A-Z

I don't know how to best title my problem, here is the problem:

There is a function y = f(x)

Domain for x is a set of string at combination of [A-Z]

Output y is one letter up of x.

ex:

x = A -> y = B

x = Z -> y = AA

x = AB -> y = AC

x = ZZ -> y = AAA

x = ZZA -> y = ZZB

Does anyone have a good way to implement this in javascript?

What I have now is very completed condition check, if Z then A, one char a time.

Answer Source

One way of doing this is look at the last letter in the stream and attempt to increase it by one by converting it to a character code. If it's already a Z, reset the last one to A and repeat the process on the second to the last letter. Repeat until you get to the end.

function increment(x) {
  if (!x) {
    return '';
  }

  // Convert the string into an array of characters
  let chars = x.split('');
  
  let i = chars.length - 1;
  for (; i >= 0; i--) {
    let oldChar = chars[i];
    if (oldChar === 'Z') {
      // If it's a Z, reset to A and process
      // the previous letter in the sequence
      chars[i] = 'A';
    } else {
      // Convert the character to a character code
      let code = chars[i].charCodeAt(0);
      // Increment that code and convert it back to a character
      let newChar = String.fromCharCode(code + 1);
      
      // Replace the existing letter
      chars[i] = newChar;
      break;
    }
  }

  // If we got all the way to the end, that means that all
  // of the letters were Z's that have now been converted
  // to A's. Append one more A to finish the incrementing
  if (i === -1) {
    chars.push('A');
  }

  // Join the array of characters together to form a string
  return chars.join('');
}

console.log(increment('A'));   // B
console.log(increment('Z'));   // AA
console.log(increment('AB'));  // AC
console.log(increment('ZZ'));  // AAA
console.log(increment('ZZA')); // ZZB

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download