Chapter 3 Exercises

  1. Minimum
function min(n1,n2){
          if (n1 == n2){
            console.log("Please give two different numbers...");
          }else if (n1 > n2){
            return n2;
          }else return n1;
          }
  1. Recursion
function isEven(n) {
  if (n == 0) return true;
  if (n == 1) return false;
  if (n < 0) return isEven(-n);
  return isEven(n - 2);
}
console.log(isEven(40));
console.log(isEven(65));
console.log(isEven(-5));

3. Bean Counting


function countChar(string, char) {
let str = String(string),
count = 0;

for (i = 0; i < str.length; i++) {
	if (str[i] === char) {
		count++;
	}
}

return count;

}

function minime( x, y ) {
return Math.min(x,y);
}

    // a stupidly recursive program
    // input can only be non negative integers
    function isEven( x ) {
        if ( x == 0 ) {
            return "even steven";
        } else if ( x == 1 ) {
            return "odd ball";
        } else {
            return isEven( x - 2);
        }
    }


    // a stupidly recursive program that handles negative numbers. 
    // input can only be any integer  -- dont get real!
    function isEvenClean( x ) {
        var xclean = Math.abs(x);
        if (xclean == 0 ) {
            return "even steven";
        } else if ( xclean == 1 ) {
            return "odd ball";
        } else {
            return isEven( xclean - 2);
        }
    }

    function countBs(str ) {
        var n = 0;
        for(var i=0; i < str.length; i++)
        {
            if (str[i] == 'B' ) {
                n++;
            } 
        }

        return n;
    }

    function countChar(inputStr, characterToCount ) {
        var n = 0;
        for(var i=0; i < inputStr.length; i++)
        {
            if (inputStr[i] == characterToCount ) {
                n++;
            } 
        }

        return n;
    }
  
    var daSmallerOne = minime( 2, 3 );
    document.write("the smaller one is " + daSmallerOne + "<br>");

    document.write("50 is an " + isEven(50) + "<br>");
    document.write("75 is an " + isEven(75) + "<br>");

    document.write("-15 is an " + isEvenClean(-15) + "<br>");

    var str1 = 'adsBfdecBvb122B32dcvtgtyh';
    document.write(` number of 'B's in '${str1}' is ` + countBs(str1) + "<br>");

    str1 = 'ad#sBfd#ecBvb12#2B32dcv#tgtyh';
    document.write(` number of '#'s in '${str1}' is ` + countChar(str1, "#")+ "<br>");
1 Like

Hi @muradawad,

I see that your Recursion exercise answer does not use any recursion itself. Can you please provide the correct answer for this.

Regards
A.Malik

1 Like

image
image
image

Console.log output:
image

1 Like

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

1 Like

1.Minimum:

function min(a , b){
     if (a == b) return ("These are the same value!");
     if (a < b) return a;
     else return b;}    
  1. Recursion:
function isEven(n){
  if (n % 2 == 0)
return true;
else return false;}


  1. Bean Counting:
    Part 1:
function countBS(str){
let count = 0;
for (let i = 0; i < str.length; i++){
if (str[i] == 'B'){
count++;
}
}return (count);}

Part 2:

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

Greetings sir,

I think there’s a little confusion, the above answer for the recursion exercise does not have recursion in it. Could you redo this exercise and post it here on the forum.

If any doubts or question please feel free to ask them in the forum.

Happy Learning! :slight_smile:

1 Like

Oh ok. Here is my updated answer:

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

Hi @Jesus,

This answer does not have recursion in it as well.

You can take reference from the above student answers to get a gist of it.

Happy Learning! :slight_smile:

1 Like

Minimum

function min(x,y){
if (x<y)  return x;
else return y;
}
var answer = min(25,50)
alert(answer)

Recursion
I don’t fully understand how this works.

function isEven(n){
if (n==0)return "even";
else if (n==1) return "odd";
else return isEven(n - 2);
}
console.log(isEven(10))

Bean Counting
I don’t understand this at all.

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

I’m also very new to this but I’ll give it a shot and try to explain it.
basicaly we are trying to determine if a given number is odd or even. We know that 1 is the lowest odd number and 0 is the lowest even number.
So we are going to reduce the given number with 2 until we obtain 0 or 1 as a result.

for example we want to know if 3 is odd or even:

function isEven(n){                   // 1st cycle: n=3.                   2nd cycle: n = 1
if (n==0)return “even”;             // 1st cycle: 3 != 0. skip      2nd cycle 1 != 0. Skip
else if (n==1) return “odd”;      // 1st cycle: 3 != 1. skip      2nd cycle 1=1 return "odd"
else return isEven(n - 2);        // 3 - 2 = 1 --> returning isEven(1)
}

I hope this makes it abit more clear.

2 Likes
// FUNKCJA MIN
  function min(number1, number2) {
      if (number1 === number2) {return number1;}
      else if (number1<number2) {return number1;}
      else {return number2;}
  }


  // FUNKCJA isEven

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

  // FUNKCJA count

  function countBs(string) {
    let counter = 0;

    for(let n = 0; n < string.length; n++) {
      if (string[n] == "B") {counter += 1}
    };

    return counter;
  }

  function countChar(string, char) {
    let counter = 0;

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

    return counter;
  }

  function countBs2(string) {
    return countChar(string, 'B');
  }
1 Like

Exercise 1)
I originally read the question wrong and made

function solve() {
    alert(Math.min(3, 2));
  }
console.log(solve())

Then i made:

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

I guess they both do the same thing in a way, but the first wasn’t the correct way to get the outcome.

Exercise 2)
My first attempt was (below), and i was really confused to start out with

function isEven(n) {
  if (n % 0 === 0) {
    return "even";
  }
  else if (n % 1 === 0) {
    return "odd";
  }
  else if (n % n - 2) return "?";
}
console.log(isEven(75));

Then i found out (below) was the answer. I thought we had to use the “%” operator in the formula, how exactly does the “==” calculate the remainder? Struggling to understand how this formula is working. Any suggestions on how to understand - should i reread and re-watch the videos?

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

Exercise 3)
Again, quite confused (my attempt below). Why is ‘ch’ in the formula? Not sure how I’m meant to understand it - any suggestions?

function countBs(a) {
  var bCounter = countBs(a[B]);
  for (var i = 0; i < bCounter.length; i++);
  return i;
}
console.log(countBs("BB"));

Edit ~
I took a little look at other people’s answers and how they arranged the formula and now i kind of understand the logic behind it. I then made this:

function countBs(string, stringChr) {
  counter = 0;
  for (var i = 0; i < string.length; i++) {
    if (string[i] === stringChr){
      counter++;
    }
  }
  return counter;
}
console.log(countBs("BBBB", "B"));
2 Likes

really good explanation !

1 Like

thanks sir :slight_smile:

MINIMUM:

              function min(x,y){

                if (x<y) return x;

                else return y;
              }

              var answer = min(3,7);
              alert(answer);

ISEVEN:

  function isEven(x){
                while (x>1) {
                  x=x-2
                }

               if (x==0) return true;

                else if (x==1) return false;
                else if (x<0) return "negative number";


              }

              var answer = isEven(-4);
              alert(answer);

BEANCOUNT:

              function countBs(word, char){
                var counter = 0;
                for (i=0;i<word.length;i++){
                if (word[i]==char);

                {
                  counter++;
                
                }
              }
              return counter;
              }
            alert(countBs("BOBBY","B"));
1 Like

Missing the countChar adaption, will just continue on at this point, have read someones answer & understand & would have got there, however I am needing to progress on.

1 Like

This really helps a lot, Joey. Thank you!

You are welcome. Glad I could help :slight_smile:

1 Like

I don’t have any prior experience so it’s much harder to grasp some of these concepts.
Thanks again for breaking it down!

Did you dump hours and hours into trying to figure out these exercises?
They were crazy difficult, I thought.