Chapter 3 Exercises

I definitely still have a misunderstanding in exercise 2 the recursive isEven function.

So after a few days I got fed up and looked up the solution. Given this solution:

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

What I am confused about is the last line of code (else return isEven(n-2);). The confusion lies in the call stack computations of n values. If I input 40, what does this line of code do with 40 to return a value of true? I suppose the n-2 condition is what I’m most confused about. Can anyone help explain what happens? Please and thank you !

1.Minimum
let num1 = Number(prompt(“Give a number”));
let num2 = Number(prompt(“Give another number”));
const Least = function (x, y) {
if (x < y) return x;
else return y;
};
document.write("The lowest number is: " + Least(num1, num2));

  1. let number = Number(prompt(“Give a positive whole number”)), toWrite;
    isEven(number);
    document.write(toWrite);
    function isEven(x) {
    if (x === 0) toWrite = true;
    if (x === 1) toWrite = false;
    if (x > 1) isEven(x - 2);
    if (x < 0) isEven(-x);
    }

  2. let string = String(prompt(“Enter string please”)), toFind = “”, char, countS = 0, countC = 0;
    while (toFind.length !== 1) {
    toFind = String(prompt(“Give a single character to count in the string”));
    }
    countBs(string);
    countChar(string, toFind);
    document.write("Found " + countS + " B’s in string.<br>Found " + countC + " " + toFind + “'s in string.”);
    function countBs(str) {
    for (i = 0; i < str.length; i++) {
    char = str[i];
    if (char === “B”) countS++;
    }
    }
    function countChar(str, chr) {
    for (i = 0; i < str.length; i++) {
    char = str[0];
    if (char === chr) countC++;
    }
    }

     //2th version of countBs
     function countBs2(str) {
         return countChar(str, "B");
     }

Answer for the minimum excercise

<body>

  <form id="form0">
  Number 1: <input name="name" type="number" size="20">
  </form>
  <br>

  <form id="form1">
  Number 2: <input name="name" type="number" size="20">
  </form>
  <br>

  <form>
    <input type="button" value="Min" onclick="alert(minimum())">
  </form>


<script>

function minimum(){
let x = [];
x[0] = document.getElementById(“form0”)
x[1] = x[0].elements[“name”].value;
x[2] = document.getElementById(“form1”);
x[3] = x[2].elements[“name”].value;

return Math.min(x[1], x[3]);
}

So if n is 40 and we run the function we check against all 4 conditions.

Obviously, we do not meet the first 3 conditions but we meet the last.

What happens on the last condition is that n becomes 38 (40 - 2). The function is then called again.

The process repeats until n is either ==1 or ==0.

Starting with 40 the function will loop around 20 times -2 each time until 40 has reduced to 0, we will then hit the “true” condition on the first condition.

I understood this recursion by thinking of it like a for loop. As the function is self-calling it causes it to make a change then start again at the top.

Hope that makes sense, ask if not.

Recursive Funtion isEven

let input = prompt(“Please enter a number”);

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); // interestingly the function runs backwards if the return is ommited from this line
}

}

document.write(isEven(input));

Character Counting

let input = prompt("Enter a string");
let charToCount = undefined;

function countChar(){
  let x = prompt("Enter the character you would like to count, this is case sensitive");
  return x;
}

function countBs(x){
  let Bs = 0;
  charToCount = countChar();
  for (counter = 0; counter < x.length; counter++){
    if (x[counter] === charToCount){
      Bs++;
    }
  }
  return Bs;
}

document.write("There are " + countBs(input) + " iterations of the character \"" + charToCount + "\" in the string you entered.");

Exercises – Chapter 3 in the book EloquentJavaScript

1. MIN FUNCTION

var k1 = 100, k2 = 201;

var ans = Math.min(k1, k2);

document.write(“Min is: ” + ans);

//will return : Min is 100.

2. RECURSION ODD or EVEN Number

for(i = 0; i <= 20; i++) {

if (i === 0) {

document.write(i + “ “ + “is EVEN”);

document.write(“<br/>”)

}

else if (i * 2 === 0){

document.write(i + “ “ + “is EVEN”);

document.write(“<br/>”);

}

else {

document.write(i + “ ” + “is ODD”);

document.write(“<br/>”);

}

}

3. BEAN COUNTING

function countBs(myString){

return countChar(myString, “B”);

}

function countChar(myString, charater) {

let count = 0;

while (myString.length > 0) {

if (myString.chart(0) == character) count++;

myString = myString.substr(1);

}

return count;

}

Console.log(countBs(“Blackberry Blue Baby!”));

Console.log(countChar(“SpriNg Pickle BegiNNiNg.”, ‘N’));

//will return 4 Bs and 4 Ns

Minimum

function isMinimun(x,y){
if(x<y) document.write(x + " is the minimun");
else document.write(y + " is the minimun");
}

Recursion

function isEven(number){
if(number%2==0) document.write(“number is even”);
if(number%2==1) document.write(“number is odd”);
if(number<0) document.write(“number cannot be less than zero ‘0’”);
}

Bean Counting

let stringTest=“BFBRF”;
let target = “B”;
function countBs(stringOfCharacters, targetChar){
let result = 0;
for(let i=0;i<stringOfCharacters.length;i++){
if(stringOfCharacters[i]==targetChar) {
result++;
}
}
return result;
}

1 Like

I was confused with RECURSION and googled a lot about it …
Now, I would like to share some pages solved my puzzle of “FACTORIAL” & RECURSION

Hope these pages can help :wink: cheers ! :beers:

  1. Why is 0! = 1?
    https://www.youtube.com/watch?v=X32dce7_D48

  2. Learn and Understand Recursion in JavaScript
    https://codeburst.io/learn-and-understand-recursion-in-javascript-b588218e87ea

:beers: :tada:

Here are my answers to Chapter 3 problems:
Minimum:

let min = function (a,b){
if (a < b){
return a;
}
else if
(b < a){
return b;
}
};
console.log(min(102,94));
// 94

Recursion:

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

console.log (isEven(75));
//false

Bean Counting Part 1:
//Question 3 Part 1
function countBeans(input){
let count = 0;
for(i=0; i<input.length;i++){
if(input[i] == “B”){
count +=1;
}
}
return count;
}
console.log(countBeans(“ByeByeBubba”))
//3

Bean Counting Part 2:

//Question 3 Part 2
function countChar(input,letter){
let count = 0;
for(i=0;i<input.length;i++){
if(input[i] == letter){
count +=1;
}
}
return count;
}
console.log(countChar(“crazyzebraszappizzas”, “z”));
// 5

minimum

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

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

bean counting

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

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

]

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

]
}

  1. Minimum
    function min(a,b) {
    if (a < b) return a;
    else return b;
    }
    console.log(min (0, 10));
    console.log(min (0, -10));

  2. Recursion
    var odd = 1;
    var even = 0;
    function isEven(N){
    if((N - 2) % 2 == even){
    return true
    }
    else {
    return false
    }
    }
    console.log(isEven(50));
    console.log(isEven(75));
    console.log(isEven(-1));

  3. Bean counting
    function countChar(string, char) {
    let count = 0;
    for (var i = 0; i < string.length; i++) {
    if (string[i] == char) {
    count++;
    }
    }
    return count;
    }
    function countBs(string) {
    return countChar(string, " ");
    }
    console.log(countChar(“Something to realize”,“e”));

1 Like

Function 3

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

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

1 Like

With some shame: copied from the resolved link:

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

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

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

  1. 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(“BBC”));
// → 2
console.log(countChar(“kakkerlak”, “k”));
// → 4

1 Like

Hello Community,

1.) Minimum

function getMinimum(first, second) {
        return Math.min(first, second);
}

var alpha = 10;
var beta = 2;

document.write(getMinimum(alpha, beta));

2.) Recursion

function isEven(input) {
     if(input % 2 === 0) {
          return true;
     } else if (input % 2 === 1) {
         return false;
     } else if (input < 0) {
          // Inverese the negative.
        return isEven(-input);
     } else {
         return input - 2;
     }
}
document.write(isEven(50) + “<\br>”);
document.write(isEven(75) + “<\br>”);
document.write(isEven(-9) + “<\br>”);
document.write(isEven(-10) + “<\br>”);

3.) Bean counting

var myString = “Busted boobs! Be aware!”;
var criteria = “B”;
var myResult = 0;

     for (var i = 0; i < myString.length; i++) {
          if(myString[i] === criteria) {
              myResult++;
     }

}
document.write("Count of ‘B’ in ‘myString’: " + myResult);

Minimum

const minNum = (num1, num2) => {
  if (num1 >= num2) {
    return num1;
  }
  else {
    return num2;
  }
};

Recursion

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

For the follow up question of using a negative number, we can circumvent it by converting any input parameter to the absolute value. Math.abs function can be used to improve the code and enable acceptance of negative whole numbers, i.e.:

function isEven(N) {
	let M = Math.abs(N);
	if (M == 0) {
		return true;
	}
	else if (M == 1) {
		return false;
	}
	else {
		return isEven(M-2);
	}
}

Bean Counting
Considering no pre-defined functions, I could write countBs function as:

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

Function looking for a specific character/s in a string by inputting 2 parameters can be written like:

function countChar(string,look){
    let lookCount = 0;
    for (let charCount = 0; charCount < string.length; charCount += 1){
        if(string[charCount] == look){
            lookCount += 1;
        }
    }
    return lookCount;
}

Now, if this function has been defined already before countBs, then I can write a shorter code for countBs:

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

Dear All,
I tried to do the bean counting function and when I saw it not working I came to check here and I don’t see huge differences.
When checking which part doesn’t work, it looks like the word.lenght doesn’t work (if I put the lenght manually, the function works perfectly, however both in the book and here I see it used in the same way).

What am I doing wrong?
Thanks

  //Bean Counting excercise
  function countChar (word, char){
    var lenghtStr = word.lenght;
    var count = 0;
    var NoChar = 0;
    for (var count =0; count < lenghtStr; count++){
      var char1 = word[count];
      if (char1 == char){
        NoChar ++;
      }
    }
    return NoChar;
    //return word.lenght;
  }

  document.write (countChar ("BeBbB","B"));

FORGET ABOUT IT… just misspelled lol :smiley:

1- Minimum

var toPrint="#";
var colomn=0;
function min(number1, number2){
if (number1<number2)
return number1;
else {
return number2;
}
}

document.write(min(1,100));

2- Recurstion

function isEven(number){

if(number !=0 && number != 1)
return isEven(number-2);
if (number == 0)
return “even”;
else if (number == 1){
return “odd”;
}

}
var num;
do{
num=prompt(“enter a number a positive number”);
}while(num < 0)

document.write(" the number " + num + " is " +isEven(num)) ;

3- Benounting
CountB==>
function countBs(stringInput){
var stringTyped=String(stringInput);
var charcter,index=0;
for(var count=0;count != stringTyped.length; count++){
character=stringInput[count];
if (character==“B”){
index=index+1;
}
}
return index;

}

CountCharacter
function countCharacter(stringInput,charcterInput){
var stringTyped=String(stringInput);
var charcter,index=0;
for(var count=0;count != stringTyped.length; count++){
character=stringInput[count];
if (character==charcterInput){
index=index+1;
}
}
return index;

}
var strin=prompt(“enter a string “);
var character=prompt(“enter the character that need to be counted”);
document.write(”
the numbers of =”+ character+"= that are on the entered string " + strin + " are " + countCharacter(strin,character)) ;

EXERCISE 1

var min = function(x,y) {
return (x<=y) ? x : y
};

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

EXERCISE 2

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

EXERCISE 3

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

console.log(countBs(‘BBC’));
console.log(countChar(‘kakkerlak’, ‘k’));

RECAP
I kind of get the first part about the min function and the use of ? and : to denote an if else function in an abbreviated. I also see the parallels between the console.log query and the function.

Now when I got to Exercise 2 is when I really got confused. Does num-2 regular make it a recursion? Like it’ll keep doing -2 till it gets to 0 or 1? That’s what I read online. Ooph.

And Exercise 3. I do see the console.log and function parallels, but I don’t get the annotation of string matches and length yet. I looked it up and I get the logic of what they’re doing, but I don’t understand why it’s annotated as such.

But at least I do see the parallels between the console log queries and the functions themselves in terms of their tagged structure. I don’t know if this really means I understand it though. :confused: