Chapter 4 - Exercises

#123

My code is not working :frowning: maybe somebody can assist me please? Ou and happy 2019 :slight_smile:

  <h2>Gib den Start und das Ende ein, um die Summe der iterierten Reichweite zu erhalten</h2>
  <input type="start" id="start" />
  <input type="end" id="end" />
  <button id="OK">OK</button>

  <script>

  $("#OK").click(function(){

    var start = $("#start").val();
    var end = $("#end").val();

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

    function sum(array){
        var x = 0;
        for (var i of array){
        x+=i;
      }
      return x;

    }
    //alert(range(start, end));
    alert(sum(range(start, end)));

  });

  </script>

</body>
0 Likes

#124

Sum of a Range

var myArray = [];
function sumArray(min,max,step){
  for (min; step&lt;0 ? min &gt;= max : min &lt;= max; step == null ? min++ : min+=step){
    myArray.push(min);
  }
  console.log(myArray);
  y=myArray.length;
var result=0;
for(var i=0; i&lt;y; i++){
  result +=  myArray[i];
}
return result;
console.log(result);

}

0 Likes

#125

Range

	function range(start, end, step = 1) {
		let first = start;
		let arr = [];
		if (start < end && step > 0) {
			for(first; start <= end; start += step) {
				arr.push(start);
			}
		} 
		else if(start > end && step < 0){
			for(start; start >= end; start += step) {
				arr.push(start);
			}
		}
		
		return arr;
	}

	console.log(range(5, 50, -5));

Sum of elements in array

	function sum(arr) {
		var a = 0;
		for(let i = 0; i < arr.length; i++) {
			a +=arr[i]
		}
		return a;
	}
	console.log(sum([3,4,5,6,7]));

Reverse array

	function reverseArray(arr) {
		let arr2 = [];
		for(let i = arr.length-1; i >= 0; i-- ) {
			arr2.push(arr[i])
		}
		return arr2;
	}
	console.log(reverseArray([1, 2, 3, 4, 5, 6, 7, 8, 9]));
0 Likes

#126

My answers:

The Sum of a Range:

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

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

Modifying the range function to include step size:

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

Reversing an Array:

1st Method (original Array is preserved):

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

2nd Method (original Array is changed):

function reverseArrayInPlace(anArray){
	let j = 0;
	for (let i = anArray.length - 1 ; i > (anArray.length - 1)/2; i -= 1){
		let placeHold = anArray[j];
		anArray[j] = anArray[i];
		anArray[i] = placeHold;
		j += 1;
	}
	return anArray;
}
0 Likes

#127

THE SUM OF A RANGE

var toReturnArray = [];

  function range(a, b){
    for(a; a<=b; a++){
    toReturnArray.push(a);
    }

    return toReturnArray;
  }

  function sum(a, b){
    range(a, b);
    let total=0;
    $.each(toReturnArray, function(index, value){
      total=total+value;
    });
    return total;
  }

  console.log(sum(1,10));
0 Likes

#128

hello, I need a little help here:
why i can’t see user input on this code, what am’i missing?
it pushing it to the list but there is not imput value…
please advise…here is the code…
@ivan


CryptosCity

Leave us your comments below

Submit
0 Likes

#130
<!DOCTYPE html>

<html>
<!--NEW CryptosCity WEBSITE-->
  <head>
      <title>CryptosCity</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

<!--COMMENTS BOX-->
<body>
      <h3>Leave us your comments below</h3>
      <ol id="CommentsList">
      </ol>

            <input id="commentstextInput" placeholder="comments here"type="text"/>
            <button  id="addCommentsButton"> Submit</button>
    <script>
      var comments = ["Welcome to CryptosCity Chat", "speak your mind out"];

function redrawlist(){
        var list = $("#CommentsList");
          list.html("");
          $.each(comments,function(index,value){
              $("<li/>").text(value).appendTo(list);
            });
    }
    redrawlist();
            $("#addCommentsButton").click(function(){
          var commentsText = $("#commentsTextInput").val();
          comments.push(commentsText);

redrawlist();

        });



</script>



</body>

</html>
0 Likes

#131

THE SUM OF RANGE

/*
Write a range function that takes two arguments, start and end, and returns
an array containing all the numbers from start up to (and including) end.
*/

    function range(firstNum, lastNum) {

      var rangeArray = [];

      for (var i = 0; i < 1+lastNum-firstNum; i++) {

        rangeArray[i]=firstNum+i;

      };

      return rangeArray;

    };

/*
Next, write a sum function that takes an array of numbers and returns the
sum of these numbers. Run the example program and see whether it does
indeed return 55.
*/

    function sum(myArray) {

      var mySum = 0;

      $.each(myArray, function(index, value) {
        mySum += value;
      });

      return mySum;

    }


/*
As a bonus assignment, modify your range function to take an optional third
argument that indicates the “step” value used when building the array. If no
step is given, the elements go up by increments of one, corresponding to the
old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7,
9]. Make sure it also works with negative step values so that range(5, 2, -1)
produces [5, 4, 3, 2].*/


function rangeBonus(firstNum, lastNum, stepInput) {

  var rangeArray = [];
  var n = 0;
  var stepFor = 1;

  if (stepInput) {
      stepFor = stepInput;
  }
  else if (lastNum<firstNum) {
    stepFor= -1;
  }

  if (stepFor>0) {

    for (var i = 0; i < 1+lastNum-firstNum; i+=stepFor) {

      rangeArray[n]=firstNum+i;
      n++;

    };

  }

  else {

    for (var i = 0; i > -1+lastNum-firstNum; i+=stepFor) {

      rangeArray[n]=firstNum+i;
      n++;

    };

  };

  return rangeArray;

};

REVERSING AN ARRAY

/* The first, reverseArray, takes an array as argument and produces a new array
    that has the same elements in the inverse order.    */

    function reverseArray(inputArray) {

      var outputArray=[];

      for (var i = 0; i < inputArray.length; i++) {

        outputArray.push(inputArray[inputArray.length-i-1]);

      };

      return outputArray;

    };



/*  The second, reverseArrayInPlace, does what the reverse method does: it modifies
    the array given as argument by reversing its elements. Neither may use the
    standard reverse method.*/

    function reverseArrayInPlace(inputArray) {

      let end = inputArray.length / 2  ;

      for (let i = 0; i < end; i++) {

        let elem = inputArray[i];
        inputArray[i] = inputArray[inputArray.length - 1 - i];
        inputArray[inputArray.length - 1 - i] = elem;

      };

      return inputArray;

    };
0 Likes

#132

Under reverseArray, with the code example below, why must we subtract 1 from ‘array.length - 1’ under the loop. Because without this operation, it gives the index: 0 undefined. I’m lost here if somebody can please explain. Thanks!

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

0 Likes

#133

The Sum of a Range

//creates and returns an array of numbers based on the starting and ending points given
  function range(start, end, step){
    if (step == undefined){
      step = 1;
    }

    var array = [];
    if (end>start){
      for (var i=start; i<=end; i+=step) {
      array.push(i);
      };
    }
    else{
      if (step == 1){
        step = -1;
      }
      for (var i=start; i>=end; i+=step) {
      array.push(i);
      };
    }
    return array;
  }

//adds all numbers in an array together and returs the sum
  function sum(list){
    var sum = 0;
    var length = list.length;
    for (i=0; i<list.length; i++){
      sum += list[i];
    };
    return sum;
  }

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

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

Reversing an Array

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

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

    return(newArray);
  }

  function reverseArrayInPlace(array){
    var length = array.length;
    for(var i=array.length-1; i>=0; i--){
      testArray.push(array[i]);
    };
    for (var j = 1; j<=length; j++){
      testArray.shift();
    };
    return(testArray);
  }

  console.log(reverseArray(testArray));
  console.log(reverseArrayInPlace(testArray));
0 Likes

#134

Sum of Range:

0 Likes

#135

array.length gives the quantity of items in an array. For example, an array containing [1, 2, 3, 4, 5] would result in an array.length of 5. Since array objects start at 0 rather than 1, the last item in the array would be equal to array.length-1. So if the example array was named testArray, to access the last element you would use testArray[4].

0 Likes

#136

function range(start, end, increment){
var result [];
if (increment == undefined)
increment = 1;
numLoops = Math.abs(end - start)/increment) +1;
for (var i=0; i<numLoops; i++){
result.push (start);
start += increment;
}
return result;
}

function sum (numArray) {
var arrayTotal = 0;
numLoops = numArray.length;
for (var i=0; i<numLoops; i++) {
arrayTotal += numArray[i];
}
return arrayTotal;
}

console.log (range(1,10));
// [1,2,3,4,5,6,7,8,9,10]

console.log (range (5,2,-1));
// [5,4,3,2]

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

0 Likes

#137

Reversing An Array:

var x = [{“score”:1}, {“score”:2}, {“score”:3}]

// copy x
y = Object.assign({}, x);
console.log(y);
x.reverse();
console.log(x);
//Result:
// 0: {score :1}
// 1: {score : 2}
// 2: {score :3}

//0: {score:3}
//1: {score:2}
//2: {score:1}

Obviously a beginner, buy that is as good as it gets, for now.

0 Likes