Chapter 4 - Exercises

Sum of Range::

Before Modification

function range(start, end,step) {

var ans = [];

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

ans.push(i);
}

return ans;

}

function sum(arr) {

let result = 0;

for(let c = 0; c < arr.length; c++) {
	result += arr[c];
}

return result;

}

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

Sum of Range::

After Modification::::

function range(start, end,step) {

var ans = [];
var stepOne = 1;

if (step != undefined){
stepOne = step;
}
if(start < end){
for(var i = start; i <= end; i += stepOne){
ans.push(i);
}
}
else if(start > end){
for(var i = start; i >= end; i += stepOne){
ans.push(i);
}
}
return ans;
}

function sum(arr) {

let result = 0;

for(let c = 0; c < arr.length; c++) {
	result += arr[c];
}

return result;

}

console.log(range(1,10,2));

Reversing The Array :::::

var ans = [];
function reverseArray(array) {
for (var i = array.length-1; i >= 0; i–) {
ans.push(array[i]);
}
console.log(ans);
}

console.log(reverseArray([2,4,6,8]));

Reverse Array in place:::

function reverseArrayInPlace(array){
for (let i = 0; i < Math.floor(array.length ); i++) {

}
return array;
}

console.log(reverseArrayInPlace([2,6,4,5,6]));

The sum of a range

<script>
        function complete(startNumber, endNumber, step) {
            let arrayForComplete = [];
            if (step < 0) {
                for (let counter = startNumber; counter >= endNumber; counter += step) {
                    arrayForComplete.push(counter);
                }
            } else {
                for (let counter = startNumber; counter <= endNumber; counter += step) {
                    arrayForComplete.push(counter);
                }
            }

            console.log(arrayForComplete);

            let sumForComplete = 0;

            for (let counter = 0; counter < arrayForComplete.length; counter++) {
                let number = arrayForComplete[counter];
                // console.log(number);
                sumForComplete += number;
            }

            console.log(sumForComplete);
        }

        complete(1,10,2);
        complete(1,5,3);
        complete(5,2,-1)

    </script>

Reversing an array

<script>
        /* */

        let arrayNew = ["Apple", "Pieapple", "Lemon", "Cherry", "Orange", "Kiwi", "Coconut", "Banana"];

        function reverseArray(arrayInput) {
            // this function creates new array with reverse order
            let newOutputArray = [];
            for (let counter = arrayInput.length - 1; counter >= 0; counter--) {
                let valueOfArray = arrayInput[counter];
                newOutputArray.push(valueOfArray);
            }

            console.log(newOutputArray);
        }

        function reverseArrayInPlace(arrayInput) {
            // this function doesn't create new array, but still reverse given array
            for (let counter = 0; counter < arrayInput.length/2; counter++) {
                let x = arrayInput[counter];
                let y = arrayInput[arrayInput.length - 1 - counter];
                let blank = x;
                arrayInput[counter] = y;
                arrayInput[arrayInput.length - 1 - counter] = blank;
            }

            console.log(arrayInput);
        }

        reverseArray(arrayNew);
        reverseArrayInPlace(arrayNew);
// checking .reverse method, needed to use it twice
        console.log(arrayNew.reverse());
        console.log(arrayNew.reverse());

    </script>

1.) The sum of a range:
image
2.) Reverse an array, reverse an array in place:

1 Like

function range(array){
var start = array[0];
var end = array[1];
return (end*(end+1) - (start-1)*start) / 2;
}
console.log(range([1 , 10]));

var fruits = [“Orange”, “Banana”, “Apple”, “Grape”];

    function reverseArray(fruitArray) {
        var newArray = [];
        for(var i = fruitArray.length - 1; i >= 0; i--) {
            newArray.push(fruitArray[i]);
        }
        return newArray;
     }
     
     console.log(fruits);
     console.log(reverseArray(fruits));

Chapter 4 exercises

Here’s my solutions:

the sum of range
a)
function range(start, end){
for(var i=start;i<=end;i++)
document.write(i);
}
range(1, 10);

b)
function range1(start, end){
var sum = 0;
for(var i=start;i<=end;i++)
sum += i;
document.write(sum);
}
range1(1, 10);

c)
function range(start, end, step){

if(step > 0){
  for(var i=start; i<=end; i += step)
  document.write(i);
  console.log(i);
}
if(step == 0){
  for(var i=start; i<=end; i++)
  document.write(i);
  console.log(i);
}
if(step < 0) {
  for(var i=start; i>=end; i += step)
  document.write(i);
  console.log(i);
}

}

range(1, 10, 2);

Reversin Array

var fruits = [ “banana”, “orange”, “coconut”];

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

}
console.log(fruits);
console.log(reverseArray(fruits));

  1. The sum of a range
  var myArray = [];
  var sum= 0;

  function returnRange(start, end, step) {
    if (step === undefined) {
      for (var start; start <= end; start++) {
        myArr.push(start);
      };
      console.log(myArray);
    } else if (step > 0) {
      for (var start; start <= end; start+=step) {
        myArray.push(start);
      };
      console.log(myArray);
    } else if (step < 0) {
      for (var start; start >= end; start+=step) {
        myArray.push(start);
      };
      console.log(myArray);
    }
  };

  function sumNumbers(){
    for (var i = 0; i < myArray.length; i++) {
      sum+=myArray[i];
    };
    console.log(sum);
  };
  1. Reversing an array
var returnArray = [];
		function reverseArray(anArray) {
			index = 0;
			for (let i = anArray.length-1; i >= 0; i--) {
			  returnArray[index] = anArray[i];
			  index++;
			}
			return returnArray;
		};

		reverseArray([5,7,8,2,1]);
		console.log(returnArray);

//Sum of a Range
var range = function(start, end){
var array = [];
counter = start;

      while (counter <= end){
        array.push(counter);
        counter++;
      }
      return array;

};

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

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


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

//Reversing an Array
function reverseArrayInPlace(array) {
for (var a = 0; a < Math.floor(array.length / 2); a++) {
var aux = array[a];
array[a] = array[array.length - 1 - a];
array[array.length - 1 - a] = aux;
}
return array;
}
var arrayValue = [1, 2, 1, 2];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

Problem 1 - Return a range of numbers
      // Takes args start and end with optional step
      function range(startNum, endNum, stepNum=1){
        var arrRtn = [];
        // Make sure we can deal with negative numbers
        var numStep = Math.abs(stepNum);
        // if start is greater than end then swap them around
        if(endNum>startNum){
          for(loop = startNum; loop<endNum+1; loop+=numStep){
            arrRtn.push(loop);
          }
        }
        else{
          for(loop = endNum; loop<startNum+1; loop+=numStep){
            arrRtn.push(loop);
          }
        }
        // Return array
        return arrRtn;
      }
Problem 2 -  - Return the sum of numbers
      // Takes a number array as an arg and retuns the sum of its contents
      function sum(arrRange){
        var numRtn = 0;
        for(loop = 0; loop<arrRange.length; loop++){
          numRtn+=arrRange[loop];
        }
        // Return number
        return numRtn;
      }
Problem 3 - Reversing an array
      // Takes an array as an arg
      function reverseArray(arrToReverse){
        var arrRtn = [];
        var numLength = arrToReverse.length;
        var numReverse = numLength-1;
        // Loop through the return array and use reverse counter to
        // populate from the input array.
        for(loop = 0; loop<numLength; loop++){
          arrRtn[loop]=arrToReverse[numReverse];
          numReverse--;
        }
        // Return array
        return arrRtn;
      }
Problem 4 - Reversing an array in place
      // Takes an array and reverses its contents in place
      function reverseArrayInPlace(arrToReverse){
        var loopFwd = 0;
        var loopRev = arrToReverse.length;
        // Keep looping until counters reach the centre of the array
        while(loopFwd<loopRev){
          let temp = arrToReverse[loopFwd];
          arrToReverse[loopFwd]=arrToReverse[loopRev-1];
          arrToReverse[loopRev]=temp;
          loopFwd++;
          loopRev--;
        }
        // Return the amended array
        return arrToReverse;
      }
1 Like

In Question 2, the hints mention an alternative solution for the  reverseArray  function, using .unshift()  instead of  .push() . It’s more straightforward than using  .push()  because you can iterate forwards, instead of having to iterate backwards. Here’s my version using  .unshift()

function reverseArray(array) {
   let newArray = [];
   for (let i = 0; i < array.length; i++ ) {
      newArray.unshift(array[i]);
   }
   return newArray;
}

I’ve also seen a few posts where the more succinct  for...of  loop has been used, which I think is an improvement.  e.g.

I really like how concise and clear this solution is.


Below is my solution for the  reverseArrayInPlace  function. It’s different to the recommended solution in the following ways:

  • It defines an additional local variable before the for loop to hold the array’s final index position ( length - 1 ) , which can then be referenced in three of the for loop’s expressions. This shortens and simplifies these expressions, making them clearer and easier to read.

  • By using   array.length - 1   instead of   array.length   within the for loop’s condition, it avoids having to use  Math.floor()  to round down.

  • Using two local variables within the  for  loop’s code block to temporarily hold the two elements to be swapped (instead of just one variable to hold just one of these elements) does make my version less concise in this part of the function; however, I think having the additional variable may make what is happening here slightly easier to conceptualise for anyone reading the code.

  • It doesn’t return a value. I’d like to get some feedback on this. Only a handful of posts have solutions that also omit the return statement.  e.g.
    https://forum.toshitimes.com/t/chapter-4-exercises/3117/7?u=jon_m
    https://forum.toshitimes.com/t/chapter-4-exercises/3117/22?u=jon_m
    I think the function works without having to return the reversed array, because object properties and array elements are both passed to functions by reference (and not by value). This means that, when the array (already assigned to the  arrayValue  variable outside the function’s local scope) is passed to the function, and its elements reversed within the function’s local scope, these changes are also reflected in the array assigned to the  arrayValue  variable outside the function. Therefore, after the function has been called, when  arrayValue  is logged to the console it reflects the reversal because of the changes made within the function directly, and not because of a value returned from the function which reflects these changes. So, I think the return statement is redundant in this exercise, and would only be necessary if the function call itself were logged to the console. I’m surprised that the recommended solution includes it. Does anyone know of any particular reason (perhaps linked to best practice, or function reusability) why it should be included? Any comments @filip?
    Here is a link to an article from Hacker Noon about the concepts of pass by value and pass by reference, the difference between them, and the implications of this.

Here’s my solution for this function:

function reverseArrayInPlace(arrayValue) {
   let final = arrayValue.length - 1;
   for (let i = 0; i < final / 2; i++) {
      let x = arrayValue[i];
      let y = arrayValue[final - i];
      arrayValue[i] = y;
      arrayValue[final - i] = x;
   }
}

I’m also impressed by the following two other alternative solutions to the  reverseArrayInPlace  function. Both employ the array method  .splice()  in different ways, and the first one, at least, is even more succinct.

.splice()  removes and/or adds and/or replaces elements in the array it is called on, and returns a separate array containing any elements removed. It takes the following parameters:
(1)     index position the change is to start at;
(2)     number of elements to be removed from (and including) the index position;
(3, 4…)  elements to be added from (including at) the index position (omitted if no elements are to be
      added).

Other Alternative 1

As mentioned above, I think the return statement can be omitted, which would condense the function even further. The iteration could also start at  index = 1  as performing the loop for  index = 0  doesn’t actually change anything — it just removes the element at index 0 and then adds it back at exactly the same position (i.e. at the beginning of the array).

Other Alternative 2

…which, although still not as succinct as Other Alternative 1, could be made slightly more concise as follows:

function reverseArrayInPlace(alwaysArray) {
     let finalIndex = alwaysArray.length - 1;
     for (let i = 0; i < finalIndex; i++) {
          alwaysArray.splice(i, 0, alwaysArray[finalIndex]);
          alwaysArray.pop();
     }
}

Note that in this modified version, the loop is exited before the final element. This is because the reversal is already complete after performing the loop for the penultimate index position; performing it again for the final element doesn’t actually make any difference.

There weren’t any recommended answers to the additional questions in the Reversing an array exercise about the differences in the reusability and execution speed of the two functions, and only a very few people have commented on these questions in this thread. Here is my attempt at an answer — I would be very interested to hear further comments and to get some feedback on this… @filip

I think the  reverseArray  function (which produces a new array that is the reverse of the original) is a pure function because:

  1. It is deterministic: the same array passed to it as an argument will always return the same reversed array.
  2. It returns a value (the reversed array) and doesn’t produce any side effects. Nothing outside of the function’s local scope is changed in any way.
  3. It doesn’t depend on, and isn’t affected by, any side effects or changes in variables defined outside of the function’s local scope.

In contrast, I think the  reverseArrayInPlace  function (which replaces the array that is passed to it with a reversed version) isnt a pure function because:

  1. By changing the array assigned to the variable arrayValue (defined outside the function’s local scope), it produces a side effect.
  2. It is dependent on, and will be affected by, any changes made outside of the function to the external variable  arrayValue .

I think all of the above points make the  reverseArray  function more reusable in other situations.

In terms of execution speed, I tried to test this using the built-in functions  console.time()  and  console.timeEnd()  but I wasn’t sure exactly where in the program these functions should be placed in order to record a meaningful comparison. After some experimentation, I came to the conclusion that there isn’t any significant difference in the speed of the two functions. If anything, the pure function  reverseArray  may be slightly faster.

The following comment is interesting, and suggests that the  reverseArrayInPlace  function may use less memory:

The following comments seem to support my conclusions:

3 Likes

Once again theses exercises from the book were very difficult. Had to be inspired from colleague and Youtube.

Sum of a Range:

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

    while (counter <= end) {
      arr.push(counter);
      counter++;
    }
    return arr;
  };
  console.log(range(1, 10));

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

    for (let i = 0; i < arr.length; i++) {
      total = total + arr[i];
    }
    return total;
  }
  console.log(sum(range(1, 10)));

  // Now for the bonus assignment with third argument:
  function range2(start2, end2, step2) {
    var range2 = [];
    var i2 = 0;

    if (step2 === undefined) {
      step2 = 1;
    }
    if (step2 < 0) {
      do {
        range2[i2] = start2;
        start2 = start2 + step2;
        i2++;
      } while (start2 >= end2);
      return range2;
    }
    else {
      do {
        range2[i2] = start2;
        start2 = start2 + step2;
        i2++;
      } while (start2 <= end2);
      return range2;
    }
  }
  console.log(range2(1, 10, 2));

Reversing an array:

  function reverseArray(arr) {
    let newArr = [];
    for(i = arr.length - 1; i >= 0; i--) {
      newArr.push(arr[i]);
    }
    return newArr;
  }

  //And now the Reverse Array in Place:
  function reverseArrayInPlace(arrValue){
    for (let i = 0; i < Math.floor(arrValue.length / 2); i++) {
      let old = arrValue[i];
      arrValue[i] = arrValue[arrValue.length - 1 - i];
      arrValue[arrValue.length - 1 - i] = old;
    }
    return arrValue;
  }
1 Like

Good job! I like your solution.

A comment about the return statement. As with many things I think it’s a personal preference of the coder. People have different styles. It can be dangerous sometime to rely on a functions utilizing “pass by reference” parameters, especially if I’m calling a function that I didn’t write or understand. As you can see here (https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language), depending on how the function is written it can either be pass by value or pass by reference, even if the parameters are objects.

It’s all very simple when functions are are few rows, but when working with huge programs with a lot of complex functions that some other person wrote I believe it can be clearer if a function actually returns something. Because I might expect the opposite: I’m not seeing any variable being changed with and “=” sign or a return statement, so I will assume that the state remains the same. But then in reality, one of the functions actually makes changes to an object or an array, without me understanding it. If the function returned the value instead I would have seen exactly where the state changes. Like:

var array = [1, 2, 3]
array = reverse(array).

That’s clearer imo than:

var array = [1, 2, 3]
reverse(array).

But you have to imagine that the function and code in question is way more complex than in this case.

2 Likes

You are completely right. Good job! I should have read this post before I typed my previous answer. I think you already understand my point :slight_smile:

1 Like

1. Range and Sum Functions

function range(a,b,c=1){
  var rangeList=[];
  if (c>=0){
    for (i=a;i<=b;i=i+c){
      rangeList.push(i);
    }
  }
  else {
    for (i=a;i>=b;i=i+c){
      rangeList.push(i);
    }
  }

  return rangeList;
}
function sumarr(numbers){
  sum = 0;
  numbers.forEach(num => { sum += num });
  return sum;
}
var rlist = range(1,10,2);
console.log(rlist);
var sum = sumarr(rlist);
console.log(sum);

2. Reverse Arrays

function reverseArr(arr){
  var newarr=[];
  for (i=arr.length-1;i>=0;i=i-1){
    newarr.push(arr[i]);
  }
  return newarr;
}
function reverseArrInPlace(arr){
  var newarr=[];
  for (i=arr.length-1;i>=0;i=i-1){
    newarr.push(arr[i]);
    arr.pop(i);
  }
  newarr.forEach(item=>{arr.push(item)});
  return arr;
}
var arr1=["one","two","three","four"];
console.log(arr1);
var arr2=reverseArr(arr1);
console.log(arr2);
reverseArrInPlace(arr1);
console.log(arr1);
1 Like

The Sum Of A Range

The should me much of IFs to check customer's entry, the exercise did not request 'em so I did not write the checks down :)

function range (start,end,step){

    var backOrForth;

          if(step > 0){
            backOrForth = true; // Means Start < End so execute the code for ascending mode 1>2>3>4>5 etc..
          } else {
            backOrForth = false; // Means Start > End so execute the code for ascending mode 5>4>3>2>1 etc..
          }

    var arr = [];
    var counter = 0;
    
    
    if(step == undefined && backOrForth == true){

      var stepCounter = 1;

    } else {

      var stepCounter = step;

    }
    
    if(step == undefined && backOrForth == false){

      var stepCounter = -1;

    } else {

      var stepCounter = step;

    }

    if(backOrForth == true){ 

      while(start <= end){

      arr.push(start);
      start = start + stepCounter;
      
      }
    } 


    if(backOrForth == false){
      
      while(start >= end){

      arr.unshift(end);
      end = end - stepCounter;
      
    }
    

}
return (arr);

}

Reversing an array

reverseArray

function reverseArray(arrayToReverse){

var newArray = arrayToReverse.reverse();
return (newArray);

}

reverseArrayInPlace

function reverseArrayInPlace (arrayToReverse){

var arrayReversed = [];
var newCounter = 0;
for(i=arrayToReverse.length-1;i >= 0;i--){

    arrayReversed[newCounter] = arrayToReverse[i];
    newCounter ++;
}

return (arrayReversed);

}

1 Like

The sum of a range

function getSum(total, num) {

return total + Math.round(num);

}

function make_arr(start,end,step=1) {

var array1 = new Array;

if (step < 0)

{

//console.log(‘neg value!’);

for (let count = start; count >= end; count = count + step)

{

array1.push(count)

}

}

else {

for (let count = start; count <= end; count = count + step)

{

array1.push(count)

}

}

return (array1); // print all valuses in the arry

}

console.log(make_arr(1, 10));//create array two params

my printout=[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

console.log(make_arr(1, 10,2));//create array two params and step size

my printout=[ 1, 3, 5, 7, 9 ]

console.log(make_arr(5, 2, -1));//create array two params and step size, backwards

my printout=[ 5, 4, 3, 2 ]

console.log('Sum of array values= '+make_arr(5, 2, -1).reduce(getSum, 0)); //function to sum all values in the array

my printout=Sum of array values= 14

1 Like

ReverseArray was a bit hard to fix, needed to sheet a bit here as I wasted to much time

function reverseArray(in_arr) {

var array1 = new Array;

//console.log('original array to reverse '+in_arr)

// a_reverse = [];

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

array1.push(in_arr[i]);

}

return array1

}

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;

}

var Myarray = [1,2,3,4,5,‘banana’]

console.log('original array to reverse '+Myarray)

my printout=original array to reverse 1,2,3,4,5,banana

console.log(reverseArray(Myarray));

my printout=[ ‘banana’, 5, 4, 3, 2, 1 ]

console.log(reverseArrayInPlace(reverseArray(Myarray)));

my printout=[ 1, 2, 3, 4, 5, ‘banana’ ]

1 Like

//Range with Step and Range Total Sum
$(’#buttonRange’).click(function(){
var start = $(’#startNum’).val();
var end = $(’#endNum’).val();
var step = $(’#step’).val();
var range = [];
var sumofRange = 0;
do {
range.push(start);
start = parseInt(start) + parseInt(step);
}
while (start <= end)
list = $(’#rangeList’);
total = $(’#sumTotal’);
$.each(range,function(index,value){
$("

  • ").text(value).appendTo(list);
    sumofRange += parseInt(value);
    });
    $("
  • ").text("Total Sum: " + sumofRange).appendTo(total);
    });

    //Reverse Order

    function runArray(){
    var myArray = [“A”,“B”,“C”,“D”,“E”]
    var newArray = [];

    for(var i = myArray.length - 1; i >=0; i--)
    {
    	newArray.push(myArray[i])
    }
    var list = $('#reverseList')
    list.html("");
    $.each(newArray,function(index,value){
    	$("<li/>").text(value).appendTo(list);
    });
    

    }

    runArray();

  • 2 Likes
    MakeArray=function(start, end, step=1)
      {
        let numbers=[];
        if(step>0)
        {
          for(i=start;i<end+1;i=i+step)
          {
            numbers.push(i);
          }
        }
        else
        {
          for(i=start;i>end-1;i=i+step)
          {
            numbers.push(i);
          }
        }
        return numbers;
      }
    
      PrintNumbers=function(numbers)
      {
        for(i=0;i<numbers.length;i++)
        {
          document.write(numbers[i]+" ");
        }
      }
    
      var numbers= MakeArray(10,1,-2);
      PrintNumbers(numbers);
    
      reverseArray=function(numbers)
      {
        let reverse=[];
        for(i=numbers.length-1;i>=0;i--)
        {
          reverse.push(numbers[i]);
        }
        return reverse;
      }
    
      reverseArrayInPlace=function(numbers)
      {
    
        for(i=0;i<numbers.length/2;i++)
        {
          temp=numbers[i];
          numbers[i]=numbers[numbers.length-1-i];
          numbers[numbers.length-1-i]=temp;
        }
        return numbers;
      }
    
      PrintNumbers=function(numbers)
      {
        for(i=0;i<numbers.length;i++)
        {
          document.write(numbers[i]+" ");
        }
      }
    
      PrintNumbers(reverseArrayInPlace([1,2,3,4,5]));
    2 Likes

    var range2=function(start,end){
    var arr=[];
    cnt=start;
    function increaseCnt(){
    if (cnt>=end){
    return arr.push(end);
    }else{
    arr.push(cnt);
    increaseCnt(++cnt);
    }
    };
    increaseCnt(cnt);
    return arr;
    };
    var sum3= function(arr){
    return arr.reduce(function(tot,val){
    return tot+val;
    });
    };
    console.log(sum3(range2(1,10)));

    1 Like