Chapter 4 - Exercises

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

console.log(range function 1 to 10: ${range(1,10)})

SUM:
function sum(arr) {
let sumArr = 0
for (num of arr) {
sumArr = sumArr + num
}
return sumArr
}

console.log(sum/range function 1 to 10: ${sum(range(1,10))})

RANGE STEP:
function rangeStep(start, end, step=1) {
let rangeArray = []
if (step < 0){
for (let i=start; i >= end; i = i + step) {
//console.log(i)
rangeArray.push(i)
}
}
for (let i=start; i <= end; i = i + step) {
//console.log(i)
rangeArray.push(i)
}
return rangeArray
}

console.log(rangeStep function {rangeStep(1,10,2)}: ${rangeStep(1,10,2)})
console.log(rangeStep function {rangeStep(5,2,-1)}: ${rangeStep(5,2,-1)})
console.log(rangeStep function {rangeStep(1,10)}: ${rangeStep(1,10)})

REVERSE ARRAY:
function reverseArray(arr){
reverseArr = []
for (element of arr){
reverseArr.unshift(element)
}
return reverseArr
}

console.log(reverseArray {reverseArray[1,2,6,7]}: ${reverseArray([1,2,6,7])})

REVERSE ARRAY IN PLACE:
function reverseArrayInPlace(arr){
let l = arr.length
for (let i = 0; i < l; i++){
arr[l * 2 - i - 1] = arr[i]
}
for (let i = 0; i < l; i++){
arr.shift()
}
return arr
}

console.log(reverseArrayInPlace {reverseArrayInPlace([11,12,16,17])}: ${reverseArrayInPlace([11,12,16,17])})

1 Like

My Solutions to the Chapter 4 exercises:

            <script>
                // Sum of Range Exercise
                function rangeArray(start, end, step = 1) {
                    let arrayNums = [];
                    for(let i = start; i <= end; i+=step){
                        arrayNums.push(i);
                    }
                    return arrayNums;
                }

                function sumOf(numberArray) {
                    let total = 0;
                    for(each of numberArray) {
                        total += each;
                    }
                    return total;
                }

                console.log(sumOf(rangeArray(1,10)));

                // Reversing an Array
                function reverseArray(anArray){
                    let reversed = [];
                    let original = anArray.concat();
                    
                    let numElems = anArray.length;
                    for( i = 0; i<numElems; i++) {
                        reversed.push(anArray.pop());
                    }
                    
                    for( i = 0; i < numElems; i++){
                        anArray.push(original.shift());
                    }
                    
                    return reversed;
                }

                function reverseArrayInPlace(anArray){
                    let reversed = [];
                    let numElems = anArray.length;
                    for( i = 0; i<numElems; i++) {
                        reversed.push(anArray.pop());
                    }
                  
                    for( i = 0; i < numElems; i++){
                        anArray.push(reversed.shift());
                    }
                    
                }

                let testArray = [10, 20, 30, 40, 50];
                console.log("Test Array Contains: "+testArray);
                console.log("reverseArray Returns: " + reverseArray(testArray));
                console.log("Test Array Contains: " + testArray);
                reverseArrayInPlace(testArray);
                console.log("After reversing in place Test Array contains: " + testArray);
            </script>
1 Like

Ch. 4 Exercises

Range function

      function range(begin,end) {
        let endOfSequence = end-begin+1 // number of elements
        let rangeArray = [];
        let start = begin;

// Create array whose values start at ‘begin’

        for(let i=0; i<endOfSequence; i++){
          rangeArray.push(start);
          start++;
        }
        console.log(rangeArray);
        return rangeArray;
      }

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

Sum function

Note: function sum calls the previously submitted function range

// The argument anArray is the array returned by the previous range function
function sum(anArray){
let sumOfArray=0
$.each(anArray, function(index,value){
sumOfArray = sumOfArray + value;

        })

        return sumOfArray;

}

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

Range function with optional third argument

// Note: Function range2 calls function reverseRange and the previously submitted function
// range

// reverseRange reverses the values of the elements of an array
// It is used by the range2 function to readily implement negative step values e.g. -4, etc.
function reverseRange(begin1, end1){
let endOfSequence = end1-begin1+1
let revRangeArray = [];
let start = begin1;

        for(let i=0; i<endOfSequence; i++){
          revRangeArray.unshift(start);
          start++;
        }

        return revRangeArray;

      }

// If step is undefined or 1 we use the previous range function

// If step is negative we call reverseRange to flip the order of the array so the
// values are flipped so we have last value to first value
// For step < -1 and step >1 we can now build the final array by iterating using step
// value in the case of positive steps and the absolute value of step in the case of negative // steps
function range2(begin1, end1, step) {

        let range2Array = [];
        let tempRange2Array = [];
        if (step == 0){console.log("0 is not a valid step value")}
        else if (step===undefined || step == 1){range2Array = range(begin1,end1);}
        else if (step>1){tempRange2Array = range(begin1,end1);}
        else  {step=0-step; tempRange2Array=reverseRange(begin1,end1);}
        console.log(tempRange2Array.length);

        if (step > 1 || step <-1){
          outputIndex=0
          for (let j=0; j<tempRange2Array.length; j=j+step){
            range2Array[outputIndex] = tempRange2Array[j];
            outputIndex++;

          };
        };
        return range2Array;

      }

Reversing an Array

      function reverseArray (anArray) {
        let rArray = [];
        let j=anArray.length - 1;
        for(let i=0; i<anArray.length; i++){
          rArray[i] = anArray[j];
          j=j-1;

        }

        return rArray;
      }

      theReverseArray=console.log(reverseArray(fruits));

Reversing an Array in Place

// First for loop places values in reverse order by prepending them to the array
// Second for loop pops the original values off the array leaving only the values
// that were reordered by the 1st loop
//

function reverseInPlaceArray (anotherArray) {
iterations=anotherArray.length-1
let j=1;
for(let i=0; i<iterations; i++){
anotherArray.unshift(anotherArray[j]);
j+=2;

        }
        for(let k=0; k<iterations;k++){
          anotherArray.pop();
          }
      }
1 Like

Your code gave me an idea on how to do the in place array reversal with one loop and in half the iterations, thanks for sharing!

Here’s the code if interested:

function reverseArrayInPlace2(anArray){
                    let numElems = anArray.length;
                    for( i = 0; i<(numElems/2); i++) {
                        let temp = anArray[(numElems - i)-1];
                        
                        anArray[(numElems - i) - 1] = anArray[i];
                        anArray[i] = temp;
                    }
                    
                }
1 Like

Curt That’s an interesting approach. You use one loop and save on the number of operations. On an 11 element array your function performs 18 writes which improves on my function that does 10 writes and 10 pops (20 manipulations total). Thanks for sharing your function.

1 Like

Its basically bubble sort without the comparison check

1 Like

The sum of an array

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

function sum(item){
  return item.reduce(function(previous, current){
    return previous + current;
  });
}

Reflection: made a few mistakes here and there. Initially, I had placed the array outside the function, which meant that every time I added a new number, or changed the array range, it would add repeat elements inside. Shifted the array into the function and it worked out fine.

Had trouble working out the reduce() function, and still getting used to the idea of anonymous functions. Also, I was stuck during the bonus assignment portion. I was writing many lines of code when the array when from big to small. Turns out the solution was very concise indeed, by using conditionals.

Reverse Array

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

For reverseArrayInPlace, I referred the the solution. My code could not replace the index without messing it up. True to its title, the book’s solution is very concise.

1 Like

Here are my Solutions for reverseArray & reverseInPlace functions

function reverseArray(l){
// This Function takes Array l and outputs the reverse of the array x
var x = [];
var i = (l.length);
do{
i --;
x.push(l[i]);
}while (i != 0);
return x;
}

function reverseInPlace(l){
// This Function takes Array l and outputs the reverse of the array x.
// It does this swapping the elements.
var h1;
var h2;
var counter = 0;
var counter2 = (l.length);
	do{
		counter2 --;
		h1 = l[counter];
		h2 = l[counter2];
		l[counter] = h2;
		l[counter2] = h1;
		counter ++;
	}while(counter != counter2);	
			return l;
	
}
2 Likes

**Copy paste fo the eloquent solution to the range and sum problem with a few comments.
Was only able to fully comprehend the first solution. So any help in understanding these solutions would be highly appreciate. Could be a video, an article, or your own argument. cheers.! **

//This function creates the array with the desired conditions

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

/think of the question mark as “then” & the colon as “else”.
condition ? value-if-true : value-if-false
/

let array = []

if (step > 0) {
for (let i = start; i <= end; i+=step) array.push(i);

// i is such that, if < end then i+=1, else i+=-1.

}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));
console.log(range(5,2));
console.log(sum(range(1,10)))

**
GUYS CAN SOMEONE HELP EXPLAIN HOW THE solution to the reverseArrayInPlace is fourmulated?

**
//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.lenth - 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);

DEEP COMPARISON

function deepEqual(a, b) {
if (a === b) return true

if (a == null || typeof a != “object” ||
b == null || typeof b != “object”) return false;

  let keysA = Object.keys(a), keysB = Object.keys(b);

  if (keysA.length != keysB.length) return false;

  for (let key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  }

  retrun true;
}

let 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}));
1 Like

Hi
My understanding is that they return the same value.
The only difference is that Inplace does an element by elmement swap. May be handy if you are dealing with an array of objects.
However I agree ! this realy isn’t very clear what is required.

2 Likes
function range(startNumber,endNumber,step){
  var newArray=[];
  if(!step){
    step=1;
  }
  if(step<0){
    for(let i=endNumber; i >=startNumber; i=i+step){
      newArray.push(i);

    }
  }
  else{
    for(let i=0; i<=endNumber-startNumber; i+=step){
      newArray.push(startNumber+i);
    }
  }
  return newArray;
}
function sum(anArray){
  var count=0;
  for(let i=0; i < anArray.length ; i++){
    count+=anArray[i];
    //console.log(anArray[i]);
  }
  return count;
}

function reversArray(theArray){
  var revArray=[];
  for(var i=0; i < theArray.length ; i++){
    revArray[theArray.length-1-i]=theArray[i]

  }

  return revArray;
}


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

function reverseArrayInPlace(theArrayInPlace){
  let copyArray=[];
  for(let i=0; i<theArrayInPlace.length ;i++){
    copyArray[i]=theArrayInPlace[i];
  }

  for(let i = 0; i < copyArray.length; i++){
    theArrayInPlace[copyArray.length-1-i]=copyArray[i]

  }

  return theArrayInPlace; 
}
var testArray=range(1,10);
console.log(testArray);
reverseArrayInPlace(testArray);
console.log(testArray);

Answer: The difference between reversArray and reversArrayInPlace is that reversArray takes in an array as an argument an then returns a revers array of this array, it does not change the array given. As for the reversArrayInPlace actually revers the array that is given to the function.

1 Like

THE SUM OF A RANGE

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

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

REVERSING AN ARRAY

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

function reverseArrayInPlace(array) {
    for (i = 0; i < array.length; i ++) {
      	let append = array.pop();
		array.splice(i, 0, append);
    }
    return array;
}
1 Like

This is the first exercise and planning to edit with the second one after I game a bit.


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


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

This is my way of resolving the second part of the exercise. It took me awhile like 30 min or so to understand the method needed to be used and figure out the math behid it. But at the end it worked. If you have a better solution and a different approach tag me with it. I would like to see other options as well. I gazed upon other codes but they were way too spesific as I could observe which I didn’t observe much but this is more general and can be applied to all sorts of arrays. Just like reverse method does.

et arrray =[1,2,3,4,5];

function reverseArray (array) {
    let newArray = [];
    for (let i = 1; i <= array.length; i++) {
       newArray.push(array[array.length - i])
    }
    return newArray
}

console.log(reverseArray(arrray));


function reverseArrayInPlace (array) {
   for (let counter = array.length-1; counter > 0; counter--) {
       array.splice(array.length, 0, array[counter-1]);
       array.splice(counter-1, 1,);
   }
   return array
}

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

2 Likes

Reversing an array

         var temp = [];

        function reverseArray(a) {
          //  var temp = [],
            var len = a.length;
                   for (var i = (len - 1); i !== -1; i--) {    
                temp.push(a[i]);
            }

               console.log(temp);
  //          return result;
        }



        function reverseArrayInPlace(a) {
      var i = 0;
      var j = a.length - 1;

      while (i < j) {
          var x = a[i];
          a[i] = a[j];
          a[j] = x;

          i++;
          j--;
      }
  }

       var a = ['Lucy', 'Cooper', 'Dianne'];

         reverseArrayInPlace(a);
         reverseArray(a);
1 Like

var anArray = [“Apple”, “Banana”, “Citrus”, “Donut”, “Electric”];

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

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

The sum of a range
Got to say I’m getting really tired and bored with the Maths problems

        var arr = [];

        function range(start, end, step) {
      
          if (arguments.length === 1) {
            edge = start;
            start = 0;
          }

          // Validate edge/start
          end = end || 0;
          step = step || 1;

          if ((Math.sign(step)) === -1) {
                       console.log("NEG");
          //          CHECKS FOR NEG VALUE


     // If neg value count down not up
     // the negative number will not act as an operator itself
          for (arr; (end - start) * step > -1; start += step) {
            arr.push(start);
                                                             }

                    }

// If not negative carry on coventional array count
else {
for (arr; (end - start) * step > 0; start += step) {
arr.push(start);
}

              }

          return arr;

        }


  //        range(1, 10, 2); // [10, 12, 14, 16, 18]
        range(5, 2, -1); // [10, 12, 14, 16, 18]

          document.write("<h3> the range is now " + arr + "</h3>" );
1 Like

function addRange(starting, ending){
total = 0
for (num = starting; num <= ending; num++){
total += num;
}
return total;
}

console.log(addRange(1,3));

1 Like

Reverse Array in place

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

The sum of a range

function range(start, end, inc){
var arr = [];
if(inc == undefined) inc = 1;
if(inc > 0){
for(var i = start; i <= end; i=i+inc){
arr.push(i);
}
return arr;
}
if(inc < 0){
inc = Math.abs(inc);
for(var i = end; i >= start; i=i-inc){
arr.push(i);
}
return arr;
}
}
function sum(arr){
var res = 0;
for(var i = 0; i < arr.length; i++){
res += arr[i];
}
return res;
}

1 Like

image

Question 1:
function range(start, end, increment) {
var array = [];
var current = start;

increment = increment || 1;
if (increment > 0) {
    while (current <= end) {
        array.push(current);
        current += increment;
    }
} else {
    while (current >= end) {
        array.push(current);
        current += increment;
    }
}
return array;

}

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

VM120:20 (3) [1, 2, 3]
VM120:21 (4) [2, 3, 4, 5]
VM120:22 (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
VM120:23 (4) [5, 4, 3, 2]

Question 2

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);
1 Like