Chapter 3 Exercises

This is my solutions to the exercises, the first one I did just with my understanding from everything that I have read in the book and from the examples, when the guy in the book is trying to explain the exercise what we need to do, I really do not understand him… I feel like I need to decode him first :joy: … In the second exercise I tried to do it even if I didn’t understand him what he wanted to say… Got it half working but just the opposite of what he wanted hahaha. The third one, again I didn’t understand until I looked for the answers on the forum and they really seemed to be explained well so it helped me alot to figure out how are they working. I did exercises couple of times, until I got the better understanding of them and how to do them withouth looking at the answers. By doing I get better understanding of them and why is something placed in the way it is :slight_smile:

function min(a,b) {

    if (a<b) return (a);
    else return (b);
}
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 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");
}
1 Like

Hi,

  1. During creation process I was playing around with document.write() function, so I maybe forgot to delete it, because even for me that kind of function in that loop doesnt make any sense. :))

  2. English is not my native language, so I found out difficult to understand conditions. I’ve read it couple of times, but obviously, it wasnt enough.
    So, I’ve read your notes and exercises couple of time more and adjusted my code. Still not 100% sure, that I get everything right. :smiley:
    Anyway, I enjoy this learning process! Finding solutions to the problems is most exciting things i this course. So please take a look at my code once again :slight_smile:
    P.s sorry for extra work which I gave you :v:

2.  function isEven(N){
if (N>=0){
  if(N==0){
    return "Even";
  }
  else if (N==1) {
    return "Odd";
  }
  else {
  return  isEven(N-2);
  }
}
else if (N<0){
    if(N==0){
      return "Even";
    }
    else if (N==-1) {
      return "Odd";
    }
    else {
    return  isEven(N+2);
    }
  }
} 
3.  function Countbs(word){
return countChar(word,"B")
}

function countChar (word,letter){
  let N=0;
  let Count=0;
  if(isNaN(word)&& isNaN(letter)){
    while (N<=word.length){
      if (word[N]==letter){
        Count++;
      }
      N++;
    }
    return Count;
  }
  else { return "Not a number";
}
}
1 Like

Minimum
console.log(Math.min(31, 30, 28) * 24 * 60); --> The minimum lenght of a month in minutes

Recursion
Define a recursive function isEven corresponding to this description

function isEven(N){

if N % 2 = 0 return=true;

else return=false;

}

N = 50
document.write(return);

I know I made a syntax error, where? Anyway this function on right syntax should work also on +1

1 Like

I could only manage 1&2

function mathmin(a,b){
if (a<b){ return a;}
else {return b;}
}
document.write(mathmin(200001,701));

let d = Number(prompt(“Pick a number”));

function isEven(x){
for (let c = 0; c=Infinity; c++ )
if( x<0) {(x = -x);
} else if (x>1) {(x = x-2);
} else if (x == 0) {return “even”; break;
} else if (x == 1) {return “odd”; break;

}}

console.log(isEven(d));

    • does not work. I wanted to do it with only one variable to begin with. If you see how to correct it please let me know thank you!

function testB(x){
var n = x.length;
for (u = 0; u = n; u++);{
var y=0;
if (x[u] == “B”) {y = y + 1;
} else if (o[u] == " ") {return x; console.log(“There are” + n + " letters and " + x + “of them are B.”);
} else {return x};
}}

1 Like

Hey @JanjoHR1!

From what you’ve explained it really seems like you have developed an excellent study method. The exercises are are real challenge, and we don’t expect you to get the same solution as the one in the book on your first attempt! That would be too easy and wouldn’t be the most effective way to learn anyway. Remember, we all learn in different ways, so don’t worry if you sometimes don’t understand how the author of the course book explains things. The main thing is that you understand the concepts and how the solutions work in the end. I say solutions, because there are always several valid alternatives, so if you write code that solves the problem and doesn’t match the model answer in the course book, or any other valid alternatives you can find here in the forum, then don’t be afraid to post it and we’ll check it for you :+1:

Keep doing what you’re doing! You seem to be getting a lot from the course, and making lots of progress! :smiley:

1 Like

Hey @Matoshi!

2. Recursion

Excellent progress! :smiley: … and excellent formatting and indentation!

Your code works and you’ve used recursion :+1:
I also like that you have obviously tried to work it out for yourself and adapted your own version — this is a great way to learn.

Just to put the finishing touches to your program…there are actually a couple of redundant pieces of code that don’t really added anything, which you can remove. There is no need to have two separate branches, with further sub-branches, based on the condition n >= 0 . You can achieve the same thing with just one set of branches, starting directly with…

if (n == 0) {...}

See if you can work out for yourself which is the other piece of code you can remove (hint — it’s in your second main branch).

But if you’ve had enough of recursion, and you now just want to leave this exercise with your code as it is, that’s fine, but you should then make sure your second, and final main branch starts with else not else if . It still runs ok as it is, but making that change makes your code more readable and clearer for other developers.

3. Bean Counting:ok_hand:

You’ve got it!
Again, I really like how you’ve experimented and put your own personal touches to the solution.

This while loop condition is performing one additional unnecessary iteration, because word.length counts the 1st letter as 1, whereas the counter starts at 0. It doesn’t make any difference to the letter count because I think the extra iteration checks to see if the letter it’s counting for exists “after” the word has already been iterated through in its entirety; so this will always just add 0 to the letter count. However, get into the habit of coding for the correct number of iterations.

You may just want to change your error message to something like “Not a word or letter”, because at the moment if you input numbers, you get the message “Not a number”! :upside_down_face:

Keep up the great work!.. I’m glad you’re enjoying the challenge :muscle:

1 Like

Hi @cincinnato,

Nice idea, but the exercise asks you to build a function that achieves the same thing as Math.min() but without using it.

Have a look at the suggestions I gave you for approaching these exercises in my post in the Chapter 2 Exercises thread.

  1. You need to call (invoke) the function:
    let n = 50;

    document.write(isEven(n));
    // the value returned from the function is returned here.
  1. Your if condition needs to be enclosed in parentheses.
  2. You need a comparison operator == (not the assignment operator = ) in the if condition.
  3. No = in the return statement:
    return true;
    return false;
1 Like

Hi @realsloth,

Minimum :ok_hand:

Recursion

Your code runs and logs the correct output to the console :+1:

  • You can remove the break statements, as they don’t achieve anything, because a return statement will cause the function body to be exited anyway.

  • Your conditional execution should finish with an else statement. This will also make the last line of your function body more succinct, because the final condition is no longer needed.

However, you haven’t actually used recursion. Recursion is when a function calls itself in order to create the repetition. Instead you’ve used a loop (and you also want to avoid code that risks getting stuck in an infinite loop). Have a look again at the course book to see how to code recursion, and how this is different from using a loop. You will see that by using recursion instead of loops for this exercise, we can achieve a simpler, clearer and more concise solution… although maybe you’ll disagree, which is fine… but it’s a good exercise to practise using recursion anyway :wink:

Most of your code can remain as it is. You just need to think about how to incorporate the recursive function calls — hint: you need to return these function calls.


Also, I can’t remember if I’ve already explained to you how to format your code when you post it here in the forum. Before you type your code, you can 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 is then also easier for you to organise with the correct spacing, indentation, nesting and brackets etc. Your code for the first exercise should end up looking something like this:

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

document.write(mathmin(200001,701));
function testB(x) {
   var n = x.length;
   var y = 0;  /* you need the letter counter variable outside the loop or
                  it keeps resetting to 0 at the start of each iteration */
   for (u = 0; u < n; u++) { //condition needs '<' not '='  //remove ';' !
      if (x[u] == "B") {
         y = y + 1;
      }
   }
   console.log("There are " + n + " letters and " + y + " of them are B.");
}

testB("BBC");
2 Likes

Minimum:

Function min(x, y){

If(x<y)

return x;

else

Return y;

}

Console.log(min(0, 10));

// -> 0

Console.log(min(0, -10));

// -> -10

Recursion:

function isEven(N){

if(N!=0 && N!=1 && N>=2){

N-=2;

isEven(N);

}

else if(N==0){

toReturn = “This is a even number”

}

else if (N==1){

toReturn = “This is an odd number”

}

else{

isEven(-N)

}

return toReturn;

}

console.log(isEven(50));

console.log(isEven(75));

console.log(isEven(-1));

Bean Countring:

function countBs(str){

var count = 0;

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

if(str.charAt(x) === “B”){

count++;

}

}

return (count);

}

console.log(countBs(“BBC”));
//-> 3
function countChar(str, char) {

var count = 0;

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

if(str.charAt(x) === char) {

count++;

}

}

return (count);

}

console.log(countChar(“kakkerlak”, “k”));
//-> 4

1 Like

Minimum:
let Output = function Inputs(a,b){
mini = Math.min(a,b);
return mini
}
console.log(Output(0,-5))

Recursion:
/* Output will be called to get the answer*/
let Output = function isEven(N) {
/* N represent the number users will input*/
N = Math.abs(N)
return (N % 2) == 0;
/* When the user enters a number for N /
/
the program will check if there is a reminder*/
/* no remender means N is even*/
function isOdd(n) {
return (N % 2) == 1;}
/* If there is a reminder than the N is odd*/
function reReturn(N){
return isEven(N - 2)
}
}
console.log(Output(75));

Bean Master:
function countChar(string, char) {
let count = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == char) { count++ }
}

return count;
}

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

}
console.log(countBs(“Barbados”))
console.log(countChar(“Canada”,“a”));

1 Like

function min (x,y){
if (x < y) return x;
else return y;
}
console.log(min(0,10));
console.log(min(0,-10));

1 Like

Minimum

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

Recursion

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

Bean Counting

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

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

Thanks man. Putting the var in the loop is the one big thing I needed to know!

1 Like
  1. even = 0;
    odd = 1;

function isEven(n)
{
if (n == even) {
return true;
}
else if (n == odd) {
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));

1 Like

Minimum

function min(a,b){
if(a<b){
return a;
} else if(b<a){
return b;
}
} console.log(min(400,200));

Recursion

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

Bean counting (credit to Guactoshi!)

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

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

1 Like

I thought the first exercise was asking me to use Math.min, so I have written he code using that and it seems to work!

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

I’m not sure I fully understood the second exercise, but again, my code seems to work even with negative numbers and is shorter than the answer.

function IsEven (a) {return ((a%2==0) || false)};

For the third exercise I had to work back from the answer;

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

MINIMUM

//using Math.min
function min(a, b){
  return Math.min(a, b);
}
console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10

alternatively

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

console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10

RECURSION

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


console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
/*Maximum call stack size exceeded
because the function escapes the condition
N==0 || N==1 as it continues to -infinity
everytime isEven(N-2) is called
*/
//  So to fix this condition 

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


console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
console.log(isEven(-50));
// → true
console.log(isEven(-75));
// → false

BEAN COUNTING

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

  
console.log(countBs("BBC"));
// → 2
console.log(countBs("BBCBBB"));
// → 5
console.log(countChar("kakkerlak", "k"));
// → undefined

/*
Adjust countBs code to accept a 2nd argument which 
chooses what character is to be counted. 
Rename the function countChar. 
To maintain the countBs function utility, 
it can call on countChar(string, "B").
*/

function countBs(string) {
  return countChar(string, "B");
}
 function countChar(string, char) {
  let result = 0;
  for (let index = 0 ; index < string.length ; index ++) {
    if (string[index] === char) {
      result ++
    }
  }
  return result ;
} 

console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4
console.log(countChar("jhs;jvneflvnfv;aejjjhgaeor", "j"));
// → 5


1 Like

Hi @laserkavajen!

Some great coding! :+1:

Bean Counting
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?

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. Your code for the first exercise Minimum fails to execute as it is, due to some errors with capital letters (highlighted below). Your code for Minimum should end up looking something like this:

function min(x, y) {        // amended F => f  (function)
   if(x < y) return x;      // amended I => i  (if)
   else return y;           // amended R => r  (return)
}

console.log(min(0, 10));    // amended C => c  (console)
// => 0

console.log(min(0, -10));   // amended C => c  (console)
// => -10
1 Like

Hi @Kingsman,

You don’t seem to have understood the point of the first two exercises (Minimum and Recursion):
Minimum : The challenge is to create a function that performs the same calculation as Math.min() but without using it. All you’ve done is wrapped Math.min() within an outer “shell” function which doesn’t actually add anything that Math.min() can’t already do on its own.
Recursion : You make it look like you’ve used recursion, but actually you haven’t. You can remove all of this code…

function isOdd(N) {
   return (N % 2) == 1;
}
function reReturn(N) {
   return isEven(N - 2)
}

…and the function Output will still return the correct answer. The above code is redundant, because the lines:

N = Math.abs(N);
return (N % 2) == 0;

… will always return true if it is a positive or negative even number, and false for a positive or negative odd number. And this is because you’ve used num % 2 which doesn’t require recursion to be used. The challenge is use recursion to generate the same functionality as num % 2 but without using it.

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!

And please format your code — it’s very hard to work with :pray:

I’m going to give you feedback on the 3rd exercise in a separate post :slightly_smiling_face:

1 Like

Hi again, @Kingsman,
…I didn’t really need to leave Bean Counter (sorry Bean Master :wink: which I think is a much better name by the way) to a separate post…
…because it’s perfect! :muscle: (apart from the formatting, of course… but I’m sure you’ll work on that for next time :slightly_smiling_face:)