I need to increment a string from.. let\'s say aaa
to zzz
and write every incrementation in the console (is incrementation even a word?). It would go s
Took a bit of algorithmic approach. This function takes initial string as an argument, increments next possible char in alphabet and at last returns the result.
function generate(str)
{
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var chars = [];
for(var i = 0; i < str.length; i++)
{
chars.push(alphabet.indexOf(str[i]));
}
for(var i = chars.length - 1; i >= 0 ; i--)
{
var tmp = chars[i];
if(tmp >= 0 && tmp < 25) {
chars[i]++;
break;
}
else{chars[i] = 0;}
}
var newstr = '';
for(var i = 0; i < chars.length; i++)
{
newstr += alphabet[chars[i]];
}
return newstr;
}
Here is the loop helper function which accepts the initial string to loop through and generate all combinations.
function loop(init){
var temp = init;
document.write(init + "
");
while(true)
{
temp = generate(temp);
if(temp == init) break;
document.write(temp + "
");
}
}
Usage: loop("aaa");
CODEPEN