Chapter 3 Exercises

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

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

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”));
}
1 Like
  1. Min:
    function min(num1, num2){
    if(num1<num2){
    return num1;
    }
    else{
    return num2;
    }
    }
    console.log(min(0,10));
    console.log(min(0,-10));
    answer = 0, -10

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

  3. Bean Counting
    function CountBs(string){
    return countChar(string, ‘B’);
    }
    function countChar(string, character){
    let result = 0;
    for (let i = 0; i < string.length; i++){
    if (string[i] === character){
    result = result + 1
    }
    }
    return result;
    }
    console.log(CountBs(“BBC”));
    console.log(countChar(“kakkerlak”, “k” ));
    answer = 2, 4

2 Likes

Minimum:

//minimum of two numbers 
      function min(a, b) {
        if (a < b)
          return a;
        else
          return b;
      }
        // Minimum - log function in console - returns 5
        console.log (min (5, 10))

Recursion:

//function to test whether number is odd or even, if even returns true, if odd returns false
        function isEven(n) {
          if (n == 0)
            return true;
          else if (n == 1)
            return false;
          else
            return isEven(n - 2);
        }

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

        //function to test whether a nagative number is odd or even. It should return false, because
        //negative numbers are not divisible by 2. I didn't know how to do it by mself, but I saw in comments someone
        //use math.abs function, so I will do it also.
        function isEven(n) {
          let number = Math.abs(n);
            if (number == 1)
              return false;
          }
        console.log(isEven(-1)); //returns false
2 Likes

1.)

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

    mathMin(5,2);
//Returns 2

2.)

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


    isEven(50);
//Returns True

3.) Found this one very hard. I had to look at the solution.

2 Likes

1. Minimum

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

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

console.log(min(40, 20));
// → 20

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(50));
// → true

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

console.log(isEven(-1));
// → false

3. Bean counting

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

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

console.log(countBs(“BaBushka”));
// → 2
console.log(countChar(“BaaBushkaa”, “a”));
// → 4

1 Like

This character counting exercise was actually quite hard to figure out. I was stuck some time in figuring how to finish it. In next chapters of javascript programming i saw the use of arrays [] which helped me in finishing the program.

Bean counting;

      //example 1 counting only B's in a word
      function countBs(string) {
          let count = 0;
          for (let i = 0; i < string.length; i++) {
              if (string[i] == "B") {
                  count++;
              }
          }
              return (count);
      }

      console.log(countBs("BBC")); //returns 2
      //example 2 counting specific definened character
      function countChar(string, x) {
        let count = 0;
        for (let i = 0; i < string.length; i++) {
          if (string[i] == x) {
            count ++;
          }
        }
        return count;
        }

      console.log(countChar("kakkerlak", "k")); // returns 4
3 Likes

Minimum Function

const minimum = (a, b) => {return((a < b) ? a : b)};

Recursion

function isEven(n){
          // Taking the absolute value of n and assigning it to the variable a ensures that the function can process positive and negative numbers
          let a = Math.abs(n);
          if(a <= 1){
            if(a == 0){
              return true;
            }
            else{
              return false;
            }
          }
          else{
            return isEven(a - 2);
          }
        }

Bean Counting

  function countBs(x = prompt("Please enter a string")){
            let counter = 0;
            for(let i = 0; i < x.length; i++){
              if(x[i] == "B"){
                counter++;
              }
            }
            return counter;
          }
function countChar(x = prompt("Please enter a string"), y = prompt("Which character do you want to count?")){
            let counter = 0;
            for(let i = 0; i < x.length; i++){
              if(x[i] == y){
                counter++;
              }
            }
            return counter;
          }
2 Likes

function min(a,b){
return Math.min(a,b);
}
console.log(min(50,2))
=> 2

1 Like
    function min(a,b){
        if (a< b) return a;
        else return b;
        }
console.log(min(100,9));
  function isEven(n){
      if (n == 0) return "true";
      else if (n == 1) return "false";
      else if (n % 2 == 0) return "true.";
      else return "false";
    }
  console.log(isEven(50));
  function countBs(string){
      let n = string.length;
      let count = 0;
      for (let i = 0; i < n; i++){
        if (string[i] == "B"){
          count += 1;
        }
      }
      return count;
    }
console.log(countBs("BippityBoppity"));
   function countChar(string,letter){
      let n = string.length;
      let count = 0;
      for (let i = 0; i < n; i++){
        if (string[i] == letter){
          count += 1;
        }
      }
      return count;
    }
console.log(countBs("BippityBoppity","p"));
1 Like

@Ivan can you or anyone will explain how this code is working for -number. I mean how it will break the if else loop to go at the point where its either become 0 or 1 and get return value of either true or false.

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

Took the liberty of including the jquery lib as it makes interacting with dom elements easier, the functions themselves are written in native js

<html>
    <head>
        <title>Ivan html 1</title>
        <style>
            body {background-color: #333; color: #CCC; font-family: sans-serif; font-size: 1.2em}
            a {color: #CCC}
            a:hover {color: #f49962}
        </style>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body>
        <input id="inp" />&nbsp;
        <input id="inp2" />&nbsp;
        <select id="sel">
            <option value="min">min</option>
            <option value="isEven">isEven</option>
            <option value="countBs">countBs</option>
            <option value="countChar">countChar</option>
        </select>
        <br /><br />
        <div>
            <span id="val"></span>
        </div>
        <script>
            var doubleArgs = ["min", "countChar"];

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

            var isEven = (x) => {
                if(typeof(x) != "number") var y = Number(x);
                else y = x;
                if(y < 0) return isEven(-y);
                switch (y) {
                    case 1:
                        return false;
                        break;
                    case 0: 
                        return true;
                        break;
                    default:
                        return isEven(y - 2);
                        break;
                }
            };

            var countBs = (x) => {
                return countChar(x, "B");
            };

            var countChar = (x, y) => {
                let count = 0;
                for (let i = 0; i < x.length; i++) {
                    if(x[i] == y) count++;
                }
                return count;
            };

            $('#inp,#inp2').on('input', function() {
                refreshData();
            });
            $('#sel').on('change', function() {
                refreshData();
            });
            
            var refreshData = () => {
                let inp = $('#inp').val();
                let inp2 = $('#inp2').val();
                let sel = $('#sel').val();
                if(doubleArgs.indexOf(sel) < 0) 
                    $('#inp2').attr("disabled", "");
                else 
                    $('#inp2').removeAttr("disabled", "");
                $('#val').text(sel + ": " + window[sel](inp, inp2));
            };
        </script>
    </body>
</html>
1 Like

if else is a conditional statement, not a loop, but I guess you meant the recursive calls the loop.
You are calling the isEven function with the argument " -x " if the input argument is less than 0, so a negative number.
Calling the function with " -x " is basically just calling the function with " -1 * x " so the negative number becomes positive and the rest of the process is the same as for the positive numbers.
I hope I could help somewhat.

Minimum
function min(x,y) {
if (x>y) return y;
else return(x);
}
console.log(min(200,500))

Recursion
function oddeven(x) {
if (Math.abs(x)==0) return Boolean(x);
else if (Math.abs(x)==1) return Boolean(x);
else return(oddeven(x-2));
}
console.log(oddeven(-1))

My solution includes solving problem with negative numbers. I use Math.abs(x) which returns absolute value.

Bean Counting
function countChar(x,y) {
var count = 0;
for (var i = 0; i < (x.length); i++) {
if (x[i]==y)
count = count +1;
}
return(count);
}

1 Like

function min (a,b) {
if (a>b) return b;
else
return a;
}
(console.log(min(3,7));

Thanks for the reply. year I got it. Minus sign keep reducing the number until it reached at zero or 1.

MINIMUM

  function myMin(x, y){
   if(x < y){
     return(x);

     }else {

       return(y);
     }
  }
   console.log(myMin(1, 32));

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));
console.log(isEven(-2));

BEAN COUNTING
// fisrtly

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

alert(countBs(“ssbbBBcrB”));

// finally:

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

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

1 Like

Exercise 1

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

Exercise 2

function is Even(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”));
}
  1. Minimum Exercise

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

  1. Recursion
    I had no idea what this exercise was asking for. Then, when I looked at the answer, I wondered why in the world anyone would ask for code to be created this way. I understand the exercise calls for recursion, but why would you want it in this instance, especially, if it costs more processing power and is more complex to write and understand? I’d rather write the code like this…

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

  1. Bean Counting
    You know those mystery novels where the detective reveals how he or she figured out who the killer is and there are a bunch of clues that we as the reader where never privy to? That’s how I am starting to feel about Eloquent JavaScript. Yeah, it all makes sense when you see the answer, but where in the chapter did it say anything about the code being able to do that?
Minimum:
function min (x,y){
    if (x < y) return x;
    else if (y < x) return y;
    else return ("try again");
}
    console.log(min(6,13));

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

console.log(isEven(-2));


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

console.log(countChar("kakkerlak", "k"));
1 Like

Min

function min(first, second) {
    return first <= second ? first : second;
}

isEven

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

countBs

function countBs(string, targetLetter = "B") {
    let matches = 0;
    for (let i = 0; i < string.length ; i++){
        if(string[i] == targetLetter) {
            matches++;
        }
    }
    return matches;
}
1 Like