Chapter 4 - Exercises

This took me quiet a while TBH. Kept running into what turned out to be the tiniest problems mostly, only after hours of googling lol. ALL array tasks (show, sum, step, reverse, and new reverse) included in this one code.

<body>
    <label>Enter a Min number:<br /></label>
    <input type="number" id="minNum" name="minNum" /><br />
    <label><br />Enter a Max number:<br /></label>
    <input type="number" id="maxNum" name="maxNum" /><br />
    <label><br />Enter a step (optional):<br /></label>
    <input type="number" id="stepNum" name="stepNum" /><br />
    <br />

    <button id="showArrayBtn">Show array</button>
    <button id="sumArrayBtn">Sum of array</button>
    <button id="stepArrayBtn">Array in steps</button>
    <br /><br />
    <button id="rvsArrayBtn">Reverse array</button>
    <button id="newRvsArrayBtn">NEW reverse array</button>
    <br /><br />

    <script>
      // global var
      var arr = [];

      // button handlers
      $("#showArrayBtn").click(function() {
        range("show");
      });

      $("#sumArrayBtn").click(function() {
        range("sum");
      });

      $("#stepArrayBtn").click(function() {
        range("step");
      });

      $("#rvsArrayBtn").click(function() {
        if (!arr.length) { // is there an array
          console.log("Please create an array first.");
        } else {
          arr = reverseArray(arr);
          console.log(arr);
        }
      });

      $("#newRvsArrayBtn").click(function() {
        if (!arr.length) { // is there an array
          console.log("Please create an array first.");
        } else {
          reverseArrayInPlace(arr);
        }
      });

      // functions
      function range(chosenBtn) {
        var stepVal = parseInt($("#stepNum").val(), 10);
        var minVal = parseInt($("#minNum").val(), 10);
        var maxVal = parseInt($("#maxNum").val(), 10);

        if (chosenBtn == "show") {
          arr = [];
          for (x = minVal; x <= maxVal; x++) {
            arr.push(x);
          }
          console.log(arr);
        } else if (chosenBtn == "sum") {
          arr = [];
          var arrSum = 0;
          for (x = minVal; x <= maxVal; x++) {
            arr.push(x);
            arrSum += x;
          }
          console.log(arrSum);
        } else if (chosenBtn == "step") {
          // is a positive int
          arr = [];
          for (x = minVal; x <= maxVal; x += stepVal) {
            arr.push(x);
          }
          console.log(arr);
        } else if (stepVal < 0) {
          // is a negative int
          arr = [];
          for (x = minVal; x >= maxVal; x += stepVal) {
            arr.push(x);
          }
          console.log(arr);
        } else {
          range("show");
        }
      }

      function reverseArray(nRa) {
        var tempRvsArr = [];
        for (c = 0; c <= nRa.length; c++) {
          if (c > 0) {
            tempRvsArr.push(nRa[nRa.length - c]);
          }
        }
        return tempRvsArr;
      }

      function reverseArrayInPlace(rA) {
        var tempRvsArr = [];
        for (c = 0; c <= rA.length; c++) {
          if (c > 0) {
            tempRvsArr.push(rA[rA.length - c]);
          }
        }
        console.log(tempRvsArr);
      }
    </script>
  </body>
1 Like

Nice job!

Look how far you have come in just 13 days or soā€¦ :hugs: Fantastic.
keep it up! :+1:

Ivo

1 Like
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>exercises chap 4</title>
  </head>
  <script type="text/javascript">

    function range (x,y,step) {
      //console.log("inside functtion");
      var array=[];
      if (step>0)
        if ((y-x)>0 && (y-x)>step)
          for (var i=0;i<=(y-x);i+=step) {
            //console.log(Number(x)+i);
            array.push(Number(Number(x)+i));
          }
      return array;
    }
    function reverse(list) {
      var inverted=[];
      for (var i=list.length-1;i>=0;i--) {
        inverted.push(list[i]);
      }
      return inverted;
    }
    function suma (listofNumbers) {
      var theSum=0;
      for (var i=0;i<listofNumbers.length;i++) {
        theSum=theSum+Number(listofNumbers[i]);
      }
      return theSum;
    }

    var interval=range(0,10,3);
    console.log("sum["+interval+"]="+suma(interval));
    console.log(reverse(interval));
  </script>
  <body>
  </body>
</html>
2 Likes

//Sum of a range
function sum(anArray){
var returnValue = 0;
for (let counter = 0; counter < anArray.length; counter++){
returnValue += anArray[counter];
};
return returnValue;
}
function theRange(start, end, step){
if (!step) step = 1;
//console.log(step);
var theRangeArray = [];
if (step >0){
for (var i = start; i <= end; i+= step){
theRangeArray.push(i);
}
} else {
for (var i = start; i >= end; i+= step){
theRangeArray.push(i);
}
}
return theRangeArray;
}
console.log(theRange(5,2,-1));
console.log(sum(theRange(5,2,-1)));

//reversing arrays
function reverseArray(theArray) {
var theReturn = [];
for (var counter = theArray.length; counter > 0; counterā€“) {
theReturn.push(theArray[counter - 1]);
}
return theReturn;
}

//copied from the answers
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([ā€œIvanā€, ā€œOnā€, ā€œTechā€]));
console.log(reverseArrayInPlace([ā€œIvanā€, ā€œOnā€, ā€œTechā€]));

1 Like

This is my solutions, my function range works differently but I think that is more logical way:

<!-- Script for sum of the range -->
    function range (start, end, step){
      if (step == null) {step = 1};
      if (step <= 0) {
        console.log("Step must be greater than zero! Step is set to " + Math.abs(step));
        step = Math.abs(step);
        };
      var arrayToReturn = [];
      if (start<end){
        while (start<=end){
          arrayToReturn.push(start);
          start += step;
        };
      } else if (start>end){
        while (start>=end){
          arrayToReturn.push(start);
          start -= step;
        };
      }
      return arrayToReturn;
    };

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

<!-- Script for reversing an array -->
  function reverseArray (array){
    var newArray = [];
    for (let i=array.length; i>0; i--){
      newArray.push(array[i-1]);
    };
    return newArray;
  };

  function reverseArrayInPlace (array){
    var tempArray = [];
    for (let i=array.length; i>0; i--){
      tempArray.push(array[i-1]);
      array.pop();
    };
    for (let i=0; i<tempArray.length; i++){
      array.push(tempArray[i]);
    };
    return array;
  };
1 Like

The sum of a range
var myArr = [];
var sum= 0;

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

function sumNumbers(){
for (var i = 0; i < myArr.length; i++) {
sum+=myArr[i];
};
console.log(sum);
};

returnRange(1, 5);
sumNumbers();

Reversing an array

var reversed = [];

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

  reverseArray([1,5,9,4,9,2]);
1 Like
  • The sum of a range
function range( start, end ) {
  var rangeList = [];
  for( var number = start; number <= end; number++ )
    rangeList.push( number );
  return rangeList;
}
            
function sum( rangeList ) {
  var total = 0;
  for( var number of rangeList )
    total += number;
  return total;
}
            
console.log( sum( range( 1, 10 ) ) ); //55
function range( start, end, step ) {
  if( step === undefined ) var step = 1;
  var rangeList = [];
  for( var number = start; step * number <= step * end; number+=step )
    rangeList.push( number );
  return rangeList;
}
            
console.log( range( 1, 10, 2 ) ); // [ 1, 3, 5, 7, 9 ]
console.log( range( 5, 2, -1 ) ); // [ 5, 4, 3, 2 ]
  • Reversing an array
function reverseArray( array ) {
  var newArray = [];
  for( var index = array.length - 1; index >= 0; index-- )
    newArray.push( array[ index ] );
    return newArray;
  }
            
  function reverseArrayInPlace( array ) {
    for( var index = 0; index < array.length / 2; index++ ) {
      var aux = array[ index ];
      array[ index ] = array[ array.length - 1 - index ];
      array[ array.length - 1 - index ] = aux;
    }
  }
            
var array = [ 1, 2, 3, 4, 5 ];
console.log( reverseArray( array ) ); // [ 5, 4, 3, 2, 1 ]
reverseArrayInPlace( array );
console.log( array ); // [ 5, 4, 3, 2, 1 ]

Side effects seem more interesting to implement user interaction, so they might be more common.
Pure functions seem to be faster, as they are self-contained and do not depend on other state updates.

1 Like

1.)The sum of a range

function sumNumbers(startNum, endNum, stepX){ 
	for (var i = startNum; i <= endNum ; i++) {
		var sampleArray = [startNum];
		if (typeof stepX === 'undefined'){
		for (var j = 0; j <= (endNum - startNum) ;j++){
			sampleArray[j] = startNum + j;
		}}
		else{
			for (var j = 0; j <= (endNum - startNum) ;j = j+stepX){
			sampleArray[j] = startNum + j;
		}}};
		console.log(sampleArray);
	var arrSum = function(arr){
  		return arr.reduce(function(x,y){
    	return x + y
  		}, 0);
		}

2.)Reversing an array

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

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

The Sum of a Range

Wow, this exercise made me sweat! :sweat_smile:

I guess the code should be cleaner, and the solution might be simpler. But it seems to work!

Here is my code:

function range(start, end, step) {

    var arr = [];

    if (step < 0) {
      for (var i = start; i >= end; i += step) {
        arr.push(i);
      }
    } else if (step > 0) {
      for (var i = start; i <= end; i += step) {
        arr.push(i);
      }
    } else {
      for (var i = start; i <= end; i++) {
        arr.push(i);
      }
    }

    console.log(arr);

    var sumArr = 0;

    for (var j = 0; j < arr.length; j++) {
      sumArr += arr[j];
    }

    console.log(sumArr);

}

range(1, 10);
range(1, 10, 2);
range(5, 2, -1);

Your comments or inputs are welcomed!

2 Likes

Actually I think it looks clean and it is easy for me to read it and I would be comfortable if I had to continue on your code.
When you write code you have to keep in mind that somebody else might continue on the code and therefore, it is important to build the code in a simple and clear way. And I think that you have managed to do that in a nice way.
About your code I donā€™t have any comments, as long as it runs correctly, Iā€™m content with that.

Ivo

2 Likes

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

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

1 Like

Reversing an Array

reverseArray function

function reverseArray(arr) {

  var myArray = [];

  for(var i = arr.length - 1; i >= 0; i--) {
    myArray.push(arr[i]);
  }

  return myArray;
}

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

result = reverseArray(testArray);

console.log(result);

reverseArrayInPlace function

function reverseArrayInPlace(arr) {

  for (let i = 0; i < Math.floor(arr.length / 2); i++) {
    let x = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = x;
  }

  return arr;
}

let testArray = ["A", "B", "C", "D", "E"];

console.log(reverseArrayInPlace(testArray));

The reverseArrayInPlace function was a tough one for me, so I basically checked the solution at different places. As hinted in the book, the idea of swapping the first and last elements of the array, then the second and the second to last, and so on, and the use of the Math.floor function to round down the half of the length of the array, is tricky and smart!

1 Like

Question:
My code is longer than in the example from the exercise but it works. However, I am upset because my code has much more lines. Am I missing something?

1 Like

I am confused with the second part of ā€œReversing an arrayā€ exercise. How is the second function different from the first. They seem identical to me. Can someone please clarify what I am not seeing?

Hi.

I wouldnā€™t worry about the length of your code. You will get a ā€œbetterā€ code with practice, practice and more practice. The most important is to keep reading and typing code, and your code structure and length will also get better by its self.

Have you posted it here yet? can we look at it?

Ivo

Here it is:
First exercise:

var rangeOf = [];

function range(start,end,step){
  var rangeOfLocal = [];
    var i = start;
    if (Number.isInteger(step) == true && step > 0 ){
      do {
        rangeOfLocal.push(i);
        i += step;
      } while (i<=end);
    } else if (Number.isInteger(step) == true && step < 0 ){
      do {
        rangeOfLocal.push(i);
        i += step;
      } while (i>=end);
    } else {
      do {
        rangeOfLocal.push(i);
        i ++;
      } while (i<=end);
    }
    return rangeOf = rangeOfLocal;
    console.log(rangeOf);
  };

function sum(range){
  var totalSum = 0;
  for(i=0; i<rangeOf.length;i++){
    totalSum += rangeOf[i];
  };
  console.log(totalSum);
};
1 Like

Exercise 2: Reversing an array

  function reverseArray(array){
          var arrayLength = array.length;
          var resultArray =[];
            for(let i=0; i<arrayLength; i++) {
                resultArray.push(array.pop());
            };
          return resultArray;
      };

      function reverseArrayInPlace(arr){
        var arrayLength = arr.length;
        var emptyArray = [];
        for (let i=0;i<(arrayLength/2);i++){
          emptyArray = arr[i];
          arr[i] = arr[arrayLength-1-i];
          arr[arrayLength-1-i]=emptyArray;
        };
        return arr;
      };
1 Like
  1. The sum of a range

  2. Reversing an array
    Schermata 2020-04-12 alle 15.36.02

1 Like

The sum of a range:
function range(start, end)
{
var arr = new Array(end ā€“ start + 1);
for (var j = 0; j < arr.length; j++, start++)
{
arr[j] = start;
}
return arr;
}

Reversing an array:
var fruits = [ā€œBananaā€, ā€œOrangeā€, ā€œAppleā€, ā€œMangoā€];
fruits.reverse();

1 Like

You can use a for loop to solve this problem, because the for loop has everything you need to solve this problem.
The other reason why your code is long is that you check if the arguments provided are integer. There is no need to check these things in a simple programming assignment.
Try to keep your code as simple as possible at first. If you need a check for arguments in the wrong format, you can do it later on.

Here is my version of range (without the third argument step):

    function range(start, end) {
      //Creating an empty array.
      var intArray = [];
      //Using a simple for loop.
      for (var index = start; index <= end; index++) {
        //Adding one element to the array with each iteration.
        intArray.push(index)
      }
      return intArray;
    }

    //This function takes the whole array as an argument.
    function sum(arrayToSum){
      totalSum = 0;
      //This syntax accesses each element of the array.
      //There is no need to take care of indices
      for (let summand of arrayToSum) {
        //Adding up each array element to the total sum.
        totalSum += summand;
      }
      return totalSum;
    }
    console.log(sum(range(1,10)));
1 Like