Chapter 3 Exercises

1-minimum function
function min (a,b) {
if (a<b) return a;
else return b;
}
console.log (min( 9, 7));

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

3-Bean counting

Exercise 1
Pretty simple to do. Didn’t have too much trouble.

//Function with 2 variables “x” and “y”.
function min (x,y) {
//Checks if “x” is smaller than “y”. If yes then return “x”.
if (x<y) {
return (x);
}
//Else return “y”.
else {
return (y);
}

}
//Calling the funcions.
console.log(min(0,10));
console.log(min(0,-10))

Exercise 2
Took me some time but still wasn’t too hard.

//Takes a number.
function isEven(x) {
//Infinite loop.
for (infcounter = 1; infcounter < 2;) {
//Checks if “x” is 0. Even.
if (x===0) {
return (“true”);
break;
}
//Checks if “x” is 1. Odd.
if (x===1) {
return (“false”);
break;
}
//Checks if “x” is smaller then 0 in order to know if the function should add or substract 2.
if (x>0) {
x=x-2;
}
else {
x=x+2;
}

  }
}
//Calling the function.
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));

Exercise 3
Took me a bit more time than others.

//Takes “x” input (string) and “y” input (character).
function countChar(x,y) {
//Defining and setting the count variable to 0. (Result).
var count = 0
//Defining the “y” input as a variable named “char”.
var char = y;
//Making a loop depending on the “x” input length.
for (numcount = 0; numcount < x.length; numcount = numcount +1)
//Checking each character in the sting if it matches the “y” input.
if (x[numcount]===char) {
//If yes then add 1 to the “count” a.k.a. our result.
count = count + 1;
}
return count;
}
//Takes “x” input (sring) but forces the other value “y” to be “B”.
function countBs(x) {
return countChar(x,“B”)
}
//Calling both functions.
console.log(countBs(“BBC”))
console.log(countChar(“kakkerlak”, “k”));

 <script>
        function min(x, y) {
            return Math.min(x, y);
        }

        console.log(min(20, 100));

    </script>
<script>
        function isEven(x) {
            if (x === 0){
                return true;
            } else if (x === 1 || x === -1){
                return false;
            } else if (x < 0){
                return isEven(x + 2);
            } else {
                return isEven(x - 2); // || isEven(x + 2);
            }
        }
        console.log(isEven(50));
        console.log(isEven(75));
        console.log(isEven(-1));
        console.log(isEven(-2));
        console.log(isEven(-50));
        console.log(isEven(-75));
    </script>
<script>
        function countBs(string) {
            let bsCounter = 0;
            for (let counter = 0; counter<string.length; counter++){
                if (string[counter] === "B"){
                    bsCounter++;
                }
            }
            return bsCounter;
        }
        
        function countChar(string, letter) {
            let bsCounter = 0;
            for (let counter = 0; counter<string.length; counter++){
                if (string[counter] === letter){
                    bsCounter++;
                }
            }
            return bsCounter;
        }

        console.log(countBs("BBB"));
        console.log(countChar("DoubleDee", "e"));
    </script>

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

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

Recursion
function evenOdd(N){
if (N % 2 == 0) {
console.log (“even”);
} else {
console.log (“odd”);
}}

console.log(evenOdd(12));

Though this code produces ‘even’ or ‘odd’ Boolean outputs, it did not utilize a recursive function, nor did I ever use N = N -2 (I think that’s what he was describing in the third point). Going to look through other people’s code and see how they did it.

Bean counting
var names = “the quick Brown fox jumps over the Big lazy dog named Ben near Buddy and Bobby”;
count = 0;
for(var i = 0; i < names.length; i++) {
if(names.charAt(i) === ‘B’){
count++;
}
}

Got it to work, but it’s not a function, the letter can even be changed as well. Going to look through other people’s code to see how to do it via function.

1. Minimum Function
Function min(x, y) {
if (x < y){
return x;
else return y;
}
}
Console.log(min(1, 11));

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

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

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

Excercise 1.
//Write a function min that takes two arguments and returns their minimum

function min(a,b) {
if (a<b){
document.write(a);
}
else {
document.write(b);
}
}

var answer = min(12,7);

//Excercise 2. I had to look up the answer and work backwards.

function test(a) {
if (a === 0){
return true;
} else if (a === 1 || a === -1){
return false;
} else if (a < 0){
return test(a + 2);
} else {
return test(a - 2);
}
}

document.write(test(0) + “
”);
document.write(test(-1) + “
”);
document.write(test(1) + “
”);
document.write(test(50) + “
”);
document.write(test(-50) + “
”);
document.write(test(-75) + “
”);

//Excercise 3. I again had to look up the answer, once I understood how ‘.length’ and ‘.charAt’ worked it made sense.

function countBs(str) {
var count = 0;
for (var i = 0; i < str.length; i++) { //the ‘.length’ in an array will return the nr of elements within it.
if (str.charAt(i) === “B”) { // the ‘.charAt()’ returns the character at a specified index.
count++;

    }
}
    return (count); // return outside of for loop

}

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

//This gives the number of ‘Bs’ in the string

function countChar(str, srch) {
var count = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) === srch) { // use the variable srch instead of the string “char”
count++;
}
}
return (count); // return outside of the for loop
}
console.log(countChar(“Beasts and Braves flock Bewilderingly”, “B”));

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

function isEven(x){
if(x % 2 == 0){
return “Even”;
}else{return “Odd”;
}
} console.log(isEven(106));

function isEven(n){
if(n == 0){
return “Even”;
}else if(n == 1){return “Odd”;
}else if (n < 0) {return isEven(-n);
}else{return isEven (n - 2);};
} console.log(isEven(3));

function countBs(string){
var numBs= 0;
for(x= 0; x < string.length; x++){
if(string[x] == “B”){
numBs++;
}
} return numBs;
} console.log(countBs(“How many B`s Bonehead before Breakfast?”));

function countChar(string , char){
var count= 0;
for(var x= 0; x < string.length; x++){
if(string[x] == char){
count++;
}
} return count;
} console.log(countChar(“How many B`s Bonehead before Breakfast?” , “B”));

Minimum
function min(x,y){
if(x<y){
return x;
} else {
return y;
}
}
console.log(min(99999,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(-1));
Beans Counting
function countBs(myStr){
return countChar(myStr, ‘B’);
}
function countChar(myStr, character){
let count = 0;
while (myStr.length > 0){
if (myStr.charAt(0)==character) count++;
myStr = myStr.substr(1);
}
return count;
}
console.log(countBs(“ajfhB B jiisdig BBB dg”));
console.log(countChar(“saghbfsdkjgblakfds”, ‘s’));

Exercise 1 Mininum

console.log(Math.min(2,8) + 100);

Exercise 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(-2));

Exercise 3 Bean Counting
function countBs(str){
var x = str.length;
var count = 0;
var letter;

  for(var i = 0; i < x; i++){
    letter = str[i]

    if(letter == "B") {
      count++;
    }
  }
  return count;
}
alert(countBs("BrB Beaches"));

1---------------->
function min(x, y){
if(x>y){
return (y);
}else{
return (x);
}
}
//END OF FUCTION, CALL AND LOG IS NOT PART OF THE FUNCTION
var Lowest = min(100, 5)
console.log Lowest

2------------------->
function isEven(x){
//HINT NEEDED FOR DEALING WITH NEGATIVES
x = Math.abs(x);
if (x == 0){
return true;
}else if (x == 1){
return false;
}else{
return isEven(x - 2);
}
}
var answer = isEven(-67)
console.log (answer)

3------------------------>
//STRUGGLED WITH THIS FOR A WHILE…
function countBs(string, char){
var counter = 0;
for (var x = 0; x < string.length; x++){
if (string[x] == char){
counter++;}
}
return counter;
}

  var Total = countBs("BRRRRRRRRRRRRRRRRRRRRBB", "R")
  console.log (Total)

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

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. MINIMUM

function findMin(a,b){
if (a<b){
return(“a is the smallest”);
}
else if (a == b){
return(“numbers are equal”);
}
else {
return(“b is the smallest”);
}
}
alert(findMin(5,2));

  1. RECURSION

function isEven(number) {
if (number<0){
number= -number;
}
if (number == 0){
return “Even”;
}
else if (number == 1){
return “Odd”;
}
else return isEven(number-2);
}
alert (isEven(-11));

  1. BEAN COUNTING 1 - (countBs)

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

  1. BEAN COUNTING 2 - (countChar)

       function countChar(string, letter){
         let counter = 0
         for (var i = 0; i<string.length; i++) {
           if (string[i] == letter) {
             counter++;
           } 
         }
         return(counter);
       }
       document.write(countChar("KaresafdasKa", "a"));

Function Number 1 (Minimum)

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

Function Number 2 (Recursion)

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

Function Number 3 (Count Char)

function countChar(word, letter) {
let found = 0;
for (let i = 0; i < word.length; i++) {
if (word[i] == ch) {
found+= 1;
}
}
return found;
}

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

// Exercise - Minimum
document.write("<h1>Problem 1 - Minimum</h1>")

function minimum(a, b){
  let rtn = 0;
  if(a>b){rtn = b;}else{rtn = a;}
  return rtn;
}

var val1 = 35;
var val2 = 9;
document.write("<h2>" + "Minimum value is: " + minimum(val1, val2) + "</h2>")

// Exercise - Recursion
document.write("<h1>Problem 2 - Recursion</h1>")

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

var testNum = -3;
var display = "";
if(isEven(testNum)){display = "even.";}else{display="odd.";}
document.write("<h2>" + "The number " + testNum + " is " + display + "</h2>")

// Exercise - Bean Counting
document.write("<h1>Problem 3 - Bean Counting</h1>")

function countBs(strTest){
  var lenCount = strTest.length;
  var numOfBs = 0;
  for(var count = 0; count<lenCount; count++){
    if(strTest[count] == "B"){numOfBs+=1;}
  }
  return numOfBs;
}

function countChar(strTest, chrTest){
  let lenCount = strTest.length;
  let numOfChrs = 0;
  for(var count = 0; count<lenCount; count++){
    if(strTest[count] == chrTest){numOfChrs+=1;}
  }
  return numOfChrs;
}

var stringToTest = "Uh ooh, Big Bad O'l Baboon BOB";
var chrToTest = "o";
document.write("<h2>" + "The number of B's is: " + countBs(stringToTest) + "</h2>")
document.write("<h2>" + "The number of " + chrToTest + "'s is: " + countChar(stringToTest, chrToTest) + "</h2>")

Hey,

I like your alternative solution to the recursion exercise:

I think using…

if (number < 0) number = -number;

… as the first if statement in the function body provides a good simple solution, which only requires one recursive function call in the final else statement, rather than the two used in the suggested solution, and my less concise solution (below).

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

console.log(isEven(-1));

Also, not sure if you know, but if you wrap the code you include in these posts in back ticks (while editing), it formats it nicely for you, making it easier to read. For an inline piece of code: surround it in single back ticks e.g. `console.log()` will appear as console.log()
For a block of code put three back ticks on the line before and on the line after e.g.

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

console.log(min(5, -3.5));
```

will appear as:

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

console.log(min(5, -3.5));

As an easy alternative to typing the back ticks manually, you can just click on the </>  in the menu bar at the top of the text input box and it will automatically give you two backticks, or two sets of three backticks, depending on whether you are inline or on a new line :smiley:

It’s using a simple markup language called Markdown. Here’s a link if you, or anyone else reading this, would like to know more: https://commonmark.org/help/

By the way, that final piece of code I used in my example is my alternative solution to the first exercise, using a ternary operator. I like how short and sweet it is :wink:

Hey!

Nice to see someone else used a ternary operator in their solution to exercise 1 :smiley:

I like how short and sweet it is!

1 Like

Thanks again Jonathan, I really appreciate your solutions. I’m going to spend some time reviewing your suggestions shortly.

Cheers,

Jeremy.

1 Like

Much of writing python had to learn to minimize lines of codes…

Hell yea, Ternary is so short and easy to read.

1 Like