Chapter 4 - Exercises

#42
var Range = new Array();
$("#IDbutton").click(function(){
  var sum=0;
  var startInput=$("#IDstartInput").val();  //ID of the starting number
  var endInput=$("#IDendInput").val();    //ID of the ending number
  var stepInput=$("#IDstepInput").val();   //ID of the step number
  document.write("choosen range is between: " + startInput + " and " + endInput+ "<br> choosen step is: " + stepInput +"<br>");
  var a = parseInt(startInput);   //change string into integer
  var b = parseInt(endInput);
  var c = parseInt(stepInput);

  if (a<b){
    if (c>0){
      for(counter=a; counter<=b; counter+=c){
        Range.push(counter);

        sum+=counter;
      }
      document.write("sum of all numbers is: " +sum);
    }
    else if (c==0){
      document.write("wrong step");
    }
    else{     // if(c<0)
      c=c*(-1);
      for(counter=a; counter<=b; counter+=c){
        Range.push(counter);
        sum+=counter;
      }
      document.write("sum of all numbers is: " +sum);
    }
  }

  else {      // if(a>b)
    if (c>0){
      for(counter=a; counter>=b;counter -= c){
        Range.push(counter);
        sum+=counter;
      }
      document.write("sum of all numbers is: " +sum);
    }
    else if (c==0){
      document.write("wrong step");
    }
    else{    // if(c<0)
      c=c*(-1);
      for(counter=a; counter>=b;counter -= c){
        Range.push(counter);
        sum+=counter;
      }
      document.write("sum of all numbers is: " +sum);
    }
  }

document.write("
"+"this is the range: "+Range);
})

0 Likes

#43

// this is the reverse function

function reverseArray(y){
let reverse = new Array();
for(var count=y.length-1;count>=0;count–){
reverse.push(y[count]);
}
document.write("
"+"this is reversed range: "+reverse);
}

reverseArray(Range);

0 Likes

#44

//how to change elements in array between themselves

let array = [“ha”,“hu”,“hey”,“wey”];
console.log("we have this array: "+array);

function change(a,b){
var T=array[a-1];
var U=array[b-1];
array[a-1]=U;
array[b-1]=T;
console.log(array);
}
//[“ha”,“hu”,“hey”,“wey”]
change(1,2); //[“hu”, “ha”, “hey”, “wey”]
change(2,3); //[“hu”, “hey”, “ha”, “wey”]
change(1,4); //[“wey”, “hey”, “ha”, “hu”]

0 Likes

#45

RANGE ARRAY and ADD ARRAY ELEMENTS

  function createRangeArray(start, end, increment){
        var rangeArray = [];
        var arrayEntry = start;
        increment = Math.abs(increment);
        for (let i = start; i < end+1; i=i+increment) {
          rangeArray.push(arrayEntry);
          arrayEntry = arrayEntry + increment;
        }
        return rangeArray;
      }

      function addArrayElements(numArray){
        var sumTotal = 0;
        for (let i = 0; i < numArray.length; i++) {
          sumTotal = sumTotal + numArray[i];
        }
        return sumTotal;
      }
      console.log("Create Range Array: " + createRangeArray(1,10,1));
      console.log("Add Array Elements: " + addArrayElements(createRangeArray(1,10,1)));
0 Likes

#46

REVERSE ARRAY

 function createRangeArray(start, end, increment){
        var rangeArray = [];
        var arrayEntry = start;
        increment = Math.abs(increment);
        for (let i = start; i < end+1; i=i+increment) {
          rangeArray.push(arrayEntry);
          arrayEntry = arrayEntry + increment;
        }
        return rangeArray;
      }

      function reverseArray(arr){
        var arr2 = [];
        var j = arr.length-1;
        var arr2Value = "";
        for (let i = 0; i < arr.length; i++) {
          arr2Value = arr[i];
          arr2[j] = arr2Value;
          j=j-1;
        }
        return arr2;
      }
      console.log("Create Range Array: " + createRangeArray(1,10,1));
      console.log("Reverse Array: " + reverseArray(createRangeArray(1,10,1)));
0 Likes

#47

REVERSE ARRAY IN PLACE

function createRangeArray(start, end, increment){
    var rangeArray = [];
    var arrayEntry = start;
    increment = Math.abs(increment);
    for (let i = start; i < end+1; i=i+increment) {
      rangeArray.push(arrayEntry);
      arrayEntry = arrayEntry + increment;
    }
    return rangeArray;
  }
  
  function reverseArrayInPlace(arr){
    var arrTemp = [];
    var j = arr.length-1;
    var arrTempValue = "";
    for (let i = 0; i < arr.length; i++) {
      arrTempValue = arr[i];
      arrTemp[j] = arrTempValue;
      j=j-1;
    }
    arr = arrTemp
    return arr;
  }
  console.log("Create Range Array: " + createRangeArray(1,10,1));
  console.log("Reverse Array In Place: " + reverseArrayInPlace(createRangeArray(1,10,1)));
0 Likes

#48

// range function

function range(start, end, step){

if (step == NaN ||
step == undefined ||
step == 1){

  	// define the array as empty
  	var array = [];

  	// start the loop, if i (start)
  	// is less than the end add another step
  	// add the value of i every loop
  	for (let i = start; i <= end; i++){
  		array.push(i);
  	}

  	// return the populated array
  	return array;
  }

else if (step >= 2) {

  var array = [];

  // start the loop, if i (start)
  // is greater or equal than the end add another step
  // add the value of i every loop
  for (let i = start; i <= end; i = i + step){
  	array.push(i);
  }
  return array;

}

else if (step <= -1) {

var array = [];

// start the loop, if i (start)
// is greater than or equal to end add another step
// add the value of i every loop
for (let i = start; i >= end; i = i + step){
array.push(i);
}
return array;
}

else if (step == 0) {
var error = “You can’t step by 0”;
return error;
}
}

// return the sum of all the numbers in an array

function sum(array){

var sum = 0;
// iterate through the values and add them to the sum.
for(let value of array){
sum = sum + value;
}
return sum;
}

function reverseArray(array){

// create a new array
var returnArray = [];

// loop through the length of the array
// remove the last item every pass and
// store it in returnArray
// at the end - return the new array
for (let i = 0; i <= array.length; i++){
let endPoint = array.pop();
returnArray.push(endPoint);
}
return returnArray;
}

function reverseArrayInPlace(array){
// keep it simple
// we already built a function that does
// what we need, so just re-use it
return reverseArray(array);
}

0 Likes

#49

function range(start, end){
var answerArray = [];
for (let i = start; i <= end; i++){
answerArray.push(i);
}
console.log(answerArray);
}

        range(8, 9);

function sum(array){
let counter = 0;
for(let i = 0; i < array.length; i++){
counter = counter + array[i];
}
console.log(counter);
}

        sum([150, 10, 5, 0]);

function range(start, end, step){
var answerArray = [];
if(step === undefined){
for (let i = start; i <= end; i++){
answerArray.push(i);
}
}
else if(step < 0){
for (let i = start; i >= end; i = i+step){
answerArray.push(i);
}
}
else{
for (let i = start; i <= end; i = i+step){
answerArray.push(i);
}
}
console.log(answerArray);
}

      range(5, 2, -1);

function reverseArray(array){
var newArray = [];
for(let i = 0; i < array.length; i++){
let answer = array[i];
newArray.unshift(answer);
}
console.log(newArray);
}

      reverseArray([1, 2, 3, 7, 8, 9, 11]);

function reverseArrayInPlace(array) {
for (let i = 1; i < array.length; i++) {
let move = array.splice(i, 1)[0];
array.unshift(move);
}
return array;
}

          reverseArrayInPlace([1,2,3,4,5,6,7,8]);
0 Likes

#50

Hi Guactoshi,
can u pls tell me why things don’t work if you put

var n = []; (First step of exercise)

outside the function, as in:

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

I still believe that the var n should have a global scope since it is then re-used as an argument inside the function sum(n).

Thx,
Daniel

1 Like

#51

Hey Samm,
This condition should be enough to support both ranges ((start - parse)*(stop-parse) <= 0). You can find my implementation in the posts above.

Mihai

0 Likes

#52

Hey,

You have to use “-1” because your num variable is initialized with the length of the array and the array is indexed from 0 to length-1.

Also you can use the count variable to access the array. You are not forced to use the for variable to increment from 0 to length. You can also decrement it from length to 0 like so:

for(var num = array.length-1; num>=0; num = num -1)
{
newArray.push(array[num]);
}

0 Likes

#53

The sum of a range
var range = function(start, end){
var formedArray = [];

	for(i= start; i <= end; i++){
		formedArray.push(i);
	}
	return formedArray;
};

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

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

	for(i = 0; i < formedArray.length; i++){
		total = total + formedArray[i];
	}
	return total;
};
console.log("The sum of the arrays' numeric elements = " + sum(range(1,5)));

Bonus part (Extra step)
var range3 = function(start, end, step = start < end ? 1 : -1){
var array = [];

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

};

Reversing an array
var arrayAsArg = [“Apples”, “Bananas”, “Fruits”, “Coconuts”];
function reverseArray(arrayAsArg) {
let output = [];
for (let i = arrayAsArg.length - 1; i >= 0; i–) {
output.push(arrayAsArg[i]);
}
return output;
}
console.log(reverseArray(arrayAsArg));

function reverseArrayInPlace(arrayAsArg){
for (let i = 0; i < Math.floor(arrayAsArg.length / 2); i++) {
let old = arrayAsArg[i];
arrayAsArg[i] = arrayAsArg[arrayAsArg.length - 1 - i];
arrayAsArg[arrayAsArg.length - 1 - i] = old;
}
return arrayAsArg;
}
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

0 Likes

#54

The Sum of a Range

function range(start, end, step){
    var range = [];
    // makes sure step allows us to converge to end
    if(step){
        if(end/step<0){
            range = [0];
        }
    }
    else{
        step=start<end?1:-1;

        for(i=start;start<end?(i<=end):(i>=end);i+=step){
            range.push(i);
        }
    }
    return range;
}

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

// Note that this part is done differently than the question asks, for my curiosity
// uses the rest parameter to accept multiple values
function sum(...range){
    var sum = 0;
    for(let number of range){
        sum += number;
    }
    return sum;
}

// if an array is passed in then use the rest parameter to deconstruct it
console.log(sum(...range(1,10)));

Reversing an Array

/* 
Reverses an array, using another array.
________________________________________
This is a pure function, since we are
only operating on local variables. 
As such, this function is expected to be
faster.
*/
function reverse(array){
    let newArray = [];
    for(i=1;i<=array.length;i++){
        newArray[i-1]=array[array.length-i];
    }
    return newArray;
}

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

/* 
Reverses an array in place.
________________________________________
This is not a pure function, since we are
modifying a global variable. 
As such, this function is expected to be
slower.
*/
function reverseArrayInPlace(array){
    // this step requires half the array length
    // because perform operations on both sides
    // in one iteration
    for(i=1;i<=array.length/2;i++){
        let pushValue = array[i-1];
        array[i-1] = array[array.length-i];
        array[array.length-i] = pushValue;
    }
    return array;
}

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

#55

It should work D. I just tested it. As long as it is declared with var it should have a global name space that is correct.

image

0 Likes

#56

1. The sum of a range

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

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

        return array;
    }

    function sum(array)
    {
        var sum = 0;
        $.each(array, function(index, value)
        {
            sum += value;
        });
        return sum;
    }

2. The sum of a range

   function reverse(array)
   {
       var newArray = [];

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

#57
function range(start,end,step){
    var array = [];
    if(typeof step === "undefined") {
        step = 1;}
    for(var i = start; i<=end;i = i+step){ 
        array.push(i)} 
    return array}

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

#58
function reverseArray(array){
    var reversedArray = [];
    for(var i = array.length-1; i>=0;i--){
      reversedArray.push(array[i])}
    return reversedArray}
0 Likes

#59

That looks a little more straight forward than what I used, but at least it worked!
Thanks for the input!

0 Likes

#60

Sum of a range
First part (range with step 1):

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

Second part (sum of an array):

<script>
function sumArray(myArray){
  let sumOfArray=0;
  for (i=0; i<myArray.length;i++){
  sumOfArray=sumOfArray+myArray[i];
}
return sumOfArray;
}
</script>

Bonus part (range with general step)

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

#61

Reversing an array

The first part (this creates a new array from old)

<script>
function reverseArray(inputArray){
let x=inputArray;outputArray=[];
for(i=0;i<x.length;i++){
outputArray[i]=x[inputArray.length-1-i];
}
return outputArray;
}
</script>

Second part (this one modifies the given array)

I am not sure about this one, but it works. I used
the previous one.

    <script>
    function reverseArrayInPlace(myArray){
      myArray=reverseArray(myArray);
    return myArray;
    }
    </script>
0 Likes