Chapter 4 - Exercises

Chapter 4 Exercises

sum_of_range.js
  var sum = 0;
  var diff = end - start;
  var phrase = "The sum of integers from " + start + " to " + end + " is ";
  for(var counter = 0; counter <= diff; counter++){
    sum += start + counter;
    console.log(sum);
  }
  console.log(phrase + sum);
}
sumOfRange(1, 10);

reversing_an_array.js

function reverseArray(arrayInput){
  var reversed = [];
  var arrayInputLength = arrayInput.length;
  for(var counter = 0; counter < arrayInputLength; counter++){
    var element = arrayInput.pop();
    reversed.push(element);
  }
  console.log(reversed);
}
reverseArray(fruits);

function reverseArrayInPlace(arrayInput){
  for(var xxx = 0; xxx < Math.floor(arrayInput.length/2); xxx++){
    [arrayInput[xxx], arrayInput[arrayInput.length-1-xxx]] = [arrayInput[arrayInput.length-1-xxx], arrayInput[xxx]]
  }
  console.log(arrayInput);
}
reverseArrayInPlace(fruits);
fruits.push("Cherry");
reverseArrayInPlace(fruits);

1 Like

For reverse array questions:

        var list = ['a', 'b', 'c', 'd', 'e'];

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

        function reverseArrayInPlace(arr){
            for(var x = 0; x < arr.length/2; x++){
                var y = arr.length-(x+1);
                var holder = arr[y];
                arr[y] = arr[x];
                arr[x] = holder;
            }
            return arr;
        }
1 Like

I’ve added a new country to the object and I can see it in the object but when the user enters that specific country it doesn’t come up, anyone that can help?

var flagObject = {“norway”: [“red”, “white”, “blue”],
“sweden”: [“blue”, “yellow”],
“denmark”: [“red”, “white”],
“finland”: [“white”, “blue”],
“japan”: [“red”, “white”],
“gabon”: [“green”, “yellow”, “blue”],
“United Kingdom”: [“red”, “blue”, “white”],
“chile”: [“blue”, “white”, “red”]
};

console.log(flagObject);
flagObject.Germany = [“black”, “red”, “yellow”];

function color() {
let country = prompt(“Choose a country”);
country = country.toLowerCase();

if (country in flagObject){
console.log(flagObject[country]);

}else {
console.log("The flag color of ", country, “is not in the list”);
}
};

color();

Sum of a Range:

let arr = [1, 4];
let fullArr = [];
let sum = 0;
const reducer = (accumulator, currentValue) => accumulator + currentValue;
arr.sort(function(a,b){return a-b});
for (let i = arr[0]; i <= arr[1]; i++) {
fullArr.push(i);
}
sum = fullArr.reduce(reducer);
console.log(sum);

function sumAll(arr) {

let fullArr = [];
let sum = 0;
const reducer = (accumulator, currentValue) => accumulator + currentValue;

arr.sort(function(a, b) {
    return a - b
});

for (let i = arr[0]; i <= arr[1]; i++) {
    fullArr.push(i);
}

sum = fullArr.reduce(reducer);

return sum;

}

Reversing an Array:

let reverseArray = (arr) => {
//Temp array
let temp = [];

for(let i = 0; i < arr.length; i++){
   //Copy all the values in reverse order
   temp[i] = arr[arr.length - i - 1];
}

return temp;
}

Input:
console.log(reverseArray([1, 2, 3, 4, 5]));

Output:
[5, 4, 3, 2, 1];

1 Like

Chapter 4 Excercises

Sum of a range function range(start, end, step = start < end ? 1 : -1) { let array = [];

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

function sum(array) {
let count = 0;
for (let value of array) {
count += value;
}
return count;
}

Reverse Array

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

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

1 Like

Here’a a different take on this problem using push and pop:

var array = [1,2,3,4,5,6,7,8,9,10];
var newArray = [];
for (var n = 0; n < 10; n++){
var removed = array.pop();
newArray.push(removed);
};

alert(newArray);

1 Like

Okay guys, this was the most fun so far! Also, for me, quite difficult to understand the logic sometimes :smiley:
I will paste my solution here, please let me know if there is redundancy. Thanks!

Sum Of A Range:

<script text="text/javascript">

            let rangeArray = [];
            function rangeMaker(a,b,c) {
                if ( c>1 && a<b ) {
                    for ( ; a<=b ; a+=c ) {
                        rangeArray.push(a);
                        console.log("1st loop");
                    }
                }
                else if ( c==1 && a<b ) {
                    for ( ; a<=b ; a++) {
                        rangeArray.push(a);
                        console.log("2nd loop");
                    }
                }
                else if ( c==-1 && a<b ) {
                    for ( ; a<=b ; a--) {
                        rangeArray.push(a);
                        console.log("3rd loop");
                    }
                }
                else if ( c<-1 && a<b ) {
                    for ( ; a<=b ; a = a-c) {
                        rangeArray.push(a);
                        console.log("4th loop");
                    }
                }
                else if ( c>1 && b<a ) {
                    for ( ; b<=a ; a = a-c ) {
                        rangeArray.push(a);
                        console.log("5th loop");
                    }
                }
                else if ( c==1 && b<a ) {
                    for ( ; b<=a ; a-- ) {
                        rangeArray.push(a);
                        console.log("6th loop");
                    }
                }
                else if ( c==-1 && b<a ) {
                    for ( ; b<=a ; a--) {
                        rangeArray.push(a);
                        console.log("7th loop");
                    }
                }
                else if ( c<-1 && b<a ) {
                    for ( ; b<=a ; a+=c) {
                        rangeArray.push(a);
                        console.log("8th loop");
                    }
                }
                else  { 
                    alert("invalid numbers");
                    }
            }
            
            function sumConstructor(rangeArray) {
                let result = 0;
                rangeArray.forEach(element => {
                    result += element;
                });
                return result;
            }
            rangeMaker(10,3,-3);
            console.log(rangeArray);
            let sumOfRange = sumConstructor(rangeArray);
            console.log(sumOfRange);
        </script>

Reverse an Array and Produce a New Array:

<script text="text/javascript">
            let theArray = [0,1,4,3,4,5];
            function reverseArray(theArray) {
                let newArray = [];
                let counter = 0;
                for (let i of theArray) {
                    newArray.unshift(i);
                    console.log("Unshifted: " + i)
                    counter++;
                }
                console.log(counter);
                return newArray;
            }
            let result = reverseArray(theArray);
            console.log("New Array: " + result);
            console.log("Original Array: " + theArray)
        </script>

Reverse an Array in Place:

<script text="text/javascript">
            let theArray = [0,1,4,3,4,5];
            let originalArray = theArray;
            
            console.log("Original Array: " + originalArray);
            function reverseArrayInPlace(theArray) {
                for ( i=0 ; i<theArray.length ; i++) {
                    theArray.unshift(i);
                    theArray.pop();
                    console.log("Unshifted: " + i);
                }
                return theArray;
            }
            let result = reverseArrayInPlace(theArray);
            console.log("New Array: " + result);
        </script>
2 Likes

// ----------------------RangeFunction-------------------
var rangeArray = [];
var step = 0;

function range(start, end, stepNum) {
if (stepNum > 0) {
for (var i = start; i <= end; i += stepNum) {
rangeArray.push(i);
}
return rangeArray;
} else {
for (var i = start; i >= end; i += stepNum) { // if stepNum is negative, <= flips to >=.
rangeArray.push(i);
}
return rangeArray;
}
};
//console.log(range(10, 1, -1)); // Range goes here to return the Range Function;

// ----------------------Addition function------------------------------
var sumNum = 0;

function sum(range) {
for (var i = 0; i < rangeArray.length; i++) {
sumNum += rangeArray[i];
}
return "Range: " + rangeArray + “\n” + "Sum: " + sumNum;
}
console.log(rangeArray); // prints range to sum below.
console.log(sum(range(100, 0, -10))); // Sum function input here to see both functions.

function startFunc() {
range();
sum();
}

startFunc();

=======================================

// Reversing an array into a new array; taking that array and reversing it back into a new array.

var array1 = [“one”, “two”, “three”, “four”, “five”, “six”, “seven”, “eight”, “nine”];
var newArray = [];
var array2 = [];

function reverseArray(arr) { // First function to reverse array.
for (var i = array1.length -1; i >= 0; i -= 1) {
newArray.push(arr[i]);
};
return "Reverse Array " + “\n”+ newArray;
}

console.log(reverseArray(array1));
//console.log(array1 === newArray); // Proves arrays are different arrays.

function reverseArrayInPlace(arr) { // Second function to reverse back the array.
for (var i = newArray.length -1; i >= 0; i -= 1) {
array2.push(arr[i]);
};
return "Reverse Array In Place " + “\n”+ array2;
}

console.log(reverseArrayInPlace(newArray));
//console.log(newArray === array2);

1 Like

It helps, thanks for the explanations :+1:

Thanks @jon_m I was looking for some discussion on this and my suspicions are aligned with your somewhat more substantiated points.

1 Like
//Hello Everyone lets do some Javascript
    console.log("Hello World");

//Calculate the sum of a range of numbers
  
sum = 0;
    
function range(x, y){
    let array =[];
    for (i = x; i < (y+1); i++){array.push(i);
    sum = sum + i;
    
    }return array; return sum;
 

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

// Reverse an array making a new array   

<DOC Type html>
<html>
    
<head>
    
<title> </title>
</head>
    

<body>

<script scr = "underscore.js"></script>
<script scr = "app.js"></script>
    
<script>

//Hello Everyone lets do some Javascript
    console.log("Hello World");
 


function reversearrayinplace(array){
length = array.length    
for(let i = length; i = 0; i--){
   array.push(array[length -i]);  
                             } return array; console.log(array);
    } 
    
    array =['5','4','3','2','1']
   console.log(reversearrayinplace(array));  
  
2 Likes

yes the reason its not showing up is because the code is written incorrectly it should be written as an array // flagObject[“Germany”] = [“black”, “red”, “yellow”]; // … edited updated… you actually can use flagObject.Germany = [“black”, “red”, “yellow”]; it is the same thing you just need to put it above the console.log… https://youtu.be/Y6nUGuoI0sQ @36:24 here is a video I have been watching to learn more about this. I always thought you use .push to add to an array but obviously you can do it this way too

Nice Coding Man… Damn makes me want to just give up now…lol jk just going to lean more towards project management then actual coding…lol

1.Sum of Range

var range = function(start, end) {
  var arr = [],
    cnt = start;
  function increaseCnt(cnt)  {
    if (cnt >= end) {
      return arr.push(end);
    } else {
      arr.push(cnt);
      increaseCnt(++cnt);
    }
  };
  increaseCnt(cnt);
  return arr;
};

var sum = function(arr) {
  return arr.reduce(function(total, value) {
    return total + value
  });
};

console.log(sum(range(1,10)));
  1. Reverse array in place.

const resverseInPlace = (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,6,7,8,9]
console.log(resverseInPlace(arr));

I know this is not the complete answers to the questions but I feel like I need to move on but I will be back to read more and better understand all of this in the near future.

2 Likes

Thank you Daniel!

I knew it works but I didnt get why I get the error. Now I know, above the console.log!

1 Like

Hi everybody,

I’ve completed the exercises. However, I am puzzled by the little question about pure functions and side effects at the end of the reverser-array exercise. Could anyone shed some light on how this question is related to the exercises?
I guess we can recycle pure functions more easily by plugging them directly into programs to get the desired actions done, but how are they related to the speed of codes?
Thank you.

Eric

1 Like

Something seems to be wrong with my solution of “The sum of a range” (see comment below). I would appreciate your help! @thecil

function range(start, end, step){
    let numbers = [];

    if ((start > end && step > 0)
        || (start < end && step < 0)){

        return numbers;
    }

    if (step > 0){
        for(let i = start; i <= end; i += step){

            numbers.push(i);
        }
    }
    else{
        for(let i = start; i >= end; i += step){

            numbers.push(i);
        }
    }

    return numbers;
}

function sum(array){
    let total = 0;

    for (let value of array){
        total += value;
    }

    return total;
}

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

// If I run any log commands after the first two, I sometimes get "Canceled" as output in the VS-Code debug console before everything is evaluated. Why? Is there anything wrong with my code?

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

Hi @derdis14, hope you are well.

I just copied/pasted your code in https://codepen.io/ and it works perfectly, so probably could be an issue with VS-code debug console.

Proof of Work :crazy_face::
image

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like

Chapter 4 exercises.

Reversing Array:

const MyArray = [ 2, 4, 6, 8 ];
console.log (MyArray): // [ 2, 4, 6, 8
]

MyArray . reverse();
console.log (MyArray); // [ 8, 6, 4, 2 ]

A call to reverse returns a reference to the reversed MyAarray.

The reverse array will be the variant that is expected to be useful in terms of computing speed.

2 Likes

Dude man, nice work!