Chapter 3 Exercises

Hi.

just use the sand-box that comes with the book.

https://eloquentjavascript.net/2nd_edition/code/#2.2

Ivo

  1. Exercise Minimum

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

}
console.log(whichLess(10, 20));
console.log(whichLess(10, -10));

  1. Exercise 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(50));
// true;
console.log(isEven(75));
// false;
console.log(isEven(-1));
// false;

  1. Exercise 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

Min

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

isEven

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

Beans

function countBs(word){
        length = word.length;
        counter = 0;
        for(var index = 0; index < length; index++){
            if(word[index] == "B"){
                counter ++;
            }
        }

        return counter;

    }

and

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

        return counter;

    }
2 Likes

Minimum function

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

  console.log( minValue(23, 16) );

Recursion

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

  console.log("True or false, 50 is even? : ", isEven( 50 ) );
  console.log("True or false, 75 is even? : ", isEven( 75 ) );
  console.log("True or false, -1 is even? : ", isEven( -1 ) );

Bean counting

  function countChar(string, character) {
    let numCharsFound = 0;
    for ( checkPos = 0; checkPos < string.length; checkPos++) {
      if ( string[checkPos] == character ) numCharsFound++;
    }
    return numCharsFound;
  }

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

  let testStr = "Black Beauty is the best of Breads";
  console.log("B's contained in: '" + testStr + "' = ", countBs(testStr));
1 Like

Minimum frunction

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

Recursion

function ifElse(x){

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

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

else {
  return ifElse(x-2);
}
}

if x = -1 (it takes into account only positive numbers)

function ifElse(x){

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

else if(x<0){
  return false;
}

else {
  return ifElse(x-2);
}
}

Bean counting

function countBs(x){

    result = 0;

    for(a = x["length"]; a>=0; a=a-1 ){

        if(x[a]=='B'){
         result = result+1;
          }
       }

return result;
}
function countChar(x,y){

    result = 0;

    for(a = x["length"]; a>=0; a=a-1 ){

        if(x[a]==y){
         result = result+1
          }
       }
return result;
}
1 Like

hello sir, please describe what you have not understand, so i can help you! :slight_smile:
Your code is running just great, but if you have any doubt just let us know!

That’s exactly the answer, the function does only take into account positive numbers!

Carlos Z.

Good day Carlos,


Thank you for taking the time looking through my homework and replying.

When I was referring to “I am not sure if I understood the second part of the exercise”, was because, when I first read the request “except it takes a second argument that indicates the character that is to be counted” looked to simple and I thought it is something more complex.

I haven’t checked other home works done by the members before finishing the assignment. After posting the homework and checked the full forum topic and realized that I understood the exercise, I forgot to edit the post. :slight_smile:

if x = -1 (it takes into account only positive numbers)

For this, I didn’t took the time to adjust the function in order to use also negative numbers.
For example:

-4%2
-0

Once again, thank you for support, and it is very good to know the persons I can ask direct questions when I get stuck. :smiley:

Kind regards,
Andrei

1 Like

Minimum

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

    console.log(minumum(11,10))

Recursion

    function diminish(a){
      while(a>=2){
        a=a-2;
      }
      return a;
    }
    function evenodd(b){
      let a = diminish(b)
      if (a==0){
        console.log("Value " + x + " is even");
      }
      else console.log("Value " + x + " is odd");
    }
    function evaluate(x){
      evenodd(Math.abs(x))
    }
    let x = -3
    evaluate(x);

BeanCounting

      function bcounter(word,char){
        var counter = 0;
        var count = word.length;
        for(var i = 0; i < count; i++){
          if (word[i] == char){
            var counter = counter + 1
          }
        }
        console.log("Found " + counter + " ''" + char + "'' chars")
      }
      bcounter("eBBravo!","B");
1 Like

Minimum Exercise

function min(a,b){

  if(a<b){
    alert(a + " is lower than " + b);
  }
  else{
    alert(b + " is lower than " + a);
  }

}

Recursion Exercise

function isEven(num){

  if(num==0){
    document.write(true);
  }
  else if(num==1){
    document.write(false);
  }
  else if(num<0){
    return isEven(-num);
  }
  else{
    return isEven(num-2);
  }

}

Bean Counting Exercise

function countChar(string, char){
  var num_char = 0;

  for(var index=0; index < string.length; index +=1){

    if((string.toLowerCase()[index] == char) || (string[index] == char) ){

      num_char += 1;
    }
  }

  document.write("<h1> The letter " + char + " appeared " + num_char + " times </h1>");
}

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

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

2, function isEven(n);{
if(n == 0) return true;
else if(n == 1) return false;
else if(n < 0) return isEven (n - 2);
}
console.log (isEven (50));
// -> true
console.log (isEven (75));
// -> false
console.log (isEven ( -1));
// -> false

3, 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
  1. Function min (a,b) {
    if(a>b) return b;
    else return a;
    }

  2. function even(n){
    if (n == 0) return 0;
    else if (n == 1) return false;
    else if (n <0) return even(-n)
    else return even(n-2)

  3.   function bCount(string,char){
     let noBs = 0;
     for(let i = 0; i< string.length; i++){
       if(string[i] == char){
         noBs += 1;
       }
     }
     return noBs;
    

    }
    function countB(string) {
    return (bCount(string,“B”));
    }

1 Like

Minimum


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

          minimum = min(6, 9)
          console.log(minimum)
          \\ -> 6

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(50))
        console.log(isEven(75))
        console.log(isEven(-1))

Bean counting

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

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

        console.log(countBs("BBC"));
        console.log(countChar("kakkerlaka", "k"));
1 Like

Minimum

    const min = function (x,y){


     if (x < y) {

       return x;

     }

       else if (x > y){

         return y;

     }

     else {

     return "Equal"

     }
     }

document.write("O menor numero é: " + min ((prompt("Preencha um número","Digite Aqui")),(prompt("",""))))

Is Even

     const isEven = function (N) {


     if(!Number.isInteger(N)) {
       return "Not a whole number";
     }

     else 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(8))

Counting Beans

  const countBs = function(string){

   let count = 0

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

     if (string[add] == "B") {
       count += 1

    }
    }

   return count;

 }

   console.log(countBs("BububuBu"))

Modified Counting Beans:

   const countChar = function(string,target){

   let count = 0

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

     if (string[add] == target) {
       count += 1

     }}

   return count;

 }

   console.log(countChar("Bubububu","B"))
1 Like

MINIMUM

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

RECURSION

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

BEAN COUNTING

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

1 Like

// To determine smaller of 2 items
function min(x, y) {
if (x < y)
return x;
else
return y;
}

// Testing for odd or even including negatives without using %2
function isEven(k) {
if (k == 0) return true;
else if (k == 1)
return false;
else if (k < 0)
return isEven(-k);
else
return isEven(k - 2);
}

// function abstraction by layering functions
function countChar(string, chr) {
var countz = 0, k = 0;
for (k; k < string.length; k++) {
if (string[k] == chr) {
countz += 1;
}
}
return countz;
}

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

1 Like

Exercise 1

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

    document.write(min(9, 6));

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

Exercise 3

I am totally lost here, I look at your answers, I look at the answer on the book and I CAN NOT get it :sob:
I feel totally stuck

This is from the book:

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

This chapter was enjoyable :slight_smile: got me thinking more along the lines of reusing and nesting functions.

Minimum

    <script>
    
    function promptNumber(){
    x = Number(prompt("Enter a number"));
        while(Number.isNaN(x)){
            x = Number(prompt("You didn't enter a number, please enter a number"));
        }    
    return x;
    }
    
    function min(x,y){
    var minimum;
    x = promptNumber();
    y = promptNumber()
        if(x<y){
            minimum = x;    
        } else {
        minimum = y;
        }
    alert("The smallest number is " + minimum);
    }
    
    min();
    
    </script>

Recursion

    <script>
    
    function promptNumber(){
    x = Number(prompt("Enter a number"));
        while(Number.isNaN(x)){
            x = Number(prompt("You didn't enter a number, please enter a number"));
        }    
    return x;
    }
        
    function evenOdd(x){
    if(x==0){
        return "The number you chose is EVEN";
    } else if(x==1){
        return "The number you chose is ODD";
    } else if (x>0) {
            return evenOdd(x-2);
    } else{
            return evenOdd(x+2);
    }       
    }
    
    alert(evenOdd(promptNumber()));
    </script>

Bean Counting

    <script>
    
        function promptString(request){
        inputString = String(prompt(request));    
        return inputString;
        }                
        
    function countChars(stringInput,characterCheck){
    stringLength = stringInput.length;
    var charCounter=0;
    for(counter = 0; counter<stringLength; counter++){
        if (stringInput[counter] == characterCheck){
        charCounter++;    
        }
        
    }   
        
        alert(charCounter);
    }
    
    countChars(promptString("Please enter a string"),promptString("Which letter would you like to count?"));
    </script>
1 Like

/*
Minimum
The previous chapter introduced the standard function Math.min that
returns its smallest argument. We can build something like that now.
Write a function min that takes two arguments and returns their minimum.
*/

function minNumFunction (n1, n2)
{
if (n1 < n2)
{
return n1;
}
else if (n2 < n1)
{
return n2;
}
}
num1 = 23
num2 = 46;
console.log(“The minimum number of " + num1 +” and " + num2 + " is :" + minNumFunction(num1, num2));

/*
Recursion
We’ve seen that % (the remainder operator) can be used to test
whether a number is even or odd by using % 2 to see whether it’s
divisible by two. Here’s another way to define whether a positive
whole number is even or odd:
55
• Zero is even.
• One is odd.
• For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description.
The function should accept a single parameter (a positive, whole number)
and return a Boolean.
Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a
way to fix this?
*/
num1 = 77;
var result = null;
function evenOdd(num)
{
if (num == 1)
{
console.log(“number is odd”);
return 1;
}
else if (num == 0)
{
console.log(“number is even”);
return 0;
}
else {

return evenOdd(num -2);
}

}
result = evenOdd(num1);

// Test it on 50 and 75. See how it behaves on -1. Why? Can you think of a way to fix this?
//USE ABSOLUTE FUNCTION PRIOR TO RUNNING MAJORITY OF FUNCTION OR ASSIGN CASE TO ADD 2 INSTEAD OF SUBTRACTING FOR
//NEGATIVE NUMBER ?

/*
Bean counting
You can get the Nth character, or letter, from a string by writing “string”[N].
The returned value will be a string containing only one character (for example, “b”).
The first character has position 0, which causes the last one to be found at position
string.length - 1. In other words, a two-character string has length 2, and its
characters have positions 0 and 1.
Write a function countBs that takes a string as its only argument and returns a
number that indicates how many uppercase “B” characters there are in the string.
Next, write a function called countChar that behaves like countBs, except it takes
a second argument that indicates the character that is to be counted (rather than
counting only uppercase “B” characters). Rewrite countBs to make use of this new function.
*/
test = “bbBbB”
function countBs(tstring)
{
counter = 0;
for (i=0; i< tstring.length; i = i + 1)
{
if (tstring[i]== ‘B’)
counter++;
}
console.log(counter);
}

countBs(test);

// PART 2 OF HOMEWORK
test = “bbBbC”
function countChar(tstring, chars)
{
counter = 0;
for (i=0; i< tstring.length; i = i + 1)
{
if (tstring[i]== chars)
counter++;
}
console.log(counter);
}

countChar(test, “C”);

1 Like

Hi guys, I got stuck with the third exercise, can someone help me please? I get Uncaught SyntaxError: Identifier ‘i’ has already been declared. As I checked many answers here, others gave similar or same code as an answer, but in my case it doesn’t work

function countBs(string) {
    let result = 0;
      for (let i = 0, i < string.length, i++){
        if (string[i] === "B") {
          result++;
        }
      }
    return result;
  }
E1 - Min

With only 2 inputs the solution is rather simple:

<html>
    <head>
        <title>EJ Ch3 E1</title>
    </head>
    <body>
        <h1>EJ Ch3 E1 - Minimum</h1>
        <h3>Tests</h2>
        <script>
            function min(a,b) {
                if (a < b){
                    return a;
                }
                return b;
            }

            
            testMin(1, 2);
            testMin(2, 1);
            testMin(1, 1);
            testMin(2, -1);
            function testMin(a,b) {
                document.write(`<p>The min of [${a}, ${b}] is ${min(a,b)}</p>`);
            }
        </script>
    </body>
</html>
E2 - Recursion

The base cases are given. The only trick is the case for negative numbers, but in that case “2 numbers before” is actually N+2.

<html>
    <head>
        <title>EJ Ch3 E2</title>
    </head>
    <body>
        <h1>EJ Ch3 E1 - Recursion</h1>
        <h3>Tests</h2>
        <script>
            function isEven(n) {
                if (n == 0) {
                    return true;
                }
                if (n == 1) {
                    return false;
                }
                if (n < 0) {
                    return isEven(n+2);
                }
                return isEven(n-2);
            }

            
            test(0);
            test(1);
            test(50);
            test(75);
            test(-1);
            test(-50);
            function test(n) {
                const result = isEven(n);
                document.write(`<p>${n} is ${result ? "Even" : "Odd"}</p>`);
            }
        </script>
    </body>
</html>
E3 - Bean Counting

Here I used a different form of for loop not covered in Ch3 that allows you to iterate over each char in the string. I also included a test case for the generic countStr() function.

<html>
    <head>
        <title>EJ Ch3 E3</title>
    </head>
    <body>
        <h1>EJ Ch3 E3 - Bean Counting</h1>
        <h3>Tests</h2>
        <script>
            function countBsOld(str) {
                let count = 0;
                for(c of str) {
                    if(c == "B") {
                        count++;
                    }
                }
                return count;
            }

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

            function countChar(charToCount, inString) {
                let count = 0;
                for(c of inString) {
                    if(c == charToCount) {
                        count++;
                    }
                }
                return count;                
            }
        
            test("B");
            test("b");
            test("BOB");
            test("");
            test("aa");            
            function test(s) {               
                const result = countBs(s); 
                document.write(`<p>There are ${result} B's in "${s}"</p>`);
            }

            const generalStr = "foo";
            const charToCount = "o";
            const result = countChar(charToCount, generalStr);
            document.write(`<p>There are ${result} '${charToCount}' in "${generalStr}"</p>`);
        </script>
    </body>
</html>
Multiply by adding example fix for negative numbers

The case where our example multiply function is called with a negative number for b results in an error. This can be handled by using the absolute value of b to perform the right number of add’s regardless of sign. Then when b is negative we must add -a to produce the desired negative result.

<html>
    <head>
        <title>Functions</title>
    </head>
    <body>
        <h1>Functions Abstractions</h1>        
        <script>
            // MULTIPLICATION
            // 4*4 = 4+4+4+4
            // Multiplication is addition with repetition

            function add(x,y) {
                return x + y;
            }

            function multiply(a,b) {
                let toReturn = 0;
                const absB = Math.abs(b);
                const toAdd = b > 0 ? a : -a;
                for(let i=0; i < absB; i++) {
                    toReturn = add(toReturn, toAdd);
                }
                return toReturn;
            }

            let answer = multiply(5,-9);
            document.write(`<p>The answer is ${answer}</p>`);

        </script>
    </body>
</html>
1 Like