Chapter 3 Exercises

Nice solutions @natanieldp :ok_hand:

Just one observation…
Your solution for Recursion successfully handles positive numbers, but you now need to add functionality to handle negative numbers. Have a look at the instructions in the course book for further details.

Keep on learning! …You’re making good progress!

Hi @Stas_Simon,

You haven’t fully understood what I meant.

Your revised version now successfully handles -1, but it can’t handle any other negative number. So in that sense, your first version was better.

I was asking if you could add functionality that will output whether any negative number is odd or even, in the same way that it does for any positive number, and zero.

If you can’t do it on your own, take a look at the course book’s model answer where you’ll be able to see how it can be done.

Keep on learning! :muscle:

Finding the minimum:

< html>
< script>
var a=window.prompt("enter a: ");
var b=window.prompt("enter b: ");
function minimum(a,b){
if(a<=b){
return a;
}
else{
return b;
}
}
document.write("The minimum of “+a+” and “+b+” is "+minimum(a,b));
< /script>
< /html>

Even/odd program:

< html>
< script>
var n=window.prompt(“enter a number: “);
abs_n=Math.abs(n);
function isEven(m){
if(m==0){
return true;
}
else{
if(m==1){
return false;
}
else{
return isEven(m-2);
}
}
}
if(isEven(abs_n)){
document.write(n+” is an even number.”);
}
else{
document.write(n+" is an odd number.")
}
< /script>
< /html>

Letter-counting program:

< html>
< script>
var inputString=window.prompt("enter a string: ");
var searchLetter=window.prompt("enter letter to search for: ");
function countLetter(inputStr,searchL){
count=0;
for(n=0; n<inputStr.length; n++){
if(inputStr[n]==searchL){
count++;
}
}
return count;
}
document.write(countLetter(inputString,searchLetter));
< /script>
< /html>

1 Like

Nice solutions, and great analysis, @Ernest_SG :+1:

It’s great that you’ve clearly thought about what the code is doing. This will help you internalise more what you’ve learnt and remember it for longer.

Here are a couple of observations:

In Minimum, I would declare the variable isLess with a keyword. Even though your code for this exercise runs successfully without it, it’s still a good idea to get into the habit of declaring your variables with one of the keywords let , const or var. Then you can gradually start to understand why, and the differences between each of them.

Maybe you didn’t realise, but there’s a final part to the Bean Counting exercise. Can you slim down your countBs() function so that it still takes just one parameter (the string) but then calls  countChar()  to always count the number of B’s, but still returns the output itself?

Keep on learning! … You’re making great progress! :muscle:

1 Like

Minimum function

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

Recursion

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

}

}

document.write(isEven(-1));

Bean Counting

function countChars (string, letter){
var count = 0;
for(i=0; i < string.length; i++){
if (string[i] == letter){
count +=1;
}
}
return count;
}
console.log(countChars(“BBBadb”,“a”));

1 Like

// Minimum Number of Two Exercise 4.
// ------------------------------
function min(a, b) {
if (a < b) return a;
else return b;
}
document.write("
");

document.write(The smaller of the two numbers is ${min(0, 10)});
// --> The smaller of the two numbers 0
document.write("
");

document.write(The smaller of the two numbers is ${min(0, -10)});
// --> The smaller of the two numbers -10

document.write("
");

// Recursion Exercise 5.
// ------------------
function isEven(N) {
if (N < 0) N = N * -1;

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

document.write(“The rumour your number is even is " + isEven(50));
// --> The rumour your number is even is true
document.write(”
");

document.write(“The rumour your number is even is " + isEven(75));
// --> The rumour your number is even is false
document.write(”
");

document.write(“The rumour your number is even is " + isEven(-1));
// --> The rumour your number is even is
document.write(”
");

// Bean Counting Exercise - 6.
// ----------------------

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, “B”);
}

document.write(countBs(“BigboldBitcoin”));
// → 2
document.write("
");

document.write(countChar(“kentuckychicken”, “k”));
// → 3

1 Like

Many thanks for your feedback. Yes you’re right I usually try to do use the var keyword, I must have skipped it by mistake. And as for the end of the last function should be like this:

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

This should do the trick and once again thanks a lot for the feedback. :mechanical_arm:

1 Like

Hi @Emmerich,

Minimum & Recursion :+1:

Bean Counting

Yes… because you are logging to the console from within your function, the function itself isn’t returning any value to the function call. Therefore if you are wrapping your function call in another console.log(), this console.log() will return undefined. In other words, you should be calling the function as follows…

countBs("Six sizzling sausages", "s");
// and not
console.log(countBs("Six sizzling sausages", "s"));   // => undefined

The idea is to write two separate functions (both of which only count and return one character):

  1. countBs    1 parameter (string)          only counts Bs
  2. countChar  2 parameters (string, character)  counts whichever character is passed

You can then replace the console.log() statements with a return statement in each function, and also wrap the function call in console.log(). Then, when the function is called, the number of Bs or specified character will still be logged to the console, but without the undefined.

Then, the final stage of this exercise is to modify countBs so that it calls countChar to count the number of Bs in its string, but then still returns the output itself.

Have another look at the course book instructions (and hints if you need to), and then have another go at this exercise.

Great job, @cryptocrom! :muscle:

Great notes, from which, once again, I can see that your approach is optimum :+1:

With BeanCounting you spent time wrestling with it yourself before looking at the solution; and then you spent time analysing how the model answer manages to achieve the task more succinctly: perfect!

You will be learning loads by taking this approach.

Really, well done! Keep on learning! :slightly_smiling_face:

1 Like

Nice solutions @Bette :ok_hand:

By the way, there’s a final part to the Bean Counting exercise. Can you slim down your countBs function so that it still takes just one parameter (the string) but then calls countChar() to always count the number of B’s, but still returns the output itself?

Nice solutions, @FrankB :+1:

Nice finishing touches with the pop-up boxes for inputs, and then displaying outputs on the web page.

Also great to see the alternative approach you came up with for Recursion, using Math.abs() to handle negative numbers, and initially calling the function within the condition of an if statement.

Just a couple of comments…

  • I would declare the variables abs_n (in Recursion) and count (in Bean Counting) with a keyword. Even though your code for these exercises runs successfully without it, it’s still a good idea to get into the habit of declaring your variables with one of the keywords let , const or var . Then you can gradually start to understand why, and the differences between each of them, which can take a while.

  • Maybe you didn’t realise, but there’s a final part to the Bean Counting exercise. You should have initially written a countBs function. Can you now slim that function down, so that it still takes just one parameter (the string) but then calls your countLetter function to always count the number of B’s, but still returns the output itself?

You’re making great progress!

Hi Jon,

First off, thanks for taking the time to look at my code and writing comprehensive answers. I appreciate that!

Back to Counting Beans. I had another crack at it.

Here’s the first part:

Works perfectly!

Here’s the second part:

Also works perfectly!

And finally:

Full disclosure. I don’t get credit for the last answer as I checked some of the other answers, because I wasn’t sure what was asked of me and I was quite confused and frustrated. In hindsight now that I see the code, it makes sense. When I call countBs it returns the function countChar, which in turn works out the amount of specified characters (in this case “B”).

Do you know of a website with similar questions and problems that I can practice a bit more, because I feel that’s what I’m lacking.

Kind regards
Em

1 Like

Thank you, Jonathan. I actually meant to define abs_n and count with ‘var’ or ‘let’ (I understand the difference in scope between the two—although there are probably some subtleties that I am not aware of yet—and I also understand the basic idea of ‘const’ which is used in PASCAL as well). It’s interesting that it actually worked without these specifications. I noticed the same phenomenon in for-loops. You don’t really have to use ‘var’ to declare the loop variable. What is Javascript’s default assumption as far as scope is concerned when you omit ‘var’ and ‘let’?

As far as your second suggestion is concerned, I can say that I am aware that the problem asked for B-counting first, but the second part contains that first part as a special case. So I only solved the more general problem—and I am not sure exactly what you are asking. It seems to me that all I would have to do to solve the first part is to call my ‘countLetter’-function with ‘B’ as the fixed second argument (or to eliminate the second argument altogether).

1 Like

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

recursion
function even(n){
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 1) return even(-n);
else return even(n - 2);
}
alert(even(50));
alert(even(75));
alert(even(-1));
bean counting
getting somewhat better, but i still had to look it up to complete…
function countChar(string, ch){
let count = 0;
for (let i = 0; i < string.length; i++){
if(string[i] == ch){
count +=1;
}
}
return count;
}
function countBs(string){
return countChar(string, “B”);
}
console.log(countBs(“BBC”));
console.log(countChar(“kakkerlak”, “k”));

1 Like

problem2

function EvenOdd(number){
     number = number<0? -1*number : number;
     if (number == 0) return ("even");
     else if (number ==1) return ("odd");
     else return EvenOdd(number-2);
}
1 Like

Problem 3

  function CountBs(string){
      let len = string.length;
      let total = 0;
      for (let count = 0; count<len; count++){
        if (string[count] == 'B') total++;
      }
      return total;
    }
1 Like

yeah… I had to struggle then go to the link.

//math min
function min(a,b){
if(a <= b){return a;}
else return b;
}
var answer= min(15,9)
console.log(answer);

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

function numChar(string, ch){
let numChar= 0;
for(let i = 0; i< string.length; i++){
if(string[i]== ch){
numChar = numChar+= 1;
}
}
return numChar;
}
console.log(numChar(“mississipi”, “s”));

1 Like

Good solutions, @CeesQ :ok_hand:

By the way, there’s a final part to the Bean Counting exercise. Can you slim down the original countBs function so that it still takes just one parameter (the string), then calls your countChars() function (which you’ve posted) to count the number of B’s, but still returns the output itself?

1 Like

Hi @Busaboy,

Nice solutions :ok_hand:
… and good use of template literals (instead of string concatenation) to include the function calls within your strings in the first exercise :+1:

Unfortunately, because you haven’t formatted your code before posting it here in the forum, all three solutions don’t execute. This is because the code you’ve posted omits:

  • each "<br>"
  • the back ticks enclosing your template literals

I think this is purely a formatting error, because when I add the above two things (and also modify some incorrectly formatted quotes) all three solutions execute perfectly :slightly_smiling_face:

To format your code, you can click on the </> icon in the menu at the top of this forum’s text editor. This will give you 2 sets of 3 back ticks.
```
input your code here
```
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 and indentation etc. It also makes it easier to spot any errors or copy-and-paste slips. Have a look at some of the other students’ formatted code which they’ve posted here in this topic. This will give you an idea of what your formatted code should end up looking like (and your "<br>"s and back ticks won’t mysteriously disappear!)

1 Like

Hi @Emmerich,

Sorry for the delay in replying.

You seem to have had a copy-and-paste or a formatting problem, because the code doesn’t appear in your post…

If you try posting your code again, I’ll take a look :slightly_smiling_face:

These exercises are a real challenge, and so if you find one too difficult to complete on your own, or by doing some research, then that’s absolutely fine to end up looking at the model answer, or other students’ alternative solutions that have been posted and reviewed here in the forum. As long as you have given it your best shot first; that’s the most important thing — to really spend time wrestling with it yourself first. You may just want to take a quick peek first to get some hints, so you can carry on and complete it yourself. The most important thing is not so much being able to complete it on your own, but how much you’ve learnt and stretched yourself in the process.

If you had to get some help, before moving on, make sure you also spend time analysing how the model answers manage to achieve what they do. This is a really important stage in the learning process. You can learn a lot by working out what another solution does differently. Then you can apply what you’ve learnt next time, and keep improving.

That’s right :+1:

Even if you didn’t get there yourself, as long as you gave it your best shot, then analysed and thought carefully about the solution until properly understanding what the code is doing, then that’s job done! :smiley:

I personally haven’t seen or used a website that has similar exercises to these. However, I first learnt JavaScript with Codecademy. I find their lessons really helpful as they are based on continual coding exercises that you complete at the same time as learning new syntax and concepts. They also have mini projects that put what you’ve learnt in the lessons into practice. It all depends on how you like to learn. I know it’s a cliché but often the best way to find exercises that are right for you is to have a search yourself based on phrases such as “JavaScript puzzles”, “JavaScript interview questions” etc. etc.

I also recommend:

  • experimenting further with both the solutions to these exercises, and your own alternative versions, by trying to extend and adapt their functionality to solve other tasks and problems that you can come up with;
  • attempting the course book exercises again from scratch without looking back at the answer (like a memory test). You can also try to do this after having left them for a certain period of time (say, the next day, then after a few days, then a week etc. etc.) This builds up longer-term retention.
1 Like