Chapter 4 - Exercises

Amazing sir! you are killing it! keep it like that please! such an amazing style to program man! :muscle:

Carlos Z.

Thanks! To be fair, I’m familiar with Test Driven Development (TDD) and have used Jasmine along with Angular and Typescript. I never really learned javascript properly, went straight to typescript from C#. Used pure javascript a bit only with nodejs on the back end for APIs. Been a while since I last used any of that though so thought I might as well take this course. jQuery is new to me, I went straight to Angular from Winforms/WPF in C#.

1 Like

1. The Sum of a Range

 <script>

      function range(start, end){
        var arr = [];
        for(var i = start; i <= end; i++) {
          arr.push(i);
        }
        return arr;
      }

      function sum(numbers){
        result = 0;
        for (let num of numbers) {
          result += num;
        }
        return result;
      }

      document.write(sum(range(1, 10)));

    </script>
1 Like
The sum of a range (+steps)
<script>

        

        function range(start, end, step){

            if (step == null) step = 1;             //  if step is not setted, the basic step is 1

            var array = [];                         // "array" named empty array

            

            if (step > 0)                           // if step is a positive number do this

            for (i= start; i<= end; i+= step ){

                 array.push(i);                     // every step pushed to the array

            } else {

                for (i= start; i>= end; i+= step){  //  if the start greater than end, steps backward

                    array.push(i);

                }

            }

            return array;                           // return the whole array

        };

        function sum(array){                        // sum function uses the array

            var total = 0;                          // total variable is 0 at the beginning

            for (i = 0; i< array.length; i++)       // adds all the elements in the array

            total += array[i];

            return total;                           // function returns the total sum

        }

    console.log(sum(range(1,100,3)));

    </script>
Reverse an Array
<script>

        

        function reverseArray(array){

            let output = [];                         // create output array

            

            for(i = array.length - 1; i >= 0; i--){

                output.push(array[i]);

            }

            return output;

        }

        function reverseArrayInPlace(array){

            for(i = 0; i < Math.floor(array.length)/2; i++){

                let old = array[i];

                array[i] = array[array.length-1-i];

                array[array.length-1-i] = old;

            }

            return array;

        }

    console.log(reverseArray(["A","B","C","D","E"]));

    //let arrayValue = [1,2,3,4,5,6,7,8,9,10];

    let arrayValue = [10,9,8,7,6,5,4,3,2,1];

    reverseArrayInPlace(arrayValue);

    console.log(arrayValue);

    </script>
1 Like

Hi, I am struggling with these and found your answer really great, step by step. Tried to do code like yours, but when I run the example program, I get 0, not the sum of the range. Is it the issue, that n_sum = 0 and later it returns the same 0, not the sum? Thanks

Hi. Could anyone help a bit as I am stuck here for few hours? My function looks like that, but I don’t get the sum, I just get all the numbers written in order 1to10 a few times in a row. As I checked many other answers in the forum, it looks like it should give me the sum. Another question: some people using let, others using var variables, what’s better in this case and why? Thank you

function range(start, end){
    let arr = [];
    for (let i = start; i <= end; i++) {
      arr.push(i);
    }
    return arr;
  }

  function sum(yy){
    result = 0;
    for (let i = 0; i <= yy.length; i++){
      result += yy;
    }
      return result;
  }

  document.write(sum(range(1, 10)));

And there is a for loop in the answer in the book for (let value of array) { total += value; }, which has completely different format from the for loop which I recognise from previous chapters. How to understand that let value of array?

Hello sir, the “let” variables will just be available to the scoped block (used only within the function that is declared), the “var” variables are global scoped (can be used or seen by the whole program), both could be used in different ways, the “let” variable for example when you dont want to let others function to access that variable, or if you want to use that variable in other functions you will use the “var” instead.

Now i have prepare this code for you to be able to deeply understand how it should work:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Vidmantas</title>
  </head>
  <body>
    <h1>Sum Of Range</h1>
    <button type="button" onclick="sumrange(1,3)">Start SumRange. </button>
    <script>
      function sumrange(x, y){
  //start with start, ending at any number
    function range(start, end){
      //array to store value
        let arr = [];
        //i = start, i less or equal than end, iteration i
        for (let i = start; i <= end; i++) {
          //add a value to array
          arr.push(i);
        }
        //just to check the array
        console.log("Array variables are: "+arr);
        //return array
        return arr;
      }
    //to sum all the values on the array
      function sum(array){
        //result to be returned
        let result = 0;
        //i = 0, i less than array lenght, iteration i
        for (let i = 0; i < array.length; i++){
          //add the array index to result
          result += array[i];
          //to check the steps of the sum
          console.log("i will add: " + array[i] + " to result");
          //to keep track of the sum
          console.log("result now is: " + result);
        }
        //return the sum of all the array
          return result;
      }
      //just to check the sum of the array
      console.log("Total sum is: "+sum(range(x, y)));
    }
    </script>
  </body>
</html>

Hope this gives you a clear view of the subject, keep learning! :slight_smile:
If you have any doubt, please let us know so we can help you!

Carlos Z.

1 Like

I got through the first exercise, however, I feel like my code is lengthy and would appreciate any feedback on where I can optimise.

I did the first part of the second exercise, creating a new array which reversed the input array. But to be honest, I couldn’t understand what second part was asking for, I’ll read through some of the forum to get some ideas.

The sum of a range

    <script>
        
       function range(start,end,step){
           let userRange = [];
                if (step == null || step ==0){
                    for(x=start; x<=end; x++){
                    userRange.push(x);
                    }   
                    return userRange;
                } else if(step>0) {
                    for(x=start; x<=end; x+=step){
                    userRange.push(x);
                    }
                    return userRange;
                } else{
                    for(x=start; x>=end; x+=step){
                    userRange.push(x);
                    }
                    return userRange; 
                }
       } 
        
        function sumRange(...input){
            let last = input.length - 1;
            var result=0;
                for(counter=0; counter<=last; counter++){
                result += input[counter];
                }
            return result;
        }
                
    alert(sumRange(...range(1,10,2)));        
    
    </script>

Reversing an Array

    <script>

        function reverseArray(...input){
            let array = [];
            let last = input.length - 1;
                for(counter=last; counter>=0; counter--){
                array.push(input[counter]);
                }
            return array;
        }
                                        
        alert(reverseArray(1,2,3,4,5));        
    
    </script>
1 Like

Hello sir, here is a little function to help you understand even better how it should work:

function reverseArray() {
  var arr = [1,2,3];
  //to save the array reversed
  var newArray = [];
  //i = parameter lenght - 1(to start at last element on the arr), 
  //i equal or greater than 0, 
  //i minus 1 for iteration
  for (var i = arr.length - 1; i >= 0; i--) {
    //add an element into new array
    newArray.push(arr[i]);
  }
  console.log(newArray);
}

Hope this gives you a clear view of the subject, keep learning! :slight_smile:
If you have any doubt, please let us know so we can help you!

Carlos Z.

Thanks, that’s very much appreciated, your function works perfectly.
I have one more question though. You put both functions into function sumrange(x,y), but when I try following the exercise in the book, it kind of pushes to have two separate functions, what all other people in the chat did as well. In that case, my sum function doesn’t work, but it looks correct for me. Following what book gives as an answer with for loop - works perfectly. Just didn’t see anything about using for loop like that anywhere in the book or even didn’t find in youtube. My function below (with book’s way blacked out with “//”)

function sum(yy){
    let result = 0;
    for (let i = 0; i <= yy.length; i++){
    result += yy[i];
    //for (let value of yy){
    //result += value;
    };
      return result;
  };

function reverseArray(array) {

		let newArray = [];

		for(let i = array.length - 1; i >= 0; i-- ) {

			newArray.push(array[i]);

		}
		return newArray;
	}


function reverseArrayInPlace(array) {

	for (let i = 0; i < Math.floor(array.length / 2); i++) {
		let old = array [i];
		array[i] = array[array.length -1 - i];
		array[array.length -1 -i ] = old;

	}
	return array;
}

console.log(reverseArray([“a”, “b”, “c”, “d”]));

let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

I don’t really get what’s the difference between reverseArray and reverseArrayInPlace? For me they both seems do the same function.

@Aigars, I might be wrong as I find everything quite hard so far, but from what I learnt, in the reverseArray you push all elements of array one position down, while in reverseArrayInPlace you swap position 0 with position 4, pos1 with pos3 and pos2 swaps with itself.

I tried to make this in two different ways, first one is exactly like yours with some explanations for myself after each line, but someone might find them beneficial too.
First way:

function reverseArrayInPlace(arr){
      let temp;
      for (let i = 0; i < Math.floor(arr.length/2); i++){ //i<5/2=2.5(downgrade to 2(position in arr))
        temp = arr[i];//temp=arr[0] >> temp=arr[1] >> temp=arr[2]
        arr[i] = arr[arr.length-1-i];//arr[0]=arr[4] >> arr[1]=arr[3] >> arr[2]=arr[2]
        arr[arr.length-1-i] = temp;//arr[4]=temp >> arr[3]=temp >> arr[2]=temp
      }
      return arr;
    }
    let arrayValue = [1, 2, 3, 4, 5];
    reverseArrayInPlace(arrayValue);
    console.log(arrayValue);

Second way:

function reverseArrayInPlace(arr){
      let result = [];
      for (let elem of arr){
        result.unshift(elem)
      }
      return result
    }
    console.log(reverseArrayInPlace([1,2,3,4,5]));

From what I understand after copying it all to here, the second way is probably more of a reverseArray and not the reverseArrayInPlace, am I correct? :slight_smile:

  1. Sum of a range

function sum(rangeArray) {
var total = 0;
for(let i = 0; i < rangeArray.length; i++) {
total += rangeArray[i];
}
console.log(total);
}
var anArray = [1,2,3,4,5,6,7,8,9,10];
sum(anArray);

  1. Reversed Array

    var fruits = [“1_apple”, “2_orange”, “3_lemon”, “4_mango”, “5_durian”];

    function reverseArray(myArray) {
    var newArray = [];
    newArrayIndex = myArray.length;
    for (var i = 0; i < myArray.length; i++) {
    newArray[–newArrayIndex] = myArray[i];
    }
    return newArray;
    }
    console.log(fruits);
    // Inversion
    console.log(reverseArray(fruits));

1 Like

Hello sir, what is not working for you? what i see is that you are not using any function to show the value in console nor the document. (console.log or document.write), so maybe the function is properly working, but how do you know that, if you dont let it show by the console to let you know that is working?

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

Carlos Z.

Hello sir, the first function will take an array and create a new one inside of his logic, it does not reverse the first one, it create a new one based on a for loop that will iterate the first one starting with the last element until the first element.

The second function use the “math.floor()” function, that will return the largest integer of a number, and then will redesign the same array that it has been inputed.

The difference? the first one will create a new array that will show a reversed array of the inputed parameter (array), the second one will change the inputed parameter (array) and reversed it step by step.

Hope this gives you a clear view of the subject, keep learning! :slight_smile:

If you have any doubt, please let us know so we can help you!

Carlos Z.

I’m trying to get my head around all this as well. Frankly, I still don’t understand much, what is what. Every time I write anything it does’t work so I have to look for the answers online or in the book. Thank you for your help and your comments they are very useful, I might start doing that as well. Good practice :ok_hand:

Thanks Carlos, now I understand the difference. However, I’m still struggling with writing any code that works by myself. By reading that book ‘EJS’, without any previous knowledge, I found it impossible to complete any exercises without looking for the answers online or in the book. The whole concept of coding is something new to me but I really wan’t to understand it and be able to write a code that works. Is there any other ‘baby steps’ you could recommend, from your experience, that might be useful to take or ‘EJS’ is the very foundation? Many thanks

2 Likes

The Sum of a Range:

function sum(array) {
var accumulator = 0;
for (var i = 0; i < array.length; ++i)
accumulator += array[i];
return accumulator;
}

Reversing An Array:

var reverse = function(arr) {
var result = [],
ii = arr.length;
for (var i = ii - 1;i !== 0;i–) {
result.push(arr[i]);
}
return result;
}

Sum of a Range:

I had console.log, just didn’t copy it here. I found out, that issue was in this row, I had “<=” instead of just “<” //for (let i = 0; i < array.length; i++){ , so finally I am all sorted with these exercises :slight_smile: Thanks for your help

1 Like