ivan milenkovic
ivan milenkovic

Reputation: 99

Can't get right letter after ciphering

I am working on this problem at CodeWars: Vowels Back Usually half of my tests fail, but from what I see every fail test is because of letter 'a' since I get '\backslash' instead of 'v'. Of course, I see from my calculations why I get '\backslash', I tried to fix it with something like Math.abs(), but then I was getting 'f', not 'v'. Can someone help me fix this please? All other letter changes seem correct.

function vowelBack(s){
  let output = '';
  let position;
  let newPosition;
  let newChar;

  for (let i = 0; i < s.length; i++) {
    position = s.charCodeAt(i);
    
    if (s[i] === 'c' || s[i] === 'o') {
      newPosition = ((position - 97 - 1) % 26) + 97;  
      newChar = String.fromCharCode(newPosition);
      if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') {
        newChar = s[i];
      }
      output += newChar;
    } else if (s[i] === 'd') {
      newPosition = ((position - 97 - 3) % 26) + 97;  
      newChar = String.fromCharCode(newPosition);
      if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') {
        newChar = s[i];
      }
      output += newChar;      
    } else if (s[i] === 'e') {
      newPosition = ((position - 97 - 4) % 26) + 97;  
      newChar = String.fromCharCode(newPosition);
      if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') {
        newChar = s[i];
      }
      output += newChar;
    } else if (s[i] === 'a' || s[i] === 'i' || s[i] === 'u') {
      newPosition = ((position - 97 - 5) % 26) + 97;  
      newChar = String.fromCharCode(newPosition);
      if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') {
        newChar = s[i];
      }
      output += newChar;
    } else {
      newPosition = ((position - 97 + 9) % 26) + 97;
      newChar = String.fromCharCode(newPosition);
      if (newChar === 'c' || newChar === 'o' || newChar === 'd' || newChar === 'e') {
        newChar = s[i];
      }
      output += newChar;

    }
   }
  return output;
}

console.log(vowelBack("testcase"));

Upvotes: 0

Views: 31

Answers (1)

koorkevani
koorkevani

Reputation: 321

In javascript, -b < (a % b) < b, as opposed to 0 <= (a % b) < b in mathmatical notation (so -1 % 5 == -1, not 4). To ensure a positive solution, write (((a % b) + b) % b).

In your situation, I would add a function:

function shiftLetter(position, shift) {
    return ((((position - 97 + shift) % 26) + 26) % 26) + 97;
}

Upvotes: 2

Related Questions