Chapter 3 Exercises

Great job, @rbrownlow! :star2:

  1.   function countBs(string){
     let result = 0;
     for(let i=0; i < string.length; i++){
       if (string[i] == "B") {
         result +=1;
       }
    

    }

    return result;
    }
    console.log(countBs(“Before Behest Brand beguile Boo”));

function countChar(string,char){

    let result = 0;

    for(let i=0; i < string.length; i++){
      if (string[i] == char) {
        result +=1;
      }

  }

  return result;

  }
  console.log(countChar("begone from here", "e"));
1 Like

Min() Function

<script language="JavaScript">
function min(val1,val2) {
  return val1 < val2 ? val1 : val2;
}

document.write("The smallest of the two numbers is " + min(Number(prompt("Input first argument of 2 for min function")), Number(prompt("Input second number of 2 for min function"))))
</script>

Recursion

<script language="JavaScript">
function isEven(val) {
  if (val == 0) {
return true;
  } else if(val == 1) {
return false;
  } else if(val < 0) {
return isEven(Math.abs(val));
  } else {
  return isEven(val - 2);
  }
}
document.write(isEven(prompt("what number would you like to test")));
</script>

Beans

<script language="JavaScript">
function cntBs(myString){
let numberOf = 0;
  for(i = 0; i < myString.length; i++) {
if(myString.charAt(i) == "B") {
  numberOf++;
  
}
  }
  var textToReturn = "<center>You passed the string <font style='color:red'>" + myString +"</font>";
  textToReturn += "<br>I found " + numberOf + " B ";
  if(numberOf > 1 || numberOf == 0) {
textToReturn += "'s";
  }
  textToReturn += "</center>"
  return textToReturn;
}

document.write(cntBs(prompt("Give me a string to test.")));
</script>

Beans MK 11

    <script language="JavaScript">
    function highlight(text,plural) {
        if(plural) {
            return "<font style='color:red'>" + text + plural + "</font>"
        } else {
            return "<font style='color:red'>" + text + "</font>";
        }
    }

    function count(myString, char, numberOf, cnt) {
        if(cnt < myString.length){
            if(myString[cnt] === char){
                return count(myString, char, numberOf + 1, cnt + 1);
            } else {
                return count(myString, char, numberOf, cnt + 1);
            }
        } else {
            if(numberOf === 1) {
                return "The string you passed was " + highlight(myString) + ".<br> The string is " + highlight(cnt) + " in length.<br>The character you are searching for is " + highlight(char) + "<br>There was " + highlight(numberOf) + " " + highlight(char) + " found.";
            } else {
                return "The string you passed was " + highlight(myString) + ".<br> The string is " + highlight(cnt) + " in length.<br>The character you are searching for is " + highlight(char) + "<br>There are " + highlight(numberOf) + " " + highlight(char,'\'s') + " found.";
            }
        }
    }

    function cntBs(myString){
         return countString = count(myString, prompt("What character do you wish to search for in the string?"), 0, 0);

    }

    document.write("<center>" + cntBs(prompt("Give me a string to test.")) + "</center>");
    </script>
1 Like

Minimum

function min(a, b) {
         return(a < b ? a : b);
      }

console.log(min(3,-4));

Recursion

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));

Bean Counting

function countBs(string) {
        return countChar(string, "B");
      }

      function countChar(string, char) {
        var charNumber = 0;
          for (var i = 0; i < string.length; i++) {
            if (string[i] == char) {
              charNumber += 1;
            }
          }
        return charNumber;
      }

console.log(countBs("BBUEIiSKB"));
console.log(countChar("AmkmAAAr", "A"));
1 Like
function min(b, c) {
  if (b < c) return b;
  else return c;
}

console.log(min(10, 40))

Will return 10.

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(50));
Will return true

console.log(isEven(75));
Will return false

console.log(isEven(-1));
Will return false

3.

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

function countBs(string) {
  return countChar(string, "B");
}
console.log(countBs("bbBbBBB"));
Will return 4
console.log(countChar("kakkkeekkekkeerlak", "k"));
Will return 9
1 Like

Hi @ArvidK,

Some really good code here! :ok_hand:

A few observations…

Minimum

You don’t need the second Boolean expression, because if the first Boolean expression evaluates to false then by default b must be the lowest. And, in addition, if you leave the second Boolean expression as it is, if both numbers (a and b) are equal, the function will return undefined. So your final solution should look like this:

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

Also, I’m not sure if you already know how to format your code when you post it here in the forum. Before you input your code, click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which then also makes it easier for you to organise with the correct spacing, indentation, nesting and brackets etc. It also helps to spot any slips with things like spelling or brackets etc.

Bean Counting

The return statement is missing from your countBs function: return count;
… and count is incorrectly written as counted in the equivalent return statement in your countChar function.

Also, there is an additional step to this exercise. Now you have the second function countChar , which has 2 parameters, can you slim down countBs() so that it still only has one parameter, but calls countChar to do the computation and then still returns the number of B’s?

Hi @DanD!

Minimum: The challenge with this one is to create a function that performs the same calculation as Math.min() but without using it. What you’ve done is just wrapped Math.min() within an outer “shell” function which doesn’t actually add anything that Math.min() can’t already do on its own. (see below for my recommended approach).

Recursion: Your version is shorter because you’ve used num % 2 which doesn’t require recursion to be used. Recursion is when a function calls itself in order to repeat its computation, but each time inputting as parameters the output returned from its previous execution i.e. performing iteration like a loop, but without using an actual loop.

The challenge, here, is to use recursion to generate the same functionality as num % 2 but without using it.

As an aside, with your “cheat” :wink: method, you can actually make it even shorter, as follows:

// Your current version
function isEven(a) {
   return a % 2 == 0 || false;
}

// More concise version
function isEven(a) {
   return a % 2 == 0;     // evaluates to true or false
}
/* The Boolean expression already evaluates to true or false, so the
   additional 'OR false' is redundant.

Have a look again at both exercises, and if you don’t understand where to start, then have a look at the hints (which you can display in the online course book by clicking below the exercise instructions). If you still don’t get it, have a look at other students’ solutions posted here. Then if you’re still stuck let us know and we’ll help you out!

That’s a good approach to take when you’ve genuinely tried all the other ways to get there yourself… You are right not to just leave it and move on, as there are obviously some important concepts that you need to assimilate. Spending time analysing and working back from the model answer is time worth spending. You can always come back to it a short while later and see if you can now rewrite it by yourself (a bit like a memory test). But do remember that there are always valid alternatives to the model answer, so still post your solution if you think that’s what you’ve come up with. You’ll also see other students’ alternative solutions posted and reviewed here in this discussion thread, so you can always check what you’ve come up with here to see if someone else has solved it in the same way.

1 Like

Great solutions, @RailGame!
… and nice commentary/analysis :+1:
… your code is also really easy to read and check, because it’s so well formatted :slightly_smiling_face:

…basically…you’re on :fire: !

You’re spot on with your second solution to Minimum. You’ve probably already realised that all your first version does is wrap Math.min() within an outer “shell” function which doesn’t actually add anything that Math.min() can’t already do on its own — i.e. it’s pretty pointless, unless of course we are going to add some additional functionality.

2 Likes

Hi @Mucha_Julius,

Great, so far :+1:

There is also an additional step to this Bean Counting exercise. Now you have the second function countChar , which has 2 parameters, can you slim down countBs() so that it still only has one parameter, but calls countChar to do the computation and then still returns the number of B’s?

1 Like

Hi, thanks for pointing it out., I totally forgot about it
I’ll try it out!

1 Like

Minimum
function findMin(x,y){
if(x<y){
return x;
}
else if(x>y){
return y;
}
else{
“they are equal”;
}
}
document.write(findMin(10,7));

Recursion
function isEven(N) {
if (N == 0){
return true;
}
else if (N==1){
return false;
}
else {
return isEven(N-2);
}

}

document.write(isEven(50));
document.write(isEven(75));
document.write(isEven(-1));

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

function countBs(string) {
return countChar(string, “B”);
}

document.write(countBs(“BBC”));
document.write("
")

document.write(countChar(“kakkerlak”, “k”));

1 Like

Thanks for the encouragement.
This is a very involved learning process but very rewarding in the end.

1 Like
function min( x, y ) {
   if ( x < y ) return x;
   else return y;
};

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 );
};
1 Like

Hi @daz3d,

You’re on :fire: !

Great use of the ternary operator in Minimum (my personal favourite for this exercise) :+1:

Recursion :ok_hand:

Bean Counting
Great…so far — you’ve got the countBs function working perfectly with the nicely formatted output printed to the page (your handling of singular and plural B/B’s is particularly impressive) :smiley:
…Could you now extend this for the additional parts to the exercise?

  • An additional function with two parameters, so we can set the letter/character to be counted.
  • Slimming down countBs so that it calls the new function to count the number of Bs there, but still returns the final result itself.

Also, try and work on improving your indentation and positioning of curly brackets in the code you post here — it will make your code easier to read :slightly_smiling_face:

2 Likes

Hi @jon_m,
I really appreciate the encouragement.
I have re-written the whole script and added the functionality you requested.
Took a complete different approach this time.
No loops this time. My attempt to introduce recursion to my vocabulary as a step away from for hell.
It could probably be done much more efficiently in another way but i found the exercise fun to do.
I also took your advice and increased my indentation in my editor.

Beans via recursion

    <script language="JavaScript">
    function makeItHot() {
        return "<font style='color:red'>" + this + "</font>";
    }
    String.prototype.hot = makeItHot
    function count(myString, char, numberOf, cnt) {
        if(cnt < myString.length){
            if(myString[cnt] === char){
                return count(myString, char, ++numberOf, ++cnt);
            } else {
                return count(myString, char, numberOf, ++cnt);
            }
        } else {
            if(numberOf === 1) {
                return "The string you passed was " + myString.toString().hot() + ".<br> The string is " + cnt.toString().hot() + " in length.<br>The character you are searching for is " + char.toString().hot() + "<br>" + numberOf.toString().hot() + " " + char.toString().hot() + " found.";
            } else {
                return "The string you passed was " + myString.toString().hot() + ".<br> The string is " + cnt.toString().hot() + " in length.<br>The character you are searching for is " + char.toString().hot() + "<br>" + numberOf.toString().hot() + " " + char.toString().hot() + "\'s".hot() + " found.";
            }
        }
    }

    function cntBs(myString){
         return countString = count(myString, prompt("What character do you wish to search for in the string?"), 0, 0);

    }

    document.write("<center>" + cntBs(prompt("Give me a string to test.")) + "</center>");
    </script>

edit #1 because I found a way to reduce by a few lines.
edit #2 now i know why var++ wasn’t working in recursion. increment first ++var no need anymore for me to be using var + 1

1 Like

function min (a,b) {
if (a< b)
return a;
else if (a>b)
return b;
}
console.log(min);
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);

function countBs(string) {
return countChar(string, “B”);
}

  function countChar(string, char) {
    var charNumber = 0;
      for (var i = 0; i < string.length; i++) {
        if (string [i] == char) {
          charNumber += 1;
        }
      }
    return charNumber;
  }
						}
1 Like

Minimum Exercise:

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

console.log(min(5, 10));
// → 5
console.log(min(9, 25));
// → 9

/*What is the difference between (9, 25) as “arguments” and “numeric value types”? Is it the same thing called differently?
*/

Recursion Exercise:

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(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false

Bean counting Exercise:

function countBs(str) {
let count=0;
for (let i = 0; i < str.length; i++) {
if (str[i]===“B”) {
count++;
}
}
return count;
}

function countChar(str, char) {
  let count=0;
  for (let i = 0; i < str.length; i++) {
	if (str[i]===char) {
	  count++;
	} 
  }
  return count;
}
1 Like

Excellent coding, Luis!

Sorry for the delay in reviewing it.

Nice use of the ternary operator in Minimum :+1: By the way you don’t need the parentheses:

return a < b ? a : b;   
1 Like

Excellent coding, @Lucky_Mkosana!

Sorry for the delay in reviewing it.

By the way, just a tip. When you format your code for posting here in the forum, you can use the same JavaScript syntax to “grey out” your comments:

console.log(countBs("bbBbBBB"));
// Will return 4
console.log(countChar("kakkkeekkekkeerlak", "k"));
// Will return 9

This also means that when someone copies and pastes your code into a text editor, like Atom, to execute it, they don’t need to manually do this themselves.

1 Like

Nice solutions, and a great effort, @ashishc!

Here are a some observations to help you correct and improve a few things:

Minimum

At the moment your code doesn’t write anything to the web page if the numbers are equal. That’s because the return keyword is missing before the string "they are equal". You need to return this string as well as the numbers x and y, so that one of them is written in each of the 3 possible scenarios.

Recursion

Your solution works for positive numbers, but doesn’t print anything to the web page for negative numbers. You need to revisit the exercise and your code, work out why, and make the necessary adjustments and additions.

If you want to use document.write() instead of console.log() then I would also add HTML line break tags so that each output is written on a separate line, instead of like this:  truefalse

Bean Counting

This is very nearly perfect :smiley: Unfortunately one minor thing causes an error on execution:

The fact that this piece of code is split over 2 lines, means that it throws an error.
A better solution to:  document.write(" ")  (which only adds an in-line space) would be the line break I mentioned above.


Also, I’m not sure if you already know how to format your code when you post it here in the forum. Before you input your code, click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which then also makes it easier for you to organise with the correct spacing, indentation, nesting and brackets etc. It also helps to spot any slips like the one I’ve just mentioned above. Your code for Minimum should end up looking something like this:

function findMin(x, y) {
   if (x < y) {
      return x;
   }
   else if (x > y) {
      return y;
   }
   else {
      return "they are equal";
   }
}

document.write(findMin(10,7));

Keep at it! You’re making good progress :muscle: