Increment a string with letters?
This function gives 3 characters based on a number:
function n2s (n) {
var s = '';
while (s.length < 3) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
To print strings from "aaa" to "zzz":
var zzz = Math.pow(26, 3) - 1;
for (var n = 0; n <= zzz; n++) {
console.log(n2s(n));
}
function n2s (n) {
var s = '';
while (s.length < 3) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
var result = [];
var zzz = Math.pow(26, 3) - 1;
for (var n = 0; n <= zzz; n++) {
result.push(n2s(n));
}
document.body.innerHTML = result.join(' ');
Ask for details :-)
Improvements
Performances compared to the accepted answer: http://jsperf.com/10-to-26.
// string to number: s2n("ba") -> 26
function s2n(s) {
var pow, n = 0, i = 0;
while (i++ < s.length) {
pow = Math.pow(26, s.length - i);
n += (s.charCodeAt(i - 1) - 97) * pow;
}
return n;
}
// number to string: n2s(26) -> "ba"
function n2s(n) {
var s = '';
if (!n) s = 'a';
else while (n) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
// pad("ba", 4) -> "aaba"
function pad (s, n) {
while (s.length < n) s = 'a' + s;
return s;
}
Usage:
var from = s2n('azx');
var to = s2n('baa');
for (var n = from; n <= to; n++) {
console.log(pad(n2s(n), 3));
}
Output:
azx
azy
azz
baa
Recursivity
Probably less efficient in terms of memory use or computation time: https://jsperf.com/10-to-26/4.
function n2s(n) {
var next = Math.floor(n / 26);
return (
next ? n2s(next) : ''
) + (
String.fromCharCode(97 + n % 26)
);
}
function s2n(s) {
return s.length && (
(s.charCodeAt(0) - 97)
) * (
Math.pow(26, s.length - 1)
) + (
s2n(s.slice(1))
);
}
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;