Chapter 3 Exercises

Well this took me 2 days but I think I got there in the end :sweat_smile:

Minimum

function min (a,b){
 return(Math.min(a,b));

}

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

Recursion

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

  else return isEven(a - 2);
}

console.log(isEven(50));

Bean Counting

function countBs (str) {
​
    let result = 0;
​
    for (x=0; x < str.length; x++) {
​
    if (str[x] == "B") {
       
    result += 1;
}
​
    }
return result;
​
}
​
console.log(countBs("BBccBB"));

function countChar (str, character) {

    let result = 0;

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

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

    }
return result;

}

console.log(countChar("jjody", "j"));

1 Like

Hi again, Frank,

My understanding is that any variable that isn’t declared with var, let or const, will have global scope, and can therefore be accessed from anywhere in the program. They will also be assigned to the global object (which is the window object in a browser environment). Based on my current knowledge, this seems to be no different to declaring a variable with var in global scope (i.e. outside of all functions). Variables declared with let outside all code blocks and functions are slightly different: they can be accessed throughout the program but are not assigned to the global object.

Whether or not we declare our variables with a keyword, and if we do, which one we use, has much less impact (if any) when our programs are so small. However, I mentioned that it was a good practice to get into because it’s easy to imagine how we could start to lose control over our variables, and their effects, in much larger and complex programs if we don’t think carefully about their scope. Not to mention our global namespace would quickly become polluted (i.e. overly cluttered).

In terms of the additional part to the Bean Counting exercise, the idea was to take the original countBs function (which is the same as the countChar function except that it only takes one parameter, the string — the letter being fixed as a capital B) and then reduce it so that it calls countChar with 2 arguments (its string parameter and the letter B) and leverages its functionality to do the main computation. I totally understand your point that we can just as easily call countChar directly with a string and the letter B. It was just an exercise in how we can call a second function from within the function we called initially. Such a technique can potentially avoid code duplication, and keep our program more concise and streamlined. You can see what the final solution would look like with this additional step, in the course book’s model answer: https://eloquentjavascript.net/code/#3.3 (You need to click on the button “look at the solution” in red letters.

Don’t worry about it too much if you can’t see the point of this extra step. I just thought it was a worthwhile extension of the exercise for the reasons I’ve mentioned.

1 Like

Hi guys, my answers here and I have to comment that Bean Counting I haven’t figured out. I understand the instructions but even if I look at the solution I still don’t understand XD.

1. MINIMUM
function min(x,y){
if (x<y) {
document.write( x + " is smaller than " + y);
}
if (x==y) {
document.write(“they are equal”);
}
if (x>y) {
document.write( y + " is smaller than " + x );
}
}
var answer = min(1,-1);

2. RECURSION

function isEven(x){
if (x==0) {
document.write(" true ");
}
if (x==1) {
document.write( “false” );
}
if (x>1) {
document.write( x + "-2 = " + (x-2) );
}
if (x<0) {
document.write(“false”)
}
}
var answer = isEven(11);

1 Like

Minimum

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

Recursion

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

Bean Counting

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

//Function find minimum value
const min = function (a,b) {
if (a<b) {return (a);} else {return(b);}
};

var firstNum = -9;
var secondNum = 5;

console.log("Of the numbers “,firstNum,” and ",secondNum,
" the smaller number is ", min(firstNum,secondNum));

//Function find Even or Odd through recursion
const oddOReven = function (N) {
if (N<0) {N=N*-1} //if negative make positive
if (N==0) {return (true);}
else {if (N==1) {return (false);}
else {
return oddOReven(N-2);
}
}

};

var numTOcheck=4;

console.log(numTOcheck,“is”,oddOReven(numTOcheck));

//Function count how many of a given char are in a string

const countChars = function (string, char) {
count=0;
for (var i = 0; i < string.length; i++) {
if (string[i] == char) {count++}
}
return count;
}

var stringOFletters = “abasdslkfjasdflkwoiuerkngmczvxnk”;
var searchChar = “A”

console.log(countChars(stringOFletters,searchChar));

  1. function min(a,b){
    if (a<b) return a;
    else return b;
    }
    console.log (min(2,3));

  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(string) {
    let result = 0;
    for (let i = 0; i <= string.length -1; i++) {
    if (string[i] === ‘B’) {
    result += 1;
    }
    }
    return result;
    }
    function countChar(string, character) {
    let result = 0;
    for (let i = 0; i <= string.length -1; i++) {
    if (string[i] === character) {
    result += 1;
    }
    }
    return result;
    }

    console.log(countBs(“CBeeBies”));

    console.log(countChar(“Ford kaka”, “k”));

Minimum

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

console.log(min(2, 8));
// → 2
console.log(min(2, -8));
// → -8

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

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 countBs(string) {
  return countChar(string, "B");
}

console.log(countBs("BitcoinBeans"));
// → 2
console.log(countChar("bitcoin", "i"));
// → 2
1 Like

Good work, @Nev!

That’s fine, as long as you’ve found a method that works for you, and you’re spending longer analysing the solution at the review and reflection stage if you had to look at it before being able to complete the exercise.

Just one comment about your Recursion:

Your code still works for any integer (because you handle 0 in the first if statement), but your code will be more intuitive if the condition in your second else if statement is n < 0notn < 1 (because this statement should only handle negative numbers).

2 Likes

Hi @loksaha1310,

I’m very impressed with your use of a ternary operator to convert all negative integers to positive ones :+1:

A very nice and concise solution :slightly_smiling_face:

By the way, I can’t see you solution to exercise 1…

1 Like

Feedback for Bean Counting

Good so far, @loksaha1310 :ok_hand:

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.

Check the exercise instructions for further details.

Try not to skip parts of each exercise, as there aren’t very many of them.

1 Like

Well done, @DeezSats, for getting there in the end! :muscle:

Bean Counting

There’s actually an additional step to this exercise. Now you have the second function numChar , which has 2 parameters, can you slim down your original countBs function so that it still only takes just one parameter (the string), but now calls numChar to always count the number of B’s, while still returning the output itself?

Check the course book instructions for further details.

In addition (and even though it doesn’t throw an error), the following line of code can be made a lot clearer and more concise:

numChar = numChar + 1;
// or
numChar += 1; 
// or
numChar++

Keep on learning!.. You’re making great progress!

1 Like

Hi @Jody,

Sorry for the delay in providing you with some feedback on your solutions to these exercises.

Don’t worry about how long it took you. As long as you are making progress, that’s what counts, and I can definitely see that you are! :smiley:  You seem to be struggling a lot less to get started. It’s also better to spend as long as possible doing what you can on your own first, rather than rushing them and looking at the model answers too soon.

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. Have a good think about the logical steps and comparisons that Math.min() needs to perform “behind the scenes” to output the minimum of a pair of numbers, whatever the combination. This more detailed breakdown of the actual calculation is what you need to code. (Hint: you are going to need to use conditional execution and perform a comparison).

Recursion

Your solution successfully handles positive numbers :ok_hand:
Now you need to add functionality to handle negative numbers. Have a look at the instructions in the course book for further details. There are several different ways to do this, so if you get stuck you might want to have a browse through other students’ solutions to this here in the forum, before looking at the model answer. (Hint: you need to find a way to convert negative numbers into positive ones, and then feed them through (or back through) the code you’ve already written for positive numbers).

Bean Counting

This is excellent! :muscle:

I’m not sure if you realised, but there’s also an additional step to this exercise. Now you have the second function countChar , which has 2 parameters, can you slim down your original countBs function so that it still only takes just one parameter (the string), but now calls countChar to always count the number of B’s, while still returning the output itself?

Check the course book instructions for further details.

Good luck with these additional tasks!

You’re making great progress, Jody!

1 Like

Hi @Pacheco,

You’ve made a really good start with these. Here are some comments to help you improve your solutions and develop them further:

Minimum

This is pretty much complete :ok_hand:

Instead of a chain of if statements, which is used when more than one of the branches can be executed, your program needs conditional execution where each of the branches is mutually exclusive (i.e. only one of the branches will be executed). This is the most common type of conditional execution, and it requires  if...else  (or in your program if...else if...else ) statements. As the final else statement is the default (i.e. handling all cases that have evaluated to false in each of the preceding statements), this means that it doesn’t need a condition.
(Note: this same point also applies to your conditional execution in the second exercise, Recursion)

Recursion

You haven’t understood how to code the actual recursion. Instead of printing the calculation that needs to be performed before starting the next recursion (e.g. 11 - 2 = 9), you need to call the function again with the answer to this calculation (i.e. 9, in this example). The function is then continuously called until the answer is either 0 or 1. We only want to print true or false, depending on whether our input number is even or odd. By reducing the number by 2 on each recursive loop, even numbers will reduce to 0, whereas odd numbers will reduce to 1.

The other problem with your code, is that you are printing false for all negative numbers. But negative numbers can also be even or odd. So in this branch you want to call the function again recursively, but with the negative number converted to positive. This way, when the function body is executed again, it will be treated like a positive number, and so everything I’ve commented on above will now apply.

Have another go, and if you find it too difficult, have a read of this post, which includes a summary of my top tips for approaching the course book exercises if you’re finding yourself struggling to do them on your own. You can also apply these approaches to the exercise Counting Beans and hopefully that will help you to gradually understand it.

Good luck with this, and just let us know if you have any questions or need any help.

Keep on learning :muscle:

1 Like

Minimum

function min (a,b){

if (a<b){
  return a
  console.log(a)
} else {
  return b
  console.log(b)
}

}

Recursion

function isEven(x){
  if (x % 2 === 0){
  console.log("true");
} else {
  console.log("false");
}
}

Bean Counter (letter B)

function countBs(string){
  let count = 0
  for (let n = string.length; n> -1; n--){
    if (string[n] == "B") {
      count += 1;
    }
  }
return count
console.log (count)
}

Count Any Character

function countChars(string, x){
  let count = 0
    
  for (let n = string.length; n> -1; n--){
    if (string[n] == x) {
      count += 1;
    }
  }
return count
console.log (count)
}

Edit: Here is the proper solution for 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);
}
1 Like

Hi @Bunbo_Hue, The recursion function, it does not seem complete, it meant to be a recursion function. if you could implement it as recursion function It would be good practice.

2 Likes

Minimum:

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

document.write(returnMin(10,5));

Recursion:

function isEven(N) {
   if (N == 0) {
     document.write ("even");
   } else if (N == 1) {
     document.write("odd");
   } else if (N < 0) {
     isEven(-N);
  } else {
  isEven(N-2);
    }
  }

  isEven(-10);

Bean Counting:

function countAs(string, char) {
     let total = 0;
     let N = 0;
     while(N < string.length) {
       if (string[N] == char) {
         total +=1;
       }
        N = N + 1;
     }

     document.write(total);
   }
   countAs("Apple");

1 Like

EXERCISE

1. MINIMUM

   function min(x, y) {
    if (x < y) return x;
    else return y;}
     
console.log(min(2, 15));

2. RECURSION

    function isEven(n){
      if (n==0)
      return true;

      if (n==1)
      return false;

      if (n<0)
      return isEven(-n);

      else return isEven(n-2);
    }

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

By placing additional else return statement when input number is less then zero return error message.

3. BEAN COUNTING

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

    function countChar(string, char){
      let count = 0;
      for (i=0;i<string.length;i++){
        if (string[i]== char){
          count += 1;
        }
      }
      return count;
    }
1 Like
		// Math Minimum exercise code 
			var FNumber = prompt("First Number Please");
			var SNumber = prompt ("Second Number Please");
			
			if (FNumber == SNumber) 
				document.write("<h3>These two numbers are the same. </h3>");
				else document.write("<h3> The minimum number is " + Math.min(FNumber,SNumber,));
			
			
		// Even or Odd exercise code 
			var number = prompt("Please enter a number");			
			
			function isEven(a){
			if(a == 0) return ("Even"); 
			else if(a == 1) return ("Odd");
			else if (a <0 ) return isEven (-a);
			else return isEven(a-2)
			}
			var results = isEven(number)
			
			document.write("<h3>The number is " + results);				
	
		
		// Bean Count exercise code
			var beanTxt = prompt("Please input a word")
			
			function countBs() {
						var str = beanTxt.match(/B/g);
						var Beans = str.length;
						document.write("<h3>The number is " + Beans);	
						}
			
			countBs()	;
			;

		// Char Count exercise code
			var beanTxt = prompt("Please input a word")
			var beanLtr = prompt("Please input a letter")
			
			function countChar() {
						let count = 0
						for (i=0; i < beanTxt.length; i++)
							if (beanTxt[i] == beanLtr)
								{count +=1;}								
						document.write("<h3>This is the count: " + count);	
						}
			
			countChar()	;
1 Like

Hi guys,
I’ve been following this class for two weeks now and as the complexity progresses I realize that I don’t seem to have a good grasp of the whole “writing grammar”. The explanation in the eloquent book are probably very logical but introduces even more foreign vocabulary in my brain.
If anybody is encountering the same issue and is of german language I found that Youtube channel that explains the stuff quite well.

2 Likes