Chapter 4 - Exercises

Hey @Gemstar, To give you a little perspective, Sometimes it takes time to mould our thought process to write algorithms like these. These problems are meant to be hard so that you can trial and error all sorts of ways and thus strengthening your fundamentals.
If you aren’t comfortable solving them, I would like you to continue with the course. Perhaps when you go through the course, you become more familiarised with language and structure, that coming back to this question will become inherently easier. It worked for many students as well.

Do not lose hope. We are here to sort things out. :slight_smile:

Happy Learning! :slight_smile:

4 Likes
  1. The sum of a range.
    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;
    };
    console.log(sum(range(1, 10)));
  2. Reversed array
    const reverseInPlace = (arr) => {
    let temp;
    for(let 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;
    }
    const arr = [“A”, “B”, “C”];
    console.log(reverseInPlace(arr));
1 Like

Thanks, Malik. Appreciate it.

1 Like
//The sum of a range with optional step
function range(start, end, step = 1){
  let rangeArray = [];
  for(start; start <= end; start += step){
      rangeArray.push(start);
  }
  return rangeArray;
}

function sum(inputArray){
  let arraySum = 0;
  $.each(inputArray, function(index, value){
    arraySum += value;
  });
  return arraySum;
}

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


//reverse array
var arr = [1,2,3,4,5];
function reverseArray(arrayToReverse){
  let reversedArray = [];
  $.each(arrayToReverse, function(index, value){
    reversedArray[arrayToReverse.length - index - 1] = value;
  });
  return reversedArray;
}
console.log(reverseArray(arr));
//-> [5, 4, 3, 2, 1]

function reverseArrayInPlace(arrayToReverse){
  let start = 0;
  let end = arrayToReverse.length-1;
  while (start < end) {
    let temp = arrayToReverse[start];
    arrayToReverse[start] = arrayToReverse[end];
    arrayToReverse[end] = temp;
    start++;
    end--;
  }
  return arrayToReverse;
}
console.log(reverseArrayInPlace(arr));
//-> [5, 4, 3, 2, 1]
1 Like

@jonny1 btw, have you seen Ivan live today?
He said someting about small consistent effort each day which adds up.

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

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

Not a fan of these exercises

1 Like

This is the first exercise that is almost like greek to me

Like most people on this forum, I found these two assignments to be incredibly difficult, and I ended up having to look up the answers. However, even after copying the answers, I couldn’t get the reverse array question to come out correctly.

  <script>
  //The Sum of an 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,10))
    console.log(range(5, 2, -1))
    console.log(sum(range(1,10)))

    //Reverse 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.lentgh - 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);

  </scrip>

I’ve broken down the 1st exercise into steps so I can get each part working and I can’t get the range to print correctly.

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

When I enter this on the eloquent javascript exercises section I get the error SyntaxError: Unexpected token ‘)’ . I know that this means it thinks there is a “)” that shouldn’t be there, but I can’t find it for the life of me, and I can’t see why the actual solution (I checked after battling with this for a good while) can produce the range of numbers but mine can’t, as there aren’t any major differences.

Anyone able to pick out the cause of the error in my code?

Edit: FOUND IT!! I had a comma instead of a semi colon after “i <= end”. Will continue working on it from here

1.The sum of a range

in solution “for (let value of array)” is used, why shouldn’t it be “for (let value of array.value)” ?

2.Reversing an array
image
The reverseArrayInPlace of solution is different and complicated, does it do different operation in comparison with mine?
3.A List

Thank you very much Simon for taking the time to explain this to me. Really helped me understand this more.

1.)


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

2.)

// shorter simplified reverse function

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

console.log(reverseArray(["A", "B", "C"]));
console.log(reverseArray([1, 2, 3, 4, 5]));
console.log(reverseArray(["Ivan", "on", "Tech"]));

/* Output =
["C", "B", "A"]
[5, 4, 3, 2, 1]
["Tech", "on", "Ivan"]
*/

1 Like
MakeArray=function(start, end, step=1)
  {
    let numbers=[];
    if(step>0)
    {
      for(i=start;i<end+1;i=i+step)
      {
        numbers.push(i);
      }
    }
    else
    {
      for(i=start;i>end-1;i=i+step)
      {
        numbers.push(i);
      }
    }
    return numbers;
  }

  PrintNumbers=function(numbers)
  {
    for(i=0;i<numbers.length;i++)
    {
      document.write(numbers[i]+" ");
    }
  }

  var numbers= MakeArray(10,1,-2);
  PrintNumbers(numbers);

2.

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

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

  PrintNumbers=function(numbers)
  {
    for(i=0;i<numbers.length;i++)
    {
      document.write(numbers[i]+" ");
     
    }
  }

  PrintNumbers(reverseArrayInPlace([5,6,7,8,9]));

Hello @muradawad, hope you are great.

Please use the “Preformatted Text” Button to encapsulate any kind of code you want to show.


function formatText(){

let words = “I’m a preformatted Text box, Please use me wisely!”

}

prefromatted_text-animated

Carlos Z.

1 Like

Reversing an array

// Make a function that takes an array and returns it reversed
function reverseArray(arr) {
  // New array for the reversed numbers
  var newArr = [];

  // For loop to loop through the index
  for(i = 0; i < arr.length; i++) {
    // New array index = to the length of the array - i - 1
    newArr[i] = arr[arr.length - i - 1];
  }
  // Returns the new array
  return newArr;
}
1 Like

Sum Of a Range

    var rangeValues = [];
    var total = 0;

   function range (num1, num2, step=1){
     rangeValues = [];
     if (step > 0){
       for (x=num1; x<= num2; x+=step){
         rangeValues.push(x);
       }
     }
     else if (step < 0){
         for (x=num1; x>= num2; x+=step){
           rangeValues.push(x);
       }
     }
     else { console.log("Invalid step value"); }

     return rangeValues;
   }

   function sum (rangeArray) {
     total = 0;
     for (x=0; x< rangeValues.length; x++){
       total += rangeValues[x];
     }
     return total;
   }

console.log(range(1, 10));
console.log(sum(range(1,10)));
console.log(range(5, 2, -1));
console.log(range(3, -6, -2));
console.log(range(3, -6, 0));

// Output
// (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// 55
// (4) [5, 4, 3, 2]
// (5) [3, 1, -1, -3, -5]
// Invalid step value`

`

1 Like

Reversing An Array


   myArray1 = [1,2,3,4];
   myArray2 = [1,2,3,4,5];
   myNewArray = [];

   function reverseArray (array) {
     //makes new array in reverse order
     let x = array.length;
     for (x; x > 0; x--) {
       myNewArray.push(x);
     }
     return myNewArray;
   }

   function reverseArrayInPlace(array) {
        //returns existing array in reverse order
     for(let i = 0; i <= Math.floor((array.length-1)/2); i++){
       let val = array[i];
       array[i] = array[array.length-1-i];
       array[array.length-1-i] = val;
     }
     return array;
   }

console.log(reverseArray(myArray1));
//(4) [4, 3, 2, 1]
console.log(reverseArrayInPlace(myArray2));
//(5) [5, 4, 3, 2, 1]
1 Like
  1. The Sum of A Range:
<html>
  <head>
<title>2020Chap4sumOfARange</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
      <script>

      var range = function(start, end, step) {
            var arr = [];
            for (var i = start; step>1 || step === undefined ? i <= end : i >= end;
            step ? i = i + step : i++)
            arr.push(i);
            return arr;
      };

      var sum = function(arr) {
            return arr.reduce(function(x,y){
                  return x + y;
            });
      };
      //tests
      console.log(sum(range(1,10)));
      //55
      console.log(range(1,10));
      // 1.2.3.4.5.6.7.8.9.10
      console.log(range (1,10,2));
      // 1,3,5,7,9,

      </script>
  </body>
</html>

  1. Reversing An Array:
<html>
  <head>
<title>2020reversingAnArray</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
      <script>

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

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

      //tests
      console.log(reverseArray(['A', 'B', 'C']));
      // "C", "B", "A"
      var arrayValue = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      reverseArrayInPlace(arrayValue);
      console.log(arrayValue);
      // 9,8,7,6,5,4,3,2,1

      </script>
  </body>
</html>

1 Like
  1. Write a range that takes two arguments “start” and “end”, and returns an array containing all the numbers from “start” up to (and including) “end”.

function range(start, end) {
var sum =0;

for (var i = start; i <= end; i ++)
sum += i;
document.write(sum);
}
range (1,10);
console.log(sum(range(1, 10)));

  1. Write the sum of a function that takes an array of numbers and returns the sum of those numbers.

function range(start, end){
let arrayRange = [];

for (i = start; i<=end; i++) {arrayRange.push(i);

}
return arrayRange;
}
console.log (sum(range(1, 10))):

  1. Modify the “range” functions to take an optional third argument that indicates the “step” value used when building the array.

function range(start,end,step){
let array=[];
for (i=0; i<=(end-start)/step; i++){
array.push(start+i*step);
}
return array;
}

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

  1. Write a function that takes an array as an argument and produces a new array that has the same elements in the inverse order.

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

console.log(reverseArray([“A”, “B”, “C”]));

  1. Write a function that also modifies the array given as an argument by reversing its elements.

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(reverseArrayInPlace([“1”,“2”,“3”,“4”,“5”]));

Range Function with Step:
image

Sum Function:
image )

Reversing Array Function:
image

1 Like