Chapter 4 - Exercises

Same boat here bro. Been learning JavaScript for months now haha

Hi,
This is the solution from the book:

// I can’t figure this one out. Can someone please explain:
in the loop why is the condition set to 2? Loop is programmed to stop when it reaches 2 is what I see. Is this right?

// also the variable old - I don’t understand the purpose of this variable, it doesn’t seem necessary.

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 = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1];

// RANGE FUNCTION – range(1,40,-2); //[40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
function range(x,y,z){
let array = [], maxValue=y;
if(z<0) {y=x;x=maxValue;}; // swap values if descending array
for(let i=0;i<Math.abs(maxValue/z);i++){
array[i] = x;
x+=z;
}
return array;
}

// SUM FUNCTION – sum(range(1,5,1)); //15
function sum(array){
let sum = 0;
for(let i=0;i<array.length;i++){
sum+=array[i];
}
return sum;
}

//REVERSE – reverseArray(range(1,20,-2)); //[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
function reverseArray(array){
let reversedArray = [];
let x = array.length-1;
for(let i=0; i<array.length;i++){
reversedArray[i] = array[x];
x–;
}
return reversedArray;
}

//REVERSE IN PLACE --myArray-range(1,20,2); reverseArrayInPlace(myArray); //[19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
function reverseArrayInPlace(array){
let x = array.length-1;
for (let i=0;i<parseInt(array.length/2);i++){
let tmp = array[i];
array[i] = array[x];
array[x] = tmp;
x–;
}
return array; // return for convenience
}

1 Like

The sum of a range

  1. a) function range(start, end) {
    var result = [ ];
    for ( let y = start; y <= end; y++)
    { result.push(y); }
    return result; }
    console.log( range(1,10) );

b) function sum(total,count)
{var total = 0, count = 1;
while (count <= 10)
{total += count;
count ++;}
return total; };
console.log(sum(1,10));

  1. a) function range(start,end,step) {
    var result = [ ];
    for (let y= start; y< end; y+=step)
    { result.push(y) ; }
    return result ; };
    console.log( range(1,10,2) );

b) function range(start,end,step)
{ var result = [ ];
for (var y=start; y>=end; y+=step)
{ result.push(y) }
return result ; };
console.log( range(5,2,-1) );

Reversing an array

  1. function reverseArray()
    {var reverseArray=[1,5,7,9].reverse( ); return reverseArray ; } ;
    console.log( reverseArray( ) );

  2. function reverseArrayInPlace(array)
    { var result = [ ];
    for (var y = array.length - 1; y >= 0; y–)
    { result.push(array[y]) ; }
    return result ; };
    console.log(reverseArrayInPlace( [2,4,7,9] ) );

1 Like

Here is my solution.

  <script type="text/javascript">
    //the sum of a range
    let range = function (start, end, step=1){
      output=[];
      if(start<end){
        for(let number=start; number<=end; number+=step){
          output.push(number);
        }
      }
      else if(start>end){
        for(let number=start; number>=end; number+=step){
          output.push(number);
        }
      }
      return output;
    };
    let computeSum = function(numbers){
      output=0;
      for(let iter=0; iter<numbers.length; iter++){
        output+=Number(numbers[iter]);
      }
      return output;
    }

    //reversing an array
    let reverseArray = function(givenArray){
      let output=[]
      for(let i=givenArray.length-1; i>=0; i-=1){
        output.push(givenArray[i])
      }
      return output;
    }
    let reverseArrayInPlace = function(givenArray){
      let temp=[];
      for(i=0;i<givenArray.length;i++){
        temp[i]=givenArray[i];
      }
      for(i=0; i<givenArray.length; i++){
        givenArray[i]=temp[givenArray.length-1-i];
      }
    }
  </script>

The sum of a range:

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

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

    // example 1

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

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


    // example 2

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

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

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

Reversing an array

const reverseArray = function(array) {

let newArray = [];
array.forEach( (item) => newArray.unshift(item))
return newArray;
}

const answer = reverseArray([1, 2, 3]);

var reverseArrayInPlace = function(array) {

var left = 0;
var length = array.length;
while(left < length) {
array.push(array[length - 1 - ++left]);
array.splice(length - 1 - left, 1);
}
return array;
}

var secondAnswer = reverseArrayInPlace([1,2,3, 4]);
console.log(secondAnswer);

1 Like

hello. Did you figure it out? I don’t get it either

Where should i put an array of numbers to check if it runs_?
(array) ???

Hi, know, and I can’t remember this one anymore. The theory is confusing, I would like more practice personally.

1 Like

I was able to get the first two parts of the first question to work, but had to look to the answer to see how the step might work.

// Q1 Part 1:  Prints the range input from "console.log(range(1, 10));"

var range = function (start, end){

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

    
    console.log(range(1, 10)); 
    
// Part 2 -------------------------------------------->

function sum(array){
    var total = 0;
    for ( var i = 0; i < array.length; i ++ )
    total += array[i];
    return total;
};    
console.log(sum(range(1, 10))); 

_______________-

1 Like

// Ch4_Q2_A - Doesn't change array [non mutating]
// creates temp version and reverses it, hence original array remains unchanged

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

  array = ['a','b','c','d','e']
  console.log(array);
  console.log(reverseArray(array));
  console.log(array);


  // Ch4_Q2_B - Changes array by flipping in place [mutates]

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

  array = ['a','b','c','d','e']
  console.log(array);
  console.log(reverseArrayInPlace(array));
  console.log(array);
  
1 Like

The sum of a range:
function range(start, end) {
var result = [ ];
for ( let y = start; y <= end; y++)
{ result.push(y); }
return result; }
console.log( range(1,10) );

function sum(total,count)
{var total = 0, count = 1;
while (count <= 10)
{total += count;
count ++;}
return total; };
console.log(sum(1,10));
//IT DOES RETURN 55

Reversing an Array:
function reverseArray()
{var reverseArray=[1,2,3,4].reverse( ); return reverseArray ; } ;
console.log( reverseArray( ) );

1 Like

THE SUM OF RANGE

function rangeArray(min, max, step = 1){
        var array = [];
        if(min < max){
          for(var i = min; i < max+1; i = i + Math.abs(step)){
            array.push(i);
          }
        }
        else if(min > max){
          for(var i = min; i > max - 1; i = i - Math.abs(step)){
            array.push(i);
          }
        }

        return array;
      }
      console.log(rangeArray(5,2,1));
      function sum(arr){
        var totalSum = 0;
        for(var i = 0; i <arr.length;i++){
          totalSum += arr[i];
        }
        return totalSum;
      }
      console.log(sum(rangeArray(1, 10)));

REVERSING AN ARRAY

var array = [1, 2, 3, 4, 5, 6];
function reverseArray(arr){
  var newArr = [];
  for(var i = arr.length; i > -1; i--){
     newArr.push(arr[i]);
  }
  newArr.shift();
  return newArr;
}

function reverseInPlace(arr){
   var count = arr.length -1;
   for(var i = 0; i < (arr.length/2); i++){
        var num1= arr[i];
        var num2= arr[count];
        arr[i] = swapValues(num1, num2);
        arr[count] = swapValues(num2, num1);
        count--;
   }
  return arr;
}
function swapValues(a,b){
   var c = a;
   a=b;
   b=c;
   return a;
}
console.log("ReverseArray function: " + reverseArray(array));
console.log("ReverseInPlace function: " + reverseInPlace(array));
1 Like

1 -

function range (start, end) {
              var array = [];
               for (let i = start; i <= end; i+= step) {
                               array.push(i);
               }
        return array;
        }
        console.log(range(1,10));
function sum (array) {
              let total = 0;
              for (let value of array) {
                    total += value;
        }
        return total;
    }
    console.log(sum(range(1,10)));

2 -

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 = 0; i <= end; i += step)
                             array.push(i);
              }
              else {
                       for (let i = 0; i >= end; i+= step)
                              array.push(i);
             }
             return array;
       }
             console.log(range(1,10,2);

3 -

function reverseArray = (array) {
              let reverseArray = [];
              for (let i = 0; i < array.length; i++) {
                    reverseArray.unshift (array [i]);
              }
              return reverseArray;
              }
              console.log(reverseArray([1, 2, 3]);

4 -

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

** Had to look the answer for this last question up, very good problem, had me totally stuck! **

1 Like
//the sum of range
function range(start, end){
	let array = [ ];

	for (let i = start; i <= end; i++){
		array.push(i);
	}
	return array;
}
console.log(range(-1,10));


//reversing an array
function reverseArray(array){
  var result = [];
  for(var i = array.length - 1; i >= 0; i--){
    result.push(array[i]);
  }
  return solution;
}

//reverseArrayInPlace
function reverseArrayInPlace(array){
  for(var i = 0; i < Math.floor(array.length/2); i++){
    var current = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = current;
  }
  return array;
}
var arrayValue = [1,2,3,4,5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
2 Likes
  1. The sum of a range:
function range(start, end){
        var field = [];
        cnt = start;

      while (cnt <= end){
        field.push(cnt);
        cnt++;
      }
      return field;
    };
    function sum(arr){
      var total = 0;

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

Here is another way to do it :

function range2(start, end){
      var arr = [],
          cnt = start;
      function increaseCnt(cnt) {
        if (cnt >= end){
            return arr.push(end);
        } else {
            arr.push(cnt);
            increaseCnt(++cnt);
        }
      };
      increaseCnt(cnt);
      return arr;
    };

    function sum3(arr) {
      return arr.reduce(function(tot, val) {
        return tot + val;
      });
    };
    console.log(sum3(range2(1, 10)));

Reversing an array:

var arr = [1, 2, 3, 4, 5]
      var arr2 = [];

        function reverse(arr) {

          while (arr.length > 0) {
            arr2.push(arr.pop());

          }
          return arr2;
        };

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

1. The sum of a range.
function range(start, end, step){
let array = [];

for (let x = start; x<=end; x+=step){
array.push(x);
}
return array;
}

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

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

returns [1, 3, 5, 7, 9] and sum of 25

2. Reversing an array
function range(start, end){
let array = [];

for (let x = end; x>=start; x–){
array.push(x);
}
return array;
}

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

2 Likes

Thank you! really like your solution :blush:

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 = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1];

1 Like