Chapter 3 Exercises

1 -
function returnMin (x, y) {
if (x< y) {
return x;
}
else return y
}
console.log(returnMin(2,8);

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);
}
console.log(IsEven(-76));

3 -
function countBs (string) {
let result = 0;
for (let i = 0; i < string.length; i++) {
if (string [i] == “B”) {
return++;
}
}
return result;
}
function countChar (string, character) {
let result = 0;
for (let i = 0; i < string.length; i++) {
if (string [i] == character) {
result++
}
}
return result;
}
console.log(countBs(“BBC”);
console.log(countChar)“TTTTTTTTTttttTTTTTTT”, “T”));

1 Like

Functions chapter 3 tests.

// Min Function test.

// Create minimum number function

function min(a,b){

if (a<b){ return a;}        // a<b test.
  else if (b<a){ return b;} // b>a test
   else return a;           // a equal b test.

}

console.log(min(0,10)); // output 0

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

console.log(min(5,5)); // output 5

// Recursive isEven function.

function isEven ( number){

if (number==0){ return true;} // number is even

else if (number==1){ return false; } // number is odd
else if (number < 0) return number; // number is negative
else { return isEven ((number -=2));} // recursive loop number-2 (subtract divide loop)

}

console.log( isEven(50)); // output true even number

console.log( isEven(75)); // output false odd number

console.log( isEven(-1)); // output calling number if negative

// Bean Counting.

function countChar( string, char){

let count=0;

for( i=0; i< (string.length ); i++){

if (string[i]==char) { count++}
}

return count;
}

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

1 Like

Minimum function

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

 alert(min(5, 25));
 alert(min(10, 5));

Recursion function:

  function isEven(x){
    if (x < 0) {
      x = Math.abs(x)
    }

    if (x == 0) {
      return true;
    }

    if (x == 1) {
      return false;
    }

    return isEven(x-2);
  }

  var a = prompt("Enter a whole number: ")
  if (a != ""){
    alert("The number is even?\n " + isEven(a));
  }

CountBs function:

function countBs(str) {
  let flagB = 0, i=0;
  while(i < str.length){
    if (str[i] === "B")
      flagB++;
      i++;
    }
  return flagB;
}

alert(countBs(“StarBuck Bubble Tea is Not Bad!”));

CountChar function:

function countChar(str, char) {
  let flagChar = 0, i=0;
  while(i < str.length){
    if (str[i] === char )
      flagChar++;
      i++;
    }
  return flagChar;

alert(countChar(“StarBuck Bubble Tea is Not Bad!”, “b”));

1 Like

Help Please @Malik & @thecil (thanks guys :pray:)

So i’ve written this which is correct in the console.log …

function countBs(str, letter)
{
var letter_Count = 0;
for (var position = 0; position < str.length; position++)
{
if (str.charAt(position) == letter)
{
letter_Count += 1;
}
}
return letter_Count;
}

console.log(countBs(“I am BBBBBBad”, “B”));

But my question is… How can i add in a prompt so users enter a phrase with B’s which then is outputted as a alert ?
I wrote the below but can’t seem to figure out how the phrase entered can then enter the function defining str and length ?

var word = prompt(“enter a phrase with capital B’s”);
var saved = “word”;

      function countBs(str, lenght)
      {
       var letter_Count = 0;
       for (var position = 0; position < str.length; position++)
       {
          if (str.charAt(position) == letter)
            {
            letter_Count += 1;
            }
        }
        return letter_Count;
      }

      var answer = countBs(saved, "b");
      alert("the number of B's is " + answer)

Hi @JDW,

You can mention your user input as I show below.

function countBs(str, lenght)
     {
      var letter_Count = 0;
      for (var position = 0; position < str.length; position++)
      {
         if (str.charAt(position) == letter)
           {
           letter_Count += 1;
           }
       }
       return letter_Count;
     }

     var answer = countBs(saved, "b");
   // prompting user
    var userInput =  alert("Enter input" );
     alert("the number of B's is " + answer)

Hope this helps.

Happy learning. :slight_smile:

in exercise 2 i don’t understand what this statement is referring to or why it allows the function to return true or false for other numbers entered into it, what’s the logic i’m missing here?: For any other number N, its evenness is the same as N - 2.

can someone explain it to me please? Why is it necessary to -2, why can’t the function recognise the number without doing this??

thanks @Malik … i’ll go through this later on after I’ve finished the current exercise i’m on :+1:

1 Like

Minimum

var x = myFunction(624, 4000);
function myFunction(a, b) {
return Math.min(a, b);
}
console.log(x);

Recursion - not quite Boolean

let x = isEven(71);
function isEven(n) {
if (n == 0) {
return “True”;
}
else if (n == 1) {
return “False”;
}
else if(Number.isInteger(n/2)) {
return “True”;
}
else {
return “false”;
}
}
console.log(x);

Real Boolean
let x = isEven(71);
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(x);

1 Like

Min

function min(a,b){
var c = Math.min(a,b);
return c;
}
var small = min(12,3);
console.log("smallest num is: " + small);

Recursion
function isEven(a){
if(a%2==0)
return console.log(true);
else if(a<0)
return console.log(“Negative num!!”);
else return console.log(false);
};

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

Bean Counting
//function one

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

//function two

function countChar(string, letter){
var count = 0;
for(var i = 0; i<string.length; i++){
if(string[i] == letter) {
count++;
}
}
return count;
}
countChar(“BigBird”, “i”);

1 Like
//Minimum
function min(number1, number2){
  if(number1<number2)return number1;
  else return number2;
}
//Recursion
function isEven(number){
  if(number==0)return "true";
    else if(number==1)return "false";
    else if(number<0)return isEven(-number);
    else return isEven(number-2);
  }
//Bean counting
function countBs(str){
  let count = 0;
  for(let a=0; i< str.length; a++){
    if(str[a]==="B"){
      count++;
    }
  }
  return count;
}

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

I’am not sure about the last one because i’ve done it with a help of yt and internet

1 Like

The approach is right but you forgot to define the variable "i".

Other than that its good to go! :smiley:

  1. MINIMUM
    Write a function “min” that takes two arguments and returns their minimum.

ANSWER:
let a = prompt(“What is a?”);
let b = prompt(“What is b?”);
console.log(min(a, b));

function min(a, b) {
if (a < b){return a}
else if (a > b){return b}
else if (a = b){return null}
}

  1. RECURSION
    Define a recursive function “isEven” correspending to the description in the book. The function should accept a single parameter (a positive, whole number) and return a Boolean. Make it work for negative numbers as well as positive.

ANSWER:
function isEven(N){
if((N == 0) || (N == 1)){
return (N==0)
}
else if (N < 0){
return (isEven(N + 2))
}
else {
return (isEven(N - 2))
}
}
console.log(isEven(//INPUT NUMBER HERE//))

  1. BEAN COUNTING
    First, write a function “countBs” that counts the number of “B’s” in a given string.
    Second, write a function “countChar” that counts the number of any given letter in any given string.

FIRST ANSWER:
let N = prompt(“Enter a word!”);

countBs(N);

function countBs(N) {
let Bs = 0;
for (i = 0; i < N.length; i++){
N[i];
if (N[i] == “B”){
Bs++
}
else {
continue;
}
}
console.log(output);
}

SECOND ANSWER:
let N = prompt(“Enter a word!”);
let B = prompt(“Enter a letter!”);

countChar(N, B)

function countChar(N, B) {
var Bs = 0;
for (i = 0; i < N.length; i++){
N[i];
if (N[i] == B){
Bs++
continue
}
else {
continue
}
return Bs;
}
console.log(Bs);
}

1 Like

Minimum

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

Recursion

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

Bean counting

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

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

Chapter 3
Exercises:
Functions
EXERCISE 1:
var min = function(x, y) {
return (x <= y) ? x : y;
};
//test//
console.log(min(0, 10));
//→ 0
console.log(min(0, -10));
// → -10
console.log(min(4, 4));
// → 4

#EXCERCISE 2:
Recursion

var isEven = function(num) {
num = Math.abs(num);
if (num === 0)
return true;
else if (num === 1)
return false;
else return isEven(num - 2);
};
//tests
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
console.log(isEven(-10002));
// → true

#EXERCISE 3:
Bean Counting

var countBs = function(str) {
return str.match(/B/g).length;
};
var countChar = function(str, character) {
var matchExp = new RegExp(character, ‘g’);
return str.match(matchExp).length;
};
//the old fashioned way
var countChar2 = function(str, character) {
var count = 0; for (var i = 0; i < str.length; i++) {
if (str[i] === character) count++; } return count;
};
//tests
console.log(countBs(‘BBC’));
// → 2
console.log(countChar(‘kakkerlak’, ‘k’));
// → 4
console.log(countChar2(‘kakkekekkkkkkkekrlak’, ‘k’));

2 Likes

Hi all,

does exist some tool to calculate “computation power cost of code”? I have two solutions for exercise two, one solution with recursive function and second solution with loop. I would like to compute which solution is more cost effective (in other words which solution takes less of computation power and is therefore quicker). It is possible that both solutions are the same. I haven’t find anything on google till now.

Solution 1 with recursion:

          else {
            return evenOdd(x-2);
          }

Solution 2 with loop:

          else {
              for (i=0; i<x/2; i++) {
                 x = x-2;
              }
           }

Edit: I have found this

var t0 = performance.now()

doSomething()   // <---- The function you're measuring time for 

var t1 = performance.now()
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

Which is cool and does work. However is there something to calculate the amount of steps?

Minimum (Option 1)

	function min(value1, value2){
			return Math.min(value1, value2);
		}

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

Minimum (Option 2)

		function min(value1, value2){
			if (value1 < value2) {
				return value1
			} else {
				return value2;
			}
		}

		console.log(min(10,20));
                // 10

Recursion

function isEven(n) {

					//what if the input is negative
					if (n < 0) {
						// make n not negative
						//assuming that n is negative (n = -n):
						n = -n;
						// I could also write n = Math.abs(n)
					}

					// if n is 0
					if (n === 0) {
						return true;
					}

					// if n is 1
					if (n === 1) {
						return false;
					}

					// in all other cases, apply isEven to (n - 2)
					return isEven(n - 2);

				}

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

Bean Counting

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

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

			// return result
			return result;
		}

		function countChar(string, character) {
			// create a result, set to 0
			let result = 0;

			// loop over the string
			for (let i = 0; i < string.length; i++) {
				// if current character is matches input character
				if (string[i] === character) {
					// increment our result by 1
					result = result + 1;
				}
			}

			// return result
			return result;
		}

		console.log(countBs("BBBBcBBC"));
		console.log(countChar("Francine", "n"));
1 Like

Yes, usually developers check how much time each function call takes and then measure with others. There are libraries that help you calculate time lesser than a millisecond but i guess milliseconds are good enough.

Hope this helps.

  function countChar(word,char){

    var x = word.length;
    var letter;
    var count = 0;

    for(var y=0; y<x;y++){
      letter=word[y];
      if (letter===char){count++;}

    }

    return count;


  }

  alert(countChar("Counting Beans","n"));
1 Like

// I. Minimum.

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

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

// II. Recursion.
var isEven = function(num) {
num = Math.abs(num);
if (num==0)
return true;
else if (num===1)
return false;
else
return isEven(num - 2);
};

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

// III. Bean counting

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

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

function countChar (str, char) {
var count = 0;
for (var i = 0; i < str.length; i++){
if (str.charAt (i) === char) {
count++;
}
}
return (count);
}

console.log(countChar(“kakkerlak”, “k”));

1 Like

MINIMUM EXERCISE

    // Function definition        
    function minNum (a,b) {
      if(a<b) {
        return a;
      } else {
        return b;
      }
    }

    // Example of application
    console.log(minNum(2,9);

RECURSION EXERCISE

      // Function defintion: it works also for negative integers
      function isEven(num) {
              if(num == 0) {
                return true;
              } else if (num == 1) {
                return false;
              } else if (num < 0) {
                return isEven(num+2);
              } else {
                return isEven(num-2);
              }
      }

      // Example of application
      console.log(isEven(-5));

BEAN COUNTING EXERCISE

       // countChar function definition
      function countChar(word,character) {
        var sum=0;
        for(i=0;i<word.length;i++) {
          if(word[i]==character) {
            sum++;
          }
        }
        return sum;
      }

      // countBs function definition
      function countBs(text) {
        return countChar(text,"B");
      }

      // Example of application
      console.log(countBs("Barber));
1 Like