Chapter 3 Exercises

Minium:
let Output = function Inputs(a,b){
mini = Math.min(a,b);
return mini
}
console.log(Output(0,-5))

Recursion:
/* Output will be called to get the answer*/
let Output = function isEven(N) {
/* N represent the number users will input*/
N = Math.abs(N)
return (N % 2) == 0;
/* When the user enters a number for N /
/
the program will check if there is a reminder*/
/* no remender means N is even*/
function isOdd(n) {
return (N % 2) == 1;}
/* If there is a reminder than the N is odd*/
function reReturn(N){
return isEven(N - 2)
}
}
console.log(Output(75));

Bean Master:
function countChar(string, char) {
let count = 0;
for (let i = 0; i < string.length; i++) {
if (string[i] == char) { count++ }
}

return count;
}

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

}
console.log(countBs(“Barbados”))
console.log(countChar(“Canada”,“a”));

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

}

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

// -> 3

console.log(countChar("kokkoriko", "k"));

// -> 4
RECURSION

function isEven(num){

num = Math.abs(num);

if(num === 0)

return "number is even";

else if(num === 1)

return "number is odd";

else

return isEven(num - 2);

}

console.log(isEven(50));

console.log(isEven(75));

console.log(isEven(-2));

Minimum

function min(y,x){

if(y < x) return y;

else

return x;

}

console.log(min(75,105));

//->75

console.log(min(31, 55));

//->31

isEven function to determine whether a number is odd or even

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

ALL WORKING

1. Minimum

function smallestNum(...numbersArray) {
    lowestNumber = true;
    numbersArray.forEach(number => {
        if (lowestNumber == true) {
            lowestNumber = number;
        }
        if (lowestNumber > number) {
            lowestNumber = number
        }
    });
    console.log("Currently the lowest number is " + lowestNumber); // for testing purposes
    return lowestNumber // for production purposes
}

2. Even or Odd

function determineIfEven(num1) {
    switch (!isNaN(num1)) {
        case (num1 == 0):
            console.log(true);
            break;

        case (num1 == 1):
            console.log(false);
            break;

        case (num1 > 1 || num1 < 0):
            if (num1 > 1) {
                while (num1 > 1) {
                    num1 -= 2;
                }
            } else {
                while (num1 < 0) {
                    num1 += 2;
                }            
            }
            determineIfEven(num1); 
        
        default:
            break;
    }
}

3. Bean Counter

function countBs(stringInput) {

    stringInput = String(stringInput);
    let letterArray = Array.from(stringInput), count = 0;

    letterArray.forEach(letter => {
        if (letter == "B" && letter == letter.toUpperCase()) {
            count++;
        };
    });
    return count;
}

function countChar(stringInput, charSelect) {

    stringInput = String(stringInput);
    let letterArray = Array.from(stringInput), count = 0;

    letterArray.forEach(letter => {
        if (letter == charSelect) {
            count++;
        };
    });
    return count;
}

Bean Counter
this one worked for me:

function countBs(string){

let resultB=0;
let resultA=0;
for (let count=0; count<string.length; count++){
string[count]==“b” ? resultA ++ : resultA=resultA;
string[count]==“B” ? resultB ++ : resultB=resultB;
}
return [resultA, resultB];
}
let answer=countBs(“BeansBeansBbbBeans”);
alert(answer);

Minimum

function min(a, b) {
if(a < b)
return a;
return b;
}
console.log(min(11, -10));

Recursion

function isEven(a) {
if (a < 0)
a *= -1;
if(a === 0) {
console.log(‘even’);
} else if(a === 1){
console.log(‘odd’);
} else {
isEven(a-2);
}
}
isEven(-1);

Bean Counting

function countChar(searchString, letter) {
let count = 0
for(let i = 0; i < searchString.length; i++) {
if (searchString[i] == letter)
count++;
}
return count;
}
console.log(countChar(‘Assassination’, ‘a’));

1_ Min

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

  console.log(min(11,12));

2_Recursions

 function isEven(x){
    let num = Math.abs(x);
    if (num == 0) {
      return true;
    }
    else if (num == 1){
      return false;
    }
    else return  isEven (num-2);
  }
  console.log(isEven(-2));

For this exercise I lost myself trying to look for a way to use a for loop to induce recursion. it was thoroughly unsuccessful, I had to look for the answer to move forward.

3_1_

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

3_2_

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

console.log(countChar("foot", "o"));

3_3

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

 function countBs(y){
   return countChar(y, "B")
}

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

I struggled ridiculously on this one again, I had to look it up for the first one. then did the second and third by myself.

Minimum

function minimum(n1,n2){
  if(n1 > n2){
    return n2;
  } else {
    return n1;
  }
}

console.log(minimum(10,6));

Recursion

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

console.log(isEven(-50));

Bean Counting
I wanted to try something different from just the for loop, as that seemed to miss the point of the exercise for me considering we just were taught about Recursion. So I used a function’s ability to call on itself, but I struggled to get it done. The issues I had were declaring a global variable and passing ruturn statements from the one function to the other. I had this idea that as long as you have a return in the final function that it would automatically pass to the previous function, this took me 2 hours to figure out that a return need to be placed on the in the countBs() function on the numB() function., but I learned a lot.

var numB = 0;
function numBs(wrds, wLength, numB){
  if(wLength > 0 && wrds[wLength - 1] === "B") {
    numB = numB + 1;
    wLength = wLength - 1;
    return numBs(wrds, wLength, numB);
  } else if(wLength !== 0 && wrds[wLength -1] !== "B"){
    wLength = wLength - 1;
    return numBs(wrds, wLength, numB);
  } else if(wLength === 0){
    return numB;
  }
}

function countBs(wrds){
var wrdsLgth = wrds.length;
return numBs(wrds, wrdsLgth, numB);
}
console.log("Number of Cap B’s: "+ countBs(“BBbbbBBbbb”));

Character Location
This showed me that the previous program I made had some major issues, being the global variable would prevent me for repeating the function without resting it’s values. The solution was the pass the variable instead.

function numBs(wrds, wrdsLgth, numB, kar, numB, sLoc){
  if(wrdsLgth > 0 && wrds[wrdsLgth - 1] === "B") {
    if (wrds[wrdsLgth -1] === kar){
      sLoc = wrdsLgth +" "+ sLoc;
    }
    numB = numB + 1;
    wrdsLgth = wrdsLgth - 1;
    return numBs(wrds, wrdsLgth, numB, kar, numB, sLoc);
  } else if(wrdsLgth !== 0 && wrds[wrdsLgth -1] !== "B"){
    if (wrds[wrdsLgth -1] === kar){
      sLoc = wrdsLgth +" "+ sLoc;
    }
    wrdsLgth = wrdsLgth - 1;
    return numBs(wrds, wrdsLgth, numB, kar, numB, sLoc);
  } else if(wrdsLgth === 0){
    return numB+" Character locations for "+kar+": "+sLoc;
  }
}

function countBs(wrds, kar){
var numB = 0;
var sLoc = “”;
var wrdsLgth = wrds.length;
return numBs(wrds, wrdsLgth, numB, kar, numB, sLoc);
}

console.log("Number of Cap B's: "+ countBs("BBbbbBBbbb", "b"));
console.log("Number of Cap B's: "+ countBs("BBbbbBBbbb", "B"));

Minimum

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

Recursion

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

Bean counting

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

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

function MINIMUM( a , b ){

if ( (a - b) > 0 ){

console.log(+b+ " is the MINIMUM");

}
else if ( ( a -b ) < 0){

console.log(+a+ " is the MINIMUM");

}

else {

console.log(“a and b are equal”);

}
}

function isEven(N){

if ( N === 0 || N === 1) return Boolean(N) ;

else if( N < 0 ) return isEven(-N);

else return isEven( N -2 );

}

function countChar(STRING,CHAR){

var LENGTH = STRING.length ;
var COUNTER = 0 ;

for (i = 0 ; i < LENGTH ; i++ ){

if( STRING[i] === CHAR){
  
  COUNTER ++ ;
}

}

return COUNTER ;

}

console.log( countChar(“BBBBBBAAABBB” , “A” ) );

min( )
This is a trivial problem. Not much to say. I reversed the sense of it just to be different.
GitHub Gist

isEven( n )
The logic on this one’s somewhat contrived (just use if n%2==0). But it’s fairly well laid-out. My only comment here is I see beginners following up a return condition with an else stanza. Fortran-style we omit the else-if nesting nonsense, because the else is that the function continues (77-pun intended). #PoorManSwitch
GitHub Gist

countChar( string, char) + countBs(string)
Again so contrived that I made it count backwards, just for grins.
GitHub Gist

1 Like
MINIMUM:

function minimum(a, b) {
  if (a < b) 
    console.log(a);
  else 
    console.log(b);
  }


RECURSION:

function isEven(a) {
  if (a === 1) 
    console.log(false);
  else if (a === 0)
   console.log(true); 
  else if (a < 0)
   return isEven(-a);
  else return isEven(a-2);
}


BEAN COUNTING:

function countBs(string){
   let count = 0; 
   for (let i = 0; i < string.length; i++) {
   if (string[i] == "B") {
   count += 1;
}}
console.log(count);
}


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

Minimum

  document.write ("<h2>Minimum</h2>");

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

  var a = prompt("Enter the first number.");
  var b = prompt("Enter the second number.");

  var smallest = min(a,b);
  document.write (smallest + " is the smallest of the two numbers. <br />");

Recursion

  document.write ("<h2>Recursion</h2>");

  function isEven (z){
    if (z<0){
      z=z*-1;
    }
    var answer = true;
    if (z == 0){
      return answer;
    }
    else if (z == 1 || z < 0){
      answer = false;
      return answer;
    }
    else {
      return isEven(z - 2);
    }
  }

  var even = isEven(a);
  document.write ("It is " + even + " that the first number you entered is even. <br />");

Bean Counting

  function countBs (str){
    var text = str;
    var bCount = 0;
    for (var place = text.length-1; place >= 0; place--){
      if (text[place] == "B"){
       bCount++;
      }
    }
    return bCount;
  }

  function countChar (str, char){
    var text = str;
    var bCount = 0;
    for (var place = text.length-1; place >= 0; place--){
      if (text[place] == char){
       bCount++;
      }
    }
    return bCount;
  }

  var c = prompt("Enter a string.");
  var d = prompt("Enter character to be counted.");
  document.write ("There are " + countChar(c,d) +" " + d + "s in your string. <br />");

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

console.log (min(3.399, 3.398));

RECURSION
function recur(a) {
a = Math.abs(a);
if (a == 0) return “even”;
else if (a == 1) return “odd”;
else return recur(a-2);
}

console.log(recur(-6));

BEAN COUNTING
function countB(target, word) {
var x = 0;
var y = 0;
while (x < word.length) {
if (word[x] == target) {y = y+1}
x++;
}
return y;
}

console.log(countB(“C”,“BaBBy+BBCBCB”));

  • Exercise 1: minimum
function min(a, b)
{
  if (typeof a != "number" || typeof b != "number")
  {
    console.log("Type error, a AND b must be numbers!");
  }
  else
  {
    if (a < b) return a;
    else return b;
  }
}

// Test type error
min("a", 3);
min(2, "b");

// Test numbers
console.log("min(2, 3) = " + min(2, 3));
console.log("min(5, 4) = " + min(5, 4));
  • 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);
}

// Test
for (let i = 0; i < 10; i++)
{
  if (isEven(i)) console.log("i = " + i + " is even");
  else console.log("i = " + i + " is odd");
}
  • Exercise 3: bean counting
function countBs(chaine)
{
    let compteur = 0;
    for (let i = 0; i < chaine.length; i++)
    {
        if (chaine[i] === "B") compteur++;
    }
    return compteur;
}

// Test
chaine = "Bonjour Bernard Brun, ça va bien ?";
console.log("Il y a " + countBs(chaine) + " 'B' dans la phrase : \n<< " + chaine + " >>");

function countChar(chaine, caractere)
{
    let compteur = 0;
    for (let i = 0; i < chaine.length; i++)
    {
        if (chaine[i] === caractere) compteur++;
    }
    return compteur;
}

// Test
chaine = "Bonjour Bernard Brun, ça va bien ?";
caractere = 'n';
console.log("Il y a " + countChar(chaine, caractere) + " '" + caractere + "' " + "dans la phrase : \n<< " + chaine + " >>");

3.1
function minn (a,b)
{
let result = 0
if (a<b){result=a;} else
{result=b;}
if (a==b) {result=equal;}
return result;
}

3.2
let ff =0
function isEvenb (targetb)
{
if (targetb==0)
{return true;
}else if(1==targetb)
{return false
}else
{return isEvenb (Math.abs(targetb)-2);
}
}
console.log(isEvenb(-150));
3.3
var Bcount=0;
function countChar (g,letter){
let width=g.length;
for (lcount=0;lcount<width;lcount++){
if(g [lcount]==letter) {Bcount=Bcount+1;
}
}
return (${g};${letter};${Bcount});
}
console.log(countChar(“dfgdfrc44”,“r”));

This Function returns the minimum of the pair. The function uses the less than operator to return the value of the x variable or else it returns the value of the Y variable depending which is less than.

function min(x,y) {

if (x<y) return x;

else return y;

}

  console.log(min(?,?));

################################################################

function isEven(n) { /////<–single input perameter
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(?));
The first statement is an IF statement and it determines what if the answer is true by checking if it is equal to zero if not the if passes the value to the else statement and that checks if it is false by compareing it to the number 1 then if not then it passes the value to the final else statement which involke it self within the statement. it takes the value and subtract the value by 2 and it then repeats all the if and else statement until it reduces to the number 1 or 0 and then and give the output. True or False. By adding this Else statement to the function the code will return the eveness of negitive numbers by turning the negatie number postive. and then passing it on to the reset of the statements. ie. else if (n < 0) return isEven(-n);

now the code looks like such :
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(?));

a better code:::::

function isEven(N){

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

N-=2;

isEven(N);

}

else if (N==0){

toReturn = “This is an even number”

}

else if (N==1){

toReturn = “This is an odd number”

}

else {

isEven(-N);

}

return toReturn;

}

console.log(isEven(?));

:::::::::::::::code with negitive included::::::::

function isEven(N){

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

N-=2;

isEven(N);

}

else if (N==0){

toReturn = “This is an even number”

}

else if (N==1){

toReturn = “This is an odd number”

}

else if (N==-0){

toReturn = “This is a Negitive even number”

}

else if (N==-1){

toReturn = “This is a Negitive odd number”

}

else {

isEven(-N);

}

return toReturn;

}

#################################################################

This Code is to Count the letter B’s within a sentence
with use of a single peramiter function one can create a function called countBs.By using let stringLength equal aString.length and let numofBs=0; as a constent then a for loop is created to read the sentence at hand then conditions can be introduced to the code, if aString [i] is to define the sentence is equal to “B” then with use of numofBs+=1 this conditions assures the counting of the B’s. and with the addition of return numofBs; will give use the sum of capital Bs , i have also incuded the second code to count lower case b’s. the third code will count words in a sentence, using charcount function.

function countBs(aString){
let stringLength = aString.length;
let numOfBs=0;
for(i=0;i<stringLength;i++){
if(aString[i]==“B”){
numOfBs+=1;
}
}
return numOfBs;
}

console.log(countBs(“Boston Bake Beans and beer for Beerfest”));

::::::::::Code 2

function countBs(aString){

let stringLength = aString.length;

let numOfBs=0;

for(i=0;i<stringLength;i++){

if(aString[i]==“B”){

 numOfBs+=1;

}

else if(aString[i]==“b”){

	numOfBs+=1;

}

}

return numOfBs;

}

console.log(countBs(“Insert Sentence That have Bs here Bro.”));

::

second part of the code question::

function countChar(newString,aChar){
let stringLength = newString.length;
let count=0;
for(i=0;i<stringLength;i++){
if(newString[i]==aChar){
count+=1;
}
}
return count;
}
console.log(countChar(“Pop Stars Popping Bottles”));

Exercises Chapter 3

  1. Minimum
  2.   function minimum(a,b){
      var min = 0;
    
      if(a<b){
        min = a;}
      else{
        min = b;}
    
      return min;
    }
    

  3. Recursion
  4. function isEven(N){
      var isit = 0
    
      if(N==0){
        isit = true;
      }
      else if (N==1) {
        isit = false;
      }
      else if (N<0){
        isit = isEven(N+2);
      }
      else {
        isit = isEven(N-2);
      }
    
      return isit
    }
    
    console.log(isEven(75));
    

  5. BeanCounting
  6. function countChar(Testtext, Zeichen){
      var ZeichenAnzahl = Testtext.length;
      var counter = 0;
    
      for(var posCount = 0; posCount < ZeichenAnzahl; posCount++){
        if(Testtext[posCount] == Zeichen){
          counter++;
        }
        else{
          //counter = counter;
        }
      }
      return counter;
    }
    
    console.log(countChar("Test this text!","t"));