Chapter 3 Exercises

Function to find minimum:

I returned a string rather than just the number…

<script>

function minimum(a,b){
  var result = ""
  if (a==b) return result = "They are the same";
  else if (a>b) return result = "The first one is larger";
  else return result = "The second is larger";
}

var numbersToCompare = minimum(7,7);

document.write("<h1>" + numbersToCompare + "</h1>")

</script>

Recursion:

<script>

function isEven(x){
var result = “”;
if (x < 0) return result = “That’s negative, bozo.”;
let numberToTest = x;
for (var counter = 0; counter<x+1; counter++){
if (numberToTest == 0) return result = “It’s Even”;
else if (numberToTest == 1) return result = “It’s Odd”;
else numberToTest = numberToTest-2;
}
}

var result = isEven(-1);

document.write("

" + result + “

”)
</script>
1 Like

1. Minimum

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

    var answer = min (3,2);
    document.write(answer);

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

    var output = isEven(75);
    document.write(output);

3. Bean Counting

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

    document.write(countChar("BuBa", "B"));
1 Like

Bean Counting

<script>

function countChar(string, charToCount){
  var numberOfLetters = string.length;
  var numberOfChars = 0;
  for (var counter = 0; counter<numberOfLetters; counter++){
    if (string[counter] == charToCount) numberOfChars++;
  }
  return numberOfChars
  }

var result = countChar("HelloHiLetsWriteJavascriipt", "i");

document.write("<h1>" + result + "</h1>")

</script>
1 Like

//exercise function minimum
function minim(a,b){
if(a<b)
return (a);
else return(b);
}
console.log(minim(5,7));

//////////
//code execise oddeven
function genapGanjil(x){
if(x<0) {return false;}
else if(x==0){return true;}
else if(x==1){return false;}
else return (genapGanjil(x-2));
}
console.log(genapGanjil(-5));

///////////////
//exercise count beanstring

function countChar(string,char){
var count=0;
for (let i=0;i<string.length; i++){
if(string[i]==char){
count+=1;
}
}
return count;
}
function countBs(string){
return countChar(string,“B”);
}
console.log(countBs(“BarBarosBar”));

1 Like

// EXERCISE Minumum

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

 console.log (min(3,6)
 // → 3

// EXERCISE Recursion

function isEven(n) {
// what if the input is negative
if (n < 0) {
// make n not negative
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;
}

// in all other cases, apply isEven to n minus 2
return isEven(n - 2);
}

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

//EXERCISE Bean Counting

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

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

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

  // return result
  return result;
}

console.log(countBs("ABBA"));
// → 2
console.log(countChar("javascript", "a"));
// → 2
1 Like

I think it’s the === when comparing your string position value to B. Try == and it should work? === means ‘precisely equal to’ and does not apply type conversion.

These are hard… then once you get them figured out, they look easy. Feeling a bit dense! Here’s what I came up with, then I added some prompt variables to make interactive web pages.

        <script>

var a = prompt("Input first number")
var b = prompt("Input second number")

        function small(a,b){
          if (a<b){
            return a;
          }
          else if (b<a){
            return b;
          }
          else if (b == a){
            return "AAHHHAH you broke me I cannot compute which";
          }
        }

document.write(a + " is your first number" + "<br>")
document.write(b + " is your second number" + "<br>" + "<br>")
document.write(small(a,b) + " is the smaller number.");


        </script>
<script>

var a = prompt("Please enter the number you'd like me to check");
document.write("You asked me to check " + a + "<br>");

function oddOrEven(n){
  if (n == 0){
    return "even";
  } else if (n == 1){
    return "odd";
  } else if (n < 0){
    return oddOrEven(-n);
  } else {
    return oddOrEven(n - 2);
  }
}

document.write("<br>" + "Your number is " + oddOrEven(a));

        </script>
<script>

    var s = prompt("Write text here");
    var c = prompt("What value should I check for?");
document.write("I can count how many characters exist within a string." + "<br>");
document.write("Here is the string you asked me to check: " + s + "<br>");
document.write("Here is the value I'm counting: " + c + "<br>");

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

document.write("I can count " + countChar(s, c) + " " + c + "'s within your input.");

    </script>
1 Like
      // Minimum
      let min = function(a,b){
        return (a < b ? a : b)
      };
      // Recursion
      let abs = x => x<0 ? -x : x
      let isEven = function(a){
        return (a === 0 ? true : (abs(a)===1 ? false : isEven( abs(a)-2 )))
      };
      // Bean counting
      let countChar = function(str,char){
        let Bs = 0;
        if (typeof(str) !== "string" ) return 0;
        for(let i=0;i<str.length;i++){
          if(str[i]===char[0]) Bs++;
        }
        return Bs;
      };
      let countBs = function(str){
        return countChar(str,"B");
      };
1 Like
//Minimum
const min = (arg1, arg2) => {
  if (arg1 === arg2){
    return arg1
  } else if (arg1 < arg2 ? arg1 : arg2)
}

//Recursion
const isEven = num => {
  if (typeof(num) === 'number') {
    if (num < 0) {
      return num + ' is not a positive integer.';
    }
    if (num === 0) {
      return true;
    }
    if (num === 1) {
      return false;
    } else {
      return isEven(num - 2);
    }
  }
}

//Bean Counting
const countBs = string => {
  let count = 0;
  let index = 0;
  while (index < string.length) {
    if (string[index] === 'B'){
      count++;
    }
    index++;
  }
  return count;
}

//Bean Counting II
const countChar = (string, target) => {
  let count = 0;
  let index = 0;
  while (index < string.length) {
    if (string[index] === target){
      count++;
    }
    index++;
  }
  return count;
}
1 Like

Minimum

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

Recursion

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

Bean counting

function countBs(string){
var counter = 0;
for(i = 0; i < string.length; i++){
if (string.charAt(i) == “B”)
counter++;
}
return counter;
}

function countBs(string){
var counter = 0;
for(i = 0; i < string.length; i++){
if (string.charAt(i) == “B”)
counter++;
}
return counter;
}

1 Like

Sorry, I don’t know why my indentations were lost. I was actually proud of them when I wrote the code originally

1 Like

//Ex.1 min function

function min(a,b){
  if (a<b) return a;
  else return b;
}
//Ex.2 isEven function

  function isEven(number){
    if (Math.abs(number)==0) return "even";
    if (Math.abs(number)==1) return "odd";
    else return isEven(Math.abs(number)-2);
  }
//Ex.3 bean counting

function countChar(word,char) {
  Char_counter=0;
  for (pointer=0;pointer<word.length;pointer++){
    if (word[pointer]==char) {Char_counter++;}
  } return Char_counter;
}
1 Like

Ch 3 Minimum
(working in Eloquent Editor)

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

CHAPTER 3 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(0));
console.log(isEven(1));
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
console.log(isEven(-10));

CHAPTER 3 Counting Char
(using Eloquent editor)


__________________________________
Biggest challenges:  (1) getting the brackets and parens correct, and to a lesser extent (2) using the right var again and using let versus var.
1 Like
      //MINIMUM
      //Write a function min that takes two arguments and returns their minimum.
      function min(a, b){
        //if numbers are equal, we return the first one
        if(a <= b) {
          return a;
        }
        return b;
      }
      console.log(min(4,1));

      //RECURSION
      function isEven(n) {
        //to fix negative value infinite recursion
        //we use the absolute value of the input number.
        let num = Math.abs(n);

        if(num == 0) {
          return true;
        } else if (num == 1) {
          return false;
        }
        return isEven(num -2);
      }
      console.log(isEven(50));
      console.log(isEven(75));
      console.log(isEven(-1));
      console.log(isEven(-14));

      //BEAN COUNTING
      function countBs(text) {
        let numBs = 0;
        for (let c = 0; c < text.length; ++c) {
          if (text[c] == "B") {
            ++numBs;
          }
        }
        return numBs;
      }
      console.log(countBs("The quick Brown fox jumps over the lazy dog. And BTC to the moon."));

      function countChar(text, char) {
        let numChars = 0;
        for (let c = 0; c < text.length; ++c) {
          if (text[c] == char) {
            ++numChars;
          }
        }
        return numChars;
      }
      console.log(countChar("The quick Brown fox jumps over the lazy dog. And BTC to the moon.", "B"));
      console.log(countChar("The quick Brown fox jumps over the lazy dog. And BTC to the moon.", "o"));

      function countBsV2(text) {
        return countChar(text, "B");
      }
      console.log(countBsV2("The quick Brown fox jumps over the lazy dog. And BTC to the moon."));

1 Like

Minimum

function min(x,y){
return Math.min(x,y);
}

document.write("The smaller of the two numbers is " + min(2,5) + “.”);

Recursion

function isEven(n){
if (n == 0) return true, document.write(“Your number is even.”);
else if (n == 1) return false, document.write(“Your number is odd.”);
else return isEven(n - 2);
}

// isEven(add number);

Counting Characters

function countBs(aString) {
return countChar(aString, ‘B’);
}

function countChart(aString, character) {
let count = 0;
while (aString.length > 0) {
if (aString.charAt(0) == character) count++;
aString = aString.substr(1);
}
return count;
}
console.log(countBs(“Buddy Bad Boy!”));

I feel like I understand functions more than loops. Going to watch those videos again!

1 Like

Excellent, once again @dAnijboned! :smiley:

It’s really good how you add comments to your code. This is good practice and certainly helps other developers read your code, and will also help you when you look back at it after a while :wink:
As someone else reading your comments, and can say they are nice and clear and easy to understand :+1:

Nice use of Math.abs() for an alternative solution to the negative number challenge in Recursion. :+1:

You’re right that the code still executes correctly if we omit the else keyword in the conditional executions in both Minimum and Recursion. However, personally, I would include it as I think it makes the control flow clearer to someone reading or working on your code. But, others may have a different view…

Here’s a challenge for you, as I think you’re up to it. In Minimum, another way to avoid having to use the else keyword, and to also omit the if keyword, is to convert this part…

…into a statement using a ternary operator. If you’re not sure what a ternary operator is, then look it up… I think they’re a really good alternative when you have a short 2-branch conditional execution, as we do here. Let me know how you get on :slightly_smiling_face:

Hey @ogm!

Great code! :muscle:

That’s great that you’re reflecting on what you find most challenging. That’ll help you focus on where to spend more time experimenting, practising and researching :+1:

Ensuring your code is always clearly formatted helps a lot with the brackets and parentheses. I’m sure your code is nicely formatted in your text editor, but I’m not sure if you know that before you type in your code to post it here in the forum, you can click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which is then also easier for you to organise with the correct spacing, indentation, nesting and brackets etc. Have a look at @dAnijboned’s post here and you’ll get an idea of what your formatted code could then end up looking like :slightly_smiling_face:

In terms of var and let , it does take a while to wrap your head around what the actual differences are. In terms of the coding you’re doing here in this course, they are pretty much interchangeable to be honest. However, there are some key differences which you need to appreciate eventually if you’re serious about your development. You should research it yourself online, but basically my understanding is that var was the only keyword used to declare variables in earlier JavaScript standardized specifications (editions). Then with the 6th edition, ECMAScript 6 (ES6) let and const were introduced as alternatives to var. There are some differences between how var and let work, but I only use either let or const to be honest, and I haven’t had any problems yet by not using var. The basic difference between let and const is as follows:

  • Use let when you want your variable to be reassignable (i.e. the flexibility to have its value changed - although it can remain constant too);
  • Use const when you want your variable’s value to remain constant. A const variable can’t have it’s value reassigned.

That’s only scratching the surface, so you’ll need to do your own research, but hopefully that will give you a good start… :slightly_smiling_face:

Keep on learning! You’re doing great!

2 Likes

Totally agree, much more compact and readable using the ternary operator:

function min(a, b){
    return (a < b) ? a : b;
}

Thanks @jon_m !

1 Like

Thank you for the input !

I am glad to learn of the forum text-editor… when I copied my code into the forum, it looked fine but yikes – I did not know that it looked like you posted below after I put it on the forum !! I will find the </> icon and use it.

I ended up using the Eloquent editor, though at first I was using Atom, then compiling on a browser.

I see that Ivan uses var (like C), and I read the differences in a couple places, but will use let and const from now on.

I appreciate you input !!!

Tara

image001.jpg

image002.jpg

1 Like