Chapter 3 Exercises

Hi Abuga:

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

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
1 Like

Ex MIN

function min(a, b) {

  if (a < b) {

    return a;
  } else {

    return b;
  }
}

min(3,7)

Ex Recursion version 1

function isEven(a) {

while(a > 1){

  a = a - 2
}

  if (a < 0) {

    while(a < -1){

  a = a + 2
}

  }  if (a == 1 || a == -1) {

    return false
  } else {

    return true
  }
}


isEven(-9)

Ex recursion version 2

function isEven(x) {

var a = x*x

while(a > 1){

  a = a - 2
}

  if (a == 1) {

    return false
  } else {

    return true
  }
}


isEven(-1)

Ex count B

function countBs(x,y) {

  var count = 0;

  for(i = 0; i < x.length; i++){

    if (x[i] == y) {

      count = count + 1;
    }

  }

return (count)


}


countBs("BBbbb", "b")

You welcome @JamieGoh, great job!
please ask me if you have any question.I am here to help.

Cheers,
Abel

1 Like

@JamieGoh Perfect! keep the great job. :clap:

1 Like

Unfortunately after a small hiatus for work this took a little longer to wrap my head around but WE DID IT :smiley: (just about)

Chapter 3 exercises:

Miniumum

My thought process for this exercise, so if we compare one value against the other. We can have one value (a) that is less than the other value it will return (a) and then using an else statement it will return the value (b) if its more than (b) as false. Simple (for now :stuck_out_tongue: well until the next question :see_no_evil:)

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

Recursion

Right this was a lot trickier to get my head around and I did cave in to look up the answers. My thoughts step by step were along the lines of name the function (isEven) and set the Boolean value True to an even number. We use 0 as the default value and an else statement to return false if the value is 1 (odd). Then I got completely lost :rofl: but in hindsight (and a bit of panic) I can see now that we can then use recursion to have the function call itself twice using the isEven(-n) and isEven(n-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);
}


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

Upon further research I really enjoyed this example from another student on how we can simplify it further.

:star_struck: Wow

Bean Counting

Well this was a mission and a half :upside_down_face:, the good news is that I’m learning the bad news :cold_sweat: is im finding it very difficult with trying to begin these questions without any prompts and generate my own ideas organically. (Still early days and must persevere :sunglasses:)

On the flip side a positive is that I am finding the answers elsewhere and not instantly hitting the look at solution button (small steps).

function countChar(string, ch) {
  var counted = 0;
  for (var i = 0; i < string.length; i++)
    if (string.charAt(i) == ch)
      counted += 1;
  return counted;
}

function countBs(string) {
  return countChar(string, "B");
}
console.log(countBs)"Bubbly Booze Tastes Brilliant"));
// → 3
console.log(countChar("improving steadily and very slowly is still progress", "s"));
// → 6

Onwards and upwards :rocket:

1 Like
//MINIMUM
function min (a, b) {
      if (a < b) {
        return a;
      } else {
          return b;
      }
      
    }
      
    console.log(min(20,10));

//RECURSION
function isEven (numb){
    if(numb == 0)return true;
     else if (numb == 1) return false;
     else if(numb < 0) return isEven(-numb);
    else return isEven(numb-2);

    }



console.log(isEven(-1));

//BEAN COUNTING
function countBs(string) {
    let count= 0;
    for(let i = 0; i < string.length; i++) {

        if (string [i] == "B") {
            count +=1;
        }
    }
    return count;
}
console.log(countBs("BoB"));

//COUNT CHAR
function countChar(string, ch) {
    let count= 0;
    for(let i = 0; i < string.length; i++) {

        if (string [i] == ch) {
            count +=1;
        }
    }
    return count;
}
function countBs(string) {
    return countChar(string, "B");
}

console.log (countChar("BABBs", "B"));

1 Like

I lost you at the first round of exercises :S so difficult.

I tried to do the first one from this chapter 3, without luck

The code show 5 on the screen, but if I put the value A to 50 for example then the screen shows
The smallest number is 50The smallest number is 10

function min(a, b){
document.write("The smallest number is " + a)
if (a<b);
else if (a>b)
document.write("The smallest number is " + b);
}
min(5, 10);

Hi @claudiorox nice try! but you missed the concept of conditions in javascript. The order is like this ,First we check the condition then block of code to be executed if the condition is true. take a look at the example below.

if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}

could you try it again now? :slight_smile: and one more thing when you post your code, please post as code format. take a look at the picture below

2 Likes

Better now ? :slight_smile: thanks for the help

           <script>
            function min(a, b){
              if (a<b){
              document.write("The smallest number is " + a)
              }
              else {
              document.write("The smallest number is " + b)
              }
            }
            min(4, 2);
          </script>
2 Likes

@it is excellent. great job!

1 Like
//MIN

function min(a,b,c){

  if(a < b && a < c){
    return a;
  }
  else if(b < a && b < c){
    return b;
    }
  else{
    return c;
    }
  }

console.log(min(22,11,64));```


//isEven

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


//BeanCounting - this one was totally hard and had to look up solution in book.

function countString(string, ch){
  
let count = 0;
 for(let a=0;a<string.length;a++){ 
 if(string[a] == ch){
   count+=1;
 }  
 }
  return count;
 }


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

console.log(countBs("CB BBB"));
console.log(countString("This is iiia test", "i"));
1 Like
  • The solution to Minimum exercise is rather short:

image

One thing to mention here is to remember the equal sign, so the function knows what to do if we give two equal numbers.

  • Here’s my solution to Recursion:

image

Here I need the || in else if only so the function knows what to do if the argument is 1. Maybe there is a shorter way to do this.
The second part of the exercise which has to take also negative numbers looks like this for me:

I decided that 0 is not really odd nor even, so in that case it should just return 0. Again, maybe there is a shorter solution, but this one is rather easy to compile - the part that deals with negative numbers is copy-paste with minor alterations.

  • I struggled quite a lot with the Bean Count. At first, I thought the exercise was to make a recursive function. I couldn’t figure out how to stop it and always filled the call stack:

image

I thought the N <= text.length statement was not working so I wrote it as if statement but it did the same:

image

At the end, I just made a for loop and the solution was short:

image

After that, adding a second argument was easy:

image

I called the argument text because I thought that string was a keyword and would cause errors. Now, though, I looked at other solutions and I see that it works. :smile:

1 Like

Minimum

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

console.log(min(2,6));
console.log(min(300, 5000));

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, ch){
  let counted = 0;
  for (let i = 0; i < string.length; i++) {
    if (string [i] == ch) {
      counted += 1;
    }
  }
  return counted;
}

console.log(countBs("BBBBBDDBBB"));
console.log(countChar("invincible", "i"));
1 Like

So not sure if I’m unique in saying this but… This stuff is really hard. I’m definitely struggling here. I understand the solutions, but find it really difficult to come up with them on my own!

Anyway, here’s my version of reversing an array:

    <script>
    function reverseArray(array){
      let newArray = [];
      for (i = array.length - 1; i >= 0; i--){
        newArray.push(array[i]);
      };
      return newArray;
    };
    console.log(reverseArray(["one","two","three", "four", "five"]));

    function reverseArrayInPlace(array){
      for (i = 0; i < array.length; i++){
        array.unshift(array.splice(i,1)[0]);
      };
      return array;
    };
    function revArrayPlaceAlt(arrayAlt){
      for (var i = 0; i < Math.floor(arrayAlt.length/2); i++){
        var firstIndex = arrayAlt[i];
        var lastIndex = arrayAlt[arrayAlt.length - i - 1];
        arrayAlt[i] = lastIndex;
        arrayAlt[arrayAlt.length - i - 1] = firstIndex;
      }
      return arrayAlt;
    };
    console.log(revArrayPlaceAlt(["one","two","three", "four", "five", "six", "seven"]));
    </script>
1 Like

Hi @jonsax, Yes these things are hard. It still troubles most of us. But surely by enough practice, you will become great at it. Hope to see you on the other side.

Happy Learning :smiley:

1 Like

Minimum

function min(x, y) {
      if (x < y) {
       return x;
      } else {
          return y;
      }
    }
    console.log(min(600, 4500));
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);
}

console.log(isEven(-6));
console.log(isEven(-5));
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
function countBs(str){
  var str_count=0;
  for(counter=0;counter<str.length; counter++){
    if(str.charAt(counter) == "B"){
      str_count +=1;
    }
  }
  return str_count;
}
console.log(countBs('BBBBbbBBBBBBbbBBBB'));```
1 Like

Minimum:

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

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

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

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

Thanks for the encouragement! I’ve been doing these same exercises over and over again until they feel familiar and effortless. I’m hoping that becoming a pro at this is basically developing your own bag of tricks that you can rely on. Not trying to reinvent the wheel necessarily…

1 Like

Minimum

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

}
console.log(min(6, 10));

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

Bean counting

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

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

function countBs(string) {

returnChar(string, “B”);
}

1 Like
  1. Minimum
    function myMin(a, b) {
    if (a<b) {
    return a;
    } else {
    return b;
    }
    }
    Use example:

myMin(3,-4)
-4
myMin(3,4)
3

  1. Recursion
    function isEvenRecursion(n) {
    while(n >1) {
    n=n-2;
    }
    if( n == 0) {
    return true;
    } else {
    return false;
    }
    }
    Use Example:

isEvenRecursion(7)
false
isEvenRecursion(8)
true
isEvenRecursion(-1)
false
isEvenRecursion(-2)
false
Correction:
function isEvenRec(n) {
while(n >1) {
n=n-2;
}
while(n <-1) {
n=n+2;
}
if( n == 0) {
return true;
} else {
return false;
}
}
Use example:
isEvenRec(-2)
true
isEvenRec(-3)
false
isEvenRec(6)
true
isEvenRec(9)
false

3.A. Been counter
function countBs (myString) {
let count =0;
for(let i = 0; i < myString.length; i++) {
if(myString[i] == “B”) {
count++;
}
}
return count;
}
Use example:

countBs(“BSDFJJJCBDBDGFCBSBS”)
5
countBs(“BSDFJJJCBDmbmfomdobmdoS”)
2

3.B. Character counter
function countChar (myString, myChar) {
let count =0;
for(let i = 0; i < myString.length; i++) {
if(myString[i] == myChar[0]) {
count++;
}
}
return count;
}

Use example:

countChar(“ANFEIUNOCMSMAML”,“M”)
3

1 Like