Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  81] [ 1]  / answers: 1 / hits: 20842  / 9 Years ago, sat, june 6, 2015, 12:00:00

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 something like this:



aaa
aab
aac
...
aaz

aba
abb
abc
...
abz

aca
acb


And so on. So far I have incremented a single letter by doing this:



String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}

string = aaa;

string = string.replaceAt(2, String.fromCharCode(string.charCodeAt(2) + 1));

//string == aab


However, I am lost when it comes to the final letter being z and it should then increment letter 2 (index 1) and reset the last letter to be a.



Does anyone have or know a smart solution to this? Thanks!


More From » jquery

 Answers
10

Treat the string like it's a base 36 number.



Convert it to decimal, add 1, convert back to base 36, and replace any zeroes with the letter 'a':





var str= 'aaa',
s= str;

while(str!=='zzz') {
str= ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'a');
s+= ' '+str;
}

document.body.innerHTML= s;




[#66302] Thursday, June 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;