Chapter 3 Exercises

Bean Counting Part 2

    function countChar(string, character){

    let result = 0;

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

      if(string[i] === character){

        result = result + 1;
      }
    }

    return result;

  }

  function countBs2(string){

    return countChar(string, 'B');
  }

  document.write(countChar("Hello my Name is Andrea. Nice to meet you", "e"));
  document.write("<br>");
  document.write(countBs2("BbBBBjoBBBBbBbBBSIASOIABBBB"));
1 Like

Hi @Kraken!

Good solutions… so far :+1:
… and nice formatting :ok_hand:

Recursion

Your solution successfully handles positive numbers, but you now need to add functionality to handle negative numbers. Have a look at the instructions in the course book for further details.

Bean Counting

In your document.write parameter, I would add a space between the output number and the letter counted. That way it’s clearer when displayed on the web page.

document.write(
   "<h1>Your sentence has " + 
   CountChar(inputString, letter) +
   " " + letter + "'s</h1>"
);

There’s a final part to this exercise. Can you slim down your countBs function so that it still takes just one parameter (the string) but then calls countChar() to always count the number of B’s, while still returning the output itself?

1 Like

Googling before :slightly_smiling_face:

1 Like

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

Recursion
function isEven(num){
if (num < 0){
return isEven(num * -1);
}
else if (num == 0){
return “even”;
}
else if (num == 1){
return “odd”;
}
else{
return isEven(num - 2);
}
}

Bean Counting
function countBs(word){
var toReturn = 0;
for (i = 0; i < word.length; i++){
if (word[i] == “B”){
toReturn = toReturn + 1;
}
}
document.write(toReturn);
}

Character Counting
function countChar(string, character){
var counter = 0;
for (w = 0; w < string.length; w++){
if (string[w] === character){
counter = counter + 1;
}
}
return counter;
}

    document.write(countChar("Hellllo", "l"));
1 Like

Hi @Stas_Simon,

Nice solutions, and great use of ternary operator in Minimum :ok_hand:

While your solution for Recursion does handle negative numbers by printing a message asking for a positive number to entered instead, can you now add functionality that will output whether any negative number is odd or even, in the same way that it does for positive numbers?

Recursion:

function isEven(N){

if(N!=0 && N!=1 && N>=2){

N-=2;

isEven(N);
}

else if(N==0){

toReturn = “This is a even number”

}

else if (N==1){

toReturn = “This is an odd number”

}

else{

isEven(-N)

}

return toReturn;

}

console.log(isEven(50));

console.log(isEven(75));

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

Minimum


function min(x, y){
  if(x<y){
    return x;
  }
  else{
    return y;
  }
}
alert(min(1,5))
alert(min(164,4))
alert(min(3,546))
alert(min(146,9))
alert(min(23,45))
alert(min(135,57))

Recursion

function isEven(n){
  document.write(n + " ");
if(n > 0){
   if(n==1){
    return "odd";
   }
       else if (n==0) {
       return "even";
       }
          else{
         return isEven(n-2);
         }
 }
else{
    if(n== -1){
    return "odd";
    }
         else if (n==0) {
         return "even";
         }
             else{
             return isEven(n+2);
            }
 }
}


alert(isEven(-54));

Counting Beans

function countB(string1){
  let length = string1.length;
  let Bs = 0;

for(i = 0; i < length; i++){
    if(string1[i] == "B"){
        Bs += 1;
    }
}
  document.write("There is " + Bs + " B's in the sentence");
}



countB("BoBBBBurB aBfrBBsfgBBB BocBcBk");


Counting Beans 2

  function countB(string1, countChar){
    let length = string1.length;
    let bs = 0;

  for(i = 0; i < length; i++){
      if(string1[i] == countChar){
          bs += 1;
      }
  }
    document.write("There are "+ bs + " "
     + countChar + "'s" + " in the sentence " + "(" + string1 +")");
  }



  countB("the dog went for a walk", "w");

1 Like

Hi @pabnan,

You’re making good progress with these! :ok_hand:
… now lets see if we can add the finishing touches…

Minimum

As you are using document.write() instead of console.log() , you need to add line breaks, as follows:

document.write("minimum is" + " " + a + "<br>");

You can also make your function more concise, by removing unnecessary code e.g.

  • You don’t need to declare variables to store the values passed in as arguments/parameters. These values can be accessed directly within the function by referencing the parameters a and  b
    var a; and  var b; are therefore superfluous and can be removed.

Recursion

Your solution successfully handles positive numbers, zero, and -1, but can you now add functionality that will output whether any negative number is odd or even, in the same way that it does for positive numbers?

How are you getting on with the third exercise, Bean Counting. If you’re unsure about anything, you can post any questions you have here.

1 Like

Nice coding, @Junte :ok_hand:

…and great formatting!

To add line breaks when using document.write() , just add HTML line break tags as strings when returning true or false:

return true + "<br>";
return false + "<br>";
1 Like

This is great @Junte!

You’re cruising at altitude! :smiley:

1 Like

Hi @qh.w

That’s absolutely fine, and actually what you should be doing if you’re not sure how to solve it on your own. As long as you give it your best shot first. That’s the most important thing — to really spend time wrestling with it yourself first. Then, if you had to get some help, before moving on, make sure you analyse the solution(s), and kind of work backwards from there. This is a really important stage in the learning process. You can learn a lot by working out what the solution does and how it does it, and also how to go about “bridging the gap” from what you managed to do (or not) on your own. As long as you understand the code you’re finally posting, that’s job done! :slightly_smiling_face:

  //MInimal
    function minimal (x,y) {
      if (x < y ) {
        return x
      } else {
        return y
      }
    }
      var a = minimal(9,8)
      console.log(a)

    //iSEven
    function isEven (x){

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

    var hasil = 0
    hasil = isEven(2945)
    console.log(hasil)
    //console.log(hasil)

    // Bean Counting

    function countBs (beans) {
      var counter = 0
      for (var i= 0 ; i <= (beans.length-1); i++) {
        if (beans[i] == "B") {
          counter+=1
        }
      }
      return counter
    }

    function countChar(beans,x) {
      var counterx = 0;
      for (var i= 0 ; i <= (beans.length-1); i++) {
        if (beans[i] == x) {
          counterx+=1
        }
      }
      return counterx
    }
    //var semua = countChar("BsfasaBfsfdsdfBfasfaBBdkdB","k")
    //console.log(semua)

    function countBsNew (beans) {
      return countChar (beans,"x")
    }

    var result = countBsNew("baksafaksfgBjaxksbk")
    console.log(result)

1 Like
function isEven(num) {

if (num == 0) return "Even";
if (num == 1) return "Odd";
if (num == -1) return "Odd";
return isEven(num - 2);
}

console.log(isEven(-1));

Here we go. I hope I understood your question properly . If not let me know:)

1 Like

MINIMUM:

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

Once given two arguments, the variable isLess will compare them and with the use of conditionals either value will be returned accordingly. If the 1st value is less than the 2nd the function will return the 1st value. Else if the 1st value is not less than the 2nd value the function will return the second value. If the values are equal it will return the 2nd value, this choice is irrelevant since both arguments are the same.

RECURSION

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

This function’s goal is to check if a given number is even. For this first we show the console two comparisons, one that returns true “Even Number” (x===0) and one that returns false "Odd Number (x===1). The console first checks these two conditional statements and if they both return false, it checks if the value is less than 0 if the result of this comparison is true then it will take the value and run it through the function isEven again but this time with the minus operator before it, converting it into a positive number (negative and negative becomes postive, -(-x) = x. Once it’s a positive value then it runs again through the function, after checking the first two comparisons without success it carries on to the else statement which will substract 2 from the number and run the result through the function over and over again until it reaches either 1 or 0, so it can return the Boleean value required.

BEAN COUNTING:

-CountBs function

function countBs(string){
var addition = 0;
  for (var i = 0; i < string.length; i++){
  if(string[i] === "B") { addition ++;
                        } 
  }
  return addition;
}

This function’s goal is to count the amount of "B"s for a given string. First we create a variable that keeps count, the we create a loop that goes through each character of the given string and within the loop we set a conditional statement that checks wheather each character is a “B” or not if this comparison is true then the 1 is added to the counting variable addition. Once the loop has gone through every character, it return the final sum of “B” characters that it counted.

-CountChar function

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

Much like the previous function, this one those basically the same thing but gives us more freedom since it checks any character that we provide, since a new parameter has been added to it. Now instead of checking for the character “B” as it iterates through the loop, now it compares wether the given char argument is equal to the character that’s being checked by the loop in each iteration. If it matches then 1 is added to the counting variable addition. Once the loop has gone through every character, it returns the final sum of char characters that it counted.

1 Like

Minimum

// Write a function min() that takes two arguments and returns their minimum

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

Recursion

// Recursive function - write a function that returns a boolean value as to whether a number is even(true) or odd(false).

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

Bean Counting

I had to use console.log (or document.write) to get the answers, because the function only takes one return value. Is there a way around this? Also, for some reason I get an “undefined” after the output answers. Does anyone know why?

// Bean Counting - write a function countBs() that takes a string and a character as arguments and that returns the amount of Bs as well as the amount of the specified characters of the string.

			function countBs(string,character) {
				let countB = 0;
				let countChar = 0;
				for (N = 0; N < string.length; N++) {
					if(string[N] == "B") {
						countB++;
					}
					else if(string[N] == character) {
						countChar++;
					}
				}
				console.log(countB);
				console.log(countChar);
			}
1 Like

Nice solutions, @alex.k :ok_hand:

Just a couple of comments…

/* Recursion */

num * -1     // this works fine

// but you can use a unary negation operator instead
-num

Apart from the operator’s name :wink: I think that this is clearer.

By the way, there’s a final part to the Bean Counting exercise. Can you slim down your countBs function so that it still takes just one parameter (the string) but then calls countChar() to always count the number of B’s, but still returns the output itself?

1 Like
//Chapter 3 exercises 16.06.2020
//1st Exercise - Minimum   (done in about 1 minute)
function min(a,b){
  if (a<b) {
  return a;
  } else {
    return b;
  }
}

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

------------------

//2nd Exercise - Recursion 16.06.20
//Completed this in about 15 minutes after reading recursion chapter.

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

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

----------------

/*3rd Exercise - Bean Counting 17.06.20
Attempt 8942-x
Maybe no that many, but spent several hours going round and round 
and trying different things.  Struggled with loop at first so tried:
- a non-scalable series of if/else statements
- implementing string.includes() and string.match() expressions
- incrementing the count using a recursive function and if/else statements
None of these seemed to eventuate to anything so went back to working on the loop.
After finally completing this and looking at the solution, I can see it
is much cleaner than mine and has used a for loop instead of a
while loop.  I can see how much cleaner the solution is in regards to calling
the function countChar inside of countBs as well.  I hadn't thought of that,
so my solution runs through each function separately.
*/
function countBs(myString) {
  let x = "B";
  let counter = 0;
  let stringPos = 0;
  while (stringPos < myString.length) {
    if (myString[stringPos] == x) {
      counter = counter + 1;
    }
    stringPos++;
  }
  return counter;
}

function countChar(myString, x) {
  let counter = 0;
  let stringPos = 0;
  while (stringPos < myString.length) {
    if (myString[stringPos] == x) {
      counter = counter + 1;
    }
    stringPos++;
  }
  return counter;
}

console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4

1 Like

Ok, here’s the code for the final exercise.

function countBsFinal(string){
    return countChar(string, "B");
 }
    document.write(countBsFinal("BBB"));
1 Like

Minimum

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

Recursion

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

Bean counting

function countBs (wordy) {
 // let words = String(wordy);
  let cnt = 0;
  for (let z = 0; z <= wordy.length - 1; z++)  {
     if (wordy[z] === "B") {      
       cnt = cnt + 1;
       //console.log(cnt);
      }     
  }  
  return cnt;     
}
function countChar (words, char) {
  let cnt = 0;
  for (let z = 0; z <= words.length - 1; z++)  {
     if (words[z] === char) {      
       cnt = cnt + 1;
       //console.log(cnt);
     }    
  }    
  return cnt; 
}
1 Like

Nice solutions @hoolie :ok_hand:
… I can see you’ve worked really hard at these! :muscle:

Here are a couple of observations…

Recursion

As the 1st main branch of your conditional execution has the condition  n > 0  there is no point including the  else if  statement in this branch, because its condition  n == 0  can never be true. Instead  n == 0  is caught in the 2nd main branch.

You can therefore remove this else if statement from the 1st main branch, and the program will still work.

Bean Counting

There’s a final part to this exercise. Can you slim down your original countB() function so that it still takes just one parameter (the string) but then calls your second function (you’ll have to change its name) to always count the number of B’s, but still returns the output itself?

Keep on learning!.. You’re making great progress!