Chapter 4 - Exercises

  • The sum of a range:

      let rangeArray=[];
    
      function range(startNumber,endNumber,step){
        if (startNumber<endNumber) {
          for (let i = 0; i <= endNumber; i++) {
            if (i==0) {
              rangeArray.push(i+1);
            } else {
              rangeArray.push(rangeArray[rangeArray.length-1]+step);
              i=rangeArray[rangeArray.length-1]+step-1;
            }
          };
        } else {
          step=Math.abs(step);
          for (let i = startNumber; i >= endNumber; i--) {
            if (i==startNumber) {
              rangeArray.push(i);
            } else {
              rangeArray.push(rangeArray[rangeArray.length-1]-step);
              i=rangeArray[rangeArray.length-1]-step+1;
            }
          };
        };
      };
    
      let startNumber=parseInt(prompt("Enter the start number:"));
      let endNumber=parseInt(prompt("Enter the end number:"));
      let step=parseInt(prompt("Enter the step:"));
    
      range(startNumber,endNumber,step);
      console.log(rangeArray);
    
      function sum(rangeArray){
        let add=0;
        for (var i = 0; i < rangeArray.length; i++) {
          add+=rangeArray[i];
        }
        console.log(add);
      }
      sum(rangeArray);
    
  • Reversing an array:

      function reverseArray(rangeArray){
        let reverseRangeArray=[];
        for (let i = rangeArray.length-1; i >= 0 ; i--) {
          reverseRangeArray.push(rangeArray[i]);
        };
        return reverseRangeArray;
      }
      console.log(reverseArray(rangeArray));
    
      function reverseArrayInPlace(rangeArray) {
        counter=0;
        for (let i = rangeArray.length-1; i >= 0 ; i--) {
          rangeArray.splice(counter,0,rangeArray[rangeArray.length-1]);
          rangeArray.pop();
          counter+=1;
        };
        return rangeArray;
      }
      console.log(reverseArrayInPlace(rangeArray));
    
  • A list:

      let arrayToList = function(array) {
        let list = null;
        for (let i = array.length - 1; i >= 0; i--) {
          list = {value: array[i], rest: list};
        }
        return list;
      };
      console.log(arrayToList([1, 2,3]));
    
      let listToArray = function(list) {
        let array = [];
        for (let node = list; node; node = node.rest) {
          array.push(node.value);
        }
        return array;
      };
      console.log(listToArray(arrayToList([1, 2, 3])));
    
      let prepend = function(value, list) {
        return {value, rest: list};
      };
      console.log(prepend(1, prepend(2, null)));
    
      let nth = function(list, n) {
        if (!list) {
          return undefined;
        }
        else if (n === 0) {
          return list.value;
        } else {
          return nth(list.rest, n - 1);
        }
      };
      console.log(nth(arrayToList([1, 2, 3]), 1));
    
  • Deep comparison:

      let deepEqual = function(value1, value2) {
        if (value1 === value2) {
          return true;
        };
    
        if (value1 == null || typeof value1 != "object" || value2 == null || typeof value2 != "object") {
          return false;
        };
    
        const keysValue1 = Object.keys(value1);
        const keysValue2 = Object.keys(value2);
    
        if (keysValue1.length != keysValue2.length) {
            return false;
        };
    
        for (let key of keysValue1) {
          if (!keysValue2.includes(key) || !deepEqual(value1[key], value2[key])) {
            return false;
          };
        }
        return true;
      };
    
      const obj = {here: {is: "an"}, object: 2};
      console.log(deepEqual(obj, obj));
      console.log(deepEqual(obj, {here: 1, object: 2}));
      console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
2 Likes

SUM OF A RANGE

var numbers = [];

function range(x,y,z) {
  if (z > 0) {
  for(var counter = x; counter <= y; counter= counter + z) {
    numbers.push(counter);
  }
 } else if (z < 0) {
    for (var counter = x; counter >= y; counter = counter + z) {
      numbers.push(counter);
      }
} else {
  for (var counter = x; counter <= y; counter++) {
    numbers.push(counter);
    }
  }
};
range(5, 2, -1);

console.log(numbers);

var total = 0;
function sum() {

  for (var counter = 0; counter < numbers.length; counter++) {
    total = total + numbers[counter];
  };
};
sum();

console.log(total);

REVERSE ARRAY

var numbers = [1, 2, 3, 4, 5, 11, 12, 13, 14, 15];

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

function reverseArrayInOrder(numbers) {
  for (var i = 0; i < numbers.length; i++) {
    var placeholder = numbers[i];
    numbers[i] = numbers[numbers.length-1-i];
    numbers[numbers.length-1-i] = placeholder;
  };
  console.log(numbers);
};
reverseArrayInOrder(numbers);
1 Like
  1. SIMPLE RANGE
    let arr= [];
    function range(start, end){
    for(i=start; i<=end; i++) {
    arr.push(i);
    }
    return arr;
    }
    console.log(range(1,10));

  2. SUM
    function sum(arr){
    let total =0;
    for(i=0; i < arr.length; i++){
    total+= arr[i];
    }
    return total;
    }
    console.log(sum(arr));

  3. 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]));

  4. 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));

1 Like

Whoa! This whole exercise has been a journey for me, I’m new to coding, so this was all painful in a good way as I really had to push through the give up phase,

I’m fine with the first part, and taken notes, but the reverse array has stumped me, below is what I have done, but for some reason, some of the results come back as undefined, any suggestions?

const reverseArrayInPlace = (arr) => {

for (let i =0; i < arr.length / 2; i++) {

temp = arr[i]

arr[i] = arr[arr.length / -1 -i]

}

return arr

}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(arr)

console.log(reverseArrayInPlace(arr))

1. Sum of Range

  const range = (start, end, step = 1) => {
        let toReturn = [];
        for(let i = start; step < 0 ? i >= end : i <= end; i+= step) //using the question mark colon operator (very usefull)
          toReturn.push(i);
        return toReturn;
      };
      const sum = (arr) => {
        let tmp = 0;
        for(i in arr)
          tmp += arr[i];
        return tmp;
      }

2. Reversing Array

      const reverseArray = (arr) => {
        var newArray = [];
        for(var i = arr.length-1; i >= 0; i--)
          newArray.push(arr[i]);
        return newArray;
      };
      const reverseArrayInPlace = (arr) => {
       //idea here is to run through half of the array and swap the element with the element 
       //that has the same distance from end than this element from start.
       // I need to save a value because it gets overwritten.
        for(var i = 0; i < arr.length/2; i++){
          let tmp = arr[i];
          arr[i] = arr[arr.length-1-i];
          arr[arr.length-1-i] = tmp;
        }
      };
1 Like

The Sum of a Range

var myArray = [];

function arrayRange(x,y,z){

if(z===0||z===null){//defining the condition of the 3rd argument(not 0, not null)
z=1;//then it needs to be 1
//next, the code branches in asceding or descending array
if(x<y){//ascending array
for(let i = x; i < y; i+=Math.abs(z)/absolute value of z/){
myArray.push(i);
}
}
else {//descending array
for (let i = x; i >= y; i-=Math.abs(z)) {
myArray.push(i);
}
}
}

else {//this will run if z is correctly defined, it is not 0 or no value
if(x<y){//ascending array
for(let i = x; i < y; i+=Math.abs(z)){
myArray.push(i);
}
}
else {//descending array
for (let i = x; i >= y; i-=Math.abs(z)) {
myArray.push(i);
}
}
}
}
arrayRange(5,2,-1);

console.log(myArray);

1 Like
	3. 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;
	}
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;
}
1 Like

Sum of Range
function createArray(start,end){
//clean out old arrayList
var newArray = [];
//start creating new array
if (end > start){
for (i = start; i <= end; i=i+1) {
newArray.push(i);
}
return newArray;
}
}

function sumArray(start,end){
var newArray2 = [];
var sumAmount = 0;
//start creating new array
if (end > start){
for (i = start; i <= end; i++) {
newArray2.push(i);
sumAmount = sumAmount + i;
}
return sumAmount;
}
}
//console.log(createArray(3,7));

$("#myNewArrayButton").click(function(){
var startNum = parseInt($("#startInput").val()); //might need to add parseInt in HERE
var endNum = parseInt($("#endInput").val());
createArray(startNum,endNum);
console.log(createArray(startNum,endNum));
console.log("The sum is: " + sumArray(startNum, endNum));
});

Reverse Array
var oldArray = [ā€œ0_Orangeā€, ā€œ1_Redā€, ā€œ2_Yellowā€, ā€œ3_Timbucktooā€, ā€œ4_Brownā€];

function reverseArray(oldArray){
var newArray = [];
newArrayIndex = oldArray.length;
for (var i=0; i<oldArray.length; i++) {
newArray[i]=oldArray[newArrayIndex-1-i];
}
return newArray;
}
console.log(oldArray);
console.log(reverseArray(oldArray));

1 Like

Exercise 4.1

            // range function that takes an increment
            function range(begin, end, increment){
                //determines default action if increment is not provided
                if (!(increment)){increment = 1}
                //defines how long the loop should last by setting a target that handles negative increments
                var tar = (end - begin)/increment
                //create num value that will be updated instead of the begin value so that variable is preserved
                var num = begin;
                //declares the empty array
                var rangeVal =[];
                // loop that adds each value starting from begin parameter supplied until reaching the end as the last value, then adds the increment value given to the num variable for the next loop.
                for (let c = 0; c <= tar; c++){
                    rangeVal.push(num);
                    num +=increment
                }
                return rangeVal;
            };

            //sum function
            function sum(value){
                //declares the SumTots variable that will be used to store the growing sum.
                var sumTots = 0;
                //a loop that takes each value from the array and adds it to the sumTots value, until reaching the end of the 'range' array.
                for (var c = 0; c < value.length; c++){
                    sumTots += value[c]; 
                    //debug: console.log(sumTots) <--returns each step in the addition.
                }
                return sumTots;
            };

Exercise 4.2

            function reverseArray(array){
                //create newArray to work with.
                var newArray = [];
                //Loop the same number of times as the length of the array using the < operator on array.length
                for (let c = 0; c < array.length; c++){
                    //update newArray with the value in the 'array' that corresponds to the index value matching the length of the array minus the count -1.
                    newArray.push(array[(array.length - c -1)]);
                };
                // return the values from the newArray variable.
                return newArray;
            };
            function reverseArrayInPlace(array1){
                // set a newArray variable equal to the incoming argument.
                var newArray = array1;
                //loop until the counter reaches the length of the array and then stop.
                for (let c = 0; c < newArray.length; c++){
                    // add the value from newArray.length minus the counter to the original array object at the same position as the 'c' counter.
                    array1[c]= (newArray.length - c);
                };
            };
1 Like

Hello fellow IoT members, I’ve kinda done the exercise. However, the last one which is the ReverseArrayInPlace im facing some trouble, I’ve managed to make it run and it produces a result. However, I tried to re-run the function by using the same reverseArrayinPlace(arrayExercise) and it will not display anything and cause my browser to hang, but the typeof arrayExercise is still considered object before and after running the function. Below is the code and any help would be appreciated!

//reverseArrayInPlace
let arrayExercise =[1,2,3,4,5,6,7,8,9,10];
let newArray = [];

function reverseArrayinPlace(){
let arrayLength2=arrayExercise.length

for (x=0; x<arrayExercise.length; x++){
    newArray.push(arrayExercise[arrayLength2-1]);
    arrayLength2--;
}
arrayExercise=[];
arrayExercise=newArray;
console.log(arrayExercise); 

}
image

*When trying to re-run reverseArrayinPlace(arrayExercise) again, no results and the browser just kinda hangs

1. The sum of a range

var range = (start,stop,step = 1) => Array.from( { length : (stop - start)/step + 1 } ,
(_,i) => start + i*step);

function sum_range(a,b,step){
var arr = range(a,b,step);
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return {range : arr, sum : sum};
}
console.log(sum_range(1,10,1));

2. Reversing an array

function reverseArray(arr1){
var arr2 = [];
var len = arr1.length;
for (var i = 0; i < len; i++) arr2.unshift(arr1.shift());
return arr2;
}
console.log(reverseArray([1,2,3,4,5]));

function reverseArrayInPlace (arr1){
var n = arr1.length;
var m = Math.floor(n/2);
for (var i = 0; i < m ; i++) {
var temp = arr1[n-1-i];
arr1[n-1-i] = arr1[i];
arr1[i] = temp;
}
return arr1;
}
console.log(reverseArrayInPlace([1,2,3,4,5,6,71]));

1 Like

Hey @KK_Cheah
The Error I got on my machine while running your code is ā€œx is not definedā€.
var x = 0; // correct
In the aforementioned code, this reverseArrayinPlace() is missing. Otherwise, it’s going great.

1 Like

Thanks for the reply @tanu_g. Appreciate the feedback ! =)

Yeah the code runs and for my case it isn’t the declaration of x as a variable that is the issue. The issue is if my array for example is [1,2,3,4,5] and i execute the reverseArrayinPlace() , the result will be [5,4,3,2,1] and it does execute as such. However, i was interested to re-run the function reverseArrayinPlace() to change back the array to its former [1,2,3,4,5] and that causes my console to freeze up and say DevTools: rendering process gone and I was wondering is there an error causing such or is the exercise really meant for single execution and not to call the function again as an error will be resulted.

Hi @KK_Cheah,
I made a few modifications to your code. I hope this is what you’re looking for.

function reverseArrayinPlace(arrayExercise){
let newArray = [];
let arrayLength2 = arrayExercise.length

for (var x=0; x<arrayExercise.length; x++){
newArray.push(arrayExercise[arrayLength2-1]);
arrayLength2 --;
}
arrayExercise=[];
arrayExercise=newArray;
console.log(arrayExercise);
return arrayExercise;
}
reverseArrayinPlace(reverseArrayinPlace([1,2,3,4,5,6,7,8,9,10]));

Specifically, in the exercise of reverseArrayInPlace, we are supposed to work solely on the argument array rather than taking a new array for operations.

1 Like

The assignment does say that, but just wanna fiddle around to break it and somehow it did. Thank you for spending your time on the solution though. Much appreciated =)

1 Like

I went through the answers and I feel like a complete moron. I don’t understand where the " step" come from.

1 Like

SUM FUNCTION

function sum (start, end) {
var sum = 0
for(counter = start; counter <= end; counter++) {
sum = counter + sum;
}
return sum;
}

RANGE FUNCTION

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

RANGE FUNCTION MODIFIED

function range (start, end, step) {
var array = []
if (step == null) {
if (start<end) {
for(counter = start; counter <= end; counter ++) {
array.push(counter);
}
return array;
}
else {
for(counter = start; counter >= end; counter --) {
array.push(counter);
}
return array;
}
}
if (start<end & step>0) {
for(counter = start; counter <= end; counter += step) {
array.push(counter);
}
return array;
}
if (start<end & step<0) {
console.log(ā€œnot definedā€);
}
if (start>end & step>0) {
console.log(ā€œnot definedā€);
}
if (start>end & step<0) {
var newstep = Math.abs(step);
for(counter = start; counter >= end; counter -= newstep) {
array.push(counter);
}
return array;
}
};

1 Like
var sum2 = function (arr) {
    var total = 0;

    for (let i = 0; i < arr.length; i++) {
        total = total + arr [i];
    }
     return total;
};
console.log(sum(range(1, 10)));
console.log(sum2(range(1, 10)));
const reverse = (arr) =>{
    let result =[]
    for(let elem of arr) {
        result.unshift(elem)
    }
    return result
}

const arr = [1,2,3,4,5,6,7,8,9]
console.log(arr)
console.log(reverse(arr))
console.log(arr)
1 Like
<script type="text/javascript">
      function rangeS(start, end, step){
        let arr = [start];

        if(start < end){
          let _step = 1;
          if(step){
            _step = step;
          }
          for(let index = start + _step; index <= end; index += _step){
            arr.push(index);
          }
        }else if(start > end){
          let _step = -1;
          if(step && step < 0){
            _step = step;
          }
          for(let index = start + _step; index >= end; index += _step){
            arr.push(index);
          }
        }
        return arr;
      }
      console.log(rangeS(1,10));
      console.log(rangeS(1,10,2));
      console.log(rangeS(10,1));
      console.log(rangeS(10, 1, -2));
      console.log(rangeS(4,4));

      function sumOfRange(arr){
        let len = arr.length;
        let sum = 0;
        for(let i = 0; i < len; i++){
          sum += arr[i];
        }
        return sum;
      }

      console.log(sumOfRange(rangeS(1,10)));
      console.log(sumOfRange(rangeS(1,10,2)));
      console.log(sumOfRange(rangeS(10,1)));
      console.log(sumOfRange(rangeS(10, 1, -2)));
      console.log(sumOfRange(rangeS(4,4)));

      function reverseArray(arr){
        let arrToReturn = [];
        let len = arr.length;
        for(let i = 0; i < len; i++){
          arrToReturn.push(arr.pop());
        }
        return arrToReturn;
      }

      function reverseArrayInPlace(arr){
        for(let i = 0; i < arr.length/2 ; i++){
          let swap = arr[i];
          arr[i] = arr[arr.length - i - 1];
          arr[arr.length - i - 1] = swap;
        }
        return arr;
      }
      console.log(reverseArray([1,2,3,4,5,6,7]));
      console.log(reverseArrayInPlace([1,2,3,4,5,6,7]));
      console.log(reverseArray([1,2,3,4,5,6,7,8]));
      console.log(reverseArrayInPlace([1,2,3,4,5,6,7,8]));
    </script>
1 Like

I would love to take credit for all of this… But google was 100% my friend lol.
I hope the notes will help people understand quicker and/or more intuitively. If the format is confusing just copy/paste into atom to iron it out. Personally I wouldn’t have been able to complete the task otherwise. Baby steps are still steps forward!

      //range function
      function range(start, end, step){
        //create result array
        var result = [];
        //test to see if we have step(increment), otherwise set to 1
        if (step == undefined)
          increment = 1;
        //calculate the number of times to loop (up or down)
        numLoops = math.abs((end - start) / increment) + 1;
        //loop this many times
        for (var i = 0; i < numLoops; i++){
          //add (push) to result array
          result.push(start);
          //step(increment) the value of start
          start += step;
        }
        //return array with all contents
        return result;
      }
      function sum(numArray){
        //set a variable to hold sum
        var arrayTotal = 0;
        //see how many numbers are in array
        numLoops = numArray.length;
        //loop that many times
        for (var i = 0; i < numLoops; i ++){
          arrayTotal += numArray[i];
        }
        //return sum
        return arrayTotal;
      }
     function reverseArray(arr){
        var newArray = [];
        //set i as the array length, meaning the last index value.
        //(array.length - 1) sets the value as the last index (starts from 0) and goes down by 1 from there
        //push(arr[i]) adds the index value to the new array
        for (var i = array.length - 1; i >= 0; i--){
          newArray.push(arr[i]);
        }
        return newArray;
      }
      //reverse array in place (array values are reversed in the existing array)
      function reverseArrayInPlace(arr){
        //start at beginning or end and finish when i is half array length
        //subtract 1 from length to account for even numbers, math.floor to round down nearest whole number
        for (var i = 0;  i <= Math.floor((arr.length - 1) / 2); i++){
          //set first element to el, set first element equal to last, and last equal to first (el)
          let el = arr[i];
          arr[i] = arr[arr.length - 1 - i];
          arr[arr.length - 1 - i] = el;
        }
        return arr;
      }
1 Like