Chapter 4 - Exercises

#1

Here is the place to discuss the exercises at the end of chapter 4. You can find the solutions here: https://eloquentjavascript.net/code/#4

2 Likes

#2

So, here’s my quick reverseArray() function: :desktop_computer:

>     // Test array
>     var fruits = ['1_apple', '2_pineapple', '3_range', '4_lemon', '5_pear'];
> 
>     // Reverses a given array
>     function reverseArray(myArray) {
>         var newArray = [];
>         newArrayIndex = myArray.length;
>         for (var i = 0; i < myArray.length; i++) {
>             newArray[--newArrayIndex] = myArray[i];
>         }
>         return newArray;
>     }
> 
>     // Before
>     console.log(fruits);
>     // After
>     console.log(reverseArray(fruits));

Result (from the console):

(5) [“1_apple”, “2_pineapple”, “3_range”, “4_lemon”, “5_pear”]
(5) [“5_pear”, “4_lemon”, “3_range”, “2_pineapple”, “1_apple”]

2 Likes

#3

Here is another possible solution. I use for loop with last element (4) and go to element 0. Because of this there is i-- instead of i++.

        var fruits = ['1_apple', '2_pineapple', '3_range', '4_lemon', '5_pear'];

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

Result:
(5) [“1_apple”, “2_pineapple”, “3_range”, “4_lemon”, “5_pear”]
(5) [“5_pear”, “4_lemon”, “3_range”, “2_pineapple”, “1_apple”]

3 Likes

#4

That’a a much nicer solution, I like it. I always forget to use ‘push’ & ‘pop’ :laughing:

1 Like

#5

For the range and sum functions

function range(a, b, c) {
  var t = [a]; //initializes empty array
  var s = c ? c : 1; //checks if there is a valid value assigned, if not gives it 1

  var i = a;

  while(i != b){
    i += s;
  
    t.push(i); //goes through numbers and adds to array
  }
  
  return t;
}


function sum(arr) {
  var t = 0;
  for(var k in arr) {
    t += arr[k];
  }
  
  return t;
}

For the reverselist:

function reverseArray(arr){
  var t = [];
  for(var i = arr.length - 1; i >= 0; i--){
    t.push(arr[i]);
  }
  
  return t;
}
2 Likes

#6

1. The sum of a range

I chose to do my range function differently from what was asked for if the book. This code takes into account the first number being larger than the second and returns the numbers in descending order (this is what the book asked for with the step as -1). I decided to use the negative steps to reverse the order instead.

    function range(num1, num2, step) {
        let array = [];

        if (num1 == num2) {
            array.push(num1);
            return array;
        }

        if (step < 0) {
            step = Math.abs(step);
            let placeholder = num1;
            num1 = num2;
            num2 = placeholder;
        }

        if (step > 0) {
            if (num1 < num2) {
                for (; num1 <= num2; num1 += step) {
                    array.push(num1);
                }
            } else {
                for (; num2 <= num1; num1 -= step) {
                    array.push(num1);
                }
            }
            return array;
        } 
        
        if (num1 < num2) {
            for (; num1 <= num2; num1++) {
                array.push(num1);
            }
        } else {
            for (; num2 <= num1; num2++) {
                array.unshift(num2);
            }
        }
        return array;
    }

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

2. Reversing an array

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

    function reverseArrayInPlace(array) {
        for (let index = 0; index < array.length; index++) {
            array.unshift(array.splice(index, 1)[0]);
        }
        return array;
    }
5 Likes

#7

Sup guys! Here are my answers for the first two exercises;

The sum of a range

  var lista = [];
  range(20,-10,-5);
  function range(start, end, step) {
    if (step == 1 || step == null) {
      for (var i = start; i < end+1; i++) {
        lista.push(i);
      }
    }else if (step < 1) {
      for (var i = start; i > end-1; i += step) {
        lista.push(i);
      }
    }else {
      for (var i = start; i < end+1; i += step) {
        lista.push(i);
      }
    }
  }
  console.log(lista);
  var count = 0;
  $.each(lista, function(index, value) {
    count = count + value;
  });
  console.log(count);

Reverse Array:

  //reverseArray
  var lista = [10,30,50,100,200,300,50000];
  var reverseArray = [];
  function reverseArray() {
    for (var i = lista.length-1; i >= 0; i--) {
        reverseArray.push(lista[i]);
      }
  }
  console.log(reverseArray);

  //reverseArrayInPlace
  var lista2 = [10,20,30,50,800,900,10000,100001];
  reverseArrayInPlace(lista2);
  function reverseArrayInPlace(listaArray) {
      for (var i = 0; i < Math.floor(listaArray.length / 2); i++) {
        var inicio = listaArray[i];
        var fin = listaArray[listaArray.length - i - 1];
        listaArray[i] = fin;
        listaArray[listaArray.length - i - 1] = inicio;
      }
    }
  console.log(lista2);
3 Likes

#8

The sum of a range: (This includes the special cases of no step given and a decreasing step)

    var arraryRange = new Array();
    console.log(sum(range(1,10,1)));

    function range(start,end,step){ // Creating an array of values from start to end...
      if (step==0 || step==null){//validating or updating the step value.
        step = 1;
        console.log("The function set step to equal 1.")
      }
        if (start>end && step<0){
          for (i=start; i>=end; i=i+step){
          arraryRange.push(i);
          }
        } else if (start<end && step>0){
        	  for (i=start; i<=end; i=i+step){
          	arraryRange.push(i);
          }
        } else {
          console.log("The input range or step is not valid.");
        }
    }

    function sum(numbArray){ // Doing the arithmetic to sum all of the elements in the array.
      let result = 0;
      for (i=0; i<arraryRange.length; i++) {
        result += arraryRange[i];
      }
      return result;
	    }

Reversing an array:

    var firstArray = [1,2,3,4,5]
    var newArray = new Array();

    console.log(firstArray + " is the original Array.");
    //1,2,3,4,5 is the original Array.

    reverseArray(firstArray);
    reverseArrayInPlace(firstArray);

    function reverseArray(array){
      for (i=0; i<array.length; i++){
        newArray[i] = array[(array.length)-1-i];
      }
      console.log(newArray + " is the new Array reversed.");
      //5,4,3,2,1 is the new Array reversed.
    }

    function reverseArrayInPlace(array){
      //This function was copied from @CompSciGuyIT (Thanks:)) on the Chp 4 exercise forms (respect).
      //The unshift(splice) is really confusing.... I only removed "[0]" from the sourced code.
      //This function puts everything at the left starting from the left to the right.
      //Hence, this puts A[0] in the first place, then A[1] in the first place, and so on...
      for (let index = 0; index < array.length; index++) {
            array.unshift(array.splice(index, 1));
        }
      return array;
    }
    console.log(firstArray + " and this is the newly ordered Original!");
    //5,4,3,2,1 and this is the newly ordered Original!
2 Likes

#9

1. The sum of a range
I did it the easy to read way, the eloquent way hahjaha, hope it helps!

  var myArr = [];
  var sum= 0;

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

  function sumNumbers(){
    for (var i = 0; i < myArr.length; i++) {
      sum+=myArr[i];
    };
    console.log(sum);
  };

  returnRange(1, 5);
  sumNumbers();

2. Reversing an array

      var reversed = [];

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

      reverseArray([1,5,9,4,9,2]);

this prints to the console the following sequence… [2,9,4,9,5,1];

hope it helps.

2 Likes

#10

SumRange

function sumVector(matrice){
let sum = 0;

    for(i=0; i < matrice.length; i++){
      sum += matrice[i];

    }
    return sum;

  }
  function range(start, end, step){
    let rangeStore = [];
    

    if(step > 0){

        
        let value = start;
          for(i = value ; value  <= end   ; value += step){
                
                rangeStore.push(value);}
       }
    else if(step < 0 ){
      
      let value = start;
        for(i = value; value  >= end   ; value += step){
         
         rangeStore.push(value);}
         // rangeStore.push(end);
      }
    return rangeStore;
  }
3 Likes

#11

** InverseArray**

var myArray = [“What”, “The”, “F***”];

function inverseArray(array){

var newArray = [];
var arrayLength = array.length
for(let i = 0; i < arrayLength; i++){

  newArray.push(arrayLength - i);
}
return newArray;

}

console.log(inverseArray(myArray));

2 Likes

#12

Simple Range function with two arguments

		function range(start, end) {
			var rangeArray = [];
			if(start < end) {
				let index = 0;
				for(let i = start; i <= end; i++) {
					rangeArray[index] = start+index;
					index++;
				}
			} else {
				alert("Provide valid argument where start is smaller than end");
			}
			console.log(rangeArray);
		}
		range(5, 10);

SUM

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

UpdatedRange Function

                  function updatedRange(start, end, step) {
			var rangeArray = [];
			if (step != null) {
				if(start <= end) {
					let index = 0;
					for (; start <= end; start+=step) {
						rangeArray[index] = start;
						index++;
					};
				} else if(end < start){		
					let index = 0;
					for (; end <= start; start-=step) {
						rangeArray[index] = start;
						index++;
					}
					
				} else {
					alert("Provide valid argument where start is smaller than end");
				}
			} else {
				if(start < end) {
					range(start, end)
				} else {
					let index = 0;
					for(let i = end; i <= start; i++) {
						rangeArray[index] = start-index;
						index++;
					}
				}
			}
			console.log(rangeArray);
		}
		updatedRange(1, 10, 2);
		updatedRange(10, 1, 2);
		updatedRange(1, 10, 3);
		updatedRange(1, 10);
		updatedRange(10, 1);

Reverse 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);
3 Likes

#13

Here are my solutions for chapter 4 exercises.

Range

function range(start, end, step = 1)  {
	
	let arr = [];

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

Sum

function sum(arr) {

	let result = 0;

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

	return result;
}

Reverse Array

function reverseArray(arr) {
	
	let newArr = [];

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

	return newArr;

}

Reverse Array In Place

function reverseArrayInPlace(arr) {

	let count = arr.length;
	let tempArr = [];

	for(i = 0; i < count; i++) {
		tempArr[i] = arr.pop();
	}

	for(i = 0; i < tempArr.length; i++) {
		arr.push(tempArr[i]);
	}

	return arr;

}

Wasn’t particularly happy with my last effort but good to see how others on here solved it.

3 Likes

#14
  1. The sum of a range 
  2. Since we are learning it is important we break down the steps to each question. The first part of this question asks the student to write a function called range that takes two arguments, a `start` and an `end`, returning an array containing all the numbers up to and including end. They are not asking you to come up with the actual range (In statistics the range is the difference between the lowest and the highest values in a string. They are also not asking for you to use the build in functions.

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

    Next, we are to write a sum function that takes an array of numbers and returns the sum of these numbers.

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

    Now the problem asks you to take the extra step of adding a third additional argument to the function range. This additional argument is indicative of the step, or increment, when building out your range. The connection to be made is that your step will be the change from one index to the next. Keep it simple.

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

    If you want to set the default value of 1 when no argument is made but also have it select -1 incase the range is in the negative direction, we will want to add some type of condition. Instead of using if functions we can shorten it to one line using the conditional (Ternary) Operator.

    function range(start, end, step = start < end ? 1 : -1){
       let n = [];
       if (step > 0){
           for (let i = start; i <=end; i += step) n.push(i);
       }else if(step < 0){
           for (let i = start; i >=end; i += step) n.push(i);
       }else console.log("Invalid Number");
       return n;
    }     
    

    Here is a link to ternary operators and how they are used

    codeburst.io

  3. Reversing an array 

In this problem we are asked to create two variants of reversing arrays without using the standards or libraries. In the first variant we are asked to produce a new array that has the same elements in reverse order. In the second we are asked to preserve the existing array and to modify it by reversing and replacing it.

The first solution I kept making the mistake of not including i = array.length - 1.

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

As the hints described in Eloquent, reversing the arrays is harder because of overwriting elements that you might later need. The trick is swapping the first and last, the second and second to last, and so on. You won't need to swap the middle element in an odd number array. This is done by looping half the length of the array and using Math.floor to round down. Elements at position i are swaped for those in position array.length -1 - i.

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

#15

1- Range Function :

function range(start,end){
if(start>end){
alert(“Start number should be smaller than the end”);
return;
}
var array1=[];
for(let i=start;i<=end;i++)
array1.push(i);

return array1

}

2- SUM

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

return total

}

3- Range Step:

function rangeStep(start,end,step){
var array1=[];
if(step>0){
if(start>end){
alert(“Start number should be smaller than the end”);
return;
}
for(let i=start;i<=end;i+=step)
array1.push(i);
}
else {
if(start<end){
alert(“Start number should be bigger than the end”);
return;
}
for(let i=start;i>=end;i+=step)
array1.push(i);
}
return array1
}

4- Reverse (new array)

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

     return revesedArray
}

5- Reverse(In place)

function reverseArrayInPlace(array){
var num=array.length;
for(let i=0;i<num/2;i++){
var dc=array[i];
array[i]=array[num-1-i];
array[num-1-i]=dc;

  }
  return array
}
1 Like

#16

The sum of a range

// Your code here.

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);
// → [5, 4, 3, 2, 1]
1 Like

#17

The sum of a range

function range(start,end,step=1) {
 ai=0;
 array=[];
 for (let i = start; i <= end; i=i+step) {
	array[ai]=i;
	ai++;
 }
 return array;
}

function sum(sumArray) {
 sumc=0;
 for (item in sumArray) {
	sumc=sumc+sumArray[item];
 }
 return sumc;
}

Reversing an array

function reverseArray(inputArray) {
 let revArray=[];
 for (i in inputArray){
	revArray[inputArray.length-i-1]=inputArray[i];
 }
 return revArray;
}

function reverseArrayInPlace(inputArray) {
 let revArray = [];
 for (i in inputArray) {
	revArray[inputArray.length - i - 1] = inputArray[i];
 }
 for (i in inputArray) {
	inputArray[i] = revArray[i];
 }
 return inputArray;
}
1 Like

#18

Hey guys, here are my answers. That last one is tough! Reversing an array in place is very useful in an embedded systems setting when a very limited amount of memory is available.

      // range function extended

  function range(_start, _end, _step) {
    var range = [];
    var i = 0;

    if (_step === undefined) {
      _step = 1;
    }

    if (_step < 0) {

      do {
        range[i] = _start;
        _start = _start + _step;
        i++;
      } while (_start >= _end);
      return range;
    }
    else {
      do {
        range[i] = _start;
        _start = _start + _step;
        i++;
      } while (_start <= _end);
      return range;
    }
  }

  // sum function

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

  // reverse array function

  function reverseArray(_array) {
    var tempArray = [];
    var j = 0;

    for (let i = (_array.length - 1); i >= 0; i--) {
      tempArray[j] = _array[i];
      j++;
    }
    return tempArray;
  }

  // reverse array using only one array

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

  // testing!

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

  console.log(range(5, 2 ,-1));
  console.log(sum(range(5, 2, -1)));
  console.log(reverseArray(arrayOne));
  console.log(reverseArrayInPlace(arrayOne));
1 Like

#19
  1. The sum of a range
function rangeFunction (start, stop, step=1) {
  var A = [];
  if(start < stop) {
    if(!(step < 0)) {
      while(start <= stop) {
        A.push(start);
        start += step;
      }
    }
  }
  else {
    if(!(step > 0)) {
      while(start >= stop) {
        A.push(start);
        start += step;
      }
    }
  }
  return A;
}
function sumFunction (array) {
  sum = 0;
  $.each(array, function(_,value) {sum += value;});
  return sum;
}
  1. Reversing an Array
function reverseArray (array) {
  A = [];
  index = array.length - 1;
  while(index >= 0) {
    A.push(array[index]);
    index--;
  }
  return A;
}
function reverseArrayInPlace (array) {
  A = reverseArray(array);
  $.each(array, function(index,value){
    array[index] = A[index];
  });
}
1 Like

#20

1. The sum of a range

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

function sum(range){
  let result = 0;
  range.forEach(function(element){
    result += element;
  });
  return result;
}

2. Reversing an array

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

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