Chapter 4 - Exercises

1.1 Range (no step)

function range (start, end) {
    let rangeArray = [];
    for(var i = start; i <= end; i++) {
        rangeArray.push(i);  
    }
    return rangeArray;
}
range(1, 6);
(6) [1, 2, 3, 4, 5, 6]

1.2 Range (with step)

function range (start, end, step) {
    let rangeArray = [];
    if (step === undefined) {
       for(var i = start; i <= end; i++) {                  
       rangeArray.push(i);
       } 
    }else if (step < 0) {
          for(var i = start; i <= end; i-=step) {                         
          rangeArray.push(i);
          }
        }else {
      	     for(var i = start; i <= end; i+= step) {             
             rangeArray.push(i);
             }
         }
   return rangeArray;
}
//range(1, 10, 2);
[1, 3, 5, 7, 9]
//range(1, 10, );
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//range(5, 2, -1);
[ ] // negative step value not returning the desired array, any ideas?

1.3 Sum of Array

function sum(input) {             
	var total = 0;
   	for(var i=0;i<input.length;i++) {             
      total += Number(input[i]);
      }                          
   return total;
}
sum(rangeArray);
//returns 21
sum([1, 2, 3, 4, 5, 6]);
//returns 21

2.1 reverseArray

function reverseArray (arr) {
let reversedArray = [];
    for (var i = 0; i <= arr.length; i++) {
    reversedArray.unshift(arr[i]);
    }
    return reversedArray; 
}
reversedArray ([1, 2, 3, 4]);
(5) [undefined, 4, 3, 2, 1] //Why is undefined included, any ideas? 

2.2 reverseArrayInPlace

function reverseInPlace (arr) {
  let leftIndex = 0;
  let rightIndex = arr.length - 1;
  while (leftIndex < rightIndex) {  
    let temp = arr[leftIndex];
    arr[leftIndex] = arr[rightIndex];
    arr[rightIndex] = temp;    
    leftIndex++;
    rightIndex--;
  }
return arr;
}
reverseInPlace ([1, 2, 3, 4, 5, 6, 7, 8]);
(8) [8, 7, 6, 5, 4, 3, 2, 1]
  • I know the reverse in place is clunky and there are math.floor and other solutions, but I was trying for a solution that made more sense to me.

  • Feedback on my reverse array (undefined included in array) and my range with negative step (returning empty array) is welcomed.

3 Likes

Hey man,

I just saw your question. If you understand everything except for the array division calculation, that’s great and makes the explanation much simpler.

What this function does is that is simply swaps the array elements with each other to reverse the array. It swaps the elements that are above the threshold “Math.floor(array.length/2)” with the elements that are below this threshold. In other words, you split the array in half and exchange all elements from the left side with all elements on the right side. When you reach the middle “Math.floor(array.length/2)”, all elements that were previously on the right side are now on the left side and vice versa, which is why the loop stops the iteration after reaching the element that is just below that threshold.

Let’s do a simple example:
array with 6 elements: [e1, e2, e3, e4, e5, e6]
Math.floor(array.length/2) = 3 // this means the loop will run until i < 3, i.e. until the element array[2], which is e3

Loop iteration 1: e1 is swapped with e6 resulting into the array [e6, e2, e3, e4, e5, e1]
Loop iteration 2: e2 is swapped with e5 resulting into the array [e6, e5, e3, e4, e2, e1]
Loop iteration 3: e3 is swapped with e4 resulting into the array [e6, e5, e4, e3, e2, e1]
Another iteration is not necessary because the array is now reversed. If you don’t divide array length by 2, the loop will continue to run for another three iterations which will swap the elements just in the same manner again which means the reversed array will be reversed back to its original state.

Just for the sake of completeness, a second example to illustrate the relevance of the “floor” method in this case:
array with 5 elements: [e1, e2, e3, e4, e5]
Math.floor(array.length/2) = Math.floor(2.5) = 2 // this means the loop will run until i < 2, i.e. until the element array[1], which is e2

Loop iteration 1: e1 is swapped with e5 resulting into the array [e5, e2, e3, e4, e1]
Loop iteration 2: e2 is swapped with e4 resulting into the array [e5, e4, e3, e2, e1]
e3 is the only unswapped element remaining (because it is the middle element of an array with an odd number of elements) but the array itself is reversed and thus the process is finished.

I hope this answers your question :slight_smile:

Cheers Alex

5 Likes

Here are my answers…

function range1(start,end,step) {

if (!step) step = 1;

let rl = [];
let length = parseInt((end - start + step)/step);
for (var i = 0; i < length; i++) {
rl.push(i*step + start);
//console.log(rl);
}
return rl;
}

function sum1(list) {

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

function reverseArray(list){

let newa = [];
const size = list.length;

for (var i = 0; i < size; i++) {
newa[i] = list.pop();
}
return newa;
}

function reverseArrayInPlace(list){

//function to swap elements in list, returns list
function swape(lista,a1,a2) {

//saving positions
var p1 = lista[a1];
var p2 = lista[a2];

//swaping elements
lista[a2] = p1;
lista[a1] = p2;

return lista;

}

console.log(list);
const size = list.length - 1;

for (var i = 0; i < size; i++) {

if (i == (size - i)) break; //exit if on middle index
else if ((i+1) == (size - i)){
  //final swap
  list = swape(list,i,size-i);
  break;
  }
else { list = swape(list,i,size-i); }


console.log(list);

}
return list;
}

1 Like

Wow! Thank you for the long and simple explanation Alex! I’m so relieved with this explanation that I liked this post, unliked it and then liked it again. You’ve saved me a lot of time in searching up the answer and reaching more dead ends. Thank you thank you! Have a good one!

:grinning:

4 Likes

The sum range
Going for a basic solution, not checking the arguments as I should.

//The sum of a range
            function range(start, end, step){
                if(step==null)(step=1);
                var allNumbers = [];
                for(i=start;i<=end;i+=step){
                    allNumbers.push(i);
                }
                return allNumbers;
            }
            function sum(numbers){
                _sum =0;
                for(num of numbers){
                    _sum +=num;
                }
                return _sum;
            }

Reversing an array

 function reverseArray(rArray){
        reversedArray=[];
        for(i=rArray.length;i=0; i--){
            reversedArray.push(i);
        }}
2 Likes

The sum of a range:

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

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

Reversing an Array:


      function reverseArray(array){
        var newArray = [];
        for(var i = 1; i <= array.length; i++){
          newArray.push(array[array.length -i]);
        }
        return newArray;
      }
      console.log(reverseArray([1,2,3,4,5,6,7,8,9]));

      function reverseArrayInPlace(array){
        var leftIndex = 0;
        var rightIndex = array.length -1;

        while(leftIndex < rightIndex){
          var temp = array[leftIndex];
          array[leftIndex] = array[rightIndex];
          array[rightIndex] = temp;
          leftIndex++;
          rightIndex--;
        }
        return array;
      }
      console.log(reverseArrayInPlace(["A", "B", "C"]));
2 Likes

I have a question about the first exercise: First of all when I put the example in (console.log(sum(range(1, 10)) ), It would not take it and put this pop-up there in the console:
myWeb.html:12 Uncaught ReferenceError: sum is not defined
at myWeb.html:12

It wont let me do it even though i still have the script tag equipped

pls help : (

Sum Range

function range(start, end){
var array=[];
function count(start){
if (start >= end){
return array.push(end);
} else {
array.push(start);
count(++start);

      }
    };
    count(start);
    return array;
  };

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

Reverse in Place

function reversearray (array){
var a=[]
for(let i=array.length-1; i>=0; i–){
a.push(array[i])
}
return a
};

  function reverseinplace (array){
    let result =[]
    for (let elem of array){
      result.unshift(elem)
    }
    return result
  };



console.log(reversearray(["1","2","3","4","5"]));
console.log(reverseinplace(["1","2","3","4","5"]));
2 Likes

First one:

function range (){
    var array = []; 
    var start = Math.min.apply(null, arguments);    
    var end = Math.max.apply(null, arguments);

    {
        console.log
    }

    for (var i=start; i<= end; i++)
    {  
        console.log(array)
        array.push(i);
    }
    return array; 

} 

function sum(array){  
    return  array.reduce((x,y)=>x+y,0);
} 
console.log(sum(range(1, 10)));


Second one: 

const galosDeBriga = ['Farisel', 'Joel', 'Marido', 'Viuvo']
function arrayreverso(listagalosDeBriga)
{
    var novoarray = [];
    for (var i = listagalosDeBriga.length - 1; i >= 0; i --)
    {
        novoarray.push(listagalosDeBriga[i]);
    }
    return novoarray;
}
console.log(arrayreverso(galosDeBriga));
2 Likes

To be honest I am still having problems and going through others peoples work, I am sort of understanding.

Thanks for the solucions!

3 Likes

Sum of the Range

// range function

 let Arr=[]
  function range(start,end,incr){ 
    Arr=[]; 
    let range1=((end-start)/incr);if (range1<0) range1=-range1;
    let addNum=start;
  
        for(let n=0;n<=range1;n++){           
            Arr.push(addNum);
            addNum+=incr;
        };
    return Arr;           
};
console.log(range(1,10,1);alert(Arr);
range(1,10,2);alert(Arr);
range(5,2,-1);alert(Arr);


//sum function

let range2=Arr.length;
let total=0;

function sum(){
        for(let n=0;n<range2;n++){
            total+=Arr[n];
        };
        return total;
};
sum();alert (total);

Reverse Array

//Reverse Array

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

};
alert(reverseArray([2,4,6,8,10]));
alert(reverseArray(["Alice","Bob","Carol","Derek","Eddie","Fred"]));

Had to redo ReverseArrayinPlace after looking at solution and realizing that an independent function was required. Also learned what Math.floor is:

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

console.log(reverseArrayInPlace([2,4,6,8,10]));
console.log(reverseArrayInPlace(["Alice","Bob","Carol","Derek","Eddie","Fred"]));
2 Likes

Hey Jack, the negative step value is not returning the array because the “start” is bigger than the “end”, in the example on the book: range(5, 2, -1) produces [5, 4, 3, 2].

This was my solution.

function range(start, end, step){
var newArray = [];
if(step === undefined){
for(i=start; i<=end; i++){
newArray.push(i)
} console.log(newArray);
}
else if(step > 0){
for(i=start; i<=end; i+=step){
newArray.push(i)
}console.log(newArray);
}
else{
for(i=start; i>=end; i+=step){
newArray.push(i)
}console.log(newArray)
}
}

2 Likes

Thanks for the feedback. All working well now after some additional checking.

I seemed to need to alter the order of my conditional checks.
Original: step is undefined, step is negative, step is positive
Updated: step is undefined, step is positive, step is negative

Furthermore, as you mentioned. I had to alter the condition in my final for statement (negative step else block) to check ‘i’ is larger than the endpoint so it can take the step and create an array.
Previously ‘i’ was stuck in place as it could not take the step, so no array could be returned.

function range (start, end, step) {
    let rangeArray = [];
    if (step === undefined) { 
       for(var i = start; i <= end; i++) {                  
       rangeArray.push(i);
       } 
    //Checking if the step is positive BEFORE checking if it is negative
    }else if (step >  0) { 
       // i needs to be LESS than end to add step and create the array
       for(var i = start; i <= end; i+=step) {                       
       rangeArray.push(i);
       }
    //Remaining condition is now the negative step
    }else { 
      // i must now be LARGER than the end to take a step and create an array  
      for(var i = start; i >= end; i+= step) {        
      rangeArray.push(i);
      }
   }
   return rangeArray;
}
range(5, 2, -1);
// returns (4) [5, 4, 3, 2]
1 Like

I was having trouble understanding this also, thank you for the clarification!.

2 Likes

Part one of exercise one:

let start = 1
let end = 10
let pushingarray = []
for (start=start; start<=end; start++){
pushingarray.push(start)
}
console.log(pushingarray)
//[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


/*
*
* SUM OF A RANGE
*
*/


/*
* Range Function - Takes 2 arguments
* Takes a range of numbers and indexes them to an array
* Optional: 3rd parameter that provides a step +/- of the range of an integer value
*/
function range(start, end,step = 1) {
    let isForward;
    let top;
    let currentNumber = 0;
    const numbers = [];

    //checks to define path and top number of for loop to avoid out of range error
    if (end > start) {
        top = (end - start);
        isForward = true;
    } else {
        top = (start - end);
        isForward = false;
    }

    // iterates through range of numbers and takes conditioned path dependent on "isForward" value
    for (let i = 0; i <= top; i++) {
        if(i === 0) {
            numbers.push(start);
            continue;
        }

        // +/- current number by the value of step
        currentNumber = start += step

        // Path of execution depending START and END argument values
        if(isForward) {
            numbers.push(currentNumber);
            if (step ===  0) step++;
        } else {
            if (start < end) break;
            numbers.push(currentNumber);
            if (step ===  0) step++;
        }

        }

    return numbers; // returns final array value
}


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



/*
* Sum Function -
* Takes an array of numbers and adds each index value to the next index value to an accumulating total
*/

function sum(array){
    // simple counter to keep track of accumulating total
    let total = 0;
    // iterates through each array value adding to the total
    for (let i = 0; i < array.length; i++) {
        total += array[i];
    }
    return total;  // returns the sum of array values
}

// Book example 3
console.log(sum(range(1,10)));


/*
*
* REVERSING AN ARRAY
*
*/


const letters = ["A","B","C"];
const numbers = [1,  2, 3, 4, 5];

function reverseArray(array) {
    let arrayLength = array.length;
    // Creates a second array to store the values to be reversed of the same length as the array provided
    let reversedArray = new Array(arrayLength);

    for (let i = 0; i < array.length; i++) {
        // The new array with a predefined array length with those indexes containing undefined values
        // inserts the array argument's leading values starting at the end of the new array
        reversedArray[arrayLength -= 1] = array[i];
    }
    return reversedArray;
}

// Book Examples
console.log(reverseArray(letters));
console.log(reverseArray(numbers));

1 Like

I hope that I am correct …

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

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

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

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

function reverseArray (array) {
let AA = [];

for (i = 0 ; i < array.length ; i++){
AA[i] = array[array.length-1-i];
}
return AA;
}

function revArrInPlace (array) {
let AA = [];

for (i = 0 ; i < array.length ; i++){
AA[i] = array[array.length-1-i];
}
return AA;

for (i = 0 ; i < array.length ; i++){
array[i] = AA[array.length-1-i];
}
return array;
}

1 Like

The sum of a range

function range(start, end, step){
    var rangeResult = [];
    if(step == 0 || step == undefined){
        if(start<end){
            for(i=start;i<=end;i++){
                rangeResult.push(i);
            }
        }else if(start > end){
            for(i=start;i>=end;i--){
                rangeResult.push(i);
            }
        }
    }
    if(step > 0){
        for(i=start;i<=end;i+=step){
            rangeResult.push(i);
        }
    }else if(step < 0){
        for(i=start;i>=end;i+=step){
            rangeResult.push(i);
        }
    }
    return rangeResult;
}
function sum(array){
    resultSum = 0;
    for(i=0;array[i]!=undefined;i++){
        resultSum += array[i];
    }
    return resultSum;
}

Reversing an array

function reverseArray(array){
    let reversedArray = [];
    for(i=0;array[i]!=undefined;i++){
        reversedArray.unshift(array[i]);
    }
    return reversedArray;
}
function reverseArrayInPlace(array){
    let reversedArray = [];
    for(i=0;array[i]!=undefined;i++){
        reversedArray.unshift(array[i]);
    }
    for(i=0;i<reversedArray.length;i++){
        array.splice(0,1);
    }
    for(i=0;i<reversedArray.length;i++){
        array.push(reversedArray[i]);
    }
    return array;
}
1 Like
  1. The sum of range:

var rangeArray = [];
function range(start, end, step){
for(var count = start; count <= end; count += step){
if (step == null){
step = 1;
rangeArray.push(count);
}
else if (step > 0){
rangeArray.push(count);
}
}
console.log(rangeArray);
}
range(10, 50, 3);
function sumArrayNumber(){
var total = 0;
for(var i in rangeArray){
total += rangeArray[i];
}
console.log(total);
}
sumArrayNumber();

  1. Reversing an array:
    1st part

var reversedArray = [];
var reverseArray = function(input){
for (var i = input.length-1; i >= 0; i–){
reversedArray.push(input[i]);
}
console.log(reversedArray);
}
var arrayToReverse = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
reverseArray(arrayToReverse);

2nd part

var reverseArray = [1, 2, 3, 4, 5];
var reverseArrayInPlace = function(reverseArray){
for (var i = 0; i < reverseArray.length; i++){
reverseArray.unshift(reverseArray.splice(i, 1)[0]);
}
console.log(reverseArray);
}
reverseArrayInPlace(reverseArray);

1 Like

Sum of a range:
function sum(array){
for (let count=1;count<array.length;count++;){
var sum = sum+array[sum]
}
}
return sum
console.log(sum(range(1,10)));

Reversing an array:
var arrays = [];
function reverseArray(array){
for (let count=0;count<array.length;count++){
}
return arrays;
}

function reverseArrayInPlace(array){
var array = [];
for(let counter=0;counter<array.length;counter++){
console.log(array);
}
return array;
}

1 Like