 # Chapter 3 Exercises

Let’s discuss the exercises from Chapter 3 here. You can find the answers here: https://eloquentjavascript.net/code/#3

11 Likes

## Function 1 / Calculate Smaller Example

``````function fnCalcMin(c,d){
return Math.min(c,d);
}
document.write("Smaller from 4 and 7 is >> " + fnCalcMin(4,7));
document.write("<br>");
document.write("Smaller from 10 and 2 is >> " + fnCalcMin(10,2));``````

## Function 2

``````function isEven(num) {
//convert to absolute value to account for negative numbers
num = Math.abs(num);
if (num === 0)
return true;
else if (num === 1)
return false;
else
return isEven(num - 2);
}
document.write("50 >> " + isEven(50) + "<br>");
if (isEven(50) == true) {document.write("its even! <br><br>");} else {document.write("its odd! <br><br>");}
document.write("75 >> " + isEven(75) + "<br>");
if (isEven(75) == true) {document.write("its even! <br><br>");} else {document.write("its odd! <br><br>");}
document.write("-1 >> " + isEven(-1) + "<br>");
if (isEven(-1) == true) {document.write("its even! <br><br>");} else {document.write("its odd! <br><br>");}``````
1 Like

## functions 3 / Bean Counting

``````function countBs(str) {
return str.match(/B/g).length;
}
function countChar(str, character) {
var matchExp = new RegExp(character, 'g');
return str.match(matchExp).length;
}
function countChar2(str, character) {
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] === character)
count++;
}
return count;
}
document.write("B comes in BCC >> " + countBs('BBC') + " times<br>");
document.write("k comes in kakkerlak >> " + countChar('kakkerlak', 'k') + " times <br>");
document.write("k comes in kakkekekkkkkkkekrlak >> " + countChar2('kakkekekkkkkkkekrlak', 'k') + " times <br>");``````
1 Like
1. Minimum
2. Standard functions are pre-build in JavaScript, but this questions asks you to recreate the math.min standard function.

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

By creating a function called min and have it take two input parameters, these are the two input values it will take. Then, those two values, are transformed through an if-else statement. If x is less than y then the number returned will be x. Else the number returned is y.

If we now ask the console

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

will return

``````0
``````

and

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

will return

``````-10
``````

3. Recursion
4. In the next question you are asked to create a recursive function named isEven. The function should have a single input parameter and return a Boolean .

The first line created should look something like this.

``````function isEven(n)
``````

The function's codeblock is then to have the following definition for an even number: If the number is zero then it is even, the number 1 is odd, and any other number it's evenness is the same as the input number minus 2.

The following if-else statements could be created inside the function’s code block.

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

In this solution the first two lines create the general argument for what is even. If n is equal to zero it is even and returns true. If it is equal to 1 the function returns false. In the third line the magic is made, where the function call on itself iterating the number decreased by 2. No mater how big the number is it will iterate until it is decreased to either 1 or zero.

The question also specified to restrict any negative numbers being imputed and a way to fix this? By placing an additional else-if statement where if n is less than zero (and thus negative) the it will call upon itself again but with the negative of the input number.

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

The final code looks like this.
``````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);
}
``````

5. Bean counting
6. This question asks to create a function called countBs that takes a string as it's only argument and returns a number that indicates how many uppercase "B" characters are in the string. The first line should look like this.

``````function countBs(string)
``````

Now for the code block logic. We first create a variable called count and make it equal to zero. We use let since we want to restrict the variable to the scope of the function. Inside the function we create a for loop with an initial iteration value of 0 (to start with the first character in the string, in the zero position). The for loop will continue until it is less than string.length (which means it will stop at string.length minus 1). Inside the for loop we make an if statement, that if the character of string in i position is equal to the character b, then increase the count by 1.

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

Now the question asks to create a function called countChar that behaves like countBs but it takes a second input paramater which is the character you are trying to count. In the if statement we change "B" to the character variable. which I chose as char.

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

We can now remodel countBs to invoke the function countChar with the second input parameter as "B".

``````function countBs(string) {
return countChar(string, "B");
}
``````
28 Likes
``````  var num1 = 20;
var num2 = 50;
function minime(x, y) {
if (x<y) {
return x;
}else if (x>y) {
return y;
}else {
return "Same number";
}
}
document.write("<h2>Min(" + num1 + "," + num2 + "):  " + minime(num1, num2) + "<h2>");
``````

hi @javedkhalil, i used your same solution but for some reason when you use a very large number, e.g. 10000000 it doesn’t work, /I think maybe the browser just quits the function after several attempts.

Minimum

``````  var num1 = 20;
var num2 = 50;
function minime(x, y) {
if (x<y) {
return x;
}else if (x>y) {
return y;
}else {
return "Same number";
}
}
document.write("<h2>Min(" + num1 + "," + num2 + "):  " + minime(num1, num2) + "<h2>");
``````

Recursion

``````      var number = prompt("Number please:");
var msj = isEven(number);
document.write(msj);
function isEven(x) {
if (x == 0) {
return ("Even");
}else if (x == 1) {
return ("Odd");
}else if (x < 0) {
return isEven(-x);
}else {
return isEven(x - 2);
}
}
``````

Bean counting

``````var str = "B + + +sws BBB dqdBBB";
var search = "B";

function countUpper(stri, lett) {
var count = 0;
for (var i = 0; i < stri.length; i++) {
if (stri[i] === lett) {
count += 1;
}
}
return count;
}``````

Exercise 1
function min (var1, var2) {
if (var1 > var2) { return (var2); }
else { return (var1);}
}

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

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

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

2 Likes

Function1

function min(a, b){
var minimum=0;

``````         if(a == b ) {console.log("idem");
minimum=0;}
else if(a < b ){minimum=a;}
else{minimum=b;}

return minimum;
}
``````

1 Like

Function2

``````        function isEven(number){

if(number > 0){
if(number == 0){test = true;}
else if(number == 1){test = false;}
else{
number = number-2;
isEven(number);}
}
else{
if(number == 0){test = true;}
else if(number == -1){test = false;}
else{
number = number+2;
isEven(number);}
}

return test;
}

var nbr=-5;
var test;
var even = isEven(nbr);

if(even == true){alert("The number " + nbr + " is even");}
else {alert("The number " +nbr+" is odd");}``````
1 Like

Function3

function countBs(word){

``````          var n = word.length;
var letter;
var count = 0;

for( var i = 0 ; i < n  ; i++ ){

letter = word[i];

if(letter == "B" ){count++ ;}

}

return count;
}

1 Like

Minimum

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

Using the mighty ternary operator. The longer `if`/`else` variant with two return statements, as suggested in the book solutions is probably more readable for most people though.

Recursion

``````function isEven(num) {
if (num < 0) num = -num; // remove negative sign
switch (num) {
case 0: return true;
case 1: return false;
default: return isEven(num-2);
}
}
``````

Unfortunately the negative case can’t be represented in a `switch`/`case` construct, hence I needed an `if`-clause before enforcing positive numbers. The more obvious solution again would be to only use `if`/`else if`/…/`else` blocks as suggested in the book solution.

Bean counting

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

function countBs(str)
{
return countChar(str, 'B');
}
``````

Pretty straight-forward.

1 Like

Minimum:

``````function returnMin(x,y){
if(x<y){
return x;
}
else return y;
}
console.log(returnMin(8,4));
``````

Recursion:

``````function isEven(N){

if(N!=0 && N!=1 && N>=2){
N-=2;
isEven(N);
}
else if (N==0){
toReturn = "This is an even number"
}
else if (N==1){
toReturn = "This is an odd number"
}
else {
isEven(-N);
}

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

Bean Counting:

``````function countBs(aString){
let stringLength = aString.length;
let numOfBs=0;
for(i=0;i<stringLength;i++){
if(aString[i]=="B"){
numOfBs+=1;
}
}
return numOfBs;
}

console.log(countBs("Bavarian beer for Beerfest"));

function countChar(newString,aChar){
let stringLength = newString.length;
let count=0;
for(i=0;i<stringLength;i++){
if(newString[i]==aChar){
count+=1;
}
}
return count;
}
console.log(countChar("Pretty Polly Parrot","P"));``````
3 Likes

Minimum

``````    function min(num1, num2) {
return num1 < num2 ? num1 : num2;
}

console.log(min(7, 7));
``````

Recursion

``````    function isEven(num) {
if (num < 0) return "Number must be a positive integer!";
if (num == 0) return "Even";
if (num == 1) return "Odd";
return isEven(num - 2);
}

console.log(isEven(-1));
``````

Bean Counting

``````    function countBs(myString) {
return countChar(myString, 'B');
}

function countChar(myString, character) {
let count = 0;
while (myString.length > 0) {
if (myString.charAt(0) == character) count++;
myString = myString.substr(1);
}
return count;
}

console.log(countBs("Blue Jean Baby!"));
console.log(countChar("Beginning Shell Scripting.", 'i'));``````
2 Likes

Exercise 3

``````    // Compare Minimum
function GetMinimum(a, b)
{
if (a < b){
return a;
}else{
return b;
}
}

//Check Even Or Odd
function IsEven(a){
if (a > 1) return IsEven(a - 2);
if (a < 0) return ("?? cannot determine negative numbers ") ;
if (a == 0) return true;
if (a == 1) return false;
}

//Bean Counting
function countChar( haystack, needle  )
{
total = 0;
for( count = 0; count <= haystack.length; count ++ )
if (haystack.substr(count, 1) == needle) total ++;
}

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

console.log(GetMinimum(0, 10) )
console.log(IsEven( 50 ));
console.log(countBs("BBC"));
console.log(countChar("kakkerlak", "k"));``````
1 Like

Minimum

``````function min(a,b){
if (a>b){
return b;
}
else if (b>a){
return a;
}
else console.log ("Your two numbers are equal!");
}

console.log ("The minimum value is " + answer);
``````

Recursion

``````    function isEven (posNumb){
//ensure that the number is positive
if (posNumb<0){
posNumb = posNumb * -1;
}
if (posNumb%2==0){
//if %2 then numb is even, else odd
return true;
}
else return false;
}

``````

Bean Counting

``````    function countBs (stringIn, target){

var counter = 0;

for (i=0; i<stringIn.length; i++){
if (stringIn[i]==target){
counter++;
}
}
return counter;
}

console.log (countBs("aBcBdBeBfBgB", "B"));``````
2 Likes

1. Minimum
Write a_ function min that takes two arguments (a, b) and returns their minimum { return a || b; }.

###### function min(a,b) {return a || b;} // We need logic for returning a or b to get their minimum. If statement is needed.

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

return b; }
}

// If equal still returns minimum.

2. Recursion
Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number)( 7 ) and { return a Boolean;}

###### function isEven(7) {return boolean; } // We need logic for return boolean and we have to use isEven.

function isEven(number) {
if number ==0{
return true;
}

if number ==1{
return false; }

if number !=0 || number !=1{
return isEven(number - 2);
}

else{
return isEven(-number);}
}

1 Like

MINIMUM

methode a:

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

methode b:

function min(x,y){

``````if (x<y) return x;
else return y;
``````

}

``````var answ2 = min(23,-4);
document.write(answ2);``````

Minimum

``````const return_min=function(a,b){
if(a<b){
return a;
}
else{
return b;
}
};
console.log(return_min(-5,3));
``````

Recursion

``````const isEven = function(number){
if(number==0){
return "true";
}
else if (number==1){
return "false";
}
else if(number<0){
number+=2
return isEven(number);
}
else{
number -=2
return isEven(number);
}
};

console.log(isEven(-100));
``````

Bean counting

``````let test_string="BabylonBabelfishBazinga";

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

console.log("B contained " + countBs(test_string) + " times.\n");

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

let test_char="a";
console.log(test_char + " contained " + countChar(test_string,test_char) + " times.\n");``````

Hey guys,

Just wondering, why is this one not working?

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

}

Returns undefined.

1 Like