Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Is this a decent way to get the answer for Letter Changes
    I just finished the easy challenge letter changes, whereby you increment each letter of the alphabet then swap the case of all the vowels. The steps I took were as followed (JavaScript): Within a for loop, I looped through the string, using a regex to trigger if/else statements. I needed a separate statement for the z->a and Z->A since they don't increment in Unicode. I then wrote the resulting character sequentially into a new string. I then took this string and looped over it, using a regex to swap the case of all the vowels, writing the result to a new string, which is returned in the answer. All the test cases panned out but I'm just curious as to whether or not there is a more efficient way of going about it. Code follows. Thanks guys!
    var newString = "";
    var newerString = "";
    var regexp = /[a-yA-Y]/;
    
    function stringlength(str) {
        for (var i=0; i<str.length; i++) {
            if(regexp.test(str[i])) {
              newString += String.fromCharCode(str.charCodeAt(i)+1);  
            }
            else if (str[i] == "z") {
              newString += "a";
            }
            else if (str[i] == "Z") {
                newString += "A";
            }
            else {
            newString += str[i];
            }
        }
    
        for (var j=0; j<str.length; j++) {
            if (/[AEIOU]/.test(newString[j])) {
                newerString += newString[j].toLowerCase();
            }
            if (/[aeiou]/.test(newString[j])) {
                newerString += newString[j].toUpperCase();
            }
            else {
                newerString += newString[j];
            }
    
        }
    
        return newerString;
    }
    
    
    sporadicles posted this question on 12/23/13 | javascript, letter, changes
    Answers
  • +
  • 7
  • -
  • As hfkiwi says, looking at other people's code is a good way to learn. Here's another way to do it without for loops, instead using String.replace() with regular expressions twice. It makes use of the fact that String.replace() can take a function as the second parameter:
    function LetterChanges(str) { 
    
      var letterPattern = /[a-zA-Z]/g;
      // function below changes letters for the next one in the alphabet:
      var newStr = str.replace(letterPattern, replaceLetter); 
      
      var vowelPattern = /[aeiou]/g;
      // and this one uppercases the vowels:
      newStr = newStr.replace(vowelPattern, replaceVowel);
      
      return newStr; 
             
    }
                               
    function replaceLetter(match) {
      if (match === "z"){
        return "a"
      }
      var ascii = match.charCodeAt(0);
      return String.fromCharCode(ascii + 1);
    }
    
    function replaceVowel(match) {
      return match.toUpperCase();
    }
    
  • +
  • 6
  • -
  • I prefer to take advantage of regex (regular expressions) when dealing with these sort of problems. It tends to make life easy:
    def LetterChanges(str)
    return str.gsub('z', 'a').gsub(/[a-y]/) {|x| x.next!}.gsub(/[a,e,i,o,u]/) {|x| x.upcase!}   
    end
  • +
  • 2
  • -
  • Congratulations!! Once you've completed a challenge you can use the "Compare Your Code" button to look at other people's solutions, and form your own opinion as to whether their approaches are more efficient or not - it's a good way to learn as there is usually more than one way to achieve the same result :) A couple of observations on your example code; once you've asked for the charCodeAt() it may be more efficient to deal with the number it returns and manipulate that rather than to translate it back into a string and then to manipulate that string - that would also allow a numerical approach to dealing with the issue you raised about "what to do with the z's". Also, I would look at the String object's replace method to capitalize the vowels, where you can also use regex to match the string you want to replace, but do it globally in one hit rather than iterate over the string. Ultimately whether these suggestions result in more efficient code is probably a matter of microseconds, but may result in more elegant code, if not necessarily more efficient :)
  • +
  • 1
  • -
  • @ninjex woops wrong syntax ;)
  • +
  • 0
  • -
  • Found most simple way using map
    function LetterChanges(str) { 
      let inMap = 'abcdefghijklmnopqrstuvwxyz',
          outMap = 'bcdEfghIjklmnOpqrstUvwxyzA',
          out = '';
    
      for(let i=0; i<str.length;i++){
          let idx = inMap.indexOf(str[i]);
          out += (idx>=0)?outMap[idx]:str[i];
      }
      
      return out; 
    }
       
    // keep this function call here 
    LetterChanges(readline());
    
  • +
  • 0
  • -
  • code 
    function replaceLetter(match) {
      if (match === "z") {
        return "a"
      }
      var ascii = match.charCodeAt(0);
      return String.fromCharCode(ascii + 1);
    }
    
    Is "match" a string or a character? Should be: match.charAt(0) === "z" || match.charAt(0) === "Z"
  • +
  • 0
  • -
  • @ninjex woops wrong syntax ;)
  • +
  • 0
  • -
  • @ninjex woops wrong syntax ;)
  • +
  • -2
  • -
  • To display code include the following tags:
    code goes here
    Isn't that Ruby @ninjex ? (.upcase()?)...
    Log in to write an answer.