Chapter 4 - Exercises

Range Function with Step:
image

Sum Function:
image )

Reversing Array Function:
image

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

  var array2 = ["yes", "no", "maybe", "always", "sometimes", "never", "if"];

  var array3 = [5,8,2,9,5,6,3,1];

  var newArray = [];

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

I will be practicing exercise this too.

1 Like
//SIMPLE RANGE
 let arr= [];
function range(start, end){
  for(i=start; i<=end; i++) {
  arr.push(i);
  }
  return arr;
}
console.log(range(1,10));


//SUM -  Not sure why but kept getting 110 as my sum. Any idea why?
function sum(arr){
 let total =0;
 for(i=0; i < arr.length; i++){
   total+= arr[i];    
 }
return total;
}
console.log(sum(arr));



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



//REVERSE ARRAY IN PLACE
arr = [1,2,3,4,5,6,7];
let temp;
function revArrInPlace(arr) {

  for (i=0; i<arr.length/2; i++) {
    temp = arr[i];
    arr[i]= arr[arr.length -1 -i];
    arr[arr.length -1 -i] = temp; 
  }
  return arr;
}
console.log(revArrInPlace(arr));


2 Likes

// range & sum
function range(start, end, step=1) {
let array = [];

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

    return array;
  };

  function sum(array) {
    let result = 0;

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

    return result;
  };

// reverse array

function reverseArray(array) {
var reversedArray = [];
let length = array.length;

    for(i=0; i<length; i++) {
      reversedArray.unshift(array[i]);
    };

    return reversedArray;
  };

  function reverseArrayInPlace(array) {
    const clone = [...array];

    for(var value of clone) {
      array.unshift(value);
      array.pop();
    };

    return array;
  };
1 Like

1**) The sum of arange**
function range(start, end, step){
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));
console.log(range(1, 10, 2));
console.log(range(5, 2, -1));
console.log(sum(range(1, 10, 1)));

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

console.log(reverseArray([“A”, “B”, “C”, “D”]));
or
function reverseArray(originalArray){
var newArray = [];
for ( let i =originalArray.length-1; i>=0; i–){
newArray.push(originalArray[i]);
}
return newArray;
}

console.log(reverseArray([“A”, “B”, “C”, “D”, “F”]));
3) A list

1 Like

The Sum of an Array
function range(start, end){
//You create an empty array to add values within
var array = [];//<<
//The loop then continously adds numbers to the empty array
for(var counter=start; counter<=end; counter++){
array.push(counter);
}
return array;
};

function sum(array){
  //A variable for the total sum of inputted numbers
  var total=0;
  //Loop checks the counter to see if it's less than the length of the array
  for(var counter=0; counter<array.length; counter++){
      //You go through each position of the array with [counter]
      total=total+array[counter];
  }
  return total;
};

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

Reversing an Array
In this section I only managed to fin a solution for the first problem. I could not understand what they wanted me to do in the second problem, but here is my first solution anyway.

let array1 = [“yes”, “no”, “maybe”, “always”, “sometimes”, “never”, “if”];
let array2 = [5,8,2,9,5,6,3,1];

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

console.log(reverseArray(array1));
console.log(reverseArray(array2));

  1. The sum of a range
function sumR(start,end,step=1){
	let numbArray = [];
	if (end < start){
		for(n = start; n >= end; n = n + step){
			numbArray.push(n);
		}
	} else {
		for(n = start; n <= end; n = n + step){
			numbArray.push(n);
		}
	}
	let total = 0;
	for(o = 0; o < numbArray.length;o++){
		total = numbArray[o] + total;
	}
	console.log(total + " is the sum of the " + numbArray.length + " numbers between " + start + " & " + end);
	console.log(numbArray);
}
  1. Reversing an array

(1)

function reverseArray(x){
	let xR = [];
	for (y = x.length - 1; y >= 0; y--){
		xR.push(x[y]);
	}
	console.log(xR);
}

(2)

function reverseArrayInPlace(x){
	if (x.length % 2 == 0){
		var c = x.length;
	} else {
		var c = x.length - 1;
	}
	var ct = c / 2;
	var z = 0;
	while(ct > 0){
		var a = x[c - z];
		var b = x[z];
		x[c - z] = b;
		x[z] = a;
		z++;
		ct--;fa
	}	
	console.log(x);
}
1 Like

My solutions:
The sum of a range:

function range(start, end){
  var counter = start;
  var newArray = [];
  while (counter <= end){
    newArray.push(counter);
    counter ++;
  }
  return newArray;
}

function sum(someArray){
  var total = 0;
  for (num of someArray){
    total += num;
  }
  return total;
}

function rangeExtended(start, end, step = 1){
  var counter = start;
  var newArray = [];
  if (step > 0 && start < end){
    while (counter <= end){
      newArray.push(counter);
      counter += step;
    }
  }else if (step < 0 && start > end){
    while (counter >= end){
      newArray.push(counter);
      counter += step;
    }
  }
  return newArray;
}

Reversing an array:

function reverseArray(someArray){
  var newArray = [];
  for(value of someArray){
    newArray.unshift(value);
  }
  return newArray;
}

function reverseArrayInPlace(someArray){
  var newArray = [];
  
  for(value of someArray){
    newArray.unshift(value);
  }
  for (var i = 0; i < newArray.length; i++){
    someArray.push(newArray[i]);
    someArray.shift();
  }
  return someArray;
}

function reverseArrayInPlace2(someArray){
  var maxIter = Math.floor(someArray.length / 2);

  for (var i = 0; i < maxIter; i++){
    var value = someArray[i];
    var start = someArray.length - 1 - i
    someArray.copyWithin(i, start, someArray.length- i);
    someArray[start] = value;
  }
  return someArray;
}
1 Like

1.The sum of range

2.Reversing an array
image

1 Like

The sum of a range
var range = function(start, end) {
var array = [];
cnt = start;

while (cnt <= end) {
array.push(cnt);
cnt ++;

}
return array;
};

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

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

};

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

};

1 Like
  1. The sum of a range

  2. Reversing an array
    image

1 Like
    1.The sum of a range 

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

function sum(arr1){
let total = 0;
for(var n of arr1){
total += n;
}
return total;
};

       2. Reversing an array 

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

1 Like

Solution: Sum of a Range

const range = function(start, end) {
const array = [];
count = start;

while(count <= end) {

array.push(count);
count++;

}

return array;

};

const sum2 = function(array) {
let total = 0;
for(i=0; i < array.length ; i++) {

total = total + array[i];
}

return total;
};
console.log(sum2(range(1,10)));

Solution Bonus Assignment:

function range(start, end, step) {
let array = [];
var step = step || 1;

if(start < end)
{
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 i = 0; i < array.length; i++)
{
total += array[i];
}
return total;
}

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

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

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

1 Like
  1. Sum of a range

-range

function range (start, end) {
	var array = [];
	for (number = start; number <= end; number++) {
		array.push(number);
	}
	console.log(array);
}
// -> undefined
console.log(range(1, 7)); //-> (7) [1, 2, 3, 4, 5, 6, 7]

-sum

function sum (start, end) {
	var array = [];
	for (number = start; number <= end; number ++) {
		array.push(number);
	}
	var result = 0;
	for (position = 0; position < array.length; position ++) {
		result = result + (array[position]);
	}
	console.log(result);
}
// -> undefined
sum (1, 10); //-> 55

-step

function rangeStep (start, end, step) {
	var array = [];
	if (step > 0) {
		for (number = start; number <= end; number += step) {
			array.push(number);
		}
	}
	else if (step == 0) {
		console.log("step 0 not possible");
	}
	else {
		for (number = start; number >= end; number += step) {
			array.push(number);
		}
	}
	console.log(array);
}
// -> undefined
rangeStep(1, 10, 2); //-> Array(5) [ 1, 3, 5, 7, 9 ]
rangeStep(5, 2, -1); //-> Array(4) [ 5, 4, 3, 2 ]
  1. Reversing an array

-reverseArray

function reverseArray (array) {
	var start = array.length - 1;
	var result = [];
	for (position = start; position >= 0; position --) {
		result.push(array[position]);
	}
	console.log(result);
}
// -> undefined

console.log(reverseArray([2, 4, 5, 6, 8])); //-> (5) [8, 6, 5, 4, 2]

-reverseArrayInPlace

function reverseArrayInPlace (array) {
	var start = array.length - 1;
	for (position = start; position >= 0; position --) {
		array.push(array[position]);
	}
	while (array.length > (start + 1)) {
		array.shift();
	}
	console.log (array);
}
// -> undefined
console.log(reverseArrayInPlace([2, 4, 5, 6, 8])); //-> Array(5) [ 8, 6, 5, 4, 2 ]
1 Like

Solution Reversing an Array:

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

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

Solution Reverse Array In Place:

const array = [1,2,3,4,5];

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

}
return array;
};

console.log(array);

console.log(reverseArrayInPlace(array));

console.log(array);

1 Like

//sum function
function sum(arr){
let result=0;
for(i=0;i<arr.length;i++){

   result=result+arr[i];
}
return result;

}

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

//function range with extra parameter

function range3(start,end,step){

let arr=[];
let length=(end-start);
if(length<0){
length=length*-1;
}
if (step==undefined){
step=1;
}
if(start<end){
for(i=0;i<((length+1)/step);i++){
arr[i]=start
start=start+step
}
}else if(start>end){
for(i=0;i<((length+1)/step);i++){
arr[i]=start;
start=start-step;
}
}else if(start=end)
{ arr[0]=start;
}
return arr;
}
2.
//reverse an array
function reverseArray(arr){

let bigR=[];

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

return bigR;

}

function reverseArrayInPlace(arr){
let temp=[];

for(i=0;i<((arr.length-1)/2);i++){
let max=(arr.length-1)-i;
if(max>=0){
temp.unshift(arr[i]);
arr.splice(i,1,arr[max]);
arr.splice(max,1,temp[0]);
}
console.log(arr);
}
return arr;
}

1 Like

Sum of Range
Part 1: range function with start and end

Test result:

Part 2: sum function of array of numbers

Test result:

1 Like

Reversing Array
Part 1: reverseArray function

Result:

Part 2: reverseArrayInPlace function

Results:

1 Like

The sum of a range

(with explanations)
  • Range

Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

Pretty straightforward, the function range takes two arguments, start and end. The first thing that happens once the function is called, is it creates a local binding array and declares it as an empty array [ ]. The loop that follows this line then sets our “index” i to equal the argument that you passed into “start”, continually checking whether index is still less then or equal to the argument you passed into “end”. If true, the array method push, adds the value held in i to the (end of the) array, the loop increments i by one, and repeats this behaviour until the condition in the loop no longer gets evaluated to true.
Control flow then exits the loop and takes the newly created array, and returns it.

function range(start, end){
	let array = [ ];

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



  • Sum

Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the example program and see whether it does indeed return 55.

Also very straightforward. This function has one parameter (array) and a for...of -loop, which can be a bit confusing the first time you see it, but is actually very simple. First, it lets you choose a variable definition (value, in this example), and second, it loops through the elements of the value given after the word of.

At each iteration of the loop, it adds the current value of value to the local binding total that was declared before the loop. Once each element of the array has been looped through, control leaves the loop and returns total, which by then contains the sum of the array given to it.

function sum(array){
	let total = 0
	for (let value of array){
		total += value;
        }
	return total;
}
console.log(sum(range(1, 10)));
// → 55



  • Range (with step parameter)

As a bonus assignment, modify your range function to take an optional third argument that indicates the “step” value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7, 9]. Make sure it also works with negative step values so that range(5, 2, -1) produces [5, 4, 3, 2].


Aight, so. We need to remake our function so that whatever numeric argument the user passes into step, it will reflect in how much the function will increment (or decrement, if the user passes a negative number) each element, as well as setting default values if the user doesn’t pass any step argument.

We start by (re)defining the function we made earlier with an extra parameter, step.
We leave the variable binding as is, however, in order to solve the issue with default values, i chose to add two conditions for this: one that checks whether the numeric argument passed into start is less than the one passed into end, and one that does the same but opposite. Both condition additionally checks whether or not the step parameter was left undefined. If either of the two conditions gets evaluated to true, the step gets defaulted to 1, or -1 (if start > end). This way you never have to specify negative or positive step values unless you want increments or decrements other than 1.

Once both conditions have been tested, one last condition tests whether the step value is a possible or negative value, and depending on whether it gets evaluated to true or false, a corresponding loop is chosen, one for counting up, and one for counting downwards. Both loops adds the value held in step to the index, which initially stores the value passed into start, effectively increasing or decreasing it (depending on whether step is negative or positive), as well as pushes this value as a new element to the array, at each iteration of the loop, with the push method.

The new array then gets returned.

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

	if (start < end && step == undefined) {step = 1}
	else if (start > end && step == undefined) {step = -1}


		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;
}
console.log(range(1, 10, 2));
// → [1, 3, 5, 7, 9]

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

console.log(range(8, 3));
// → [8, 7, 6, 5, 4, 3]


Reversing an array

(with explanations)

Arrays have a reverse method that changes the array by inverting the order in which its elements appear. For this exercise, write two functions, reverseArray and reverseArrayInPlace. The first, reverseArray, takes an array as argument and produces a new array that has the same elements in the inverse order. The second, reverseArrayInPlace, does what the reverse method does: it modifies the array given as argument by reversing its elements. Neither may use the standard reverse method.


  • reverseArray

So in this first part of the assignment we begin by declaring a function reverseArray with array as it’s parameter. The purpose of loop inside the function body is to loop through the length of the array, and for each iteration, takes the value held at position i of array, and inserts it at the beginning of the reversed array.
It does this by setting i (Index) to 0, checking whether the value held at i is less than the length of the array (that you call the function with), if true, the array method unshift takes the value held att position i of the array, puts it at the beginning of our new array, and increments the value held in binding i by one.

This way, as the loop cycles through each position in array, .unshift continually adds a new first position to the new array, where it also stores the value held in postition i of the old array. Creating a new, completely reversed array, which is then returned.

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

	for (let i = 0; i < array.length ; i++){
		reversed.unshift(array[i]);
	}
	return reversed;
}
console.log(reverseArray(["A", "B", "C"]));
// → ["C", "B", "A"];

  • reverseArrayInPlace

"… The second, reverseArrayInPlace, does what the reverse method does: it modifies the array given as argument by reversing its elements. Neither may use the standard reverse method."

Allright so, i tried all i could think of trying to solve this exercise but to no avail, both looking at the hints section (which were really helpful) and in the forum. In the end i just had to look it up in the sandbox solution on eloquentjavascript.net. But since i struggled so with this i figured i would atleast explain it as good as i can. And i start doing that by posting the hints section found in the book:

FROM THE HINTS SECTION:

Reversing the array in place is harder. You have to be careful not to overwrite elements that you will later need. Using reverseArray or otherwise copying the whole array ( array.slice(0) is a good way to copy an array) works but is cheating.

The trick is to swap the first and last elements, then the second and second-to-last, and so on. You can do this by looping over half the length of the array (use Math.floor to round down—you don’t need to touch the middle element in an array with an odd number of elements) and swapping the element at position i with the one at position array.length - 1 - i . You can use a local binding to briefly hold on to one of the elements, overwrite that one with its mirror image, and then put the value from the local binding in the place where the mirror image used to be.

So, when i look at the function now, it doesn’t seem so puzzling anymore. I redid the whole code found in the sandbox environment in sublime text, piece by piece, until i understood it fully. And at this point i feel like i could probably do it a couple of other ways.
(I guess it pays of to really take solutions apart in this manner.)

Basically the two most important parts of this code to grasp is:

  1. The loop, which uses an index i, set to 0, the condition, using Math.floor (from the math object in the book) in combination with the expression array.length / 2, Translating this loop in it’s entirety to plain English would translate to " Set i to 0. While i is less than half the length of the array, rounded down to it’s nearest whole number, do following - then increment i by one"
    But anyway, here’s what happens at each iteration of the loop:
    First, let temp = array[i]; means "store the value held at position [i] of array in this temporary variable temp". Remember that i basically cycles through the array, element by element. Making it so that at each iteration of the loop, the value held at position i of the array will be stored in temp
  2. The second thing to understand about this function is the math. My incredibly math resistant brain absolutely does not like math, at all. But anyway the key to being able to understand these expressions to this is to be able to translate these expressions again and again, until they make sense.
    Like this: Let array at position [i] store the value held at the length of the array (-1 -i).
    This is the part where my brain crawled out of my ear, made a run for it, and jumped off a cliff. But the math’s involved here is like this:
    To translate this expression i had to imagine a length to the array, as well as what i is in this imaginary example, so lets imagine: If the length in array.length -1 -i; is for example, 9, and the loop looped 3 times, reevaluating this expression to numeric only would then be something like 9 + (-1)+(-3). Adding these two negative values produces -4, and 9 - 4 is five.
    And voila! The expression: array[i] = array[array.length -1 -i]; now translates to: “Let array at position 3 contain the value held at array in position 5.”
    So now, in our nine-element-long array, the value held at position 3, (the fourth), has now been overwritten by the value held at position 5 (the sixth).
    Or to demonstrate in a more visual way: [0, 1, 2, 3, 4, 5, 6, 7, 8].
    The third and final part of our loop’s body then assigns the previously overwritten value that we stored in temp to the array at position 5.
    Making the swap this iteration of the loop complete.
function reverseArrayInPlace(array){
	for (let i = 0; i < Math.floor(array.length / 2); i++){
		let temp = array[i];
		array[i] = array[array.length -1 -i];	
		array[array.length -1 -i] = temp;
	}
	return array;
}

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

I really hope this helps someone!
And as always, let me know if i made any mistakes. :)

6 Likes

THE SUM OF A RANGE

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

}

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

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;

}

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;

}

REVERSING AN ARRAY

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

}

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

}

1 Like