# Chapter 4 - Exercises

#103
1 Like

#104

Can someone explain to me the diference between the reverse array and in-place reverse array. thanks

1 Like

#105
Exercise HTML + JavaScript Code
``````<!DOCTYPE html>
<html>
<title>Exercise!</title>
<body>
<script type="text/javascript">
function range(start, end, step = 1) {
var arr = [];
var is_not_end = function(a) {
return (start <= end && a <= end) ||
(start > end && a >= end);
}
for(let i = start; is_not_end(i); i += step)
arr.push(i);
return arr;
}
function sum(array) {
var _sum = 0;
for(i in array){
_sum += parseInt(array[i]);
}
return _sum;
}
function reverseArray(array) {
var new_array = [];
for (i in array) {
new_array.push(array[array.length - i - 1]);
}
return new_array;
}
function reverseArrayInPlace(array) {
var tmp;
for (var i = 0; i < Math.floor(array.length / 2); i++) {
tmp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = tmp;
}
return array;
}
console.log(sum(range(1,10)));
console.log(range(1, 10, 2));
console.log(range(5, 2, -1));
console.log(reverseArray(range(1,10)));
console.log(reverseArrayInPlace(range(1,10)));
</script>
</body>
</html>
``````
1 Like

#106

SUM OF THE RANGE

For this exercise I wanted to do an instance that combines both ASCENDING and DESCENDING alternatives, and evaluates all possible β and valid β start/end/step combinations.

I wanted to do it all within a working HTML page that requests all 3 inputs from the user,
and with just a bit of CSS to style the input boxes. Hopefully, someone will find it helpful.

Click here to see the code within the context of an HTML page...
``````<html>
<title>Chapter 4 - EXERCISES Parts 1-4</title>
<body>
<h1>Chapter 4 - EXERCISES</h1>
<h2>The Sum of a Range, Parts 1-4 combined</h2>
<h4>Make it work with either ascending or descending numbers and either a positive or negative step.</h4>
<h4> <strong>NOTE:</strong>  JS booleans don't work well when evaluating negative numbers,
so I created 5 valid instances that use subtraction (START - END) instead of GREATER THAN
to evaluate which of these 2 values is greater. It's a roundabout process, but it works.</h4>

<input id= "rangeStart" type="number" placeholder=" Array START" style="font-size:1em; padding:10px; margin:10px; width:350px;"//>
<br />
<input id= "rangeEnd" type="number" placeholder="Array END" style="font-size:1em; padding:10px; margin:10px; width:350px;"//>
<br />
<p> Write STEP number, if different than 1:</p>
<input id= "rangeStep" type="number" value = "1" placeholder="Array STEP (if different than '1')" style="font-size:1em; padding:10px; margin:10px; width:350px;"//>

<div id= "rangeButton">
<button  type="submit" style="font-size:1em; padding:10px; margin:10px; width:350px;">Create Array and Range Sum</button>
</div>
<div id= "showStep"><p> <p> </div>
<br />
<div id= "showArray"><p> <p> </div>
<br />
<div id= "showRangeSum"><p> <p></div>
<br />

<script>
// FUNCTION TO EVALUATE STEP NUMBER

function verifyNumbers (start, end, step) {
var firstNumber = start;
var lastNumber = end;
var jumpNumber = step;

// INSTANCE A: 2 negatives (or START = 0), DESCENDING
if (start<=0 && end<0 && start-end>end && step <=-1) {
console.log("Success! (A: 2 negatives, DESCENDING)");
rangeDown(firstNumber,lastNumber,jumpNumber);
sumDown(firstNumber,lastNumber,jumpNumber);
}
// INSTANCE B: 2 negatives (or END = 0), ASCENDING
else if (start<0 && end<=0  && start-end<end && step >=1) {
console.log("Success! (B: 2 negatives, ASCENDING)");
rangeUp(firstNumber,lastNumber,jumpNumber);
sumUp(firstNumber,lastNumber,jumpNumber);
}
// INSTANCE C: 2 positives (or START = 0), DESCENDING
else if (start>=0 && end>0 && start-end<start && step <=-1){
console.log("Success! (C: 2 positives, DESCENDING)");
rangeDown(firstNumber,lastNumber,jumpNumber);
sumDown(firstNumber,lastNumber,jumpNumber);
}
// INSTANCE D: END is POSITIVE, START either, but end > start), ASCENDING
else if (start-end<start && step >=1) {
console.log("Success! (D: END is positive, START is either, ASCENDING ");
rangeUp(firstNumber,lastNumber,jumpNumber);
sumUp(firstNumber,lastNumber,jumpNumber);
}
// INSTANCE E: END is NEGATIVE, START is positive, DESCENDING
else if (start-end >start && step <=-1) {
console.log("Success! (E: END is negative, START is positive, DESCENDING)");
rangeDown(firstNumber,lastNumber,jumpNumber);
sumDown(firstNumber,lastNumber,jumpNumber);
}
// INSTANCE F: else... ALERT TO REVISE NUMBER COMBO
else
alert ("Make sure your 3 numbers given make sense to compute! Try again!");

// BELOW curly brace closes verifyNumbers FUNCTION
}

/* NOW THAT THE VALIDATION WORKS CORRECTLY, I'll create below 2 sets of functions:
1 ASCENDING "rangeUp" and "sumUp"), AND
"rangeDown" and "sumDown"
*/

// ASCENDING FUNCTIONS...

function rangeUp(start,end,step){
var newArray = [start];
var startNumber = parseInt(start);
var endNumber = parseInt(end);
var stepNumber = parseInt(step);
document.getElementById("showStep").innerHTML = "<br />The CHOSEN step is: " + stepNumber;

for (counter = startNumber + stepNumber; counter <= endNumber; counter += stepNumber){
var nextNumber = counter ;
newArray.push(" " + nextNumber)
};
document.getElementById("showArray").innerHTML = "<br />The new array is: " + newArray;
}
function sumUp(start,end,step){
var total = 0;
var startNumber = parseInt(start);
var stepNumber = parseInt(step);
var endNumber = parseInt(end);
for (var counter=startNumber; counter<=endNumber ; counter += stepNumber){
var total = total + parseInt(counter);
};
document.getElementById("showRangeSum").innerHTML = "<br />The sum of the range is: " + total ;
};

// DESCENDING FUNCTIONS...

function rangeDown(start,end,step){
var newArray = [start];
var startNumber = parseInt(start);
var endNumber = parseInt(end);
var stepNumber = parseInt(step);
document.getElementById("showStep").innerHTML = "<br />The CHOSEN step is: " + stepNumber;

for (counter = startNumber + stepNumber; counter >= endNumber; counter += stepNumber){
var nextNumber = counter ;
newArray.push(" " + nextNumber)
};
document.getElementById("showArray").innerHTML = "<br />The new array is: " + newArray;
}
function sumDown(start,end,step){
var total = 0;
var startNumber = parseInt(start);
var stepNumber = parseInt(step);
var endNumber = parseInt(end);
for (var counter=startNumber; counter>=endNumber ; counter += stepNumber){
var total = total + parseInt(counter);
};
document.getElementById("showRangeSum").innerHTML = "<br />The sum of the range is: " + total ;
};

// END OF ALL FUNCTIONS
//  Now, the jQuery that waits for the click, saves written values and calls the verification function.

\$("#rangeButton").click(function(){
var firstNumber = \$("#rangeStart").val();
var lastNumber = \$("#rangeEnd").val();
var jumpNumber = \$("#rangeStep").val();
verifyNumbers(firstNumber, lastNumber, jumpNumber);
});
</script>
</body>
``````

REVERSING AN ARRAY - Part 1: Creating a new array.

Write a function, `reverseArray` that takes an array as an argument and produces
a NEW array that has the same elements in the inverse order.

``````function reverseArray(initialArray){
var newArray = [];
var lastElement = initialArray[initialArray.length - 1];
for (counter = initialArray.length - 1; counter>=0; counter--){
toReverse = initialArray[counter];
newArray.push(" " + toReverse);
};
}
reverseArray(["apples", "oranges", "mangos", "bananas" , "avocados"]);
``````

REVERSING AN ARRAY - Part 2: Using the same array.

Without using the standard reverse method, modify the array given as argument in order to reverse its elements.

``````function reverseArrayInPlace(alwaysArray){
var numberOfItems = alwaysArray.length;
for (counter = 0 ; counter<= ( numberOfItems-1 ) ; counter ++){
var lastItem = alwaysArray[numberOfItems-1];
alwaysArray.splice (counter, 0, lastItem);
alwaysArray.pop()
};
}
reverseArrayInPlace(["apples", "oranges", "mangos", "bananas", "avocados"]);``````
3 Likes

#107

Hi Basem,

For the first exercise, reverse array, you create a NEW array with the reversed items. The original array stays intact. For the reverse-in-place, the challenge is to move the items within the same array, without using a second array. If needed, see how I did it below, below @jozannaβs comment.

2 Likes

#108

Understood thank you so much

1 Like

#109

I think there are 4 exercises in chapter 4β¦? Anyone ?

1 Like

#110

# Sum of a range excercise

("#button").click(function(){ let input1 = parseInt((("#textInput1").val()));
let input2 = parseInt((("#textInput2").val())); let input3 = parseInt((("#textInput3").val()));

``````if(input3==0){
alert("0 is an invalid step");
}

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

function range(lowNum,highNum,step){
let myArray = [];
if(step>=1){
for(i=lowNum; i<=highNum; i+=input3){
myArray.push(i);
}
return myArray;
}

else{
for(i=lowNum; i>=highNum; i+=input3){
myArray.push(i);
}
return myArray;
}
}
``````

console.log(sum(range(input1,input2,input3)));

});

});

# Reverse Array Excercise

\$("#button").click(function(){

input1 = parseInt((("#textInput1").val())); input2 = parseInt((("#textInput2").val()));
input3 = parseInt((("#textInput3").val())); input4 = parseInt((("#textInput4").val()));
input5 = parseInt((\$("#textInput5").val()));

let myArray = [input1, input2, input3, input4, input5];
let arrayInPlace = [input1, input2, input3, input4, input5];

function reverseArray(funcArray){
let newArray =[];
let loopCounter = funcArray.length;
for(i=0; i<loopCounter; i++){
newArray.push(funcArray.pop());
}
return newArray;
}

document.write("Array reversed with first function: " + reverseArray(myArray) + β

β);

function reverseArrayInPlace(internalArray){
let internalArray2 = [];
let loopCounter2 = internalArray.length;
for(i=0; i<loopCounter2; i++){
internalArray2.push(internalArray.pop());
}
arrayInPlace = internalArray2;
}

reverseArrayInPlace(arrayInPlace);
document.write("Array reversed with second function: " + arrayInPlace + β

β);

});

1 Like

#111

Yes, Sanni, there are 4 exercises in the book but Ivan requested only the first 2, at least for now.

2 Likes

#112
``````**Sum of a Range**
<!DOCTYPE html>
<htmL>
<title>Sum Of A Range</title>
<body>
<h1>Sum of a range of numbers</h1>
<ol id="rangeOfNumbers"></ol>
<script>
startNumber =1;
endNumber=10;
var i;
var numberArray=[];
function buildArray(startNumber,endNumber){
for (i=startNumber; i<=endNumber;i++) {
numberArray.push(i);}};
buildArray(startNumber,endNumber);
var total =0;
var list =\$("#rangeOfNumbers");
\$.each(numberArray,function(index,value){
\$("<li/>").text(value).appendTo(list);
currentValue=parseInt(value);
});

return runningTotal+parseInt(arrayValue);
};

console.log(numberArray);
console.log(total);
</script>
</body>
</html>

**Sum of a Range Reversed**
<!DOCTYPE html>
<htmL>
<head> <title>Sum Of A Range</title> <script
</head> <body> <h1>Sum of a range of numbers</h1> <ol
id="rangeOfNumbers"></ol>
<script>
startNumber =1;
endNumber=10;
stepNumber=1;
var i;
var numberArray=[];

function buildArray(startNumber,endNumber,stepNumber){
if (startNumber<endNumber) {
for (i=startNumber;i<=endNumber;i=i+stepNumber) {
numberArray.push(i);}
} else {
for (i=startNumber;i>=endNumber;i=i+stepNumber) {
numberArray.push(i);}
};
}
buildArray(startNumber,endNumber,stepNumber);

var total =0;
var list =\$("#rangeOfNumbers");
\$.each(numberArray,function(index,value){
\$("<li/>").text(value).appendTo(list);
currentValue=parseInt(value);
});

return runningTotal+parseInt(arrayValue);
};

console.log(numberArray);
console.log(total);
</script></body> </html>

**Reversing an Array**``````
1 Like

#113

The sum of a range

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

#114

Sum Of Range

``````function range(start, end, step = start < end? 1:-1){

//ternary object is simeple if else statment: if(start<end){step =1;} else {step =-1;}

let array =[];

//make an empty array for yourself first in order to fill up your numbers later on.

if (step >0){

for (let i = start; i <= end ; i+= step)array.push(i);

//i <=end which shows positive number and array.push to push in numbers in [] each time when i iterates.

}else{

for (let i = start; i >= end ; i+= step)array.push(i);

//i >= end shows (-numbers) and array.push to push in numbers in [] each time when i iterates.

}

return array;

// to show the array which you ask in console.

}

function sum(array){

//a function calls array to be involved.

let total = 0;

//to start with 0 so the next number won't be adding other number to itself.

for (value of array){

//this is saying what's inside the array [1,2,3,]

total+=value;

//total 0+1+2+3

}

//to show your result which you ask in console.

}

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

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

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

Reverse Array

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

let arrayValue = ["a","b","c","d","e"];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//(5) ["e", "d", "c", "b", "a"]
0:"e"
1:"d"
2:"c"
3:"b"
4:"a"
length:5
``````

:

1 Like

#115

//Sum of range
let Sum = function (a,b) {
let SumResult = 0;
let result = range1(a,b);

``````for (var i = 0 ; i <= result.length - 1 ; i++) {
SumResult = SumResult + result[i];
}
return SumResult;
``````

}
console.log(Sum(1,10));

// advanced sum of range with step
let range2 = function (a,b,c){
if (a>b && c == null ) { //test if the increment Β© must be positive or negative and check if c has a value
c = -1; // if both condition met, c = -1
}
else if (a<b && c == null) { //test if the increment Β© must be positive or negative and check if c has a value
c=1; // if both condition met, c = -1
}
let result = []; //Creates an empty array
if (Math.signΒ© == 1){ //test if c is positive

``````    for (var i = a ; i <= b ; i = i + c){ //loop to sum all intries in the array
result.push(i);
}
}
else { //if c is negative

for (var i = a ; i >= b ; i = i + c) { //loop to sum all intries in the array
result.push(i);
}
}
return result; //return the sum
``````

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

//REVERSING ARRAY
let ReverseArray = function (Array1){
let Array2 = []; //Creates an empty array
for ( var i = Array1.length -1 ; i>= 0 ; iβ){ //loop backward in array1
Array2.push(Array1[i]); //push the value to the new array2
}
return Array2

}
console.log(ReverseArray([βAβ,βBβ,βCβ]));

//Reverse array in place

let ReverseArrayInPlace = function (Array1){
let StorageValue = 0
for ( var i = 0 ; i < Math.floor(Array1.length / 2) ; i++ ){
StorageValue = Array1[i];
Array1[i] = Array1[Array1.length -1 -i];
Array1[Array1.length -1 -i] = StorageValue;
}
return Array1
}
console.log(ReverseArrayInPlace([1,2,3,4,5]));

1 Like

#116

Sum of Array:

``````  var arrayReturn = [];

function range(x,y,z) {
arrayReturn = [];
if (x>y && z<0) {
while (x>=y) {
arrayReturn.push(x);
x=x+z;
}
}
else if(x<y && z>0) {
while (x<=y) {
arrayReturn.push(x);
x=x+z;
}
}
else {
console.log("No valid input");
}
}

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

console.log("Summe 1: "+sum(range(2,9,-2)));
console.log("Summe 2: "+sum(range(9,2,-2)));
console.log("Summe 3: "+sum(range(2,9,2)));
console.log("Summe 4: "+sum(range(1,10,1)));
console.log("Summe 5: "+sum(range(7,2,-3)));
``````

Reverse Array:

``````  var newArray =[];
var arrayToReverse = [2,4,6,8];

function reverseArray(arrayGiven) {
for (counter=(arrayGiven.length-1); counter>=0; counter--){
newArray.push(arrayGiven[counter]);
}
}

function reverseArrayInPlace() {
var tempArray = [];
for (counter=(arrayToReverse.length-1); counter>=0; counter--){
tempArray.push(arrayToReverse[counter]);
}
arrayToReverse = [];
for (counter=0; counter<tempArray.length; counter++){
arrayToReverse.push(tempArray[counter]);
}
}

reverseArray([2, 3, 4, 5, 6, 7, 8, 9]);
console.log("New array in reversed order: " + newArray);

reverseArrayInPlace(arrayToReverse);
console.log("Original array reversed: " + arrayToReverse);``````
1 Like

#117
1. Function to return range from start to end with given step size as βstepβ.
``` function range(start,end, step) { var myArr = []; if (start < end) { for (var k=start; k<=end; k+=step) { myArr.push(k); } return myArr; } else { for (var k=start; k>=end; k+=step) { myArr.push(k); } return myArr; }```

}

1. Function to sum the array
``` function sumArr(arr) { var total = 0; for (var i in arr) { total += arr[i]; } return total; }```

2. Function to reverse an array
``` function reverseArray(arr) { var newArr = []; for (var k=(arr.length); k>=0; kβ) { newArr.push(arr[k]); } return newArr; }```

1 Like

#118

Thanks for the detailed explanation! it helped me a lot!

1 Like

#119

My answers to Chapter 4 Exersises

var myArray = [];
var sum = 0;

function ranges(num1, num2, step) {
if (step === undefined || step == null) {
for (var num1; num1 <= num2; num1++) {
myArray.push(num1);
};
console.log(myArray);
} else if (step > 0) {
for (var num1; num1 <= num2; num1+=step) {
myArray.push(num1);
};
console.log(myArray);
} else if (step < 0) {
for (var num1; num1 >= num2; num1+=step) {
myArray.push(num1);
};
console.log(myArray);
}
};

console.log(myArray);

ranges(1,10,1);

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

//Reverse Arrays

/**
function reverseArray(myArray){

reverseA=[];
for (a =myArray.length - 1; a>=0; aβ){
reverseA.push(myArray[a])
};
return(reverseA);
};

document.write(reverseArray(myArray));
**/

//Reverse In Place

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

document.write(reverseArrayInPlace(myArray));
**/

I dont know which is more useful or faster, but the first option seems simpler to me, as there are less lines of code. I dont know if its faster to write a new array or to do all the math in order to come up with the Reverse In Place Array.

1 Like

#120

Hello @ivan and dear community,

EXERCISES CHAPTER 4

THE SUM OF A RANGE

Function βrange()β

``````function range(start, end) {
if (start < end) {
var myArray = [];
for (var i = 0; i <= (end - start); i++) {
myArray[i] = start + i;
}
} else {
alert("The first value must be lower than the second value!");
}
return myArray;
}
``````

Function βsum()β

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

Usage of the functions βrange()β and βsum()β:
`console.log(sum(range(1, 10)));`

Bonus

``````<HEAD>
<Script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></SCRIPT>
<BODY>
<SCRIPT>

var start = 1;
var end = 10;
var inc = -2;
console.log(start + " to " + end + " by " + inc + " = " + sum(range(start, end, inc)));

function range(start, end, increment) {

var myArray = [];

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

if (start < end) {
// Invert the increment
if (increment < 0) {
increment *= -1;
}
for (var i = 0; i <= (end - start); i++) {
if (i * increment <= end - start) {
myArray[i] = start + i * increment;
console.log(start + i * increment);
}
}
} else {
if(increment < 0) {
increment *= -1;
}
for (var i = 0; i <= (start - end); i++) {
if (i * increment <= start - end) {
myArray[i] = start - i * increment;
console.log(start - i * increment);
}
}
}
return myArray;
}

function sum(iArray) {
let iResult = 0;
for (var i = 0; i < iArray.length; i++) {
iResult += iArray[i];
}
return iResult;
}
</SCRIPT>
</BODY>
``````

REVERSING AN ARRAY

Function βreverseArray()β (system-embedded solution)

``````<HEAD>
<Script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></SCRIPT>
<BODY>
<SCRIPT>
function iReverseArray(inputArray) {
return inputArray.reverse();
}

let myArray = ["Ivan", "On", "Tech"];
console.log(iReverseArray(myArray));
</SCRIPT>
</BODY>
``````

Function βreverseArrayInPlace()β (own solution by me βOtenMotenβ)

``````<HEAD>
<Script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></SCRIPT>
<BODY>
<SCRIPT>
function iReverseArrayInPlace(inputArray) {
let outputArray = [];
let iSize = inputArray.length;

for (var i = 0; i < iSize; i++) {
outputArray.push(inputArray.pop());
}
return outputArray;
}

let myArray = ["Ivan", "On", "Tech"];
console.log(iReverseArrayInPlace(myArray));
</SCRIPT>
</BODY>
``````

Cheers
OtenMoten

0 Likes

#121

Here is the part for Reversing the Array in Place.

var originalArray=[1,2,3,4,5];
var reverseArray=[];
var FinalArray=[];
length=originalArray.length

reverseInPlaceFunction(originalArray,length);
function reverseInPlaceFunction(arrayName,arrayLength){
for (i=arrayLength; i>=1;i=i-1) {
reverseArray.unshift(arrayLength-i+1);}};

0 Likes

#122

Sum and Range:
function range(start, end, step = start<end ? 1 : -1){
var ans = [];
if (step > 0) {
for (let i = start; i <= end; i += step) ans.push(i);
} else {
for (let i = start; i >= end; i += step) ans.push(i);
}
return ans;
}
function sum(num){
let s = 0;
for(let i =0;i<num.length;i++){
s=s+num[i]
}
console.log(s);
}
console.log(sum(range(1,10)));

Reversing an Array:
let array1 = [βoneβ, βtwoβ, βthreeβ, βfourβ, βfiveβ, βsixβ, βsevenβ];
let array2 = [1,2,3,4,5,6,7,8];
function reverseArray(arr) {
let newArray = [];
for (let i = arr.length - 1; i >= 0; iβ) {
newArray.push(arr[i]);
}
return newArray;
}
function reverseArrayInPlace(arr) {
for (var i = 0; i <= Math.floor((arr.length-1) / 2); i++) {
let rAIP = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = rAIP;
}
return arr;
}
console.log(reverseArrayInPlace(array1));

0 Likes