Chapter 3 Exercises

Hey,

I like your alternative solution to the recursion exercise:

I think using…

if (number < 0) number = -number;

… as the first if statement in the function body provides a good simple solution, which only requires one recursive function call in the final else statement, rather than the two used in the suggested solution, and my less concise solution (below).

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

console.log(isEven(-1));

Also, not sure if you know, but if you wrap the code you include in these posts in back ticks (while editing), it formats it nicely for you, making it easier to read. For an inline piece of code: surround it in single back ticks e.g. `console.log()` will appear as console.log()
For a block of code put three back ticks on the line before and on the line after e.g.

```
function min(x, y) {
 return x < y ? x : y;
}

console.log(min(5, -3.5));
```

will appear as:

function min(x, y) {
  return x < y ? x : y;
}

console.log(min(5, -3.5));

As an easy alternative to typing the back ticks manually, you can just click on the </>  in the menu bar at the top of the text input box and it will automatically give you two backticks, or two sets of three backticks, depending on whether you are inline or on a new line :smiley:

It’s using a simple markup language called Markdown. Here’s a link if you, or anyone else reading this, would like to know more: https://commonmark.org/help/

By the way, that final piece of code I used in my example is my alternative solution to the first exercise, using a ternary operator. I like how short and sweet it is :wink:

Hey!

Nice to see someone else used a ternary operator in their solution to exercise 1 :smiley:

I like how short and sweet it is!

1 Like

Thanks again Jonathan, I really appreciate your solutions. I’m going to spend some time reviewing your suggestions shortly.

Cheers,

Jeremy.

1 Like

Much of writing python had to learn to minimize lines of codes…

Hell yea, Ternary is so short and easy to read.

1 Like

I did some research on the web and the community here because those exercises were a bit difficult for me.

1 - Minimum:

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

  document.write(min(0,10));
  document.write(min(-10,0));

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

  document.write(isEven(50) + "<br>");
  document.write(isEven(75) + "<br>");
  document.write(isEven(-1) + "<br>");

3 - Bean counting

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

AND:

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

}

document.write(countChar("karlekkak","k"));

// Exercise return min.

  function returnMin (a,b){
    if(a>b){
      return b;
    } else{
      return a;
    }
  }
  document.write (returnMin (5,3));

// excercise isEven?

  function isEven (num){

    if (num < 0) {
      num = num * -1;
    }

    if(num == 0){
      alert (" Even ");
    }

    if (num == 1){
      alert (" Odd ");
    }

    if(num != 0  && num != 1){
      isEven (num -=2);
    }

  }

// Counter

  function countBs (text , whatToSearch){

    var counter = 0;
    var textLenght = text.length;

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

      if(text [i] == whatToSearch){

        counter +=1;

        
      }
      
    }

    console.log(counter);
    
  }

console.log(countBs (“Ivan on Tech accademy is changing my life”,“g”));

how do I make the Bean counter NOT case sensitive ??

I’ve had a play around with this, and I’ve managed to remove the case sensitivity by converting both sides of the comparison expression in the if condition to upper case, as follows:

if (string[i].toUpperCase() === char.toUpperCase()) { ... }

// My 'string' parameter = your 'text' parameter.
// My 'char' parameter = your 'whatToSearch' parameter.

With this modification, it also doesn’t make any difference whether you pass an upper or lower case letter as your  char / whatToSearch  parameter.  e.g.

console.log(countChar("not case sensitive", "s"));  // => 3
console.log(countChar("NOT CASE SENSITIVE", "s"));  // => 3
console.log(countChar("not case sensitive", "S"));  // => 3
console.log(countChar("NOT CASE SENSITIVE", "S"));  // => 3
console.log(countChar("Not Case Sensitive", "s"));  // => 3
console.log(countChar("Not Case Sensitive", "S"));  // => 3

And, by the way, if you’re logging the function call to the console, you want a  return  statement at the end of your function, instead of…

1 Like

Sweet solution dude thank you:)

1 Like

Write a function

Minimum

min that takes two arguments and returns their minimum.

function retmin(a,b)

{

res = Math.min(a,b)

return res

}

console.log(retmin(2,4))

Recursion

function isEven(num) {

if (num < 0) return “Number is negative!”;

if (num == 0) return “Even”;

if (num == 1) return “Odd”;

return isEven(num - 2);

}

console.log(isEven(3));

console.log(isEven(4));

console.log(isEven(50));

console.log(isEven(75));

console.log(isEven(-1));

/*

Bean counting

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.

*/

function countBs(astring) {

var result = 0

//return astring.length +" Chars in the string";

for (let number = 0; number <= (astring.length+1); number = number + 1)

{

if (astring[number] == ‘B’)

{

//console.log(astring[number]);

console.log('B is on pos ’ + (number+1)) ;

result++

}

}

if (result == 0)

return “it’s none " + result + " B:s in the word”

else return "Found “+ result + " B:s”

}

function countChar(astring, findchar) {

var result = 0

//return astring.length +" Chars in the string";

for (let number = 0; number <= (astring.length+1); number = number + 1)

{

if (astring[number] == findchar)

{

//console.log(astring[number]);

console.log(findchar + " is on pos " + (number+1)) ;

result++

}

}

if (result == 0)

return “it’s none " + result + " " + findchar + " in the word”

else return "Found "+ result + “” + findchar + " "

}

console.log(countBs(‘testBB’));

console.log(countChar(‘TestaAA’, ‘A’));

I might have done it a little different from other people and made it more complicated than it needed to be for the Bean counting segment.
Minimum
function min(x,y){
if(x<y){
console.log(x);
}
else{
console.log(y);
}
}

Recursion
function isEven(x){
if(x==0){
alert(“It’s even!”);
}
else if(x==1){
alert(“It’s odd!”);
}
else if(x<0){
isEven(x*(-1));
}
else(isEven(x-2));
}

Bean counting part 1
function countBs(x){
Bs=0;
for(counter=x.length;counter>=0;counter-=1){
if(x[counter] == “B”){
Bs+=1;
}
}return Bs;
} console.log(countBs(“Bob has bunches of bananas from Borneo.”));
// returns 2
Bean counting part 2
function countChar(x,y){
foundYs = 0;
for(counter=x.length;counter>=0;counter-=1){
if(x[counter] == y){
foundYs+=1;
}
}return foundYs;
} console.log(countChar(“Learning Javascript is fun”,“n”));
// returns 3

ex 1

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

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

ex 2

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

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

ex 3

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

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

<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>searchengine</title>
  </head>
  <body>
    <script>
      var a=8,b=5;
    function min(a,b) {
        if (a<b) document.write("&nbsp <h2>"+"b is bigger"+"</h2>");
          else document.write("&nbsp <h2>"+"a is bigger"+"</h2>");}
      function isEven(a) {
        if (a<0) a=a*(-1);
        if (a==0) return true;
          else if (a==1) return false;
            else return isEven(a-2);}
      function countBs(a) {
        let c=0;
        for (let i=0;i<a.length;i++) if (a[i]==('b'||'B')) c++;

        return c;
      }
      function countChar(a,c) {
        let count=0;
        for (let i=0;i<a.length;i++) {
          if (a[i]==c) count++;
        }
        return count;
      }

      document.write("<h1>"+"Minimum"+"</h1>");
      document.write("&nbsp <h2>"+"a="+a+" b="+b+"</h2>");
      min(a,b);
      document.write("<h1>"+"Even odd"+"</h1>");
      if (isEven(b)) document.write("<h2>"+a+" is even!</h2>"); else document.write("<h2>"+a+" is odd mann!</h2>");
      let seekChar="d", firstWord="ivan ban all", secondWord="onTech";
      document.write("<h1>"+"Words challenge"+"</h1>");
      document.write("<h2> First words challenge is: '"+firstWord+"' which contains  "+countBs(firstWord)+" 'b'");
      document.write("<h2> Second words challenge is: '"+secondWord+"' which contains  challenge letter '"+seekChar+"' "+countChar(secondWord)+" times");
    </script>
  </body>
</html>

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

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

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;}
console.log(countChar(“kakkerlak”, “k”));
// → 4

Recursion:

<script type="text/javascript">



function isEven (a){

  while(a>1){
      a = a - 2;
  }

  while(a<0){
    a = a + 2;
  }

  if(a==0){
    return true;
  }
  else if (a==1) {
    return false;
  }
}

console.log(isEven(-10));



</script>

Bean Counting:

var a = "Baba";
var y = 0;

function countBs (a){

  for(var x=0; x<a.length; x=x+1){

  if (a[x]=="B"){
    y = y+1;
  }
}
return y;
}




console.log(countBs(a));

Bean counting second part:

var y = 0;

function countChar (a,b){
    for(var x=0; x<a.length; x=x+1){

    if (a[x]==b){
      y = y+1;
    }
  }
  return y;
}

console.log(countChar("babaz","z"));

Hello,

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

else {console.log(b)}

}

minimum(8,6);

  1. function isEven(n){

    if (n == 0)

    return true;
    
    else if (n === 1) return false;
    
    else return isEven(n-2);
    

    }

  2. had problems with this one, looked at solution.

best

//minimum
function min(x,y){
return Math.min(x,y);
}
var a = min(10,12);
alert(a);

//Recursion
function isEven(x){
  function isEvenSolution(n){
    if ( n == 0){
      return true;
    } else if (n == 1  || n < 0) {
        return false;
      } else {
        return isEven(n-2)
      }
    }
   return isEvenSolution(x);
}
alert(isEven(-1));
alert(isEven(50));

//CountChar
function CountChar(myString, myChar){
var count = 0;
for (var i = 0; i < myString.length; i++){
if(myString[i] == myChar)
{
count++
}
}
alert("CountChar " + myChar + " " + count);
}
CountChar(‘AAABBBCCAAADDDA’, “A”);

   function min(a,b)
   {
    if(a<b){return a;}
    else return b;
   }
   isEven=function(num)
   {
    if(num==1){return false;}
    else if(num==0){return true;}

    return isEven(num-2);
   }

If num = -1 then recursion will repeat infinitely. We can write an alert that wrong value was inserted or turn negative nubers into positives by using math.abs function.

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

  function countChar(word,toCount)
  {
    count=0;
    for(var i=0;i<word.length;i++)
    {
      if(word[i]==toCount)
      {
        count++;
      }
    }
    return count;
  }

Now we can rewrite countB:

  function countBs(word)
  {
    countChar(word,"B");
  }
1 Like
  1. Minimum - using JavaScript in-built Math function. eg

console.log(Math.min( 9,8))

  1. Recursion

function isEven (N) { if ( N === 0) console.log ( “True”);
else if ( N === 1 ) console.log ( " False" );
else console.log ( isEven ( N - 2 ))}

isEven ( 50)
isEven ( 57)

  1. Bean Counting

var countBs = [ ’ B ‘, ’ B’, ’ C '];

console.log(countBs.length);
console.log( countBs [2]);

1 Like

1. Math.min

console.log(Math.min(2, 3));

2. isEven

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(“50”))
console.log(isEven(“75”))
console.log(isEven("-1"))

3.Bean

let text = “Bruce is my Baby Brother”;

function countBs(text)
{
let charcounter = 0;

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

console.log("‘B’ appears " + countBs(text) + " time(s) in “” + text + “”.");

1 Like

Minimum:

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

Recursion:

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

Bean Counting:

function countBs(word,countchar){
counter = 0;
letters = word.length;
for(i=0; i<letters; i++){
    if(word[i]==countchar){
        counter+=1;
        }
}
console.log("the number of " +countchar +"'s " is: " + counter)
}
1 Like