My another Caesars Cipher algorithn

So i try to solve caesars cipher with for looping and indexOf array properties. But, i still confused in this part :

alpha[(ind + 13)  % 26

if you guys have some ref for me learn more deep about part that i confused, please share to me.
tis is the codes :

function rot13(str) {
  let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let arr = [];
  let spl = str.split("");
  for(let i = 0; i < spl.length; i++) {
    let ind = alpha.indexOf(spl[i]);
    if(ind !== -1 && ind !== undefined) {
       arr.push(alpha[(ind + 13)  % 26])
    } else {
      arr.push(spl[i])
    }
  }

  return arr.join("")
}

It looks like a working solution, so I added spoiler tags.

You need to check how modulus works on javascript

Just some testing, imagine that in one letter of the string you have ā€œaā€, so the index will be 0. Applying alpha[(ind + 13) % 26] will result in alpha[(0+13) % 26]

0 + 13 = 13
13 % 26 = 13 (remainder)

Now imagine we got the letter ā€œzā€ in the string, so the index will be 25 (26 0-indexed). In this case we have:

25 + 13 = 38
38 % 26 = 12 (remainder and perfect position)
// That's because we need to start again 
// once we get to the end
1 Like

A post was split to a new topic: Help with global variables

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.