Chapter 4 - Exercises

SUM OF RANGE

<html>

    <head>
        <title>PART3</title>
        <h1>PART3param</h1>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>


    <body>
      <h2>SumRange</h2>
      <input type ="number" id="StartVal" value=0 title="Start value"/>
      <input type="number" id="EndVal" value=0 title="End value"/>
      <input type="number" id="Step" value=0 title="input step interval"/>
      <button id="Calc">Calculate</button>
      <br><br>
      <h4>ListNumbers:</h4><br>
      <ol id="ordList"></ol><br>
      <h4 id="SumNum">Sum of numbers:</h4><br>

      <script>


          //Create array of numbers
          function MakeArray(a,b,c) {
            var numbers = [];
            var numList = $("#ordList");
            var sumall = 0;


            numbers.length = 0;
            //check negative --> switch vars
            if ( Number(c) < 0 ) {
              //make array
              for (i=Number(b); i>=Number(a) ; i=i+Number(c)) {
                numbers.push(i);
                sumall += i;
                $("<li/>").text(i).appendTo(numList);
              }
      
            }
            else {
              //make array
              for (i=Number(a); i<=Number(b) ; i=i+Number(c)) {
                numbers.push(i);
                sumall += i;
                $("<li/>").text(i).appendTo(numList);
              }
            }
            $("#SumNum").text("Sum of all numbers in array= " +sumall);
            console.log(numbers)
          };

            //when button clicked
            $( "#Calc" ).click(function() {
                $("#ordList").html("");
                MakeArray( $('#StartVal').val(), $('#EndVal').val(), $('#Step').val() );
              });



      </script>

    </body>
</html>

Reversing array

<html>

    <head>
        <title>PART3</title>
        <h1>P3: ReverseArray</h1>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>


    <body>
      <h2>ReverseArray</h2>
      <input type ="number" id="StartVal" value=0 title="Start value"/>
      <input type="number" id="EndVal" value=0 title="End value"/>
      <input type="number" id="Step" value=0 title="input step interval"/>
      <button id="Calc">Process</button>
      <br><br>
      <h4>ListNumbers:</h4><br>
      <ol id="ordList"></ol><br>
      <h4>ListNumbers ReverseArray:</h4><br>
      <ol id="ordListRev"></ol><br>
      <h4>ListNumbers ReverseArrayInPlace:</h4><br>
      <ol id="ordListRevIp"></ol><br>

      <script>
          var numbers = [];
          var RevNumbers = [];

          function showarray(ar,name){
            //show an array that comes in: par1 is the array itsel, par2 is the name of the array
            $.each(ar, function( i, value ) {
              $("#"+name).append("<li>"+ value + "</li>");
            });
          };

          //Create array of numbers
          function MakeArray(a,b,c) {
            numbers.length = 0; // make sure array is empty
            //make numbers array based on parameters
            for (i=Number(a); i<=Number(b) ; i=i+Number(c)) {
                numbers.push(i);
              }
            showarray(numbers,"ordList");
          };

          //reverse an array that comes in and store it in another array
          function ReverseArray(a) {
              RevNumbers.length = 0; // make sure array is empty
              for (i=a.length; i > 0  ; i--) {
                  RevNumbers.push([i]);
                }
              showarray(RevNumbers,"ordListRev");
            };

            //reverse an array that comes in and store it in the same array
            function ReverseArrayInPlace(a) {
                //make temp array
                var temparray = [];
                temparray.length = 0; // make sure array is empty
                var b = 0;
                for (i=a.length-1; i >= 0  ; i--) {
                    temparray.push(a[i]);
                    b++;
                  }
                a.length = 0; //empty original array
                for (i=0; i < temparray.length  ; i++) {
                      a.push(temparray[i]);
                    }
              //  temparray.length = 0;
                showarray(a,"ordListRevIp");
              };


          //when button clicked
          $( "#Calc" ).click(function() {
                $("#ordList").html("");
                $("#ordListRev").html("");
                $("#ordListRevIp").html("");
                MakeArray( $('#StartVal').val(), $('#EndVal').val(), $('#Step').val() );
                ReverseArray(numbers);
                ReverseArrayInPlace(numbers);
              });



      </script>

    </body>
</html>

question about performance

Some things can more efficiently be expressed by using side effects, so that would be the reason not to go for a pure function because it can be slower

The Sum of a Range:

function range(start, end, step)
{
    var array = [];
    if(typeof step != "undefined")
        if (step > 0){
            for(var i = start; i <= end; i+=step)
                array.push(i);
        
            return array;
        }
        else if(step < 0){
            for(var i = start; i >= end; i+=step)
                array.push(i);
        
            return array;
        }
        else{
            console.log("Step Error!");
            return 0;
        }
    else{
        for(var i = start; i <= end; i++)    
        array.push(i);
                       
        return array;
    }           
};

function sum (array)
{
    var cont = 0;

    for(var i = 0; i < array.length; i++){
        cont += array[i];
    }

    return cont;
}

var array1 = range(10,-1,-1);
console.log(array1);

var suma = sum(array1);
console.log(suma);

Result:
Array(12) [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, -1 ]
54

Reversing an Array:

function reverseArray(array)
{
    var newArray = [];
    var j = array.length-1;

    for(var i = 0; i < array.length; i++)
    {
        newArray[i] = array[j];
        j--;
        console.log(newArray);
    }
    
    return newArray;
};

function reverseArrayInPlace(array) // Book Solution
{
   for(var i = 0; i < Math.floor(array.length/2); i++){

        var temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length -1 - i] = temp;
        console.log(array);
   }
   return array;
};

var array = [1, 2, 3, 4, 5];
reverseArray(array);
console.log("----------------");
var array = [1, 2, 3, 4, 5];
reverseArrayInPlace(array); 

Result:

Array [ 5 ]
Array [ 5, 4 ]
Array(3) [ 5, 4, 3 ]
Array(4) [ 5, 4, 3, 2 ]
Array(5) [ 5, 4, 3, 2, 1 ]
----------------
Array(5) [ 5, 2, 3, 4, 1 ]
Array(5) [ 5, 4, 3, 2, 1 ]

Discussion:

The second solution shows how with only two iterations we can have the problem solved. As well, the second solution does not include a new structure to the code only a simple variable. In my opinion, the reverseArrayInPlace function is better because it is a pure function, has no side effects, saves memory and it is faster.

Hey. Here’s my code for exercise 4:

The sum of a range

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

function sum(range) {
 answer = 0;
  for(var i = 0; i <= range.length; i++) {
    answer += i;
  }
  return answer;
}

Reversing an array

function reverseArray(array) {
  reverse = [];
  for(let item of array) {
   reverse.unshift(item); 
  }
  return reverse;
}

I’m still working on the ‘reversing in place’, but for now, it’s back to work…

had some trouble with bringing the array value out, it only works if the functions were wrapped around my range function.

Sum of an Array
function range (start, end, step = 1) {
  if (step === 0) {
    step++;
  }
  let list = [];
  if (step > 0) {
    while (start <= end) {
      list.push(start);
      start = start + step;
    }
    return list;
  }
  else {
    while (start >= end) {
      list.push(start);
      start = start + step;
    }
    return list;
  }
}

function sum (list) {
  let total = 0;
  for (let i = 0; i < list.length; i++) {
    total = total + list[i];
  }
  return total
}
Reversing an Array
function reverseArray(list) {
  let rev = []
  for (let i = 1; i <= list.length; i++) {
    rev.push(list[list.length - i]);
  }
  return rev
}

function reverseArrayInPlace(list) {
  lon = list.length;
  for (let i = lon; i > 0; i--) {
    list.push(list[i-1]);
  }
  for (let i = 0; i < lon; i++) {
    list.shift();
  }
}

Range() and Sum()

function range(start,end,step=1){
    result=[];
     if(start>end){
     //make start <= end
          temp=start;
          start=end;
          end=temp;
      }
     if(step==0){//if step is 0 then return empty result
          return result;
     }
     if(step<0){//for negative step go from end to start
          for(i=end;i>=start;i+=step){
               result.push(i);
           }
      }else{//for positive step go from start to end
          for(i=start;i<=end;i+=step){
               result.push(i);
           }
      }
     return result;
}

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

Reversing an array

reverseArray()

function reverseArray(arr){
     result=[];
     for(let i in arr){
          result.unshift(arr[i]);
     }
     return result;
}

reverseArrayInPlace()

  function rev(arr){
     		for(i=0;i<(arr.length/2);i++){

  		//swap only if i is not at middle
  		if(i!=arr.length/2&&i!=arr.length-(i+1)){
  
  			//swap in place
         	arr[i]=arr[i]+arr[arr.length-(i+1)];
          	arr[arr.length-(i+1)]=arr[i]-arr[arr.length-(i+1)];
  			arr[i]=arr[i]-arr[arr.length-(i+1)];
          }
      }
      return arr;
  }

having a good deal of difficulty with this, but I think this is right…

The sum of a range:
function range(start, end) {
var rangeArray= [];
if(start < end) {
let index= 0;
for (let i= start; i<=end; i++){
rangeArray[index] = start+index;
}
} else {
alert(“Provide argument where start is smaller than the end.”);
}
console.log(rangeArray);
}
range(5,10);

Reversing an array: *this is one I had a lot of trouble with:

function reverseArray (int arr[], int start, int end){
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start ++;
end–;
} else {
function reverseArrayInPlace(start > end, start++);
}
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";

cout << endl;
}
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6};

// To print original array
printArray(arr, 6);
 
// Function calling
rvereseArray(arr, 0, 5);
 
cout << "Reversed array is" << endl;
 
// To print the Reversed array
printArray(arr, 6);
 
return 0;

}
}

//The Sum of a Range:
let arr = [];
let sumTotal = 0;

	function range (start, end, step) {

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


	function sum(myArray) {

		for(i=0 ; i< myArray.length; i++){
			sumTotal = sumTotal+myArray[i];
		}
		return sumTotal;

	}

//reverse array
let myArray = [1,2,3,4,5,6,7,8,9,10];
let newArray =[];

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

//reverse array in place
function reverseArrayInPlace(arr) {
let numOfSwaps = Math.floor(arr.length / 2);
for(i=0 ; i < numOfSwaps; i++) {
let holdValue = arr[i];
arr[i]=arr[arr.length-1-i];
arr[arr.length-1-i]=holdValue;
}
return arr;
}

  1.      <script>
       function range(a,b,c=1){
         let ran_array = [];
         if (a<b){
           for (let i=a; i<=b;i+=c){
             ran_array.push(i);
           }
           return ran_array;
         }
         else{
           if(c<0){
             for (let i=a; i>=b;i+=c){
               ran_array.push(i);
             }
             return ran_array;
           }
           else{
             return 'not possible'
           }
         }
       }
       function sum(numbers){
         let summ = 0;
         for(let numbs of numbers){
           summ += numbs;
         }
         return summ;
       }
       console.log(sum(range(1,10)));
       console.log(sum(range(1,10,2)));
       console.log(range(5,2,-1));
       </script>
    
  2.  <script>
         let first_array = ['q','w','e','r','t'];
         let second_array = ['q','w','e','r','t'];
         function reverseArray(a) {
           let new_array = [];
           for (let i of a){
             new_array.unshift(i);
           }
           return new_array;
         }
         function reverseArrayInPlace(a) {
           a_len = a.length;
           for(let i=0;i<=Math.floor(a_len/2);i++){
             let old_val = a[i];
             console.log(old_val);
             a[i] = a[a_len-1-i];
             a[a_len-i-1] = old_val;
           }
           return a;
         }
         console.log(reverseArray(first_array));
         console.log(first_array);
         console.log(second_array);
         console.log(reverseArrayInPlace(second_array));
         console.log(second_array);
       </script>
1 Like

Actually var (or let) is no needed in code until is really needed:) Code works even when you take out all var-s (or let-s):P:)

1 Like

**Chapter 4 **

EX 1
The sum of a range

      function ArRange(x,y,step){
      arr=[];
      for (counter=x; counter<=y; counter+=step){
        arr.push(counter);
        }
      console.log(arr);
    }

    function ArSum(arr){
    var sum=0;
    var n=arr[arr.length-1];
    $.each(arr, function(index, value){
         sum +=value;
     });
       console.log(sum);
     }
           ArRange(1,10,1);
           ArSum(arr);

EX2
Reverse Array

   function reverseArray(arr){
   var revArr=[];
   var n=arr.length-1;
    for (counter=n; counter>=0; counter--){
                  revArr.push(arr[counter]);
                   }
                   console.log(revArr);
                }


    function reverseArrayInPlace(arr){
              var arrLen=arr.length;
              for (counter=0; counter<(arrLen-1); counter++){
                    var old_val=arr[counter];
                    arr[counter]=arr[arrLen-1-counter];
                    arr[arrLen-1-counter]=old_val;
                }
                console.log(arr);
        }
1 Like
// The Sum of a Range
function range(start, end, step){
	let arrayRange = [];
  if(step){
    if(end < start){
      for(let i = start; i >= end; i+=step){
      	arrayRange.push(i)
      }
    }
    else {
      for(let i = start; i <= end; i+=step){
      	arrayRange.push(i)
      }
    }
  }
  else {
   for(let i = start; i <= end; i++){
      arrayRange.push(i)
    }
  }
  return arrayRange;
}

function sum(arraySum){
  let result = 0;
  for(let number of arraySum){
    result += number;
  }
  return result;
}


// Reversing an Array
console.log("Reversing an Array");
function reverseArray(a){
	let arrayNew = [];
	for(let i = a.length - 1; i >= 0; i--){
		arrayNew.push(a[i]);
	}
	return arrayNew;
}

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

1 Like

And that is my solution:

var sumValue = 0;

function sum(a){
  $.each(a,function(index,value){
    sumValue = value + sumValue;
    console.log(index, value, sumValue)
  });
  sumValue = 0;
}

function range (start,end,step){
  var array = [];
  if (step==0) {step = 1};
  if (start<end){
    for (start; start <= end; start = start + step){
      array.push(start);
    }
  }else if(start>end){
    for (start; start >= end; start = start + step){
      array.push(start);
    }
  }
  return array;
}
console.log(sum(range(1,10,2)));

function reverseArray(array){
  var newArray = [];
  for(var x = 0; x<array.length; x++){
    newArray.push(array[array.length-1-x]);
  }
  return newArray;
}
console.log(reverseArray([2,4,6]));

function reverseArrayInPlace(array){
  for(var x = 0; x<array.length;x++){
    var store1 = array[array.length-1-x];
    var store2 = array[x]
      console.log(store1,store2)
    array[x] = store1;
    array[array.length-1-x] = store2;
  }
  return array;
}
console.log(reverseArrayInPlace([2,4,6]));
1 Like

The sum of a range

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

function sum(array) {
if(array.length === 0)
return 0;
return array.pop() + sum(array);
}

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

1 Like

Reversing an Array
function reverseArray(a){
let arrayNew = [];
for(let i = a.length - 1; i >= 0; i–){
arrayNew.push(a[i]);
}
return arrayNew;
}
console.log(reverseArray([2,4,6,10]));

function reverseArrayInPlace(a){
for(let i = 0; i < Math.floor(a.length/2); i++){
let aux = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = aux;
}
return a;
}
console.log(reverseArrayInPlace([2,4,6]));

1 Like

Range Function

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

Sum Function

function sum(a){
let result = 0;
for(let number of a){
result += number;
};
return result;
};

Reverse Array Function

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

Reverse Array in Place Function

function reverseInPlace(…a){
let arr=[];
arr.push(…a);
for (var i = 0, j = arr.length - 1; i < j; i++, j–) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
return arr;
};

1 Like

This is my solution to “The Sum of a Range”:

        function range(start, end, step) {

            let rangeArray = [];

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

            return rangeArray;
        }

        function sum(numberArray) {
            let totalSum = 0;
            for(let i = 0; i < numberArray.length; i++) {
                totalSum += numberArray[i];
            }
            return totalSum;
        }

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

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

“Reversing an Array”:

        let testArray = [0, 4, 10, 30, 49];

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

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

            }
            return array;
        }

        console.log(reverseArray(testArray));
        //Array(5) [ 49, 30, 10, 4, 0 ]
        console.log(reverseArrayInPlace(testArray));
        //Array(5) [ 49, 30, 10, 4, 0 ]

// Compute range between two parameters //
function computeRagme(start,end){
let arrayofNum = [];
let count = 0;
for(i = start; i <= end; i++){
arrayofNum[count] = i;
count++;
};
return(arrayofNum);
};

// Sum of a range //
function arraySum(arrayofNum){
let sum = 0;
for(let item of arrayofNum){
sum = item + sum;
};
return sum;
};

// Compute range between two pararameters allowing negative and positive steps //
function computeRange(start,end,step=1){
let arrayofNum = [];
let count = 0;
if(start < end){
for(i = start; i <= end; i=i+step){
arrayofNum[count] = i;
count++;
};
}else{
for(i = start; i >= end; i=i+step){
arrayofNum[count] = i;
count++;
};
};
return(arrayofNum);
};

// Reverse Array Creates New Arra //

function reverseArray(myArray){
arrayLength = myArray.length;
newArray = [];
for(let i=0; i < myArray.length; i++){
newArray[arrayLength-1] = myArray[i];
arrayLength = arrayLength - 1;
};
return newArray;
};

1 Like