Chapter 4 - Exercises

Under reverseArray, with the code example below, why must we subtract 1 from ‘array.length - 1’ under the loop. Because without this operation, it gives the index: 0 undefined. I’m lost here if somebody can please explain. Thanks!

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

The Sum of a Range

//creates and returns an array of numbers based on the starting and ending points given
  function range(start, end, step){
    if (step == undefined){
      step = 1;
    }

    var array = [];
    if (end>start){
      for (var i=start; i<=end; i+=step) {
      array.push(i);
      };
    }
    else{
      if (step == 1){
        step = -1;
      }
      for (var i=start; i>=end; i+=step) {
      array.push(i);
      };
    }
    return array;
  }

//adds all numbers in an array together and returs the sum
  function sum(list){
    var sum = 0;
    var length = list.length;
    for (i=0; i<list.length; i++){
      sum += list[i];
    };
    return sum;
  }

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

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

Reversing an Array

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

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

    return(newArray);
  }

  function reverseArrayInPlace(array){
    var length = array.length;
    for(var i=array.length-1; i>=0; i--){
      testArray.push(array[i]);
    };
    for (var j = 1; j<=length; j++){
      testArray.shift();
    };
    return(testArray);
  }

  console.log(reverseArray(testArray));
  console.log(reverseArrayInPlace(testArray));

Sum of Range:

array.length gives the quantity of items in an array. For example, an array containing [1, 2, 3, 4, 5] would result in an array.length of 5. Since array objects start at 0 rather than 1, the last item in the array would be equal to array.length-1. So if the example array was named testArray, to access the last element you would use testArray[4].

function range(start, end, increment){
var result [];
if (increment == undefined)
increment = 1;
numLoops = Math.abs(end - start)/increment) +1;
for (var i=0; i<numLoops; i++){
result.push (start);
start += increment;
}
return result;
}

function sum (numArray) {
var arrayTotal = 0;
numLoops = numArray.length;
for (var i=0; i<numLoops; i++) {
arrayTotal += numArray[i];
}
return arrayTotal;
}

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:

var x = [{“score”:1}, {“score”:2}, {“score”:3}]

// copy x
y = Object.assign({}, x);
console.log(y);
x.reverse();
console.log(x);
//Result:
// 0: {score :1}
// 1: {score : 2}
// 2: {score :3}

//0: {score:3}
//1: {score:2}
//2: {score:1}

Obviously a beginner, buy that is as good as it gets, for now.

  1. Sum of range
function range(start, end)
{
    let result = [];
    result.push(start);
    for (let i = 1; i < end - start + 1; i++)
    {
        result.push(start + i);
    }
    return result;
}

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

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

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

function rangeBonus(start, end, step = 1)
{
    let result = [];
    for (let i = 0; i < end - start + 1; i += step)
    {
        result.push(start + i);
    }
    return result;
}

// Test 
console.log(sum(rangeBonus(1, 10)));
console.log(sum(rangeBonus(1, 10, 2)));
  1. Reversing an array
function reverseArray(tab)
{
    let result = [];
    for (let i = 0; i < tab.length; i++)
    {
        result.push(tab[tab.length - 1 - i]);
    }
    return result;
}

// Test
chiffres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
inverseChiffres = reverseArray(chiffres);

function afficheTableau(tab, ordre)
{
  let phrase = "Tableau des chiffres dans l'ordre " + ordre + " :";
  console.log(phrase);
  console.log("-".repeat(phrase.length));
    
  if (ordre.toUpperCase() === "CROISSANT") console.log(tab);    
  else if (ordre.toUpperCase() === "décroissant".toUpperCase())   console.log(reverseArray(tab));
  else console.log('Error!');
}

afficheTableau(chiffres, "croissant");
console.log("\n\n");
afficheTableau(chiffres, "décroissant");


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

// Test
function afficheTableau(tab, ordre)
{
  let phrase = "Tableau des chiffres dans l'ordre " + ordre + " :";
  console.log(phrase);
  console.log("-".repeat(phrase.length));
    
  if (ordre.toUpperCase() === "CROISSANT") console.log(tab);    
  else if (ordre.toUpperCase() === "décroissant".toUpperCase())   console.log(reverseArrayInPlace(tab));
  else console.log('Error!');
}

chiffres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
afficheTableau(chiffres, "croissant");
console.log("\n");
afficheTableau(chiffres, "décroissant");

console.log(chiffres === reverseArrayInPlace(chiffres));

// Book's solutions
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;
}

When I read the assignment it felt overwhelming and very challenging, I basically lost steam to push through. I ended up breaking it down into small bite size parts and building up from there. After looking at other’s answers, I was able to get a better idea but did not make it much easier to understand what the purpose was. The thing I struggled the most with was syntax errors and logic format, were I’m calling for undefined variables. I had to go back to some real basic lessons because as I was not practicing everyday I lost the skills, this was the most frustrating part of the whole thing, just spending 20min a day on trying to learn a some more code seems to make a huge difference.


/** all functions and variables are loaded before document ready is called, **/
var numberArr =[]; // creates an array from user input

// yourArray() is used to write values of the array to the document
function yourArray(showArray) {
  for(x=0; x < showArray.length; x++) {
    if(showArray[x] != undefined ){
      document.write(" Index No." + x + " Value: " + showArray[x] + "<br>");
    }
  }
}

// addYourArray is used to calculate the sum of the values in the array
function addYourArray(showArray) {
  var ad = 0;
  for(x=0; x < showArray.length; x++) {
    ad = showArray[x] + ad;
  }
    document.write("<br> Sum of Array is:<br> " + ad +"<br><br>");
}

// reverseArray uses a secondary array to store array values is reverse order
function reverseArray() {
  var revNumberArr =[];
  for(x= numberArr.length; x != 0; x--) {
    revNumberArr.push(numberArr[x-1]);
  }
  return revNumberArr;
}

// reverseArrayInPlace uses a logistical rearrangment of data within the same array to achive a reversed array
function reverseArrayInPlace() {
  var l = numberArr.length;
  for(x=0; x < l; x++){
    numberArr.push(numberArr[x]);
    numberArr[x] = numberArr[numberArr.length-1];
  }
  for(x=l; x<numberArr.length; x++){
    delete numberArr[x];
  }

  yourArray(numberArr);
}

$(document).ready(function(){
  $("button").click(function(){
    var StNum = parseInt(initialNum.value);
    var EnNum = finalNum.value;
    if (!stepSqnc.value) { // if the step value from the user is null then create input of array will 1 value incruments
          if (StNum < EnNum ){ // check to see if the start number is smaller than the end numbers
            window.alert("asending");
            for(x = StNum; x <= EnNum; x++){
              numberArr.push(x);
            }
          } else {
            window.alert("desending");
            for(x = StNum; x >= EnNum; x--){
              numberArr.push(x);
              window.alert(x);
            }
          }

    } else { // if the user step value is not null then use the step value to create values for the array
          if (StNum < EnNum) { // check to see if the start number is smaller than the end numbers
            for(x = StNum;x <= EnNum; x = x + parseInt(stepSqnc.value)) {
              numberArr.push(x);
            }
          } else {
            for(x = StNum;x >= EnNum; x = x - parseInt(stepSqnc.value)) {
              numberArr.push(x);
            }
          }
    }
    document.writeln("Your Array: <br>"); // title of the first array that was created by user input
    yourArray(numberArr); // prints out the array on screen
    addYourArray(numberArr); //adds all the values in the array
    reverseArray()
    document.writeln("Revered Array: <br>"); // title
    yourArray(reverseArray());
    document.writeln("<br>Revered Array In Place: <br>");//title
    reverseArrayInPlace()
  })
});
</script>
</head>
<body>
  <input id="initialNum" type="text" value="2"></input> <!-- default of 2 used for first number input -->
  <input id="finalNum" type="text" value="60"></input> <!-- default of 60 used for last number input -->
  <input id="stepSqnc"  type="text" value="4"></input> <!-- default numbers to skip between range -->
  <button>submit</button>
</body>
</html>

var Exercise = [“Pushups”,“Squats”, “Burpees”, “Situps”,“Pullups”];

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

         console.log(Exercise);
         console.log(reverseArray(Exercise));

Result in console

(5) [“Pushups”, “Squats”, “Burpees”, “Situps”, “Pullups”]
(5) [“Pullups”, “Situps”, “Burpees”, “Squats”, “Pushups”]

// The 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, 20))
console.log(range(5, 2, -1));
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);

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

4.2

Sum of Range::

Before Modification

function range(start, end,step) {

var ans = [];

for (let i = start; i <= end; i++) {

ans.push(i);
}

return ans;

}

function sum(arr) {

let result = 0;

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

return result;

}

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

Sum of Range::

After Modification::::

function range(start, end,step) {

var ans = [];
var stepOne = 1;

if (step != undefined){
stepOne = step;
}
if(start < end){
for(var i = start; i <= end; i += stepOne){
ans.push(i);
}
}
else if(start > end){
for(var i = start; i >= end; i += stepOne){
ans.push(i);
}
}
return ans;
}

function sum(arr) {

let result = 0;

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

return result;

}

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

Reversing The Array :::::

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

console.log(reverseArray([2,4,6,8]));

Reverse Array in place:::

function reverseArrayInPlace(array){
for (let i = 0; i < Math.floor(array.length ); i++) {

}
return array;
}

console.log(reverseArrayInPlace([2,6,4,5,6]));

The sum of a range

<script>
        function complete(startNumber, endNumber, step) {
            let arrayForComplete = [];
            if (step < 0) {
                for (let counter = startNumber; counter >= endNumber; counter += step) {
                    arrayForComplete.push(counter);
                }
            } else {
                for (let counter = startNumber; counter <= endNumber; counter += step) {
                    arrayForComplete.push(counter);
                }
            }

            console.log(arrayForComplete);

            let sumForComplete = 0;

            for (let counter = 0; counter < arrayForComplete.length; counter++) {
                let number = arrayForComplete[counter];
                // console.log(number);
                sumForComplete += number;
            }

            console.log(sumForComplete);
        }

        complete(1,10,2);
        complete(1,5,3);
        complete(5,2,-1)

    </script>

Reversing an array

<script>
        /* */

        let arrayNew = ["Apple", "Pieapple", "Lemon", "Cherry", "Orange", "Kiwi", "Coconut", "Banana"];

        function reverseArray(arrayInput) {
            // this function creates new array with reverse order
            let newOutputArray = [];
            for (let counter = arrayInput.length - 1; counter >= 0; counter--) {
                let valueOfArray = arrayInput[counter];
                newOutputArray.push(valueOfArray);
            }

            console.log(newOutputArray);
        }

        function reverseArrayInPlace(arrayInput) {
            // this function doesn't create new array, but still reverse given array
            for (let counter = 0; counter < arrayInput.length/2; counter++) {
                let x = arrayInput[counter];
                let y = arrayInput[arrayInput.length - 1 - counter];
                let blank = x;
                arrayInput[counter] = y;
                arrayInput[arrayInput.length - 1 - counter] = blank;
            }

            console.log(arrayInput);
        }

        reverseArray(arrayNew);
        reverseArrayInPlace(arrayNew);
// checking .reverse method, needed to use it twice
        console.log(arrayNew.reverse());
        console.log(arrayNew.reverse());

    </script>

1.) The sum of a range:
image
2.) Reverse an array, reverse an array in place:

function range(array){
var start = array[0];
var end = array[1];
return (end*(end+1) - (start-1)*start) / 2;
}
console.log(range([1 , 10]));

var fruits = [“Orange”, “Banana”, “Apple”, “Grape”];

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

Chapter 4 exercises

Here’s my solutions:

the sum of range
a)
function range(start, end){
for(var i=start;i<=end;i++)
document.write(i);
}
range(1, 10);

b)
function range1(start, end){
var sum = 0;
for(var i=start;i<=end;i++)
sum += i;
document.write(sum);
}
range1(1, 10);

c)
function range(start, end, step){

if(step > 0){
  for(var i=start; i<=end; i += step)
  document.write(i);
  console.log(i);
}
if(step == 0){
  for(var i=start; i<=end; i++)
  document.write(i);
  console.log(i);
}
if(step < 0) {
  for(var i=start; i>=end; i += step)
  document.write(i);
  console.log(i);
}

}

range(1, 10, 2);

Reversin Array

var fruits = [ “banana”, “orange”, “coconut”];

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

}
console.log(fruits);
console.log(reverseArray(fruits));

  1. The sum of a range
  var myArray = [];
  var sum= 0;

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

  function sumNumbers(){
    for (var i = 0; i < myArray.length; i++) {
      sum+=myArray[i];
    };
    console.log(sum);
  };
  1. Reversing an 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);

//Sum of a Range
var range = function(start, end){
var array = [];
counter = start;

      while (counter <= end){
        array.push(counter);
        counter++;
      }
      return array;

};

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

  while(array.length > 0){
      total = total + array.pop();
  }
  return total;
};


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

//Reversing an Array
function reverseArrayInPlace(array) {
for (var a = 0; a < Math.floor(array.length / 2); a++) {
var aux = array[a];
array[a] = array[array.length - 1 - a];
array[array.length - 1 - a] = aux;
}
return array;
}
var arrayValue = [1, 2, 1, 2];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

Problem 1 - Return a range of numbers
      // Takes args start and end with optional step
      function range(startNum, endNum, stepNum=1){
        var arrRtn = [];
        // Make sure we can deal with negative numbers
        var numStep = Math.abs(stepNum);
        // if start is greater than end then swap them around
        if(endNum>startNum){
          for(loop = startNum; loop<endNum+1; loop+=numStep){
            arrRtn.push(loop);
          }
        }
        else{
          for(loop = endNum; loop<startNum+1; loop+=numStep){
            arrRtn.push(loop);
          }
        }
        // Return array
        return arrRtn;
      }
Problem 2 -  - Return the sum of numbers
      // Takes a number array as an arg and retuns the sum of its contents
      function sum(arrRange){
        var numRtn = 0;
        for(loop = 0; loop<arrRange.length; loop++){
          numRtn+=arrRange[loop];
        }
        // Return number
        return numRtn;
      }
Problem 3 - Reversing an array
      // Takes an array as an arg
      function reverseArray(arrToReverse){
        var arrRtn = [];
        var numLength = arrToReverse.length;
        var numReverse = numLength-1;
        // Loop through the return array and use reverse counter to
        // populate from the input array.
        for(loop = 0; loop<numLength; loop++){
          arrRtn[loop]=arrToReverse[numReverse];
          numReverse--;
        }
        // Return array
        return arrRtn;
      }
Problem 4 - Reversing an array in place
      // Takes an array and reverses its contents in place
      function reverseArrayInPlace(arrToReverse){
        var loopFwd = 0;
        var loopRev = arrToReverse.length;
        // Keep looping until counters reach the centre of the array
        while(loopFwd<loopRev){
          let temp = arrToReverse[loopFwd];
          arrToReverse[loopFwd]=arrToReverse[loopRev-1];
          arrToReverse[loopRev]=temp;
          loopFwd++;
          loopRev--;
        }
        // Return the amended array
        return arrToReverse;
      }