Chapter 4 - Exercises

You’re very welcome, @Zoltan!

Yes, you can go a lot deeper into JavaScript, but you have now covered enough material to build a basic front-end for a dapp which links to a back-end with smart contracts deployed on a blockchain such as Ethereum or EOS. As the main focus of these courses is on programming for blockchain developers, we want to get you started on smart contracts as soon as is practically possible.

Good luck and enjoy C++ ! But keep your JavaScript going as well :muscle:

3 Likes

Ah, that makes sense. Hopefully I’ll get somewhere someday!

Thanks a lot Jon!
I’ll see you around. :slightly_smiling_face:

1 Like

By the way, I’ve just heard this afternoon that a ReactJS course is being launched soon. ReactJS is a JavaScript library. That will be a great lead-on from this course, especially if you want to go deeper into JavaScript frontend development :ok_hand:

2 Likes

I will check it out.
Thank you Jon :slightly_smiling_face:

1 Like

The sum of a range

Reversing an array
reverseArray

script>

let arr = [1,2,3,4,5]
let reverseArray = arr.reverse();

console.log("reversed array")
console.log(reverseArray)
console.log("original array")
console.log(arr)

reverseArrayInPlace

let arr = [1,2,3,4,5] let reverseArrayInPlace = [...arr].reverse(); console.log("reverseArrayInPlace") console.log(reverseArrayInPlace) console.log("original array") console.log(arr) </script

Thank you @jon_m! I looked at the hints and I still don’t really understand it. But I will do my best with the information you gave me. :smile:

1 Like

Hi @Yavuz_Gedik,

Your solution to The Sum of a Range is missing. Did you forget to add it?

(…and your code for reverseArrayInPlace is exactly the same)

The idea here is to reverse the array without using the reverse() array method. Go back and have another good look at the exercise. Take your time, these exercises are a real challenge. If you need some help, I would suggest these possible approaches (depending on what you’ve already tried yourself) and in the following order:

  1. Have a look at the hints (which you can display in the online course book by clicking below the exercise instructions).
  2. If you still don’t get it, have a look at other students’ posts here, with their attempts, solutions, and the help, comments and feedback posted as replies.
  3. Look at the model answer given in the course book. Try to work out how it achieves the desired result, and then maybe think about how you would have done it, which could well be different. Then attempt to code it yourself without referring to the solution to see how much you can remember.
  4. Please do post, here, any questions you may have about specific aspects of the exercise and its code, before you feel ready to post your final solutions.
1 Like

Hi @Markus_Bielaszka,

If you’re still struggling, I would also suggest having a look at other students’ posts, here (in this discussion thread) with their attempts, solutions, and the help, comments and feedback posted as replies.

There are also some YouTube videos where people write the code to these actual exercises, step by step. You don’t have to watch these all the way through to the final solution straight away. You could watch just enough to help you get started, and then try to continue yourself… watch a bit more to check you’re on the right track if you need to… work through it in stages, checking as you go… etc. etc.

If, having tried all of these different approaches, you are still having difficulties, then look at the model answer given in the course book. Try to work out how it achieves the desired result, and then attempt to code it yourself without referring to the solution, to see how much you can remember.

Please do post, here, any questions you may have about specific aspects of the exercise and its code, before you feel ready to post your final solutions.

2 Likes

Hi JP Morris,

Thanks for the feedback. I’ll will redo the exercises.
Its tricky… but as you wrote great exercises to master!

Regards,
Yavuz

1 Like

Hi Jon,
Thanks for the feedback and sorry for the delay in attempting to fix this. So I did it differently, using “while” instead of “let” for sum range. Looking for sum of 28.

Sum Range

var range = function(start,end) {
    var arr = [];
        cnt = start;

        while (cnt <=end) {
            arr.push(cnt);
            cnt++;
        }   
        return arr;
};

var sum = function(arr) {
     var total = 0;

     while(arr.length > 0) {
         total = total + arr.pop();
     }
     return total;
};

console.log(sum(range(1,7)));

/////////////////////////////////////////////////

**ReverseArray**

let arr = [1,2,3,4,5,6,7]
//  [7,6,5,4,3,2,1]

let reverseArr = arr.reverse();

console.log(reverseArr)

////////////////////////////////////////

**reverseArrayInPlace**

const reverseInPlace = (arr) => {
    let temp
    for(let i = 0; i < arr.length / 2; i++) {
        temp = arr[i]
        arr[i] = arr[arr.length -1 -i]
        arr[arr.length - 1 -i] = temp
    }
     return arr

}
const arr = [1,2,3,4,5,6,7]
console.log (reverseInPlace(arr)
1 Like

Hi @jon_m

Thanks for helping out!
I will do so! :smiley:

1 Like

Hi @CryptoVic,

No problem at all — it’s best not to rush these exercises! Take your time… we’re here to help and review whenever you’re ready.

Sum of a Range

Great! :+1: That’s an original solution you’ve come with, especially how in sum() you’ve decided to iterate backwards through the array removing each number with pop() as it’s counted. Very clever! :smiley:

So, that’s the first part sorted. Whenever you’re ready, you now need to try adding functionality to…

  1. handle reverse arrays (where start > end); and
  2. handle varying increments/decrements between the numbers in the array, by introducing a 3rd step parameter.

This is all explained in the exercise instructions in the course book, and if you need a bit more help getting started you can always look at the hints (which you can display by clicking below the exercise instructions). But just let us know if you need any additional support, or don’t understand something.

Reversing an Array

Your solution for the 2nd part (reversing the array in place) is good :+1: You successfully return a reversed array, and the original input array is also reversed, which you can confirm by logging arr to the console:

console.log(arr);

Some observations:

  • Your console.log is missing a closing bracket.
  • There is no need to first declare temp as undefined before the for loop, and then assign it the array index within the for loop. You can do both together in the for loop:
       let temp = arr[i];
  • If an arrow function only has one parameter, you can omit the brackets:
       const reverseInPlace = arr => { ... };

Otherwise, nice use of an arrow function :ok_hand:

For Part 1, you’ve cheated :wink:
The idea is to reverse the array without using the reverse() array method — this time returning a new array which is the reverse of the input array, with the input array remaining unchanged. Have another look at this part.

Keep at it — you’re making great progress! :muscle:

1 Like

The closest I’ve been to understanding this exercise so far.
The only thing I find confusing is why i += step in both the if and the else. Shouldn’t that mean that regardless if start is smaller or bigger than end it keeps pushing a higher number?

1 Like

The Sum of a Range

function range(start, end, interval = start < end ? 1 : -1){
  var array = [];

      if (interval > 0){
        for(let count = start; count <= end; count += interval) array.push(count);
      }
      else {
        for(let count = start; count >= end; count += interval) array.push(count);
  }
  return array;
}

function sum(array){
  var total = 0
  for(var value of array){
    total += value;
  }
  return total;
}

Reversing an Array

function reverseArray(array){
  var solution = [];
  for(var i = array.length - 1; i >= 0; i--){
    solution.push(array[i]);
  }
  return solution;
}

function reverseArrayInPlace(array){
  for(var i = 0; i < Math.floor(array.length/2); i++){
    var current = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = current;
  }
  return current;
}
var arrayValue = [1,2,3,4,5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
1 Like

After manually copying classmates answers for hours to get a feel for technicalities, to debug, manipulate and examine the code I’ve decided to post first half of this assignment so I can let it go and focus 100% on the reversing of arrays.
I’ve added comments to thread out the code as far as I understand it. I still get the terms confused at times, feel free to correct me or come with alternative ways of explaining what the code does as it still isn’t as obvious to me as I wish it was

function range (start, end, step = 1) {
var arr = [ ];
if (step === 1 && end < start) step = -1;
//range is the array,
// arr holds an empty space for the values of the variables
// The if function below says that if the end is smaller than start like -10 < -5, the step should be negative too
if (start < end) {
for (let i = start; i <= end; i += step){
arr.push(i);
}
}
//if start is smaller than the end use .push to add a step
else {
for (let i = start; i>= end; i+=step){
arr.push(i);
}
}
//else will .push start negatively in case it’s bigger than the end
return arr;
};
console.log(range(5, 10,1));
console.log(range(-5, -10,-1));

function sum(array){
var total = 0;
for (var i = 0; i < array.length; i++){
total = total + array[i];
}
return total
//The sum calculates the range of the array
//The variable total begins at zero
//A for loop is used, count starts at zero, adds one and adds the new number to the old one until the end of range
}
console.log(sum(range(1, 10)));

1 Like

Considering how hard this assignment was for me, this was basically plagarism, but hey they say practice makes perfect, and that you have to imitate others until you find your own voice.
I’ve added commentary as to follow my line of reasoning, and if this is nothing useful for the pros I sure hope it will help other n00bs like me to easier grasp this assignment. All input welcome.

function reverseArray(array){
i = [ ];
index = array.length - 1;
//index starts at full length of the array -1, because the zero counts -1 turns into the 5 in the array
while(index >= 0){
i.push(array[index]);
index–;
}
return i;
//while loop will chop of the number at the back and return it first in order, and then take the next number in order as long as it’s no smaller than zero
}
var arrayOne = [1,2,3,4,5];
console.log(reverseArray(arrayOne));

function reverseArrayInPlace(array){
var neg = array.length -1;
let i = 0;
while(i<array.length/2){
let position = array[i];
array[i] = array[neg - i];
array[neg-i] = position;
i++;
}
//This while loop effects half of the length of the array. Since an array with odd amount numbers, like 1,2,3, doesn’t need to move the number in center there is no need for any =
//Mathematically reads like this first loop
//position = 0
//0 = 1,2,3 [-1 -0];
//1,2,3 [-1 -0] = position
return array;
}
//Because the array start to count from 0 number 3 in the array is actually 4
//because of i++ all 0s turns to 1s in next iteration of the loop, and then into 2s etc
console.log(reverseArrayInPlace([1,2,3]));

1 Like

I agree whole-heartedly! Keep practicing a little every day and you will get better and better! Nice commenting, BTW.

1 Like

Thanks for the tip! :slight_smile:

1 Like

Making an array from a list really stumped me. This is the answer from the book and I totally don’t get the for loop increment “node = node.rest”. Is it like skipping over the rest of the list?

function listToArray(list) {
  let array = [];
  for (let node = list; node; node = node.rest) {
    array.push(node.value);
  }
  return array;
}

I’m hoping lists aren’t used too much in reality. Recursion probably is and that is scary. If so, I need to find a couple practice problems. Very confusing for a function to call itself.

Hi again @jon_m

I tried to do something like this, I know it is completely wrong and I don’t know what I really did. I don’t know what I’m supposed to do from here or how I should begin with this exercise.

I think that the biggest problem is that I don’t understand what the exercise is all about. I think I understand it better than in the beginning when I started but I don’t understand it fully.

function reverseArray(array) {
    let array = [0,1,2,3,4,5];

    for(var i = 0; i < array.length - 1; i--) {
      return newArray = []
      }
      reverseArray()
    }
    console.log(reverseArray())