Chapter 3 Exercises

@jon_m thanks for feedback and yeah, I would spend time trying to figure it out and I’m super close but for final touches had to look it up and then spent lots of time analyzing as to why… as for the feedback, yeah, I caught that after I’ve shared what I’ve done… it needs to be <0 not 1. Great catch.

1 Like

Question 1 : Finding minimum function

        // minimum function exercise
        function min(a, b){
          if(a<b){
            return a;
          } else{
            return b;
          }
        }

        console.log(min(5,8));

Question 2 : Recursion

        // recursion function exercise
        function isEven(a){
          if(a == 0){
            return true;
          } else if(a == 1){
            return false;
          } else if(a < 0){
            return isEven(-a);
          } else{
            return isEven(a-2);
          }
        }

        console.log(isEven(50));
        console.log(isEven(75));
        console.log(isEven(-1));

Question 3 : Bean counting

        //Bean counting function exercise (counting "B")
        function countBs(word){
          var numBs = 0;
          for(n = 0; n < word.length; n++){
            if(word[n] == "B"){
              numBs += 1;
            }
          }
          return numBs;
        }

        console.log(countBs("gjjBHggBgg"));

        //Counting Character function exercise (counting any char)
        function countChar(word, char){
          var numChars = 0;
          for(n = 0; n < word.length; n++){
            if(word[n] == char){
              numChars += 1;
            }
          }
          return numChars
        }

        console.log(countChar("kddjhjfpoh", "h"));
1 Like

Ex 2 - Recursion:

took me a minute to get the function call of itself inside itself to create it’s own “loop”. But now I get it… it keeps getting to the point in the function where “n” is now an increment of 2 smaller, and the function recurs inside itself, again and again, subtracting 2 each time from “n” until it returns true or false which gets us out of the recursion process. The return of either boolean gets us to exit the function. It’s a way to create a loop without using while or for loops. Genius! In the case of n < 0, just call the isEven function inside itself with -n as it’s argument, then the same boolean/recursion process will ensue to produce the eventual boolean value return.

Anyway, here’s my code:

    <script>
    function isEven(n){
      if (n == 0){
        return true;
      } else if (n == 1){
        return false;
      } else if (n < 0){
        return isEven(-n);
      } else {
        return isEven(n - 2);
      }
    };
    console.log(isEven(2));
    </script>
1 Like

here’s my code for Bean Counter:

    <script>
    function beanCounter(word,n){
      var beanCount = 0;
      for (count = 0; count < word.length; count++){
        if (word[count] == n){
          beanCount++;
        };
      };
      return beanCount;
    };

    function countBs(string){
      return beanCounter(string,"B");
    }
    console.log(beanCounter("mississippi","p"));
    console.log(countBs("Bob's Burgers"))
    </script>
1 Like

Hi again @jon_m,

Some improvements below (hopefully):

function min (a,b) {
    if (a < b) {
        return b; 
}
    else return a; 

}

console.log(min(6,4));

function isEven(a) {
  if (a==0) {
    return true;
  }
  else if (a==1) {
    return false;
  }

  else if (a < 0) {
     return isEven(-a);

}
  else return isEven(a - 2);
}

console.log(isEven(-1));

function countBs (str) {
return countChar(str, "B");

}

function countChar (str, character) {

    let result = 0;

    for (x=0; x < str.length; x++) {

    if (str[x] == character) {
       
    result += 1;
}

    }
return result;

}

console.log(countBs("BBbb", "B"));
1 Like

Sir, loved how you created a dynamic input option for the user.
Now, one thing i noticed is – The Bean count code cannot handle words where I don’t have a “B” in it. Suppose, if I enter “Malik” in the prompt, it throws an error. You might want to handle a scenario where the “match” method returns null when there are no matches for B’s.

1 Like
  function min (a, b) {
    if (a < b) {
      return a;
    }
    else {
      return b;
    }
  }
  console.log(min(43, 10));
  console.log(min(23, 90));

  function isEven (a) {
    if (a == 0) {
      return true;
    }
    else if (a == 1) {
      return false;
    }
    else if (a < 0) {
      return isEven (-a);
    }
    else {
      return isEven (a-2);
    }
  }
  console.log(isEven(50));
  console.log(isEven(75));
  console.log(isEven(-3));

  function countBs(string) {
    let charcounter = 0;
    for (let position = 0; position < string.length; position++) {
      if (string[position] == "B") {
        charcounter++;
      }
    }
    return charcounter;
  }
  console.log(countBs("Ba"));
  console.log(countBs("BaBa"));
  console.log(countBs("BaBaBaBaB"));

  function countChar(string, char) {
    let charcounter = 0;
    for (let position = 0; position < string.length; position++) {
      if (string[position] == char) {
        charcounter++;
      }
    }
    return charcounter;
  }
  console.log(countChar("aBa", "a"));
  console.log(countChar("BaBabBbB", "B"));
  console.log(countChar("BaBcBcBaBBBc", "c"));
1 Like

inspired by other students

  1. function showMin (a, b){
       if (a > b) {
          return b 
       }
       else {
          return a
       }
    }
    console.log(showMin(0, 10));
    console.log(showMin(0, -10))
    
  2.  function isEven(n) {
          if (n == 0) {
            return true
          }
          else if (n == 1) {
             return false
          }
         else if (n < 0){
             return isEven(-n)
          }
         else {
            return isEven(n - 2)
          }
      }
    
  3. function countBs(str) {
      return countChar(str, "B");
    }
    function countChar(str, ch) {
     let res = 0;
     for (i = 0; i < str.length; i++) {
     if (str[i] === ch) {
     res ++
         }
     }
     return res;
    }
    
    console.log(countBs("BBC"));
    console.log(countChar("javascript", "a"));
1 Like

So for my code, I have a question:

    <script>
      function countChar(string,c){
      var charTotal = 0;
      for (counter = 0; counter < string.length; counter++){
        if (string[counter] == c){
          charTotal++;
        }
      }
      return charTotal;
    }
    function countBs(string){
      return countChar(string,"B");
    }
    console.log(countChar("jonathan","a"));
    console.log(countBs("BDC"));
    </script>

When I wrote countBs() initially, I didn’t have the "return countChar(string, “B”); and just called the function instead without returning it. My logic was that the function countChar(string,c) already has a return statement so adding one when it is called in countBs is redundant. But without the return statement added to countChar() inside of countBs I get an “undefined” result. A "return countChar(string, “B”) is necessary. Isn’t this redundant to return a function that itself produces a return?

Please explain…

1 Like
<script>

//Minimum Exercise - Chapter 3 - Eloquent Javascript

function min(a, b) {
  if (a < b) return a;
  else return b;
                   }
  console.log(min(14, 10, 22, 33, 44, 55));

  //Recursion - isEven

  function isEven(n) {
    if (n == 0) return true;
    else if (n == 1) return false;
    else if (n < 0) return isEven(-n);
    else return isEven(n - 2);
                      }
  console.log(isEven(30));


  //Bean Counting

  function countChar(string, ch){
    let counted = 0;
    for (let i = 0; i < string.length; i++) {
      if (string[i] == ch) {
        counted += 1;
                                }
                                            }
    return counted;
                           }

  function countCs(string) {
    return countChar(string, "c");
                           }
   console.log(countCs("charlie chuckled"))


</script>
1 Like

Answer to math.min:

//With the function of math.min. Write a function that math.min that takes two arguments and return their minimun

//First we write a function and namne it min, assigning 2 parameters to it then run a statement to return the lowest value

function min (a, b){
  var a=101; b=102
  if (a<b) return a;
  else return b; 
}

console.log(min (a, b));

Am I correct to write in this way?

1 Like

Answer Recursion:

//Recursion basically find an answer through a few objects or Numbers
//Function it first to search from one area, if found return true
//Otherwise return false
//If not continue to find using while loop (-n)

//First to check if a number is divisble by 2, if yes it is Even. 
//e.g (n%2=0) even ; (n%2=1)odd 

  
function isEven(n) {
  if (n%2 == 0) 
    return true;
  else if (n%2 == 1) 
    return false;
  else if (n < 0) 
    return isEven(-n);
  else return isEven(n - 2);
}

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));

Bean Counting Answer:

Tutorial from YouTube

function countBs(string) {
//create a result, set to 0
let result = 0

  //loop over the string
  for (let i = 0; i < string.lenght; i++) {
    //if current character is a "B"
   if (string[i] === 'B') {
     //increment our result by 1
     result = result + 1;
   }  
  }
  //returm result
  return result;
}

function countChar(string, character) {
  //does stuff
  let result = 0
  //loop over the string
  for (let i = 0; i < string.lenght; i++) {
    //if current character matches input character
   if (string[i] === character) {
     //increment our result by 1
     result = result + 1;
   }  
  }
}
1 Like

Hi @jonsax , If I have understood you correctly, you what a function countBs to call a function countChar and return the result. that is great practice. Your first attempt was calling countChar in countBs then return the result, the calling worked perfectly but the function countBs does not know what to do with the return from countChar, so if you want to return it you have to tell the main function(in this case countBs) to return the result. Otherwise it does not know what to do with the return from countChar.

I hope this helpful.

1 Like

HI @JamieGoh your logic is correct, however the implementation does not work. did you run it?
correct implementation would be:
First step, remove the var a = 101 and var b= 102 because you have declared them as parameter,
Second step, pass the value you want to compare when you call the function not a, b. they have to be a real number.
I would recommend you to read chapter 3 again.

Thank you,
Abel

2 Likes

it is helpful! But I’m still struggling to understand why if a function calls another function, which produces a return, why that isn’t enough. Why must the main function be instructed to return the return? Calling the inner function which produces a return, should produce a return for the main one automatically if the inner function does. But I guess this is just a JS coding convention and what I want the code to do doesn’t matter. Conventions must be followed and understood. This one defies logic in my mind, but okay, this is just how it works I guess!

2 Likes

HI @JamieGoh, this function should check the number if it is even or not by using recursion system . In your case you are using % operation which is a solution as well, but it is not recursion. what I am trying to say is, else return isEven(n-2) will be never used because n%2 is always 0 0r 1 (assume n is an integer). So it is better to use n == 1 and n == 0 then you can apply the recursion solution.

2 Likes

Hi @jonsax,

Well, The creators of Javascript have also had the same line of thought and had created a new syntax for implicit returns when nested functions are there. It is called ES6 functions. Also known as “Arrow Functions” because they are denoted by arrows “=>”.

When one function has only one inner function, we have the ability to do an implicit return with them. But what if the main function has two or more inner functions ? In that case, we need to explicitly mention the “return” keyword here as well.

You can search it online. It’s a little advance concept in JS but I would be happy if you dig the rabbit hole yourself and figure out the details. It’s really interesting. :nerd_face:

Hope this gives you some context.

Happy Learning! :slight_smile:

3 Likes
//Minimum
      function min(x,y){
      if (x>y)
      return y;
      else
      return x;
      }
        var answer = min(2,0);
        console.log(answer);
    //  document.write ("<h2>" + answer + "</h2>");

//Recursion
        function isEven(n) {
        if (n == 0) return true;
        else if (n == 1) return false;
        else return isEven(n - 2);
        }
        console.log(isEven(22));

//Bean counting
        let string = "BksdlksBBckdsfjlsjBB";
        function countBs(string) {
          let counter = 0;
          for (x=0; x < string.length ; x++) {
            if (string[x]=='B'){
            counter++;
            }
          }
        return counter;
        }
        console.log(countBs(string));

//Bean counting, 2 arg
      //  let string = "BksdlksBBckdsfjlsjBB";
        let char = "B"
          function countChar(string,char) {
          let counter = 0;
          for (x=0; x < string.length ; x++) {
            if (string[x]== char){
            counter++;
            }
          }
        return counter;
        }
        console.log(countChar(string,char));


1 Like

Thank you so much Abuga on your pointers. I have re-read chapter 3, this time with more understanding. I started off with zero knowledge on programming and hence the first time I read, I couldn’t get what the book is trying to explain 95% of the time. I have to google for video which explain in a way which I can understand better. This time around I can grasp slightly more info. Guess I will have to re-read it over and again as and when I progress.

Back to the exercise, I got what your trying to point out:

function min (a, b){
if (a<b) return a;
else return b;
}

console.log(min (101, 102));
1 Like