Wednesday, June 8, 2016

a/A Practice Problems: Nearby AZ

Practice Problem 8 of 21 and the first medium! It's exciting stuff happening 'round these parts. Without further adieu...

Write a method that takes a string in and returns true if the letter "z" appears within three letters **after** an "a". You may assume that the string contains only lowercase letters.

This is a little trickier, but still employs the same methods and logic that we've already seen. A couple loops and if statements.

1.  Declare our function with one parameter, string.

function nearbyAZ (string) {
}

2.  I wanted to declare a variable, index1, that would hold the place of the position in which the letter "a" appears. This will be helpful later when determining if there's a "z" within the next three letters.

function nearbyAZ (string) {
   var index1 = 0;
}

3. We want to loop through all the letters in order to see if there's an "a".  The code block within the loop will be an if/else statement. If there's an "a", store it's index number in the variable, index1, and break out of the loop. Else, I want to increase index1 by one with each iteration of the loop. This way we will store the correct position number.

function nearbyAZ (string) {
   var index1 = 0;
   for (var i = 0; i < string.length; i++) {
      if (string[i] === "a") {
         index1 = i;
         break;
      }
      else {
         index1++;
      }
   }
}

4.  After the previous loop, I want another variable, index2, which will store the value of index1 + 1. This will be where our loop will start, and it should end at the third letter after the first a: index1 + 3. 

function nearbyAZ (string) {
   var index1 = 0;
   for (var i = 0; i < string.length; i++) {
      if (string[i] === "a") {
         break;
      }
      else {
         index1++;
      }
   }
   var index2 = index1 + 1;
   for (var j = index2; j <= index1 + 3; j++) {
   }
}

5. Start the loop at index2 because we are only concerned with the first three letters after the letter "a". Likewise, we'll want to stop the loop once it reaches that third letter. An if statement is the last part required to return true or false if there's a "z". 

function nearbyAZ (string) {
   var index1 = 0;
   for (var i = 0; i < string.length; i++) {
      if (string[i] === "a") {
         break;
      }
      else {
         index1++;
      }
   }
   var index2 = index1 + 1;
   for (var j = index2; j <= index1 + 3; j++) {
      if (string[j] === "z") {
         return true;
      }
   }
   return false;
}


Check out past problems here:

No comments :

Post a Comment