Chapter 4 - Exercises

I have challenged myself to combine the two exercises and add a form with a button:
On the page you enter the Start, End and Step of the Array.
Console will return the array and also the array in reverse.

It was harder than i thought but it finally worked out.
It is fun to play with, when you make large arrays you get interesting patterns in the console.
This could be a great exercise for all students.

How can i clear the form after the button is pushed?
I tried some stuff i found on the web but it did not work out.

Here is my code:

<html>
  <head>
      <title> Range Array </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

  </head>

  <body>

    <input id="inputStart" placeholder="Start" type="text">
    <input id="inputEnd" placeholder="End" type="text">
    <input id="inputStep" placeholder="Step" type="text">
    <button id="rangeButton">Range</button>

    <script>
//The sum of a range
  function range(start, end, step) {
    if (typeof step === 'undefined') {
     step = 1;
      }

  	var len = end - start + 1;
  	var outputArray = new Array(len);
  	for (let i = 0; i < len; i+= step) outputArray[i] = start + i;
  	//return outputArray;

    var filtered = outputArray.filter(function (el) {
      return el != null;
    });
//delete all empty values (filter)
    return filtered;

  }



$("#rangeButton").click(function(){
  var rangeStart = $("#inputStart").val();
  var rangeEnd = $("#inputEnd").val();
  var rangeStep = $("#inputStep").val();

  console.log(range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep)));
  console.log(reverseArray(range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep))));

});

/*Reverse Array
*/

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

  return rArray;

}

    </script>
  </body>
</html>
1 Like

Aloha! I finally managed to solve the range and sum functions but the step argument is still breaking my head. When I look at some of the solutions here and in the book i totally get it. I am trying as hard as possible to adjust my range function to include the step because I want to solve it on my own as a total noob to programming. Proud that I made it this far…

Any input and constructive criticism is highly appreciated :slight_smile:

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

    if (start > end){
 
	for(i=start; i>=end; i--) arr.push(i)
    }

 else {
  
  for(i=start; i<=end; i++) arr.push(i)
 }

return arr;

};

function sum(arr){

let result = 0;

for (i=0; i<=arr.length; i++){
 	result = result + i
  }

return result

};

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

1 Like

Hi Malik,
I appreciate the likes you give on the homework assignments, but a little feedback would be nice.
Also i asked a question but did not get any response.
:v:

Please let me know if there are more efficient ways to do these!

Sum of Range

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

      function sumArray(array){
        if (toString.call(array) === "[object Array]"){
          var totalValue = 0;
          $.each(array,function(index,value){
            totalValue += value;
          });
          return totalValue;
        }
        else{return "Invalid Parameters"}
      }

      function sumRangeStep(start, end, step){
        var sum = sumArray(range(start,end,step));
        return sum;
      }

Reverse Array

      function reverseArray(array){
        newArray = [];
        $.each(array,function(index,value){
            newArray.unshift(value);
        });
        return newArray;
      }

      function reverseArrayInPlace(array){
        for(i=0; i<(array.length)/2; i++){
          var back = array[array.length - (i+1)];
          var front = array[i];
          array[array.length - (i+1)] = front;
          array[i] = back;
        };
        return array;
      }
1 Like

Hey @Gos ,

To clear the input fields you can simply do a value reassignment on a button click.

Please check the code below –

<html>
  <head>
    <title>Range Array</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>

  <body>
    <input id="inputStart" placeholder="Start" type="text" />
    <input id="inputEnd" placeholder="End" type="text" />
    <input id="inputStep" placeholder="Step" type="text" />
    <button id="rangeButton">Range</button>

    <script>
      //The sum of a range
      function range(start, end, step) {
        if (typeof step === "undefined") {
          step = 1;
        }

        var len = end - start + 1;
        var outputArray = new Array(len);
        for (let i = 0; i < len; i += step) outputArray[i] = start + i;
        //return outputArray;

        var filtered = outputArray.filter(function (el) {
          return el != null;
        });
        //delete all empty values (filter)
        return filtered;
      }

      $("#rangeButton").click(function () {
        var rangeStart = $("#inputStart").val();
        var rangeEnd = $("#inputEnd").val();
        var rangeStep = $("#inputStep").val();

        console.log(
          range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep))
        );
        console.log(
          reverseArray(
            range(parseInt(rangeStart), parseInt(rangeEnd), parseInt(rangeStep))
          )
        );

        $("#inputStart,#inputEnd,#inputStep").val("");
      });

      /*Reverse Array
       */

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

        return rArray;
      }
    </script>
  </body>
</html>

type or paste code here

Hope this helps. :slight_smile:

1 Like

1:
function range(start, end, step) {
arrey = [];
if (start < end) {
for (start; start < end+1; start = start + step) {
arrey.push(start);
}
}

      else {
        for (start; start > end-1; start = start + step) {
          arrey.push(start);
        }
      }
      return arrey;
    }



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

2:
function reverseArray (array) {
for (i = array.length -1; i > -1; i = i-1) {

          array.push (array[i]);
          array.splice(i, 1);
        }
        return(array);
      }


      console.log(reverseArray(["A", "B", "C", "D"]));

      let arrayValue = [1, 2, 3, 4, 5];
      reverseArray(arrayValue);
      console.log(arrayValue);
1 Like

Sum of Range:

var range = function (start, end) {
  var arr = [];
      cnt = start;

      while (cnt <= end) {
      arr.push(cnt);
      cnt++;
      }
      return arr;
};

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

      while (arr.length > 0)  {
      total = total + arr.pop();
}
      return total;
};

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

Reversing an array:

const reverseInPlace = (arr) => {
let temp
for (let i = 0; i < arr.length / 2; i++) {
temp = arr[i]
arr[i] = arr[arr.length - 1 - i]
arr[arr.length - 1 - i] = temp
}
return arr
}
const arr = [1, 2, 3, 4, 5]
console.log(reverseInPlace(arr))
1 Like

im getting a NaN here and i dont know why. can you shed some light please?

@Malik

function range (start, end){
var ofRange=[];
for (var x=start; x<=end; x++){
ofRange.push(x)
}
return ofRange;
}
console.log (range(1,10));
var arr2=[];
arr2=range(1,10);

function sum (arr1){
var total=0;
for (var x=0; x<=arr1.length; x++){
total=total+arr1[x]
}
return total;
}
console.log (sum(arr2));

1 Like

I’m completely confused on this one. I’m new to coding, and this is getting difficult. Would anyone be willing to help?

HI @dpturner,

You can check out these posts for a better understanding of these problems –



If these posts didn’t help either, I would suggest you fo the course videos again and understand the logic flow of the language. On top of that, you can take help from the internet specifically YouTube videos to speed up your understanding.

Hope this helps.

Happy Learning! :smiley:

sum_range
<script>

  function range(start,end){ // create range function that take in two arguments
    arr = [];// return an array
    counter = start;

    while (counter <= end){

      arr.push(counter); // push to array the count value
      counter++; // until the end value
    }

    return arr;



  };




  function sum(arr){ // array pass into this sum function
    var total = 0;
    for (let i = 0; i < arr.length; i++){
      total += arr[i];


    }

    return total;

    };



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


 //Reverse array



   var new_array = []; //make an empty new_array

   function reverseArray(arr){



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



   };

   reverseArray([5,6,7,8,9,10]);














</script>
1 Like

var array = [];

            function range(arr, arr1) {
                var lower = Math.min(arr);
                var upper = Math.max(arr1);
                for (var i = lower; i <= upper; i++) {
                    array.push(i);
                }
            }

            function sum() {
                var total = 0;
                for (var i = 0; i < array.length; i++) {
                    total = total + array[i];
                }
                return total;
            }
            console.log(sum(range(1, 10)));
      var returnArray = [];
		function reverseArray(anArray) {
			index = 0;
			for (let i = anArray.length-1; i >= 0; i--) {
			  returnArray[index] = anArray[i];
			  index++;
			}
			return returnArray;
		};

		reverseArray([5,7,8,2,1]);
		console.log(returnArray);
1 Like

//reverseArray()
var array1 =[0,1,12,2,2,3,4,7];

var newInvertedArray =[];

function reverseArray(){
for (cnt=array1.length-1;cnt>=0;cnt–) {
newInvertedArray.push(array1[cnt]);
}};
reverseArray();

//reverseArrayInPlace(){
function reverseArrayInPlace(){
var initialLengthOfArray = array1.length;
for (cnt=array1.length-2;cnt>=0;cnt–) {
let varcnt = array1[cnt];
array1.push(varcnt);
};

array1.splice(0,initialLengthOfArray-1);

}
reverseArrayInPlace();

1 Like

Sum Of Range

var range = function(start, end){
var arr = [];
cnt = start;

  while (cnt <= end){
    arr.push(cnt);
    cnt++;
  }
  return arr;

};

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

  while(arr.length>0) {
       total = total + arr.pop();
  }
  return total;

};

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

Reverse Array

var ansArray = [];

function reverseArray(anArray){
index = 0;
for (let i= anArray.length-1; i>=0; i–){
ansArray[index] = anArray[i];
index++;
}
return ansArray;
};

reverseArray([2,4,6,8,10]);
console.log(ansArray);

1 Like
  <button>Reverse Array</button>
    <ul>
      </ul>

  <script>

//The Sum Of A Range
var range = function(start, end) {
var arr = [];
cnt = start;

    while (cnt <= end) {
      arr.push(cnt);
      cnt++;

    }
    return arr;
 };

 var sum1 = function(arr) {
   var  total = 0;

   while(arr.length > 0) {
     total = total + arr.pop();
   };
   return total;
 };

 var sum2 = function(arr) {
   var total = 0;

   for (let i = 0; i < arr.length; i++) {
     total = total + arr[i];
  }

  return total;

};

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

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

//Reverse An Array
let arrys = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
//console.log(arry.length);
function reverseArray(){
let arryTemp = arrys.map(arry => ‘

  • ’ + arry + ‘
  • ’).join(’\n’);
    document.querySelector(‘ul’).innerHTML = arryTemp;
    }
      reverseArray();
       document.querySelector('button').addEventListener('click', () => {
        arrys = arrys.reverse();
       reverseArray();
      });
    1 Like

    Sum ranges:

    let sumArray = [];

    function range(x,y){
    for(i=x; i<=y; i++){
    sumArray.push(i);
    }
    return sumArray
    }

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

    let sumArrayB = []
    function rangeStep(a,b,c){
    if (c > 0){
    for(i = a; i <= b; i = i += c){
    sumArrayB.push(i);
    }
    }
    if (c < 0){
    for(i = a; i >= b; i = i += c){
    sumArrayB.push(i);
    }
    }
    return sumArrayB
    }

    The two reverse arrays:

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

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

    1 Like

    THE SUM OF A RANGE

    function sum_of_range(start, end) {
    return end * (end + 1) / 2 - start * (start + 1) / 2;
    }

    1 Like
    <script>
    
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    
    document.getElementById("demo").innerHTML = fruits.reverse();
    
    </script>
    
    </body>
    
    </html>
    
    1 Like

    Here are my solutions. I still need to work on the steps part, will update the code soon.

    1. The sum of a range
        <div>
          <p id="orderedList"></p>
          <p id="inverseList"></p>
          <p id="reversedList"></p>
        </div>
    
    
        <script>
        // reversing an array
    
        let numbersArray = [];
    
        let reverseArray = [];
    
        function reverseNumbers(start, end){
          // with this code we add the numbers to our list
          for (var i = 0; i <= 10; i++){
    
            numbersArray.push(i);
          };
    
          document.getElementById("orderedList").innerHTML = "The numbers on this list are in order: " + numbersArray + "";
    
          // with this code we reverse the numbers in the list
          for (let i = numbersArray.length -1; i >= 0; i--){
    
            numbersArray.push(i);
          };
    
        };
    
        reverseNumbers(1,10);
    
        reverseArray = numbersArray.slice(11,22);
    
        console.log(reverseArray);
    
        document.getElementById("inverseList").innerHTML = "The numbers on the list have been reversed! " + reverseArray + "";
    
        </script>
    
    1. Reversing an array
        <script>
        // reversing an array in place
    
        var arrayinPlace = [1,2,3,4,5,6,7,8];
    
        function reverseArrayInPlace(arr) {
          for (var i = 0; i <= (arr.length / 2); i++) {
              let number = arr[i];
              arr[i] = arr[arr.length - 1 - i];
              arr[arr.length - 1 - i] = number;
          }
          //return number;
        };
    
        reverseArrayInPlace(arrayinPlace);
    
        console.log(arrayinPlace);
    
        document.getElementById("reversedList").innerHTML = "This list in place is reversed! " + arrayinPlace + "";
    
        </script>
    
    1 Like