0

How could this one be tweaked so that it could increment a set of two letters, so that it'd look like this:

AA, AB, AC...AZ, BA, BB, BC, etc

This is borrowed from tckmn, but it addresses one letter only.

var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
function incrementChar(c) {
    var index = alphabet.indexOf(c)
    if (index == -1) return -1 // or whatever error value you want
    return alphabet[index + 1 % alphabet.length]
}

Appreciate your help!

onit
  • 2,275
  • 11
  • 25

2 Answers2

1

You just need two loops. One to iterate over the alphabet, and the second to iterate over the alphabet on each iteration of the first loop.

const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

const arr = [];

for (let i = 0; i < alphabet.length; i++) {
  for (let j = 0; j < alphabet.length; j++) {
    arr.push(`${alphabet[i]}${alphabet[j]}`);
  }  
}

console.log(arr);
Andy
  • 61,948
  • 13
  • 68
  • 95
  • So...in the example in the question, a letter is passed. What would be the change to get this to work based on a set of letters passed and increment on the top of it once? Thank you! – onit Apr 29 '22 at 14:16
  • I'm not really sure what you're asking. You can passing the alphabet as an argument to the function, but I don't understand what the second part means. What output are you expecting from the function? @santosOnit – Andy Apr 29 '22 at 14:38
  • That would be only the next combination of letters based on the one passed. Because I need to be "infinite", meaning: After ZZ, AAA, AAB, etc... I had to resort to another approach. I did test yours, thouhg and learned from it. – onit Apr 29 '22 at 17:26
0

In your situation, how about the following sample script?

const increase = s => {
  const idx = [...s].reduce((c, e, i, a) => (c += (e.charCodeAt(0) - 64) * Math.pow(26, a.length - i - 1)), -1);

  // Ref: https://stackoverflow.com/a/53678158
  columnIndexToLetter = (n) => (a = Math.floor(n / 26)) >= 0 ? columnIndexToLetter(a - 1) + String.fromCharCode(65 + (n % 26)) : "";

  return columnIndexToLetter(idx + 1);
};

const samples = ["A", "Z", "AA", "AZ", "ZZ"];
const res1 = samples.map(e => increase(e));
console.log(res1); // <--- [ 'B', 'AA', 'AB', 'BA', 'AAA' ]

// If you want to give one value, please use the following script.
const sample = "AA";
const res2 = increase(sample);
console.log(res2); // <--- AB
  • When this script is run, ["A", "Z", "AA", "AZ", "ZZ"] is converted to [ 'B', 'AA', 'AB', 'BA', 'AAA' ].

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • @santosOnit Did my answer show you the result what you want? Would you please tell me about it? That is also useful for me to study. If this works, other people who have the same issue with you can also base your question as a question which can be solved. If you have issues for my answer yet, I apologize. At that time, can I ask you about your current situation? I would like to study to solve your issues. – Tanaike May 16 '22 at 04:19