Chapter 4 - Exercises

THE SUM OF A RANGE:

I managed to get it solved but after looking at the answer I didn’t quite understood the difference and basically how the ternary operator worked there. I leave the solution that is given in the book down below, hoping that someone can clarify this for me.

My solution:

  function range(start, end, optional){
   var rangeArray = [];
     
     if (optional === undefined){
       for(var i = start; i <= end;i++){
     	rangeArray.push(i);
     }}
     else if(optional > 0){
     for(var i = start; i <= end; i += optional){
     	rangeArray.push(i);
       
     }} else if(optional < 0 ){
     for(var i = start; i >= end; i += optional){
     	rangeArray.push(i);
     }}
     return rangeArray;
  }
 
	

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

The book’s solution:

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

Basically I didn’t quite understand how is it possible that once that the condition checks either true or false with the ternary operator, after it assigns a value to the “step” parameter, why in the code it runs a different given number, is the new value overriding the one that is given after the condition is checked? I hope that someone can help me with this.

REVERSING AN ARRAY:

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

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

The first function of this exercise takes a given array, loops through each value backwards and pushes each value in a new array.

On the other hand, the second one is a a bit more complex. It requires a swap between the first value with the last, the second value with the second last and so forth and also avoid overwrite values that will be needed. It is due to this reason that me must iterate only through the first half of the array and then swap the value.

The loop iterates through each i value of the array until it reaches half its length to avoid overwriting values. It then creates a local variable to which the i is assigned, then this value is swapped with its mirror value. This is achieved by subtracting i to the last value of the array, this will give the mirror index of the i value.

Example

var array = [1, 2, 3, 4, 5, 6, 7]

If i = 0 then array[i] = 1

if we subtract i (which in this case is 0) to the array[array.length - 1] (the last value of the array) that would give us its mirror value.

array[0] = array[6-0]   or array[0] = array[6]
array[1] = array[6-1] or array[1] = array[5]
array[2] = array[6-2] or array[2] = array[4]

and so on...

Once the first value is assigned with last value then we need to assign the last value to the first.

array[6-0] or array [6] = localVariable

The last array is assigned again to the local variable which was previously assigned with the first value.

Once the iteration is over the function returns the array with its swapped values.

1 Like

The sum of a 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, 10)));

Reversing an Array

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

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

// REVERSING AN ARRAY

    function reverseArray(array) {
        let output = [];
        for (let i = array.length - 1; 1 >= 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"]));

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

    // THE 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;
    }

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

    console.log(range(5, 2, -1));

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

Below I’ve combined both questions together such that the functions interact with each other.

     function range(start,end,step){

      var numberArray=[];
      if (step==0 || step==undefined)step=1; //deal with null value for step


      if (start>end) {                //if sequence is descending
        var firstNum=end;             //switch the values around
        var lastNum=start;
      }else {
        var firstNum=start;
        var lastNum=end;
      };

      for (var i = firstNum; i <= lastNum; i+=Math.abs(step)) {
        numberArray.push(i);          //create sequence
      }

      if (start>end) {      //if sequence is descending switch back
       numberArray=reverseArrayInPlace(numberArray);
      }
      return numberArray;
    }

    function sum(numberArray){      //function add nums in array
      var Total=0;
      for (var i = 0; i <numberArray.length; i++) {
        Total += numberArray[i];
      }
      return Total;
    }

    function reverseArrayInPlace(Array) { //reverse contents of array
      var reversedArray = [];
      while (Array.length) reversedArray.push(Array.pop());
      return reversedArray;
    }


    console.log(sum(range(5,2,-1)));



1 Like

I will need to practice and dive deeper into arrays but here is the exercise solutions from me.

Sum function
function sum(array){
let sumNum= 0;
for(var i=0;i< array.length; i++){
sumNum += array[i];
}
console.log(sumNum);
};

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

1 Like

Hi @DeezSats, These functions work as expected. However, Please mention your code in code format. While replying on a forum, you have a choice of selecting code format. Please do use that. Also, you forgot to mention the function keyword before defining reverseArray.

@laserkavajen, Could you also add a way to handle the sum of range when the start and end numbers are reversed. Example - console.log(sum(range(10, 1))); . This will make the function more versatile.

1 Like

Hi Sir, Excellent answer from your side. To follow up to your question –

In Javascript, we have a way to give default values in function arguments if the argument is not passed.
By not passing the “step” argument–
range(5,10)
By passing the “step” argument –
range(5,10,1)

If the “step” argument is not passed, the ternary operator evaluation takes place. If “step” argument is passed, the ternary valuation is skipped.

Hope this answers your question.

Happy Learning :slight_smile:

2 Likes

Sum of a Range
…thanks for your tips and encouragement @jon_m
…fixed my prior issue of not auto-detecting the need for decrement instead of increment

function range(start, end, step) {
  //console.log(step);
  let chase = [];//this assignment can't be outside function
  if (typeof step === 'undefined') {
    step = 1;
  }
  //console.log(step);
  if (start > end) {
    step = -1;
    for (start; start >= end; step) {
      chase.push(start);
      start = start + step;
    }
  }
  else {
  for (start; start <= end;) {
  chase.push(start);
    start = start + step;
       }
  }
  return chase;
}
function summ(x) {
    let arrayLength = x.length;
  console.log("AL = " + arrayLength);
  let result = 0;
  for (let j = 0; j < arrayLength; j++) {
    result += x[j];
  }
  return result;
}

Reversing an Array
…changed prior solution that used pop() method and left first array empty to one that calculates position

function reverseArray (oldArray) {
      newArray = [];
      let size = oldArray.length;
      for (let i = 0; i < size; i++) {
        newArray[i] = oldArray[size - 1 - i];
      }
     return newArray;
    }

    function reverseArrayInPlace(ax) {
      //swaps the first and last items, 2nd item with 2nd to last item, ...
      let size = ax.length;
      for (let i = 0; i < Math.floor(size/2); i++) {
        j = ax[i];
        k = ax[size - 1 - i];
        ax[i] = k;
        ax[size - 1 - i] = j;
      }
      return ax;
    }

1 Like
  <script>

// Excercise -4- Page 91 Eloquent_javascript
// 1] The sum of a range ( should be 55 )
// 2] Reversing an array

    function range(Begin,End,Step){
       var WorkArray = [] ;
       if (typeof Step === "undefined") {                      // Check if 'Step' parameter exsist, else just step 1
          Step = 1;
       }
         for (let Index = Begin; Index <= End; Index+=Step) {  // let for use only within function
           WorkArray.push(Index) ;
      }
      return WorkArray;
    } ;


    function sum(My_Array){
      let total = 0 ;
      for (let Index = 0 ; Index < My_Array.length; Index++) {  // let (instead of var) for use only within function
      total += My_Array[Index] ;
     };
     return total ;
   };

     function ReverseArray(My_Array){
       var TempArray = [];
       for(let Index = My_Array.length - 1;  Index != -1; Index--) {
         TempArray.push(My_Array[Index]);
       }
       return TempArray;
     }

     function reverseArrayInPlace(My_Array){
   for(var Index = 0; Index < Math.floor(My_Array.length/2); Index++){
        let swap = My_Array[Index];
        My_Array[Index] = My_Array[My_Array.length - Index - 1 ];
        My_Array[My_Array.length - Index - 1] = swap;
      }
     return My_Array;
    }

    console.log(     range(1,10,2))  ;              // Chech for 1 3 5 7 9
    console.log(sum (range(1,10,1))) ;              // Check for sum = 55
    console.log(ReverseArray([1,2,3,4,5]));         // Check for 5,4,3,2,1
    console.log(reverseArrayInPlace([1,2,3,4,5]));  // Check for 5,4,3,2,1

  </script>

Result console :
image

1 Like

The Sum of a Range

			//Write a function that displays it's content as an array of numbers.

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


			//Write a function that adds the elements of a given array.

			function sum(array){
				var add = 0;
				for(let number of array) {
					add += number;
				}
				return add;
			}
			console.log(sum(range(1,10)));

The Sum of a Range modified

			/*Modify the range function to add a "step" argument that indicates
			a step value (distance between values) used in the array*/

			function range(start,end,step) {
				var answer = [];
				if(step < 0) {
				for(i=start; i>=end; i+=step) {
					answer.push(i);
				}
			}
			else {
				for(i=start; i<=end; i+=step){
					answer.push(i);
				}
			}
				return answer;
			}
			console.log(range(100,10,-3));

Reversing and Array

			/*Write two functions. The first takes an array as argument and
			produces a new array with the original array's elements in reverse order.
			The second function also takes an array as argument and modifies
			the array so as to reverse the order of its elements*/

			//Function one: reverseArray()                        

			var numbers = [1,2,3,4,5,6];

			function reverseArray(array) {
				var newArray = [];
				for(let element of array) {
					newArray.unshift(element);
				}
				return newArray;
			}
			console.log(reverseArray(numbers))


			// Function two: reverseArrayInPlace()

			var words = ["Hi", "how", "are", "you", "today?"]

			function reverseArrayInPlace(array2) {
					for(i=array2.length-1; i >= 0; i--) {
						console.log(array2[i]);
					}
			}
			console.log(reverseArrayInPlace(words));
1 Like

The sum of a range function

        // Exercise : The sum of a range function
        function range(start, end){

          var myArray = [];
          for(i = start; i <= end; i++){
            myArray.push(i);
          };
          return myArray;
        }

        console.log(range(1, 10));
        console.log(range(-5, 10));

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

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

Bonus assignment (add “step” argument)

        // Bonus assignment (The sum of a range function)
        function range(start, end, step=1){
          var myArray = [];
          if(step >= 0){
            for(i = start; i <= end; i += step){
              myArray.push(i);
            };
            return myArray;
          }
          else{
            for(i = start; i >= end; i += step){
              myArray.push(i);
            };
            return myArray;
          }
        }

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

Reversing an array function

        // Reversing an array function
        function reverseArray(oldArray){
          var newArray = [];
          for(i = 0; i <= oldArray.length - 1; i++){
            newArray.push(oldArray[oldArray.length - 1 - i]);
          }
          return newArray;
        }

        console.log(reverseArray([1, 2, 3, 4, 5, 6, 7, 8]));
        console.log(reverseArray(["one", "two", "three", "four", "five", "six"]));

Reversing an array function (modified)

        //Reversing an array function (modified)
        function reverseArrayInPlace(myArray){
          var holder = 0;
          var numElement = myArray.length;
          for(i = numElement - 1; i >= 0; i--){
            holder = myArray.pop();
            myArray.splice(numElement - i -1, 0, holder);
          }
          return myArray;
        }

        console.log(reverseArrayInPlace([1, 2, 3, 4, 5, 6, 7, 8]));
        console.log(reverseArrayInPlace(["one", "two", "three", "four", "five", "six"]));
1 Like

The Sum of a Range:

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

    function sumArray(array) {
      var sum = array.reduce(function(a,b) {
        return a + b;
      }, 0);
      return sum
    }

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

The Sum of a Range - Modified:

    function range(start,end,step) {
      var rangeArray = [];
      if(step > 0) {
        for(let count = start; count <= end; count+=step){
          rangeArray.push(count);
          }
        }
      else if (step < 0) {
        for(let count = start; count >= end; count+=step){
          rangeArray.push(count);
        }
      }
    return rangeArray;
    };


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

Reversing an Array:

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

    console.log(reverseArray([0,1,2,3,4,5]));

Reversing Array in Place:

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(reverseArrayInPlace([2,3,4,5,6,7]));
1 Like

The Sum of a Range:

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

  function sum (arr){
    let arr_sum = 0;
    for(var i=0; i<arr.length; i++){
      arr_sum += arr[i];  
    }
return arr_sum;
}

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

Range - Modified:

  function range (start,end,step=1){
      let arr = [];
      if(start<end){
        for(var i=start ;i< (end+1) ;i+=Math.abs(step))
        {arr.push(i)}
      }
      else {
        for(var i = start; i > end - 1; i -= Math.abs(step))
        {arr.push(i);}
      }
    }
console.log(sum(range(5,2,-1)));

Reversing a array:

      function reverseArray(arr){
        let newArr = [];
        for(i =arr.length -1; i >=0; i--){
          newArr.push(arr[i]);
        }
        return newArr;
}
console.log(reverseArray([0,1,2,3,4,5,6,7,8,9]));

Reversing a array in place:

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

console.log(reverseArrayInPlace([1,2,3,4,5,6,7,8,9]));

Hey @Lukasz, a great answer from your side. Looking at your code above I guess you did a simple mistake. The return statement should be outside the for loop in your The Sum of a Range answer. Below is the corrected snippet of the code.

for(var i=0; i<arr.length; i++){
      arr_sum += arr[i];
    }
return arr_sum;

Another issue is with Range - Modified answer, the function does not give the right answer. You might wanna spend some time to figure out what went wrong or take some inspiration from students above. Either way, you’ll learn a lot!

Also, in Reversing a array answer, you forgot to close the function with the closing bracket.

Happy Learning ! :slight_smile:

1 Like

Sum of a 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;
}

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

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 Like

Thank you for tips. :slight_smile: I have long way to go :D.

1 Like

Sum of a range

var array1 = [];

    function range(start, end, step){
      array1.length = 0;


          if (step === undefined){
            for(i = start; i <= end; i++){
            array1.push(i);
            }
          }

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

                                  else{
                                        for(i = start;  i >= end; i += step){
                                        array1.push(i);
                                        }
                                     }

                                     return (array1);
    }




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

Tried reverse array in place with no luck, looked up solution makes no sense to me, need a detailed explanation or video. thanks

  function reverseArray(array1){
    var array2 =[];

        for (var i = array1.length - 1; i >= 0; i--){
        array2.push(array1[i]);
        }
        
    return (array2);
  }



    function reverseArrayInPlace(array3){


      //will be used at temp array
      var array4 =[];

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

              // pushing reverse numbers into temp array
              array4.push(array3[i]);

            }
            console.log(array3);

      //clearing origional array
      array3.length = 0;

      //setting origional array to equal temp array
      array3 = array4;
      console.log(array3);

return (array3);
    }
1 Like

Sum of a Range:

    <script>
    function range(start,end,step){
      let numArray = [];
        if (step > 0 & start < end){
          for (let i = start; i <= end; i += step){
            numArray.push(i);
            };
        } else if (step > 0 & end < start) {
          alert("the first number must be less than the second if your step is positive, try again!");
        } else if (step < 0 & end < start){
          for (let i = start; i >= end; i += step){
            numArray.push(i);
          };
        } else if (step < 0 & start < end) {
          alert("the first number must be greater than the second if your step is negative, try again!");
        } else if (start > end){
          for (let i = start; i >= end; i--){
            numArray.push(i);
          };
        } else {
          for (let i = start; i <= end; i++){
            numArray.push(i);
          };
        };
      return numArray;
      };
      function sum(array){
      let numSum = 0;
      for (i = 0; i < array.length; i++){
        numSum = numSum + array[i];
      };
      return numSum;
    };
    console.log(sum(range(1,10)));
    </script>
1 Like

The Sum of a 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;
  };

Reversing an Array

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

1 Like
function range(start, end, step){
  step=step||1;
  var numbers = [];
  if (start<=end)
  for(i=start; i<=end; i+=step){
    numbers.push(i);
  }
  else if (start>end)
    for(i=start; i>=end; i-=step){
      numbers.push(i);
  }
  return numbers;
}


function sum(numbers){
var sum = 0;
  $.each(numbers, function(index, value){
    sum+=value;
  })
  return sum;
}

function reverseArray(numbers){
  var newArray = [];
  $.each(numbers, function(index,value){
    newArray.unshift(value);
  })
  return newArray;
}

function reverseArrayInPlace(arrayValue){
  for(i=arrayValue.length-2; i>=0; i--){
  var missingItem = arrayValue.splice(i, 1);
  arrayValue.push(missingItem[0]);
}

return arrayValue;
}
1 Like