Chapter 4 - Exercises

  1. Sum of Range
    var sumrange = function(array){
    var total = 0;

     for (let i = 0; i<array.length; i++){
       total = total + array[i];
     }
     return total;
    

    };
    console.log(sum(range(1, 10)));

2 Reversing an Array
Reverse:
const reverse = (arr) =>{
let flip = []
for(let elem of arr){
flip.unshift(elem)
}
return filp
}
const arr = [1,2,3,4,5,6,7,8,9]
colsole.log(reverse(arr))

and… Reverse in Place
const revereInPlace = (arr) => {
let flip
for(let i=0; i<arr.length/2; i++){
flip = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = flip;
}
return arr;
};
const arr = [1,2,3,4,5,6,7,8,9];
console.log(reverseInPlace(arr));

1 Like

Sum of range (part 1):

      //function range takes arguement start and end.
      function range(start, end) {
          //we define array as an array.
          let array = [];
             //we for loop that i is start, and that i is less than or equal to end, and end the for loop with an increment operation of i
            for (i = start; i <= end; i++){
              //we use method .push that adds an element i to the end of array and returns the new length of the array
              array.push(i);
            }
            //at the end we return the whole array that has been for looped
            return array;
            
      }

      console.log(range(1, 10)); // result is range of the array from 1 to 10  - (10) [1,2,3,4,5,6,7,8,9,10]

Sum of range (part 2):

 
       //in the second part we will add a function that will calculate the sum of out previous array
       function range(start, end) {
           let array = [];
             for (i = start; i <= end; i++){
               array.push(i);
             }
             return array;
       }
 
       //we define the function sum that takes the array as the parameter from previous function
       function sum(array) {
         //we create a new variable x outside the loop range and set its value to 0
         let x = 0;
           // we create a loop that keeps adding array values to the value of x
           for (let i in array) {
             x = x + array[i];
           }
             return x;
       }
 
       console.log(sum(range(1, 10))); //result is 55

Sum of range (part 3):


      //in the third part we will add a third arguemnt called step which would change by how many increments the elements change
      function range(start, end, step){
        let array = [];
          if (step > 0) {
            for (i = start; i <= end; i += step)
              array.push(i);
            }
          // for negative step values, where we count backwards, i value must be greater or equal to the end 
          else{
            for (i = start; i >= end; i += step)
              array.push(i);
          }
          return array;
      }
      
      console.log(range(5, 2, -1)); // result is (4) [5,4,3,2]
      console.log(range(1, 10, 2)); //result is (5) [1,3,5,7,9]
1 Like

Reversing an array (part 1):

      //we will write a function that reverses an array
      function reverseArray(array) {
        //we crate a new variable x that is an array which will be used to return the new reversed array
        let x = [];
        // in the loop we create a new variable i that is the length of the array - value of 1
        //i must be greater or equal to value of 0
        //decrement of i
        //basicaly we iterate over the array backwards and push it to the variable x
        for (i = array.length - 1; i >= 0; i--) {
          x.push(array[i]);
        }
        return x;
      }


      console.log(reverseArray(["A", "B", "C"])); // results is (3) ["C", "B", "A"]

Reversing an array (part 2):

//I am stuck here, i don't really understand this math.floor part, I will return to it later, once I figure it out

Hello everyone, here is my post. I found this code in GitHub.
The sum of a range.
// range function
function range( start, end, increment ) {

// create the result array
var result = [];

// test to see if we have an increment, otherwise set it to 1
if ( increment == undefined )
increment = 1;

// calculate the number of times to loop (this is because you might be going
// up or down with your increment)
numLoops = Math.abs( (end - start)/ increment ) + 1 ;

// loop that many times
for ( var i = 0; i < numLoops; i ++ ) {

// add (push) the value of start to the array
result.push( start );
 
// increment the value of start
start += increment;

}

// return the array with all the things in it
return result;
}
function sum( numArray ) {
// set a variable to hold the sum
var arrayTotal = 0;

// see how many numbers are in the array
numLoops = numArray.length;

// loop that many times
for ( var i = 0; i < numLoops; i ++ ) {
// add the number at that index to the sum
arrayTotal += numArray[i];
}
// return the sum
return arrayTotal;
}
console.log(range(1, 10));
// β†’ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// β†’ [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// β†’ 55

Reversing the array is

function reverseArray(array) {
result = [];
for (let item of array) {
result.unshift(item);
}
return result;
}
function reverseArrayInPlace(array) {
let len = array.length;
for (let i = 0; i < Math.floor(len/2); i++) {
console.log(i, len-i-1, array[i], array[len-i-1], array);
let swap = array[i];
array[i] = array[len-i-1];
array[len-i-1] = swap;
}
return array;
}
console.log(reverseArray([β€œA”, β€œB”, β€œC”]));
// β†’ [β€œC”, β€œB”, β€œA”];
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// β†’ [5, 4, 3, 2, 1]
let arrayValue2 = [1, 2, 3, 4];
reverseArrayInPlace(arrayValue2);
console.log(arrayValue2);
// β†’ [4, 3, 2, 1]

1 Like

The sum of a range?
const sum = numbers => {
return numbers.reduce((acc, number) => acc + number, 0);
};
const range = (start, end, step = 1) => {
const arr = [];
if (step === 1 && end < start) step = -1;
if (start < end) {
for (let i = start; i <= end; i += step) {
arr.push(i);
}
} else {
for (let i = start; i >= end; i += step)
{ arr.push(i);}
}
return arr;
};
console.log(range(1, 10));
// β†’ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// β†’ [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// β†’ 55

Reversing an array?
// Your code here.
const reverseArray = arr => {
return [ …arr ].reverse();
};
const reverseArrayInPlace = arr => {
arr.reverse();
}
console.log(reverseArray([β€œA”, β€œB”, β€œC”]));
// β†’ [β€œC”, β€œB”, β€œA”];
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

1 Like

The sum of a range

Function rangeToArray

function rangeToArray(startValue, endValue, step=1){
        var numArray = [];
        if(startValue <= endValue && step > 0){
          for(let i = startValue; i <= endValue; i += step){
            numArray.push(i);
          }
        }
        else if(startValue >= endValue && step < 0){
          for(let i = startValue; i >= endValue; i += step){
            numArray.push(i);
          }
        }
        // If you enter for example rangeToArray(1, 20, -1), it is not possible to compute
        else{
          return "Computation not possible";
        }
        return numArray;
      }

Function arraySum

  function arraySum(a){
        let numSum = 0;
        for(let value of a){
          numSum += value;
        }
        return numSum;
      }

Reversing an array

Function reverseArray - I made it a little bit more complicated than necessary, but the result is the same :wink:

  function reverseArray(array){
        let arrayReversed = [];
        for(let i = 0; i < array.length; i++){
          arrayReversed.push(array[array.length - (1 + i)]);
        }
        return arrayReversed;
      }

Function reverseArrayInPlace
I commented some code lines for better understanding.

function reverseArrayInPlace(array){
        // You swap the elements within an array. In case the array holds an odd number of elements, the middle element does not have to be changed (simply because there is no counterpart). This is why rounding down the number of "array.length / 2" is necessary - you skip the middle element in this case, i.e. leave it unchanged
        for(let i = 0; i < Math.floor(array.length / 2); i++){
          // Variable x serves as a temporary storage for the value held in index position i of the original array, because the latter value is overwritten in the following step but needs to be inserted again in the third step
          let x = array[i];
          array[i] = array[array.length - (i + 1)];
          array[array.length - (i + 1)] = x;
        }
        return array;
      }
1 Like

I copied these solutions from the book because I could not figure it out. I’m still struggling to understand why this solution works. Can someone walk me through how these solutions work exactly? Or point me in the direction to a video or article I can watch/read to better understand the concepts used here?

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

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

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

console.log(range(1, 10))
// β†’ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// β†’ [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// β†’ 55
function reverseArray(array) {
  let output = [];
  for (let i = array.length - 1; i >= 0; i--) {
    output.push(array[i]);
  }
  return output;
}

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"]));
// β†’ ["C", "B", "A"];
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// β†’ [5, 4, 3, 2, 1]

1.The sum of a range:

  <body>

    <input placeholder="write first number" id="firstNumber" type="text"/>
    <input placeholder="write last number" id="lastNumber" type="text"/>
    <input placeholder="give step" id="step" type="text"/>

    <button id="ourButton"> press to calculate </button>

    <meta charset="UTF-8"/>

  <script>

      $("#ourButton").click(function(){

      var first=$("#firstNumber").val()
      var firstNum=parseInt(first)

      var last=$("#lastNumber").val()
      var lastNum=parseInt(last)

      var step_=$("#step").val()
      var stepNum=parseInt(step_)

      //if argument empty step will be 1, otherwise as given
      if (step_==""){
        var stepNum=parseInt(1)
      }

      //from lower to higher
      if(firstNum<lastNum){
        sum=0
          function getNumberRange(firstNum, lastNum, stepNum) {
             var arr = [];
             for (var i = firstNum; i <= lastNum; i+=stepNum) {
                 arr.push(i);
                 sum+=i
             }
            return arr;
          }
      }

      //from higher to lower
      if(firstNum>lastNum){
        sum=0
          function getNumberRange(firstNum, lastNum, stepNum) {
             var arr = [];
             for (var i = firstNum; i >= lastNum; i+=stepNum) {
                 arr.push(i);
                 sum+=i
             }
            return arr;
          }
      }
      
      console.log("array: "+getNumberRange(firstNum, lastNum, stepNum))
      console.log("sum: "+sum)
      })
  </script>

  </body>

  1. Reversing an array
<body>

    <input placeholder="write first number" id="firstNumber" type="text"/>
    <input placeholder="write last number" id="lastNumber" type="text"/>
    <input placeholder="give step" id="step" type="text"/>

    <button id="ourButton"> press to calculate </button>

    <meta charset="UTF-8"/>

  <script>

      $("#ourButton").click(function(){

      var first=$("#firstNumber").val()
      var firstNum=parseInt(first)

      var last=$("#lastNumber").val()
      var lastNum=parseInt(last)

      var step_=$("#step").val()
      var stepNum=parseInt(step_)

      //if argument empty step will be 1, otherwise as given
      if (step_==""){
        var stepNum=parseInt(1)
      }

      //create reverse array from given array, but inverse order-NON PURE
          function reverseArray(firstNum,lastNum,stepNum){
            sum=0
            var arr = [];
              for (var i = firstNum; i <= lastNum; i+=stepNum){
                  arr.push(i);
                  sum+=i
              }
            return arr.reverse();
           }

      console.log(reverseArray(firstNum,lastNum,stepNum))

//create reverse array by array given as argument, unshift is adding new items to the beginning of array-NON PURE
          function reverseArrayInPlace(firstNum,lastNum,stepNum){
            sum=0
            var arr = [];
                for (var i = firstNum; i <= lastNum; i+=stepNum){
                    arr.unshift(i);
                    sum+=i
                }
              return arr;
            }

      console.log(reverseArrayInPlace(firstNum,lastNum,stepNum))

    })


    </script>

    </body>

The more useful situation? The fastest one?

Pure functions are faster but can be harder to understand. Both are correct.
It depends what is program used for. In most cases functions with side effects (non pure) are useful and easier to understand and read.

I am not sure if everything is correct, especially second part but
I must say that it takes time to write the code by your own but at the end it pays off. Do not give up. Try, things, be angry and try , try, try…

1 Like

Hi @Renz,

You could check out these posts for understanding -

2 Likes
  1. Sum of a Range
  let lowerBound = 2;
    let upperBound = 20;
    let array = [lowerBound];
    let step = 2;

    while (lowerBound < upperBound){
      lowerBound += step
      array.push(lowerBound)
    };
  console.log(array);

    let sum = 0;
    for(let i = 0; i < array.length; i++){
      sum += array[i]
    };
  console.log(sum);
  1. Reverse an Array
    let fowardArr = ["One", "Two", "Three", "Four", "Five"];
    let reverseArr = [...fowardArr].reverse();
  console.log(fowardArr)
  console.log(reverseArr)
2 Likes

1b - sumarray function
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum = sum + array[i];
};
console.log(sum);

1.c - step array
var numberList = [];
function range(start,end,step) {
for (var i = start; i < (end+1); i=i+step) {
numberList.push(i)
};
};
range(-1,20,3);
console.log(numberList);

reversing an array
2a - reverseArray
var testArray = [1,2,3,4,5,6,7,8,9];
function reverseArray(arr) {
var array1 = [];
for (var i = 0; i < arr.length; i++) {
array1.push(arr[arr.length-i]);
};console.log(array1);
};

2b - reverseArrayInPlace
function reverseArrayInPlace(arr) {
var array1 = [];
array1 = arr;
for (var i = 0; i < arr.length; i++) {
arr[i] = array1[arr.length-i];
};console.log(array1);
};

1 Like

Q1:
function rangeFunction(a,b){
lengthOfRange= b-a+1;
arrayConstruction=[];
for (i=0;i<lengthOfRange;i++){
c=a+i;
arrayConstruction.pushΒ©
}
return arrayConstruction;

}

function sumFunction(a){
addedAlready=0;
for (i=0;i<a.length;i++){
addedAlready+=a[i];
}
return addedAlready;
}

Q2:
function reverseNew(oldArray){
newArray=[].
for (i=oldArray.length-1; i>=0;i–){
newArray.push(oldArray[i]);
}
return newArray;
}

2 Likes

A.1. The sum of a range

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

if (step > 0) {
for (let number = start; number <= end; number += step) array.push(number);
}

else {
for (let number = start; number >= end; number += step) array.push(number);
}

return array;
}

function sum(array) {
let total = 0;

for (let value of array) {
total += value;
}

return total;
}

console.log(range(1, 10));
// β†’ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

console.log(range(5, 2, -1));
// β†’ [5, 4, 3, 2]

console.log(sum(range(1, 10)));
// β†’ 55

A.2. Reversing an array

function reverseArray(array) {
let output = [ ];
for (let number = array.length - 1; number >= 0; number–) {
output.push(array[number]);
}

return output;
}

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

return array;
}

console.log(reverseArray([β€œA”, β€œB”, β€œC”]));
// β†’ [β€œC”, β€œB”, β€œA”]

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

console.log(arrayValue);
// β†’ [5, 4, 3, 2, 1]

1 Like

The Sum of a Range

      /*Names a function range and set its properties to start, end, and step.
        Sets the value of step to 1 if start is less than end, or sets the
        value of step to -1 if start is greater than end*/
      function range(start, end, step = start < end ? 1 : -1){
          //names the new array.
          let rangeArray = [];

          /*if step is a positive value, start must be less than or equal
          to end to loop*/
          if (step > 0){
            for (rangeCount = start; rangeCount <= end; rangeCount += step)
              //adds the rangeCount to rangeArray
              rangeArray.push(rangeCount);
            /*if step is a negative value, start must be greater than or equal
            to end to loop*/
          } else {
            for (rangeCount = start; rangeCount >= end; rangeCount += step)
              //adds the rangeCount to rangeArray
              rangeArray.push(rangeCount);
          }
          //returns the new array after looping finishes
          return rangeArray;
        }

      //Names a function, sum
      function sum(range){
        //Names a variable as a placeholder for the variable value
        let total = 0;
        /*creates a variable named value that holds the current index of range;
         sets current index to 0;and loops until index equals range.length */
        for (let value of range) {
          //Adds the current index value to the total value
          total += value;
        }
        //returns the total value after looping is finished
        return total;
      }

Reverse Array

  //Names the function reverseArray
        function reverseArray(array){
          //Names a variable for the new array
          let output = [];
          /*loops through the given array. array.length needs - 1 because the
          the count of .length begins at 1.
          Using .length - 1, in effect, begins the count at 0.*/
          for (let i = array.length - 1; i >= 0; i--){
            //adds the result of the for statement to the new array
            output.push(array[i]);
          }
          // returns the result of the new array once looping is complete
          return output;
        }

        //names the function reverseArrayInPlace
        function reverseArrayInPlace(array) {

          /*loops through the given array as long as the index is less than the array
          length divided by 2 and rounded down. */
          for (let i = 0; i < Math.floor(array.length / 2); i++) {
            //names a variable as a placeholder for the current index
            let old = array[i];
            //I don't know what the next two lines are doing.
            //Does the next line remove the current index from the array?
            array[i] = array[array.length - 1 - i];
            //I have no clue what the next line does.
            array[array.length - 1 - i] = old;
          }
          return array;
        }

Also, I have no idea why I would use reverseArrayInPlace instead of reverseArray. reverseArray is much easier to understand and write.

1 Like
  1. The sum of a range

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

  1. Reversing an array

var arr = [1,2,3,4,5];

arr.reverse();

//[5,4,3,2,1]

Console.log(arr);

The exercise wanted you to implement this functionality without using the inbuilt javascript functions. This is required because it will teach you how to think and create algorithms on your own. Please give it a try.

Happy learning.

A.Malik

  1. The Sum Of A Range
            // Part 1
            function rangeVar(start, end) {
                var container = [];
                for (var i = start; i <= end; i++) {
                    container.push(i);
                }
                console.log(container);
            }
            rangeVar(1, 10);
            // Output -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


            // Part 2
            function summedVar(array) {
                var summedAmount = 0;
                for (var j = 0; j <= array.length; j++) {
                    summedAmount += j;
                }
                console.log("Summed Amount = " + summedAmount);
            }
            summedVar([1,2,3,4,5,6,7,8,9,10]);
            // Output -> 55



            // Part 3 (Bonus)
            function bonusRange(start, end, step) {
                var bonusContainer = [];
                if (step != undefined) {
                for (var k = start; Math.abs(k) <= Math.abs(end); k += step) {
                    bonusContainer.push(k);
                }} else {
                for (var k = start; Math.abs(k) <= Math.abs(end); k++) {
                    bonusContainer.push(k);                    
                }}
                console.log(bonusContainer);
            }
            bonusRange(1, 10, 2);
            // Output -> [1, 3, 5, 7, 9]
            bonusRange(1, 10);
            // Output -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
            bonusRange(1, -10, -2);
            // Output -> [1, -1, -3, -5, -7, -9]
  1. Reversing An Array
            function reverseArray(array1) {
                var newArray1 = []
                for (var l = array1.length -1; l >= 0; l--) {
                    newArray1.push(array1[l]);
                }
                console.log(newArray1);
            }
            reverseArray([3, 6, 8, "hi"]);
            // Output -> ["hi", 8, 6, 3]



            // Part 2
            function reverseArrayInPlace(array2) {
                for (var m = array2.length - 2; m = 0; m--) {
                    array2.push(array2[m]);
                    array2.splice(m, 1);
                }
                console.log(array2);
            }
            reverseArrayInPlace([7, 4, 29, 5, 25, 1, 30]);
            // Output -> [30, 1, 25, 5, 29, 4, 7]
1 Like

//Sum of Range

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

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

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

// ReverseArray
function reverseArray(array) {
  let output = [];
  for (let i = array.length - 1; i >= 0; i--) {
    output.push(array[i]);
  }
  return output;
}

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;
}
2 Likes
  1. Sum of range/1.
function arrRange(start, end) {
  let arr []; 
  for( i=start; i<=end; i++)
    arr.push(i);
    return arr;
  };
  console.log(arrRange(1,10);

Sum of range/2.

function sumAll(arr) {
      var start = Math.min(arr[0], arr[1]);
      var end = Math.max(arr[0], arr[1]);
      var total = 0;
      for (var i=start; i<=end; i++){
        total +=i;
      }
      return total;
    }
    console.log(sumAll([1,10]));
  1. reverse array
function arrRange(start, end) {
  let arr []; 
  for( i=start; i<=end; i++){
    arr.push(i);
    return arr;
  };
  console.log(arrRange(1,10);
2 Likes

Hey guys, I have question regarding the reverse array in place exercise. My solution to the exercise was the following: var array = [1,2,3,4,5];

function reverseInPlace (arr) {
for (i = 0; i < Math.floor(arr.length/2); i++) {
var old = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[array.length - 1 - i] = old;
}
return arr
}

console.log(reverseInPlace(array))

I understand everything going on here except for why I’m supposed to divide arr.length by 2. Does i just constantly keep going up to arr.length/2 until it completes the array? The simplest breakdown of this action would be greatly appreciated.

Thanks!

1 Like