Chapter 3 Exercises


#82

Hi ian,

this is the Statement:

if (string[i]==“B”)

If you want zo test it, you can do something like:

console.log(“Test String”[2]);

This will give you the “s”,


#83

Minimum

function minimum(a,b)
{
if(a>b){ return b;}
else if(a<b){ return a;}
else return “Numbers are equal”;
}

var no = minimum(3,6)
console.log(no);

Recursion

function iseven(a){
if(a%2==0)
{ return “even”;}
else if (a%2==1) {
return “odd”;}
else return iseven(a-2);

}

var b= iseven(50);
console.log(b);

Bean Counting

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

return count;
}

var countingBs= countBs(“BoolbBoolB”)
console.log(countingBs);


#84

Yes Counted should be count. I don’t know why I wrote counted. As for the countBs function I wrote

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

Is’nt the return correct in that?


#85

//MIN
function min (a,b){
if(a<b) return a;
else if(a>b) return b;
else return “a=b=”+a;
}

var a = prompt ("MinFct : First number = ");
var b = prompt ("MinFct : Second number = ");
var ans = min(a,b);
alert(ans);

//IsEVEN
function isEven (a){if(a<0) a=-a;
if(a==0) return ‘even’;
else if(a==1) return “odd”;
else {
a = a-2;
return isEven(a);
}
}
a = prompt ("isEven : number = ");
var ans2 = isEven(a);
alert(ans2);

//countBs
function countBs (word){ var Bs = 0;
for(i=0;i<word.length;i++){
if(word[i]==“B”) Bs+=1;
}
return Bs;
}

var word = prompt ("countBs : give me Word = ");
var ans3 = countBs(word);
alert(ans3);

//countcountChar
function countChar (word,c){ var Bs = 0;
for(i=0;i<word.length;i++){
if(word[i]==c) Bs+=1;
}
return Bs;
}

word = prompt ("countChar : give me Word = ");
var c = prompt ("countChar : Letter to look for = ");
var ans4 = countChar(word,c);
alert(ans4);


#86

Thanks! :slight_smile: It would have helped if I had not been using testString[4] when the fifth character in my string (counting from zero) was a space! :wink:

The following worked fine for my test, before starting on the logic of counting Bs.

    function countBs(testString) {
      return testString[5];
    }

    console.log(countBs("Arty Budget Bouquet! Buy before it's too late!"));
    alert("Arty Budget Bouquet! Buy before it's too late!");

As you will be aware, the alert showed my whole string, and the Console received just the B.

And the following worked identically.

    function countBs(testString) {
      return testString[5];
    }
    let myString = "Arty Budget Bouquet! Buy before it's too late!";
    console.log(countBs(myString));
    alert(myString);

#87

And here’s my Bean Counting exercise!

    let testChar = "B";
    let myString = "Arty Budget Bouquet! Buy before it's too late!";

    function countBs(testString) {
      let count = 0;
      let i = 0;
      while (testString.length > i) {
        if (testString[i] == testChar) {
          count++;
          i++;
        }
        else {
          i++;
        }
      }
      return count;
    }
    console.log(myString);
    alert(countBs(myString));

AND the generalised function:

    let myString = "Arty Budget Bouquet! Buy before it's too late!";

    function countChar(testString,testChar) {
      let count = 0;
      let i = 0;
      while (testString.length > i) {
        if (testString[i] == testChar) {
          count++;
          i++;
        }
        else {
          i++;
        }
      }
      return count;
    }
    console.log(myString);
    alert(countChar(myString,"b"));

#88

Here are my answers to the excersice. In all cases, an invalid input will cause a “NaN” as an output:

Minimum
function minimum(num_a, num_b) {
  let min_num = 1;
  if (!(isNaN(num_a)) && !(isNaN(num_b))) {
    if (num_a == num_b) {
      min_num = num_a
    }
    else if (num_a > num_b) {
      min_num = num_b;
    }
    else {
      min_num = num_a;
    }
  }
  else {
    min_num = NaN
  }
  return min_num;
}
Recursion
function isEven(num) {
  if (!(isNaN(num))) {
    if (num % 1 == 0) {
      if (num < 0) {
        num *= -1;
        isEven(num);
      }
      else {
        if (num == 0) {
          ev = true;
        }
        else if (num == 1) {
          ev = false;
        }
        else {
          num -= 2;
          isEven(num);
        }
      }
    }
    else {
      ev = NaN;
    }
  }
  else {
    ev = NaN;
  }
  return ev;
}
Bean Counting
/* Counts only Bs */

function countBs(text) {
  let i = 0;
  let count = 0;
  while (i < text.length) {
    if (text[i] === "B") {
      count++;
      i++;
    }
    else {
      i++;
    }
  }
  return count;
}

/* Counts any character */

function countChar(text, char) {
  let i = 0;
  let count = 0;
  if (char.length == 1) {
    while (i < text.length) {
      if (text[i] === char) {
        count++;
        i++;
      }
      else {
        i++;
      }
    }
  }
  else {
    count = NaN;
  }
  return count;
}

#89

Minimum

function min(a, b) {
 	if(a == null || b == null ) { // if either a or b is undefined
 		console.log(-1);
 		return -1;
 	}
 	else if(a < b){
 		console.log(a);
 		return a;
 	}
 	else { // covers case were b < a and when a === b
 		console.log(b);
 		return b;
 	}
 }

Recursion

  function isEven(num) {
    	if(num < 0) {
    		console.log(num + " <  0");
    		return -1;
    	}
    	else if(num === 0){
    		console.log(num + " is even");
    		return true;
    	}
    	else if(num === 1){ 
    		console.log(num + " is odd");
    		return false;
    	}
    	else if(num > 1) 
    	 	return isEven(num - 2);
    }

Bean Counting

function countBs(str){
	let bNum = 0;
	for(let i=0; i<str.length; i++){
		if(str[i] === "B")
			bNum++;
	}	
	console.log("The number of uppercase 'B' characters in the string " + str + " is: " + bNum);
	return bNum;
}

countBs("Blowing Bubbles");
countBs("Blowing BuBBles");


function countChar(str, index) {
	var bNum = 0;
	for(let i=0; i<=index; i++){
		if(i === index && str[i] === "B")
			bNum++;
	}
	console.log("The character in the string " + str + " at index " + index + " is: " + str[index] + ".  Number of uppercase 'B' characters is: " + bNum);
	return bNum;
}

countChar("Bubbles", 0);
countChar("bubBles", 3);
countChar("Bubbles", 2);

#90

Chapter 3 Exercise - Minimum

let n1 = Number(prompt("Enter a number (no input = 0):"));
let n2 = Number(prompt("Enter another number (no input = 0):"));

//function for determining minimum
function findMin(x1, x2)
{
  if(x1 < x2)
  {
    return x1;
  }
  else if(x2 < x1)
  {
    return x2;
  }
}

//Output on console
if(n1 == n2)
{
  console.log(n1 + " and " + n2 + " are equal.");
}
else if(Number.isNaN(n1) || Number.isNaN(n2))
{
  console.log("Did you enter a number?");
}
else
{
  console.log("The minimum value is " + findMin(n1,n2) + ".");
}

//Output on webpage
if(n1 == n2)
{
  document.write("<h2>" + n1 + " and " + n2 + " are equal.</h2>");
}
else if(Number.isNaN(n1) || Number.isNaN(n2))
{
  document.write("<h2>Did you enter a number?</h2>");
}
else
{
  document.write("<h2>The minimum value is " + findMin(n1,n2) + ".</h2>");
}

Chapter 3 Exercise - Recursion

let n1 = Number(prompt("Enter a whole number (even = true & odd = false):"));

console.log(isEven(n1));

function isEven(x1)
{
  if(x1 == 0)
  {
    document.write("<h2>" + n1 + " is even.</h2>");
    return true;
  }
  else if(x1 == 1)
  {
    document.write("<h2>" + n1 + " is odd.</h2>");
    return false;
  }
  else
  {
    if(Number.isNaN(x1)) //If not a number
    {
      document.write("<h2>" + x1 + " is not a number.</h2>" );
      console.log(x1 + " is not a number.");
    }
    else if(x1 < 0) //If the number is negative
    {
      return isEven(x1 * -1);
    }
    else //If the number is >1
    {
      return isEven(x1 - 2);
    }
  }
}

Chapter 3 Exercise - Bean Counting (countBs)

let word = String(prompt("Enter some text:"));
alert("The 'B' count will commence.");

console.log("The character 'B' appears " + countBs(word) + " time(s) in \"" + word + "\".");
document.write("<h2>The character 'B' appears " + countBs(word) + " time(s) in \"" + word + "\".</h2>");


function countBs(text)
{
  let charcounter = 0;

  for(let i = 0; i < text.length; i++)
  {
    if(text[i] == "B")
    {
      charcounter++;
    }
  }

  return charcounter;
}

Chapter 3 Exercise - Bean Counting (countChar)

let word = String(prompt("Enter some text:"));
let character = String(prompt("Enter a letter to determine the character count in the text:"));

console.log("The character '" + character + "' appears " + countChar(word, character) + " time(s) in \"" + word + ".");
document.write("<h2>The character '" + character + "' appears " + countChar(word, character) + " time(s) in \"" + word + "\".</h2>");


function countChar(text, charElement)
{
  let charcounter = 0;

  for(let i = 0; i < text.length; i++)
  {
    if(text[i] == charElement)
    {
      charcounter++;
    }
  }

  return charcounter;
}

#91

Minimum

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

Recursion
To fix the issue with negative numbers, whenever the number is negative it gets
multiplied by -1, to get it to be positive.

<script>
function isEven(n){
  if(n<0){ // this if takes care of the negative case, flipping the value to positive
    n=-n;
    return isEven(n);
  }
  else if(n==0){
  return   true;
  }
  else if(n==1){
  return   false;
  }
  else {
  return  isEven(n-2)
  }
}
</script>

Counting B’ s

<script>
function CountB(s){
let n=0;
let CB =0;
while(n<s.length){
  CB=CB+(s[n]=="B");
  n=n+1;
}
return CB
}

Counting other characters

<script>

// s is a string, ch is also a string of length 1

    function CountChar(s,ch){
    let n=0; // n is counter that will run over the letters of s
    let CB =0; // CB is a variable that will store the result
      while(n<s.length){
        CB=CB+(s[n]==ch); // note:  true+true=2, true+false=1
        n=n+1;
      }
    return CB
    }
    </script>

#92

Hi criberio

In your code for minimum: if you drop the console.log(a) and console.log(b) does
the code still works? do you really need it?


#93

// MINIMUM
function min(a,b){
if(a<b) return a;
if(b<a) return b;
return “N/A”;
}
console.log(min(5,10));
console.log(min(-1,50));

// RECURSION
function abs(x){
if (x<0) return x*-1;
return x;
}
function isEven(N) {
if (N==0) return true;
if (N==1) return false;
return isEven(N-2);
}
console.log(isEven(abs(50)));
console.log(isEven(abs(75)));
console.log(isEven(abs(-1)));

// BEAN COUNTING
function countChar(phrase,char){
j=0;
for(i=0;i<phrase.length;i++){
if(phrase[i]==char) j++;
}
return j;
}

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

console.log(countBs("Bubbles is a Bad Boy"));
console.log(countChar("kakkerlak", "k"));

==================================================
Alas, I found the instruction by Ivan, as well as the [pretty poorly chosen, IMHO] videos, to be in the format I’m accustomed to. But the book came at things in a way I didn’t really grasp. For example, the first thing shown was

const square = function(x) {
return x * x;
};

I don’t understand this construction.

They later mention this:
function square(x) {
return x * x;
}

and describe it as “slightly simpler”. It sure is. I can tell what it means.

THEN, came the => figure as in:

const power = (base, exponent) => {
let result = 1;
for (let count = 0; count < exponent; count++) {
result *= base;
}
return result;
};

Between the => and the setting of a binding (which everyone calls “variable”, after we were “taught” not to think of it that way, I’m very aware that I’m “getting by”, but that I don’t really understand. Am I alone in this? If there are folks out there as adept at explaining as they are at understanding, I’d love to hear from you.


#94

Exercise 3 # 1
function min(one, two){
if (one < two)
return one;
else return two;}
console.log(min(24,100));
Exercise 3 # 2
function isEven(x)
{
if (x == 0)
{
return true;
}
else if (x == 1)
return false;
else
return isEven(x - 2);
}
console.log(isEven(-1));

Exercise 3 # 3
function charCount(str, letter)
{
var letterCount = 0;
for (var position = 0; position < str.length; position++)
{
if (str.charAt(position) == letter)
{
letterCount += 1;
}
}
return letterCount;
}

function countBs(str) {
return charCount(str, “o”);
}

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


#95

//Question # 4 Eloquent Javascript

Basically it compares one parameter against the other. If the left hand value is less than the right hand value based on the < operand, it will return left hand value. and by using an else statement, it will otherwise return the right hand value if it is false.

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

console.log(min(283747, 38485698));

//Question # 5 Eloquent Javascript

Since we are instructed to name the function isEven we set the Boolean value True to represent an even number. We select 0 as a baseline value and use an else statement to return false if the value is 1 (odd). We can then “recursively” have the function call itself to evaluate the mathematical proof (n-2) which was a hint provided in the exercise question.

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

console.log(isEven(6));

//Question # 6 Eloquent Javascript

I was able to google a function for returning the character count of a string. (whoops, cheating!). But it basically re-iterates the looping concepts we just learned and using the str.length feature which was a hint in the question. Than you just need to return the result of the character count function in the code block of the function we were instructed to create: countBs(str).

function char_Count(str, letter)
{
 var letter_Count = 0;
 for (var position = 0; position < str.length; position++)
 {
    if (str.charAt(position) == letter)
      {
      letter_Count += 1;
      }
  }
  return letter_Count;
}

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

console.log(countBs("BBC"));

#96

Good stuff. I have basically the same solution on the first two. I’m still working
on “counting.” Am I missing something or are you not supposed to give it a string
to test? Otherwise how can you tell it’s properly counting the given character in
a string?


#97

minimum

function min(x,y){

if (x > y)
return(y)
else {
return(x)
}

}

Recursion

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

Bean Counting

function bcounter(word, letter){
var b = 0
for(var count = 0; count < word.length; count++){

if (word.charAt(count) == letter)
b++

}
console.log(b)
}


#98
1.
function min (x,y){
if (x<y) return x;
else return y;
}
console.log(min(2,4));

//OR 

**console.log(Math.min(2,4)); //2**

2. A working solution with modulus method.

//Your code here.
function isEven(num){
 if(num % 2 == 0){return true;} else{return false;}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
 
OR working solution base on the book exercise without modulus. 

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

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

3. I am finally got full working solution for exercise 3 :smile: .

// Your code here.
function countChar(stringNumber, char){
var str = stringNumber.length;
let counted = 0;
for (let i = 0; i < str; i++) {
if(stringNumber.charAt(i) == char ){
counted += 1;
}
}
return counted;
}
function countBs(stringNumber){
return countChar(stringNumber, "B");
}
console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4

#99

Minimum

function min(a,b){
    console.log(a<b?a:b);
}

min(75,9);
// 9
min(9,9);
// 9
min(9,0);
// 0

Recursion

function isEven(a){
    a==0||(a-2)==0?even=true:(a-1)==0?even=false:isEven(a-2);
    return even
}

console.log(isEven(50));
// true
console.log(isEven(75));
// false
console.log(isEven(0));
// true
console.log(isEven(-1));
// RangeError: Maximum call stack size exceeded (line 3 in function isEven)

/* 
This program recursively subtracts 2 from the number, checks if it is
even against 0, and if not, checks if it is odd against 0 by subtracting 1.
The initial parameter of checking if the number is 0 is necessary to avoid
the same issue with the number being -1, i.e. infinite repition as the
range is negative and always less than the comparison parameters for each
case, thus defaulting to the recursive isEven call
*/

Bean Counting

function countChar(a,char){
    let count = 0;
    for(i=0;i<a.length;i++){
        a[i]=="B"?count++:{}
    }
    return count;
}

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

console.log(countBs("BeanStalks make Beans baby!"));
// 2

#100





#101

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

function isEven(a){
if (a == 0){return true;}
else if (a == 1){return false;}
else {isEven(a-2);}
}
//is even recursive

function countB(a,b){
let counter= 0;
for (i=0;i<a.length;i++){
if (a[i] == b){counter++;}
}
return counter;
}

countB(“Boss Baby”,“B”);
2

Technically we were not asked to post these solutions here :slight_smile: