Chapter 4 - Exercises

#21

The sum of a range

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

function sum(numbers) {
  var sum = 0;
  for (let number of numbers)
    sum += number;
  return sum;
}
0 Likes

#22

Reversing an array

function reverseArray(arr) {
  var reverseArr = [];
  for (element of arr)
    reverseArr.unshift(element);
  return reverseArr;
}

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

In contrast to the book’s solution, the first function reverseArray uses the unshift() method rather than push().

0 Likes

#23
       function range(start, end, step = 1) {
         var ary = [];
         for (var i = start
            ; (i <= end && start < end) || (i >= end && start > end)
            ; i += step) {
            ary.push(i);
        };
        return ary;
    }

    function sum(ary) {
        var tot = 0;
        for (n in ary) {
           tot +=ary[n];
        }
        return tot;
    }

    console.log(range(1, 100, 21));
    console.log("Sum of array is: "+sum(range(1, 100, 21)));
0 Likes

#24

Range and Sum
function range (start, stop, step = 1) {
 let array = [];
 let parse = start;
  /* could be done easy with (parse != stop)
   but in this way we also catch situations where
  step increments will skip the stop value*/
 while ((start - parse)*(stop-parse) <= 0) {
  array.push(parse);
  parse += step;
 }
 return array;
}

function sum (array) {
 let _sum = 0;
 for (let i in array) {
  _sum +=array[i];
 }
 return _sum;
}

Reverse Array
function reverseArray (array) {
 const len = array.length - 1;
 let new_array = [];
 for (var i in array) {
  new_array.push(array[len - i]);
 }
 return new_array;
}

function reverseArrayInPlace (array) {
 const len = array.length - 1;
 let i = 0;
 while (i < array.length/2) {
  let temp = array[i];
  array[i] = array[len - i];
  array[len- i] = temp;
  i++;
 }
 return array;
}

0 Likes

#25

Range function:

var array = [];

function range(start, end)
{

for(var count = start; count <= end; count++)
{
array.push(start);

start++;

}

return array;

}

range(1,10);

// I am having trouble with the sum(range()) function though…

0 Likes

#26

Range function with the sum:

var array = [];

function range(start, end)
{

for(var count = start; count <= end; count++)
{
array.push(start);

start++;

}

return array;

}

range(1,5);

function sum(array)
{

var total = 0;

for(var count1 = 0; count1 < array.length; count1++)
{

total = total + array[count1]

}

console.log(total);

}

sum(range());

// @Samm
// I was trying to build mine similar to yours. When I saw you did it I tried again slowly observing every step and it worked this time. Took an hour to do each one.

With the “step” parameter:

var array = [];

function range(start, end, step)
{

for(var count = start; count <= end; count = count + step)
{
array.push(start);

start = start + step;

}

return array;

}

range(1,10,2);

0 Likes

#27

Reversing an array [] : :nerd_face:

var array = [“bmw”, “ford”, “mazda”, “benz”]

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

var num = array.length;

for(var count = 0; count<array.length; count++)
{

// Anyone know why I had to include “-1” to make this work?

newArray.push(array[num - 1]);

num = num -1;

}

return newArray;

}

reverse(array);

0 Likes

#28

The sum of a range
The introduction of this book alluded to the following as a nice way to compute
the sum of a range of numbers:
console.log(sum(range(1, 10)));
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 .
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.
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 range(start, end, step){
var output = [];
if (step == undefined || step == null || step == 0)
	step = 1;
	console.log("The step increment by default will be set to one.");

if (start>end && step<0){
	for(i=start;i>=end;i=i+step){
		output.push(i);
    }
} else if (start<end && step>0){
	for (i=start; i<=end; i=i+step){
			output.push(i);
    }
} else {
	alert("Invalid range or step increment/decrement.");
}
return output;

}

function sum(numOutput){
    var outputTotal = 0;
    numbers = numOutput.length;
    for(var i = 0; i < numbers; i++){
	    outputTotal += numOutput[i];
    }
    return outputTotal;
}

console.log(range(1,19));
console.log(range(21,3,-2));
console.log(sum(range(1,75)));

Reversing an array
Arrays have a reverse method that changes the array by inverting the order in
which its elements appear. For this exercise, write two functions, reverseArray
and reverseArrayInPlace . The first, reverseArray , takes an array as argument
and produces a new array that has the same elements in the inverse order. 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.
Thinking back to the notes about side effects and pure functions in the
previous chapter, which variant do you expect to be useful in more situations?
Which one runs faster?

function reverseArray(a){
    var output = [];
    for(i=0;i < a.length;i++){
      var entry = a[i];
      output.unshift(entry);
    }
    return output;
};

function reverseArrayInPlace(arg){
 var result;
 for(i=0; i<arg.length/2;i++){
	result = arg[i];
	arg[i] = arg[arg.length - 1 - i];
    arg[arg.length - 1 - i] = result;
 }
}

console.log(reverseArray([“Coffee”,“Pineapple”,“Apricot”]))

var coding = [3,1,4,9,5];
reverseArrayInPlace(coding);
console.log(coding);

1 Like

#29

Exercise 1

function range(num1,num2,step){
   let array1=[num1];
   for (i=num1+1;i<=num2;i+=step){
      array1.push(i);
   };
   return array1;
}
function sum_of_array(array_input){
  var sum=0;
  array_input.forEach(function(entry){
  sum=sum+entry;});
 return sum;
};

console.log(sum_of_array(range(1,10,1))) returns 55

0 Likes

#30
function reverseArray(array_input){
 var array_output=[];
 array_input.forEach(function (item) {array_output.unshift(item)});
 return array_output;
}
0 Likes

#31

The sum of a range

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

function sum(array) {
  let sumNumbers = 0;
  for (let i = 0; i < array.length; i++){ // for...of loop
    sumNumbers += array[i];
  }
  return "Sum of array values is: " + sumNumbers;
}

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

Reversing an array

function reverseArray(array) {
  let showArray = [];
  for (let i = array.length - 1; i >= 0; i--) {
    showArray.push(array[i]);
  }
  return showArray;
}
console.log(reverseArray(["A", "B", "C"]));

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

#32

//EX1
function range(start, end, step)
{
let rangeArray = [start];

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

	console.log(range(1, 10));
	console.log(range(1, 10, 2));
	console.log(range(5, 2, -1))
	
	function sum(inArray)
	{
		let sum = inArray[0];
		
		for (let i 	= 1; i < inArray.length; i++)
		{
			sum = sum + inArray[i];
						}
		return sum;
	}
	
	console.log(sum(range(1, 10)));
	console.log(sum(range(5, 2, -1)));

//END EX1

//-------------------

//EX2
function reverseArray(inArray)
{
let count = inArray.length - 1;
let outArray = [inArray[count]];

		for (let i = count; i > 0; i--)
		{
			outArray.push(inArray[i-1]);	
		}
		
		return outArray;			
	}

	console.log(reverseArray([0,7,4,6,8,10]));

//END EX2
//-------------------

1 Like

#33

The sum of a range

Version 1:

 <script>

          var sumOfRange;

          function range(start, end){
          /*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.
          */
            var ArrayRange = [];
            var i;
            for (i=start; i<=end; i++){
              ArrayRange.push(i);
            }
            return ArrayRange;
          }

          function sum(numberArray){
          /*Write a sum function that takes an array of numbers and
          returns the sum of these numbers.
          */
            var n;
            var sumOfNumbers=0;
            for (n=0; n<numberArray.length; n++){
              sumOfNumbers+=numberArray[n];
            }
            return sumOfNumbers;
          }
          sumOfRange = sum(range(1, 10));
          console.log(sumOfRange);
        </script>
0 Likes

#34

The sum of a range
Bonus version:

<script>

  var sumOfRange;

  function range(start, end, step){
  /*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].
  */

    var ArrayRange = [];
    var i;

    if (step === undefined) {
      if (start <= end) {
        step = 1;
      } else {
        step = -1;
      }
    }

    console.log("--------");
    console.log(start);
    console.log(end);
    console.log(step);
    console.log("--------");

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

    console.log(ArrayRange);
    return ArrayRange;
  }

  function sum(numberArray){
  /*Write a sum function that takes an array of numbers and
  returns the sum of these numbers.
  */
    var n;
    var sumOfNumbers=0;
    for (n=0; n<numberArray.length; n++){
      sumOfNumbers+=numberArray[n];
    }
    return sumOfNumbers;
  }

  console.log(sum(range(1, 10)));
  console.log(sum(range(1, 10, 1)));
  console.log(sum(range(1, 10, -1)));
  console.log(sum(range(-5,5)));
  console.log(sum(range(-5,5,1)));
  console.log(sum(range(-5,5,-1)));
  console.log(sum(range(10,1,2)));
  console.log(sum(range(10,1,-2)));
</script>
0 Likes

#35

Reversing an array

<script>
    /*Arrays have a reverse method that changes the array by inverting the order in
    which its elements appear. For this exercise, write two functions, reverseArray
    and reverseArrayInPlace.
    */

    function reverseArray(inputArray) {
    /*The first, reverseArray, takes an array as argument and produces a new array
    that has the same elements in the inverse order.
    */
      var outputArray=[];
      var len=inputArray.length;

      for (i=len-1; i>=0; i--) {
        outputArray.push(inputArray[i]);
      }

      console.log(inputArray);
      console.log(outputArray);
      return outputArray;
    }

    function reverseArrayInPlace(inputArray) {
    /*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.
    */
      var len=inputArray.length;
      var numberLoop=Math.floor(inputArray.length/2);
      var elem;

      for (i=0; i<numberLoop; i++) {
        elem = inputArray[i];
        inputArray[i] = inputArray[len - (i + 1)];
        inputArray[len - (i + 1)]=elem;
      }

      console.log(inputArray);

    }

    reverseArray([]);
    reverseArrayInPlace([]);
    reverseArray([1]);
    reverseArrayInPlace([1]);
    reverseArray([1, 2]);
    reverseArrayInPlace([1, 2]);
    reverseArray(['a', 'b', 'c']);
    reverseArrayInPlace(['a', 'b', 'c']);
    reverseArray([1, 2, 3, 4]);
    reverseArrayInPlace([1, 2, 3, 4]);
    reverseArray([1, 2, 3, 4, 5]);
    reverseArrayInPlace([1, 2, 3, 4, 5]);

    </script>
0 Likes

#36

Reverse Array

let arr = [“Ivan”, “On”, “Tech”];
console.log(arr);
arr.reverse();
console.log(arr);

Output

Array(3) [ “Ivan”, “On”, “Tech” ]
Array(3) [ “Tech”, “On”, “Ivan” ]

0 Likes

#37

But does your range function handle negative numbers?
I was looking for the most elegant way to support range(10,1,-2) for example.
I’m not so sure it was the most elegant way, but it seems to work!

I’m totally enjoying this course. How about you?
-Samm

0 Likes

#38

I think if you had used newArray.push(array[–num]), it would have decremented num before referencing the element in the array. Then you wouldn’t have to use num = num -1 afterwords.
-Samm

0 Likes

#39

I think if you would have used function range(start, end, step=1){…
it would assign the default value of 1 to step.

Hope you are enjoiying this class as much as I am!
-Samm

0 Likes

#40

There must be a more elegant way to support pos or neg ranges, but I guess if it works, it works!
-Samm

0 Likes