Chapter 3 Exercises

Hello thecil,

Thank! I’ve been doing better with the exercises, but still have questions, I will post as I go along. This one is a solution, I couldn’t figure it out when I analyze it “num in list” specifically “num” and “num in”. I did not know about this or could find it anywhere in my searches. Can you explain what it is. i.e. keyword or something like that:

const list = [6, 4, 1, 7, 2, 8, 3, 9, 11];

var smallest = list[0];
for (num in list){
if (num < smallest){
smallest = list[num];
}
}

console.log(smallest);

var largest = list[0];
for (num in list){
if (num > largest){
largest = list[num];
}
}

console.log(largest);

1 Like

Here is the code but commented to understand te process of this script:

/*
//array of constant numbers 
//const define a variable which value(s) will always be the same (constant values)
*/
const list = [6, 4, 1, 7, 2, 8, 3, 9, 11];
//bind value of list[0] in variable 'smallest'
var smallest = list[0];
//for loop, iterate 'num' over the list array
for (var num in list) {
  //if num value is less than 'smallest' value, do...
  if (num < smallest) {
    //assign the new value to 'smallest'
    smallest = list[num];
  }
}
//print 'smallest' value in console
console.log(smallest);

//same process but for the largest number in the array
var largest = list[0];
for (num in list) {
  if (num > largest) {
    largest = list[num];
  }
}

console.log(largest);

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1st exersize:
Math.min(3, 89)
3
function min(x, y){
return console.log(Math.min(x, y))
}

undefined
min(43, 5)
5

  1. recursion exersize help https://www.youtube.com/watch?v=lkom4MrsTTU
  2. Here is a really helpful video on the last problem https://www.youtube.com/watch?v=3ZyG-lpl1w0&t=8s
1 Like
// create a recursive function to find if a number is even or odd without %
// Your code here.
 function isEven(n){

   //what is the input is negative
   if(n < 0){
     // make n not negative
     //math.abs gives us the absolute value of the number
     n = Math.abs(n);
   }

   // if n is 0
   if (n === 0){
     //return true
     return true;

   }

  //if n is 1
  if (n === 1) {
    //return false
    return false;
  }
// above this is the base cases (n === 1)(n === 0)

// under this is the recursive case
   // in all other cases apply isEven to n minus 2
   return isEven(n - 2);
 }
 console.log(isEven(-1));

 // because this function calls for isEven which is itself that makes this a recursive
 //--> solution (continued)
//create a function countBs that takes a string as its only argument and returns a number that
//indicates how many uppercase B's are in the string



function countBs(string){
//return a call to countChar with input 'B'
  return countChar(string, 'B');
}




function countChar(string, character){
  // create a result set it to 0
   let result = 0;

  // loop over the current string
  for(let i=0; i < string.length; i++){
    // if current character is a "B"
    if(string[i] === character) {
        // increment result by 1
        result = result + 1;
    }
  }

  //return result
    return result;

}
console.log(countBs("BBBBFBBC"))
console.log(countChar("kakkkkkkerlakjkujj", 'k'))
1 Like

any idea when I type the same thing in my browser i get an error? how is he able to run the ajax or json or whatever it is that it is doing and i am not?

1 Like

Hi @monstrosity, hope you are good.

You should not follow the commands used in that video, they are using tools that are not being explain, all they want is to show you the entire result of the process, but no how the process is made.

Their probably using a web-server software to run a file which contain the logic for that call.

Just to give you a quick understanding on that line:

  • http://127.0.0.1 is a local IP assigned by default in most software that is running locally in a PC, you can also use the keyword “localhost” to refer to the same address.
  • :8080 is the port number used to assign that software to communicate in the network. Is set by default but it can be customized to other port.
  • /quote?symbol=NFLX should be a function that exist inside of the invoked file from the webserver.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

// MINIMUM
function minimum(x,y){
return x<=y ? x : y;
}

//ISEVEN
function isEven(num){
num = num<0 ? -1*num : num; // convert negatives to positive
var result = num;
if(result>1) result = isEven(result-2);
return result;
}

//BEAN COUNTING
function countChar(text, char){
var charCount = 0;
for(var x=0;x<text.length;x++){
if(text[x]==char) charCount++;
}
return charCount;
}

1 Like

Ch. 3 Exercise Answers

function pico(num1, num2){
if(num1<num2){
return console.log(num1);
}else if(num2 < num1){
return console.log(num2);
}

}
console.log(pico(1000, 4));
console.log(pico(1, -4));

function isEven(n){
if(n%2==0){
return console.log(true);
}else return console.log(false);
};

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

function countBs(word){
let counter = 0;

for(let count=0;count < word.length; count++){
if(word[count] == “B”){
counter+=1;
}
}
return counter;
}

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

function countChar(word, abc){
let runner = 0;
for(let count = 0; count<word.length;count++){
if(word[count] == abc){
runner+=1;
}
}
return runner;
}

console.log(countChar(“kakkerlakK”, “k”));

1 Like

These are not the most eloquent answers, but here I go:

Minimum function:

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

isEven, part 1

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

isEven, part 2

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

countBs

function countBs(TEXT) {
 let Bcount = 0;
 if (typeof TEXT === "string") {
    for(var position = 0; position <= TEXT.length; position++) {
      if (TEXT[position] === "B")
      Bcount++;
    };
    return Bcount;
  }
  else return "ERROR NOT A STRING";
};

countChar Checking type for second variable is not necessary because the function will work, and show there are zero of the second value. If I want the second value to be checked, I can use if (typeof TEXT === “string” && typeof CHAR === “string”)

function countChar(TEXT, CHAR) {
 let charCount = 0;
 if (typeof TEXT === "string") {
    for(var position = 0; position <= TEXT.length; position++) {
      if (TEXT[position] === CHAR)
      charCount++;
    };
    return charCount;
  }
  else return "ERROR NOT A STRING";
};
1 Like

Okay. I basically completed the task after like an hour of researching, and this thread helped a lot, but I still don’t understand what is happening at Excercise2. (3rd day of programming…)
Could someone be so kind and explain in plain English what is going on here??

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

console.log(isEven(50));

I don’t understand how on Earth “return isEven(a-2);” produces a Boolean and how it understood that it is “true” at all. In my mind this should just print 48 (based on the example). I think I am really over/under thinking something here… Please help!!

1 Like

Hi @andor, hope you are ok.

I will comment step by step your code so you can understand what is happening or how it calculate the Even number.

//function get a number "a", evaluate conditions
function isEven(a){
 //if number is equal to 0, return true
 if (a == 0){
 return true;
 }
 //else if number is equal to 1, return false
 else if (a == 1){
 return false;
 }
 //else, return the function evaluating (a-2), will return false or true
 else {
 //this will create a loop by taking "a-2",until the number is 0 or 1
 return isEven(a-2);
 }
}

console.log(isEven(50));

So basically the function will: (for a = 50)

  • Evaluate the 1st condition (50 is not equal to 0).
  • Evaluate the 2nd condition (50 is not equal to 1).
  • Else, restart the function but take minus 2 on the argument A (a-2) .
  • will repeat the same process until the number is 1 or 0.

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

Minimum Exercise

function minimum(a, b){
          if(a < b){
            alert(a);
          }
          else if(b < a){
            alert(b);
          }
        }

Recursion Exercise

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

Bean Counting Exercise

function countBs(s){
            let count = 0;
            for(let i = 0; i<s.length; i++){
              if(s[i]==="B"){
                count++;
              }
            }
            return count;
          }
          function countChar(s, char){
            let count = 0;
            for (let i = 0; i < s.length; i++){
              if(s[i]===char){
                count++;
              }
            }
            return count;
          }
1 Like

Math Minimum Exercise

function min(a,b){
if(a<b){
return console.log(a);
}
else if(b < a){
return console.log(b);
}
}
console.log(min(5,4));

Recursion Exercise

function isEven(x){
if(x%2==0){
return console.log(true);
}else return console.log(false);
};

console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1)); // Why? Because it is a negative number

Bean Counting Exercise
Not Answered :stuck_out_tongue:

@thecil Carlos Sir,
Thank you very much for taking the time to reply to me.
It is much more clear now!

1 Like

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

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

function countBs(str) {
let count=0;
for ( i=0; i<str.length; i++) {
if (str[i]=== “B”) {
count++;}
}
return count;
}

function countChar(str,char) {
let count=0;
for ( i=0; i<str.length; i++) {
if (str[i]=== “char”) {
count++;}
}
return count;
}

1 Like

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

function isEven (n){
if (n<0)
n=Math.abs(n);
if (n === 0)
return true;
if (n === 1)
return false;

  return isEven (n-2);

}

Bean

function countBs (string){
let result = 0;
for (let i = 0; i<string.length; i++) {
if (string [i] === B)
result += 1;
}
}
return result;

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

1 Like

Minimum
function min (a,b){
if (a<b){
return (a);} else {return (b);}
}
console.log(min(8,9));

1 Like

Exercise 1

let a=prompt (“hello, choose a number”);
let b=prompt (“hello, choose another number”);
function minimum(a,b)
{if (a>b) return("the minimum is “+b);
else return"the minimum is “+a};
document.write(minimum(a,b)+”\n”);

Exercise 2

let n=prompt (“hello, choose an even number”);
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)};
document.write("the number is "+isEven(n))

Exercise 3
I am stuck with this one, even when reading the solution i dont understand it.
I dont understand the string and charecter…

You can get the Nth character, or letter, from a string by writing “string”[N].
The returned value will be a string containing only one character (for example,
“b”). The first character has position 0, which causes the last one to be found at
position string.length - 1. In other words, a two-character string has length
2, and its characters have positions 0 and 1.
Write a function countBs that takes a string as its only argument and returns
a number that indicates how many uppercase “B” characters there are in the
string.
Next, write a function called countChar that behaves like countBs, except
it takes a second argument that indicates the character that is to be counted
(rather than counting only uppercase “B” characters). Rewrite countBs to
make use of this new function.

Could anyone explain it to me?

MINIMUM

function getMin(x, y){
          var minimum = Math.min(x,y);
          return minimum;
        }
// Test
var answer = getMin(5, 10);
alert(answer);

RECURSION

function isEven(number){
var value = false;
if(number % 2 == 0){
      value = true;
    }
      return value;
}
// Test 1
var answer = isEven(4);
alert(answer);

// Test 2
answer = isEven(5);
alert(answer);

BEAN COUNTING

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

// FUNCTION TWO
function countChar(string, letter){
var toReturn = 0;
for(var i = 0; i < string.length; i++){
      if(string[i] == letter){
         toReturn++;
       }
    }
return toReturn;
}
//Function 1 - test
var num = countBs("BaBandtBandBTwo");
alert(num);

//Function 2 - test
num = countChar("ToungueTwisTers", "T");
alert(num);
1 Like

FINDING MINIMUM

function min(x,y){
ergebniss=(Math.min(x,y));
console.log(ergebniss);
}

IS EVEN FUNCTION

function isEven(a){
if(a==0){console.log(“even”);
else if(a==1){console.log(“not even”);
else{return isEven(a-2)};

B.COUNTING

function countBs(str){
let BsReturn=0;
for(c=0;c<str.length;c++){
if(str[c]==“B”){BsReturn++;
}
}
console.log(BsReturn);
}

function countChar(str,X){
let BsReturn=0;
for(c=0;c<str.length;c++){
if(str[c]==X){
BsReturn++;
}
}
console.log(BsReturn);

1 Like