String string.fromCharCode()

Asked

Viewed 268 times

1

The following script found here in Stack prints from "aaa" to "zzz" by incrementing letters in order, one by one:

var str= 'aaa',
s= str;

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

document.body.innerHTML= s;

Exit:

aaa
aab
aac
...
aba
abb
abc
...
zzy
zzz

My intention is to continue this logic, but including special characters, using String.fromCharCode() from 33 to 126.

This numeric range already includes all the special characters, letters and numbers.

The desired output should contain 16 characters, not only the three above.

What modifications would be required in the script to perform this task?

3 answers

1


In theory the code will solve your problem, I used the variable "n" as a pointer to know which position of the array should increment, but I believe that in practice it will take a lot to execute this script independent of the medium to be used.

var v = [33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33];
var result = [];
var n = 15;
result.push(String.fromCharCode(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15]));

while (v[n] != 126 || n != 0) {
  if (v[n] == 126 && n != 0){
    v[n] = 33;
    n--;
  }
  else {
    if (v[n] != 126) {
      v[n]++;
      result.push(String.fromCharCode(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15]));
      n = 15;
    }
    else {
      result.push(String.fromCharCode(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8],v[9],v[10],v[11],v[12],v[13],v[14],v[15]));
    }
  }
};

var retorno = result.join('<br/>');

  • I will test as soon as possible and give feedback. Thank you.

1

The simplest way in this case is to do three cycles for chained, however due to the large number of results (1 092 727) will become a little slow... in the test I did took 28,75s

var str='';
s= str;

for(i=33;i<=126;i++)
  for(j=33;j<=126;j++)
    for(k=33;k<=126;k++)
      str+=String.fromCharCode(i)+String.fromCharCode(j)+String.fromCharCode(k)+' <br/> ';

document.body.innerHTML= str;

Exit:

!!!
!!"
!!# 
...
"<@|
<@}
<@~
" 
  • In case I would need an output with 16 characters... Would be 16 loops for... Is there another way? I will add this data to the question.

1

To do this you need, I recommend using "String.fromCharCode".

It would look something like this:

var s = [];
var retorno = '';

for (c3 = 33; c3 < 126; c3++)
   for (c2 = 33; c2 < 126; c2++)
      for (c1 = 33; c1 < 126; c1++)
         s.push(String.fromCharCode(c1,c2,c3));
      
retorno = s.join('<br/>');      

I hope I’ve helped.

  • In case I would need an output with 16 characters... Would be 16 loops for... Is there another way? I will add this data to the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.