Sunday, May 30, 2021

Javascript Practice 69: JS Hero - gcd

 
Question: 

Write a function gcd that takes two natural numbers and calculates their gcd.

Example: gcd (6, 15) should return 3.




Answer: 

function gcd (a,b) {

if (b == 0) {
return a;
} else { 

let remainder = a % b; 
return gcd (b, remainder);
}
}

--- we need to understand 'euclid's alogrithm for gcd'
--- if we subtract a smaller number from a larger (we reduce a larger number), GCD doesn’t change. So if we keep subtracting repeatedly the larger of two, we end up with GCD.
--- now instead of subtraction, if we divide the smaller number, the algorithm stops when we find remainder 0.
--- If A = 0 then GCD(A,B)=B, since the GCD(0,B)=B, and we can stop
--- If B = 0 then GCD(A,B)=A, since the GCD(A,0)=A, and we can stop.

> we declare a function 'gcd'
> it has 2 parameters: 'a' and 'b'
> if b is equal to 0, then a shall be the gcd (if you understand euclids alogorithm)
> if b is not equal to 0, then we calculate the remainder
> we create a variable 'remainder'
> we initialize it with a value / remainder that we get by dividing a by b; using modulo operator
> like this a % b; we use the modulo / remainder operator
> we then return the same function gcd with two parameters (b, remainder) 
> this will again call the function gcd (a,b) but this time it will have a value of (a = b, b = remainder)
>>> we should try and understand this with an example to get clarity
>>> let us assume that we call the function gcd with some numbers
>>> like this: gcd (45, 99) ====>>> gcd (a,b)
>>> first it will check if b = 0; but b = 99
>>> so it will execute the code in the else block
>>> it will divide 45 / 99 using the remainder operator and store the output in the remainder variable
>>> the output shall be 45 % 99 = 45; so remainder = 45
>>> now we return the gcd function again with new values
>>> gcd (99, 45) ====>>> gcd (b = 99, remainder as calculated = 45)
>>> so our original parameters shall now be gcd(99, 45) ====>>> gcd(a = 99, b = 45)
>>> first it will check if b = 0; but b = 45
>>> so it will execute the code in the else block
>>> it will divide 99 / 45 using the remainder operator and store the output in the remainder variable
>>> the output shall be 99 % 45 = 9; so new remainder = 9
>>> now we return the gcd function again with new values
>>> gcd (45, 9) ====>>> gcd (b = 45, remainder as calculated = 9)
>>> so our original parameters shall now be gcd(45, 9) ====>>> gcd(a = 45, b = 9)
>>> again it will check if b = 0; but b = 9 >>> so it will execute the code in the else block
>>> it will divide 45 / 9 using the remainder operator and store the output in the remainder variable
>>> the output shall be 45 % 9 = 0; so remainder = 0
>>> now we return the gcd function again with new values
>>> gcd (9, 0) ====>>> gcd (b = 9, remainder as calculated = 0)
>>> so our original parameters shall now be gcd(9, 0) ====>>> gcd(a = 9, b = 0)
>>> again it will check if b = 0; and this time b = 0 
>>> so it will return a which is 9 
>>> and this is our GCD value for 2 numbers

Saturday, May 29, 2021

Javascript Practice 68: JS Hero - do...while loop

 
Question: 

Write a function lcm that takes two natural numbers and calculates their least common multiple (lcm). The lcm of two natural numbers a und b is the smallest natural number that is divisible by a and b.

Example: lcm(4, 6) should return 12.




Answer: 

function lcm(a, b) {

  let theLCM = 0;
  let remainderA;
  let remainderB;

  do {

    theLCM++;
    remainderA = theLCM % a;
    remainderB = theLCM % b;

  } while (remainderA !== 0 || remainderB !== 0)

  return theLCM;
}



> we declare a function lcm
> it has 2 parameters: 'a' and 'b'
> we declare a variable 'theLCM' & initialize it with a value of 0; 
> we declare 2 empty variables: 'remainderA' & 'remainderB' 
> we open a do while loop 
> do/while loop is a variant of the while loop
> this loop will execute the code block once, before checking if the condition is true
> then it will repeat the loop as long as the condition is true
> to understand this function, we shall illustrate this function with an example of lcm(2,4)
> when the function lcm (2,4) is called, the loop will execute the code block (the 'do' part)     
>>> it will first add 1 to theLCM variable (0 +1)
>>> it will then store the remainder value of ' theLCM%a ' in remainderA variable
>>> like this: 1 % 2 = 1 (it is actually 0.5 and there has to be a reason for it which I do not know as of now)
>>> it will then store the remainder value of ' theLCM%b ' in remainderB variable
>>> like this: 1 % 4 = 1 (it is actually 0.25 and there has to be a reason for it which I do not know as of now)
>>> it will now check if the condition is true (the 'while' part)
>>> our condition is basically checking if remainderA or remainderB is 'NOT' equal to 0
>>> since both remainderA & remainderB are 1 and 1 is not equal to 0; our loop is repeated
>>> it keeps repeating till the time our remainderA is equal to 0
>>> then it will check if remainderB is not equal to 0
>>> if remainderB is also equal to 0, then our loop will stop 
>>> in our case the loop will stop at 4 as ' 4 % 2 = 0 ' & ' 4 % 4 = 0 '
>>> and once the loop stops, the function will execute the statement after the loop
>>> our last statement is the return statement and we shall return the variable theLCM

Friday, May 28, 2021

Javascript Practice 67: JS Hero - while loop

 
Question: 

Write a function spaces that takes a natural number n and returns a string of n spaces.

Example: spaces(1) should return ' '.





Answer: 

function spaces (num) {

  let mySpaces = '';

  while (num-- > 0)

    mySpaces += ' '; 

  return mySpaces;

};




> declare a function spaces
> it has 1 parameter 'num'
> declare a variable mySpaces
> initialize it with an empty string
> we use a while loop as we need to repeat an action multiple times
> in this case we need to add blank spaces to a string 
> our '''empty spaces string''' will be stored in the variable mySpaces
> blank spaces will be equal to the 'num' parameter, which is fed when the function 'spaces' is called
> while loops have: a condition and a code (loop body) 
> our condition is to ensure that the code should execute as long as the num is greater than 0
> our condition is (num-- > 0)
> our code is: mySpaces += ''
> so if our function is called with the following parameter then how would this while loop work
>> spaces (3)
>> first it will check if 3 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be ' ' (1 space)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 3 = 2
>> it will check if 2 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be '  ' (2 spaces)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 2 = 1
>> it will check if 1 > 0; which it is and it will execute the code
>> mySpaces = mySpaces + ' '; the result in variable mySpace will now be '   ' (3 spaces)
>> then since we have used the num as a counter (num--), the loop will reduce 1 from 1 = 0
>> it will check if 0 > 0; which it is not and it will only execute the code after the while loop
>> we return the mySpaces variable which will give us the final result

Wednesday, May 26, 2021

Javascript Practice 66: JS Hero - Loops and arrays

 
Question: 

Write a function mean that accepts an array filled with numbers and returns the arithmetic mean of those numbers.

Example: mean([1, 2, 3]) should return (1+2+3)/3 = 2.




Answer: 

function mean (arr) { 

let sum = 0; 
for (let i = 0; i < arr.length; i++) { 

sum = sum + arr[i]; 

return sum / arr.length
}





> we declare a function mean
> it has one parameter 'arr'
> we declare a variable sum and initialize it with a value of 0
> we first use the for loop to add up all the elements of an array 
> first expression: let i = 0
> second expression or condition: i < arr.length
> third expression: i++ (i++ is identical to i = i + 1)
> loop code: sum = sum + arr[i]
> to understand this for loop, we call the function mean with an arr of 3 elements
> [1, 2, 3] 
> in the start expression ' i ' is initialized with a value of 0
> this means that 0 < 3; hence the loop code is executed
> sum = sum + arr[0]; ∴ sum = 0 + 1 = 1 (as index 0 of arr is 1)
> in the final or third expression i is increased by 1 (0 + 1 = 1)
> this means that 1 < 3, hence the loop code is executed
> sum = sum + arr[1]; ∴ sum = 1 + 2 = 3 (as index 1 of arr is 2)
> in the final or third expression i is increased by 1 (1 + 1 = 2)
> this means that 2 < 3, hence the loop code is executed
> sum = sum + arr[2]; ∴ sum = 3 + 3 = 6 (as index 2 of arr is 3)
> in the final or third expression i is increased by 1 (2 + 1 = 3)
> now 3 < 3 is no longer fulfilled 
> the loop is terminated and the program execution continues after the loop 
> in this case the program executes and returns the 'sum' variable to us
> we divide the returned sum variable by the length of the array
> our code example has added all the elements in an array and divided it by the length of the array
> hence we get the mean of the array

Javascript Practice 65: JS Hero - Factorial

 
Question: 

Write a function factorial that calculates the factorial of a positive integer.

Example: factorial(3) should return 6.




Answer: 

function factorial (num) {

let product = 1; 

for (let i = 1; i <= num; i++) {

product = product * i } 

return product
}




> we declare a function factorial
> it has one parameter 'num' 
> we first declare a variable 'product' with a value of 1
> we then open the 'for' loop 
>> let us assume that we call the factorial function with number 3 as a 'num' parameter
>> first expression: let i = 1
>> second expression or condition: i <= num
>> third expression: i++ (i++ is identical to i = i + 1)
>> loop code: product = product * i
>> in the start expression ' i ' is initialized with a value of 1 
>> the loop condition is i <= num (3);
>> if ' i ' is less than or equal to the num then the loop code is executed (1 <= 3)
>> the product variable shall receive the value of product * i or (1 * 1 = 1)
>> in the final or third expression i is increased by 1 (1 + 1 = 2)
>> ' i ' thus receives the value 2
>> the second loop starts with the evaluation of the loop condition
>> the condition 2 <= 3 is fulfilled
>> the loop code is executed again and product is now given the value (1 * 2 = 2)
>> in the final or third expression i is increased by 1 (2 + 1 = 3)
>> ' i ' thus receives the value 3
>> the second loop starts with the evaluation of the loop condition
>> the condition 3 <= 3 is fulfilled
>> the loop code is executed again and product is now given the value (2 * 3 = 6)
>> in the final expression ' i ' is increased again and gets the value  (3 + 1 = 4)
>> the second loop starts with the evaluation of the loop condition
>> the condition 4 <= 3 is no longer fulfilled
>> the loop is terminated and the program execution continues after the loop 
>> in this case the program executes and returns the 'product' variable to us
>> our code example has multiplied all natural numbers smaller or equal to 3

Javascript Practice 64: JS Hero - for loop

 
Question: 

Write a function addTo that accepts a number as a parameter and adds all natural numbers smaller or equal than the parameter. The result is to be returned.

Example: addTo(3) should return 1+2+3 = 6.




Answer: 

function addTo (num) {

let sum = 0;

for (let i = 1; i <= num; i++) {

  sum = sum + i;

}

return sum

}




> we declare a function addTo
> it has one parameter 'num' 
> we first declare a variable 'sum' with a value of 0
> we then open the 'for' loop 
> the 'for' statement creates a loop 
> this loop consists of 3 optional expressions
> these 3 expressions are enclosed in parenthesis
> they are separated by semi colons
> like this (let i = 0; i < 10; i++) 
> the 'for' loop is usually followed by a statement / block statement which is to be executed in the loop; also called loop code
>  the first expression is the start expression 
> it is executed once at the beginning of the loop 
> the loop variable is initialized in the first expression like this: " let i = 0; "
> the second expression is the loop condition
> it is evaluated to true or false before each loop iteration
> if this expression evaluates to true, the loop code is executed
> if this expression evaluates to false, the loop is terminated and the program execution continues after the loop 
> the third expression or final expression is executed after each loop iteration
> the loop variable ( ' i ' ) is normally increased here
> then a new loop iteration is started with a new evaluation of the loop condition
> the loop code follows the three control expressions in brackets
>> let us assume that we call the addTo function with number 3 as a 'num' parameter
>> in our solution we declare a variable sum that has a value of 0
>> first expression: let i = 1
>> second expression or condition: i <= num
>> third expression: i++ (i++ is identical to i = i + 1)
>> loop code: sum = sum + i
>> in the start expression ' i ' is initialized with a value of 1 
>> the loop condition is i <= num (3);
>> if ' i ' is less than or equal to the num then the loop code is executed (1 <= 3)
>> the sum variable shall receive the value of sum + i or (0 + 1 = 1)
>> in the final or third expression i is increased by 1 (1 + 1 = 2)
>> ' i ' thus receives the value 2
>> the second loop starts with the evaluation of the loop condition
>> the condition 2 <= 3 is fulfilled
>> the loop code is executed again and sum is now given the value (1 + 2 = 3)
>> in the final or third expression i is increased by 1 (2 + 1 = 3)
>> ' i ' thus receives the value 3
>> the second loop starts with the evaluation of the loop condition
>> the condition 3 <= 3 is fulfilled
>> the loop code is executed again and sum is now given the value (1 + 2 + 3 = 6)
>> in the final expression ' i ' is increased again and gets the value  (3 + 1 = 4)
>> the second loop starts with the evaluation of the loop condition
>> the condition 4 <= 3 is no longer fulfilled
>> the loop is terminated and the program execution continues after the loop 
>> in this case the program executes and returns the 'sum' variable to us
>> our code example has added all natural numbers smaller or equal to 3

Javascript Practice 63: JS Hero - null

 
Question: 

Write a function cutComment that takes one line of JavaScript and returns a possible line comment trimmed. If the line contains no line comment, null should be returned. For simplicity, we assume that the code does not contain the comment characters within a string.

Example: cutCommt ('let foo; // bar') should return 'bar'.




Answer: 

function cutComment (line) {

let a = line.indexOf('//'); 

if (a === -1) { 

return null; 

} else {

return line.slice(a+2).trim(); 

}}; 




> we declare a function cutComment
> it has one parameter 'line'
> we need to check if the function cutComment is called with a string that has a comment line 
> if it has a comment line then we need to remove it 
> and return all the elements of the string after the comment line characters ' // ' 
>>>> so our solution will begin with declaring a variable ' a ' 
>> it will be initialized with a value returned from the indexOf method on the parameter 'line'
>> we basically check for the line comment characters ' // ' in our parameter 'line' 
>> we then store it in the variable ' a ' 
>> we can expect that by using the indexOf method we can get two results
>> first, if there is a comment line character, then we shall be returned with a number
>> second, if there is an absence of comment line character, then we shall be returned with -1
>> we then open an if / else statement 
>> our first condition is to check if there is an absence of value in the variable 'a'
>> like this: a === -1
>> if a === -1, is true then, we return null
>> else we return the line with the elements; 
>> sliced from the beginning of the 'second line comment' character 
>> & trimming all the spaces between the line comment character and the elements after it
>> like this: line.slice(a+2).trim()
>> (a + 2) is used as there are 2 forward slashes that denote a line comment ' // '
>> when we get the indexOf value of the line comment; 
>> it includes only the index of the first forward slash
>> in order to slice the line from the second forward slash we have to add 2 to the variable 'a'
>> this will ensure that the slicing method will start from the end of the 2nd forward slash  
>> we then add the trim method after the slicing has been done
>> the trim method will remove the whitespaces from both the ends of the string that is sliced

Javascript Practice 62: JS Hero - undefined

 
Question: 

Write a function hello having one parameter and returning 'Hello <parameter>!'. If hello is called without an argument, 'Hello world!' should be returned.

Example: hello('Nala') should return 'Hello Nala!'.




Answer: 

function hello (p) {

if (p === undefined) {
        
return `Hello world!`;

} else {
        
return `Hello ${p}!`}

};




or




function hello (param) {

if (param) {

return 'Hello ' + param + '!' ;

} else { 

return 'Hello world!'}

};




> we declare a function 'hello' 
> it has one parameter - 'p'
> we open if / else statements to check 
>> if the function 'hello' is called with a parameter 'p'
>> or it is called without a parameter
> if it is called with a parameter then we have to return a string 
> this string will append the parameter 'p' to 'Hello' and return it
> in case the function is called without a parameter
> then we should simply return 'Hello world!' 
> we can solve it in many ways
> we have two solutions here
> the first solution checks if the parameter 'p' is undefined
> like this: p === undefined
> if it is undefined then the function will return 'Hello world!' 
> or else it will return `Hello ${p}!`
> the second solution checks if the parameter ' param' exists
> like this (param) 
> if it exists then we get 'Hello ' + param + '!' 
> if it does not exist then we shall be returned 'Hello world!'

Tuesday, May 25, 2021

Javascript Practice 61: JS Hero - Comments

 
Question: 

Write a function median that takes an array of ascending numbers and returns the median of that numbers.

Example: median([1, 2, 10]) should return 2 and median([1, 2, 10, 100]) should return 6.




Answer: 

function median (arr) {

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

let isVar = arr.length / 2;

if (isVar % 1 == 0) {

return (arr[isVar  - 1] + arr[isVar]) / 2 } else {

return arr[Math.floor(isVar)];

}

};




> declare a function median 
> it has 1 parameter 'arr' 
> the median function will only take arrays as arguments when called 
>>>>> we first need to ensure that the array is in ascending order
> we shall need to sort the array before any other operation is done on the array
> we sort the array using the sort method
> as the name suggests, this method, sorts the elements of an array and returns the sorted array
> the default sort order is ascending
> it first converts elements into strings
> it then compares it's sequences of UTF-16 code units values
> for eg. so 7 comes before 60, but because numbers are converted to strings, '60' comes before '7' in the unicode order  
> sort method is a higher order function 
> when you have to sort something in Javascript, you have to write your own comparing function
> sort method expects as an argument a 'function'
> we insert a function in to the 'sort' method parameter
> this function has 2 parameters: 'a' & 'b'
> we simply subtract b from a like this: a - b and return the value inside the sort method
> this operation will mainly subtract the second element of the array from the first element
> it works as a function that compares the two elements 'a' and 'b'
> so if a - b <= 0; then the sort method will leave a & b unchanged; which means it wont change the index order for a & b
> if a - b > 0; then the sort method will sort b before a 
> if b - a > 0, then the sort method will sort a before b 
> this operation will be conducted on each and every element of the array
> so the first operation, the 'median' function will perform is to sort the array in ascending order
>>>>> after the sorting of the array, we will need to find the median of the array
> we declare a variable 'isVar'
> we initialize it with a value that shall be returned when we divide the length of the array by 2
> whenever we divide a number by 2, then we shall get 2 outputs
> one will be a whole number, which will mean that the array length is even
> one will be a decimal number; which will mean that array length is odd
> this will be the first step in determining if the array has an odd or even number of elements
> we then use if / else statements to proceed with the next step of determining if the array length is odd or even
> based on the conditions mentioned in the if / else statements we can execute specific tasks
> our first if condition is to determine if the array length is even 
> we use the modulo operator on variable 'isVar' like this: ''' isVar % 1 == 0 '''
> now we know that the variable 'isVar' stores the ouput of: the length of an array divided by 2
> now if the variable 'isVar' ; if divided by 1 has a remainder which is equal to 0 then we can be sure that the array length is even in number
> this is because if an even number is divided by 2 then we will always get a whole number
>  ∴ if the condition '' isVar % 1 == 0 ''' is true then we want the following task to be executed
>  (arr[isVar  - 1] + arr[isVar]) / 2 
> now in order to get the median value of an even number we need to add the two middles and then divide it by 2 
> so in our function we need to access the array elements using the number in the 'isVar' variable
> for eg if total number of elements in an array is 10, then the isVar variable will have the stored value of 5
> in order to get the median value for our eg, we shall need both the 5th and the 6th elements and then divide it by 2
> we access the 5th element of the array like this: arr[isVar]
> however the 5th element is actually the 6th element, as array indexes start from 0
> we remember that we need the 6th element too as it becomes a part of the two middles we need
> we then need to access the 5th element to add it to the 6th element
> so we deduct 1 from the 6th element in order to get the 5th element like this: [isVar  - 1]
> we then divide the sum of both the elements by 2 like this: (arr[isVar  - 1] + arr[isVar]) / 2 
> this task will provide the median value if the array length is an even number
> but what if the array length is an odd number
> we then use an else statement as it is the only other option left 
> and we return it with the following task that needs to be executed: arr[Math.floor(isVar)]
> Math.floor function rounds a number downwards to the nearest integer and returns the result
> for eg 7 / 2 = 3.5; then Math.floor(3.5) = 3 
> ∴ if the isVar is a decimal number (which confirms that the length of the array is an odd number) then we can access the median of an array by simply using the rounded down number stored in the variable '''isVar'''
> this will work as the index value of an array starts with 0  

Sunday, May 23, 2021

Javascript Practice 60: JS Hero - Array of arrays

 
Question: 

Write a function flat that flattens a two-dimensional array with 3 entries.

let row1 = [4, 9, 2];
let row2 = [3, 5, 7];
let row3 = [8, 1, 6];
let loshu = [row1, row2, row3];

Example: flat(loshu) should return [4, 9, 2, 3, 5, 7, 8, 1, 6]. Thereby loshu is the magic square from the example above.




Answer: 

function flat (array) {

let entryA = array[0]; 
let entryB = array[1]; 
let entryC = array[2]; 

let finalD = entryA.concat(entryB, entryC);

return finalD;

};




> declare a function flat
> it has 1 parameter array
> we know that we need to flatten a two dimensional array which has 3 entries / arrays
> an array that contains an array is called a two dimensional array
> we declare 3 variables that access the three entries / arrays within the 2D array
> we then concat all three arrays using the concat () method and store the output in another variable finalD
> we return the finalD variable to get our single flattened array  

Javascript Practice 59: JS Hero - Array: join()

 
Question: 

Write a function list that takes an array of words and returns a string by concatenating the words in the array, separated by commas and - the last word - by an 'and'. An empty array should return an empty string.

Example: list(['Huey', 'Dewey', 'Louie']) should return 'Huey, Dewey and Louie'.




Answer: 

function list (array) {

if (array.length === 0) {

return ''; } else if (array.length === 1) {

return array[0]; } else { 

let wordsExLast = array.slice(0, array.length - 1); 
let lastWord = array[array.length-1]; 
return wordsExLast.join(', ') + ' and ' + lastWord;
}; 

};





> we create a function declaration 'list'
> it has a parameter array
> we then open if / else if / else statements
> the first condition is to check if the array length is 0
> if it is 0 then the function should return an array which is empty
> else if the length of the array has only one word then the function should return just that element
> or else the function should do the following: 
>>> create a variable wordsExLast
>>> it should contain all the elements of the array except the last word
>>> we use the slice method to return a shallow copy of the array without the last word
>>> like this: array.slice(0, array.length - 1)
>>> create another variable lastWord
>>> this variable is to store the returned word when we access the last word of the array
>>> we then concatenate and join the two variables - wordsExLast & lastWord
>>> wordsExLast.join(',') + 'and' + lastWord

Thursday, May 20, 2021

Javascript Practice 58: JS Hero - Array: slice()

 
Question: 

Write a function halve that copies the first half of an array. With an odd number of array elements, the middle element should belong to the first half.

Example: halve([1, 2, 3, 4]) should return [1, 2].




Answer: 

function halve (array) {

let half = Math.ceil(array.length / 2); 

return array.slice(0, half);

};




> we declare a variable halve
> it has one parameter - array
> this function will basically copy the first half of an array and return those elements
> in order to divide an array in half, we simply divide the length of an array by 2
> now the array length could be even or odd
> if its even then we get a whole number 
> but if its odd then we get a number with a decimal 
> also if the array is odd then we need to ensure that the middle element is added to the first half
> so in order to solve this we basically first declare a variable half in the function 
> we initialize it with a value array.length / 2
> however, that alone won't work 
> as we need to account for the possibility of the length that could be an odd number 
> furthermore we need to also ensure that if the array length is odd then we want the middle element to be returned in the first half of the array 
> so we use the Math.ceil() method on (array.length/2)
> the Math.ceil() function will always round a number up to the next largest integer
> for eg 1.5 will be 2
> so by doing it we will initialize the variable half by storing the value returned from 
> Math.ceil(array.length / 2)
> if the number is even then the Math.ceil will have no effect 
> if the number is odd then the Math.ceil will round up the decimal to the next highest integer
> this will also take care of the condition that if the length of the array is odd then the middle element will be included in the half variable after the slice function
>>> for eg if we call the function halve([ 'a', 'b', 'c' ])  
>>> then array.length / 2 = 1.5 
>>> Math.ceil(array.length/2) = 2 
>>> half = 2 (and not 1.5, due to the Math.ceil() method)
> note that half has a value of 2 
> we then use the slice method on the array 
> the slice () method does not alter the original array 
> it returns a shallow copy of elements from the original array
> syntax of slice() is (start, end) - 2 arguments
> start: the index at which to start extraction
> end: the extraction will continue up to (but not including) the index number we enter
> we use the slice method to return the first half of the array for our function halve
> like this: array.slice(0, half)
> array.slice is the method
> start: we start extraction at index 0 of the array
> end: instead of the number we enter the variable half as the array could be of any length
> we know that the half has a value of 2; halve([ 'a', 'b', 'c' ]); 3/2 = 1.5; math.ceil = 2;
> our extraction will start at 0 = 'a' and end at 'c' (but not include 'c')
> so we will get 2 elements from the index 0 of the array 
> this will include the element in the position 0 and position 1, which is 'a' & 'b'
> note that 'b' is the middle element of the array
> and hence we shall get the middle element also when we call an array whose length is an odd number

Javascript Practice 57: JS Hero - Array: indexOf()

 
Question: 

Write a function concatUp that concatenate two arrays. The longer array should be appended to the shorter array. If both arrays are equally long, the second array should be appended to the first array.

Example: concatUp([1, 2], [3]) should return [3, 1, 2] and concatUp([5, 7], [6, 8]) should return [5, 7, 6, 8].





Answer: 

function concatUp (a1, a2) {

if (a2.length >= a1.length) {
return a1.concat(a2); 
} else {
return a2.concat(a1); 
}
};





> we declare a function concatUp 
> it has 2 parameters a1, a2
> this function will concatenate two arrays - a1 & a2
> the two arrays can be of equal length
> or a1 can be longer than a2
> or a2 can be longer than a1
> if a2 is longer than a1, then we append (meaning add to the end) a2 to a1
> like this: a1.concat(a2)
> if a1 length is equal to a2 length then we again append a2 to a1
> so we have 2 conditions for same output
> else if a1 is longer than a2 then we append a1 to a2
> like this: a2.concat(a1)

Javascript Practice 56: JS Hero - Array: indexOf()

 
Question: 

Write a function add that adds an element to the end of an array. However, the element should only be added if it is not already in the array.

Example: add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].




Answer: 

function add (arr, e) {

if (arr.indexOf(e) === -1) {

arr.push(e);
return arr;

} else {

return arr; 

}
}; 





> declare a function add
> it has 2 parameters arr & e
> we need to first check if 'e' is already present in the array - arr
> if it is present then it will not be added to the array - arr 
> if it is not present then it will be added to the array - arr
> so after we declare the function, we will open an if / else statement
> the condition will be to check if the indexOf method on the array contains the 'e' element
> if it returns the -1 or is equal to -1, then we shall add that element using the push method
> or else we shall just return the original array 

Javascript Practice 55: JS Hero - Array: shift() and push()

 
Question: 

Write a function rotate that rotates the elements of an array. All elements should be moved one position to the left. The 0th element should be placed at the end of the array. The rotated array should be returned.

Example: rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].




Answer: 

function rotate (array) {

let firstEl = array.shift();
array.push(firstEl);
return (array); 

}




> we declare a function rotate
> it has one parameter array
> we declare a variable firstEl 
> we initialize it with a value of an array on which we have used the shift method
> this method changes the length of the array 
> the shift method removes the first element from an array and returns that removed element
> it also shifts all other elements to a lower index
> we then use the push method on the array 
> we push the 'firstEl' variable where we stored the first element which we removed from the same array
> the push method will add the first element that we removed to the end of the array
> we then return the array and get our result

Wednesday, May 19, 2021

Javascript Practice 54: JS Hero - Sorting arrays

 
Question: 

Write a function sort that takes an array filled with 3 numbers and returns these 3 numbers sorted in ascending order as an array.

Example: sort([2, 3, 1]) should return [1, 2, 3].




Answer: 

function sort (array) {

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

}





> declare a function sort
> it has one parameter array
> we use the sort () method to sort the array elements in ascending order
> we declare a function within a function
> if we subtract b - a, then we will get the elements sorted in descending order

Javascript Practice 53: JS Hero - Array: length

 
Question: 

Write a function getLastElement that takes an array and returns the last element of the array.

Example: getLastElement([1, 2]) should return 2.




Answer: 

function getLastElement (anArray) {

  let lastIndex = anArray.length - 1;
  return anArray[lastIndex];

}




> we learn how to access the last element of an array 
> we use the length property 
> this property will return the number of elements in the array 
> subtracting 1 from the length of an array gives the index of the last element of that array
> this index can be used to access the last element of that array 
> we declare a function getLastElement
> it has 1 parameter anArray
> we declare a variable lastIndex
> we initialize it with a value, which will be the index of the last element of the array
> we then return the last element like this: anArray [lastIndex]

Javascript Practice 52: JS Hero - Set array elements

 
Question: 

Write a function setFirstElement that takes an array and an arbitrary variable. The variable should be inserted as the first element in the array. The array should be returned.

Example: setFirstElement([1, 2], 3) should return [3, 2].




Answer: 

function setFirstElement (array, v1) {
array[0] = v1; 
return array
}





> declare a function setFirstElement 
> it has 2 parameters array & v1
> we set the first element of the array to the v1 parameter
> like this: array[0] = v1
> we return the array
> we learnt how to get the element of an array in the last exercise
> and now we learnt how to set an element in this exercise

Javascript Practice 51: JS Hero - Get array elements

 
Question: 

Write a function getFirstElement that takes an array and returns the first element of the array.

Example: getFirstElement([1, 2]) should return 1.




Answer: 

function getFirstElement (array) { 

let firstEl = array[0];
return firstEl

}





> declare a function getFirstElement 
> it has 1 parameter array
> we declare a variable firstEl 
> we initialize it with the first element of the array
> we access the first element of the array by entering '0' in between the square brackets
> index in an array begins with '0' 
> we return the firstEl variable 

Javascript Practice 50: JS Hero - Arrays

 
Question: 

Write a function toArray that takes 2 values and returns these values in an array.

Example: toArray(5, 9) should return the array [5, 9].




Answer: 

function toArray (a,b) {

let array = [a, b]; 
return array 

}




> declare a function toArray
> it has 2 parameters
> we declare a variable array
> we initialize it with an array that contains the two parameters 
> like this [a, b] 
> we return the array

Javascript Practice 49: JS Hero - else if

 
Question: 

Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.

Example: addWithSurcharge(10, 30) should return 44.




Answer: 

function addWithSurcharge(a, b) {

    let sum = a + b;

    if (a <= 10) {
            sum += 1;
} else if (a <= 20) {
            sum += 2;
} else     {sum += 3;}

    if (b <= 10) {
            sum += 1;
} else if (b <= 20) {
            sum += 2;
} else     {sum += 3;}

    return sum;
}; 





or 




function lineItemToSurcharge(a) {
  
if ( a <= 10) {
            
            return 1;
  
} else if (a <= 20) {

            return 2

  } else {

            return 3
}}

function addWithSurcharge (a,b) { 
  
let sum = a + b; 
return sum + lineItemToSurcharge(a) + lineItemToSurcharge(b); 
}





> the first solution is fairly easy to understand
>> we declare a function addWithSurcharge
>> it has two parameters
>> we declare a variable sum
>> we initialize it with a value 
>> this value will be the sum of the two parameters which are numbers
>>> we then open our first if / else if / else statement 
>>>> our first condition is to check if the first digit is less than or equal to 10
>>>> if it meets the condition then we shall be adding 1 to the sum
>>>> our second condition is to check if the first digit is less than or equal to 20  
>>>> if it meets the condition then we shall be adding 2 to the sum
>>>> our final condition will be to add 3 to the sum; if the first number is above 20
>>> we then open our second if / else if / else statement 
>>>> our first condition is to check if the second digit is less than or equal to 10
>>>> if it meets the condition then we shall be adding 1 to the sum
>>>> our second condition is to check if the second digit is less than or equal to 20  
>>>> if it meets the condition then we shall be adding 2 to the sum
>>>> our final condition will be to add 3 to the sum; if the second number is above 20
> the second solution is fairly simple too 
>> we use two separate functions to get our code to successfully execute 
>> we first declare a function lineItemToSurcharge
>> it has only one parameter which will be a number
>> we then open our if / else if / else statement in this function
>> we check to see if the number is less than equal to 10, 20 or above 20
>> similar to what we did in the first solution
>> we then declare another function addWithSurcharge
>> this function has 2 parameters that are numbers
>> we simply add the two numbers first 
>> we declare a variable 'sum' and store the result of the addition of the two numbers in it
>> we then call the function lineItemToSurcharge within this function 
>> we call the function lineItemToSurcharge with the arguments being the two numbers declared as parameters in the function addWithSurcharge
>> we simultaneously add the result of the function lineItemToSurcharge to the  'sum' variable
>> we then return that entire addition 

Monday, May 10, 2021

Javascript Practice 48: JS Hero - if...else

 
Question: 

Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10, the surcharge is 2.

Example: addWithSurcharge(5, 15) should return 23.




Answer: 

function addWithSurcharge (a,b) {

if (a <= 10 && b <= 10) {

return a + b + 2; 

} else if (a > 10 && b > 10) { 

return a + b + 4; 

} else return a + b + 3;

} ;




or 




function addWithSurcharge(a, b) {

  let surcharge = 0;

  if (a <= 10) {
    surcharge = surcharge + 1;
  } else {
    surcharge = surcharge + 2;
  }

  if (b <= 10) {
    surcharge = surcharge + 1;
  } else {
    surcharge = surcharge + 2;
  }

  return a + b + surcharge;
}




> in the first example we declare a function addWithSurcharge
>>> it has two parameters
>>> we create if / else if / else statements to execute a block of code
>>> our first condition is to add a + b + 2 if both the values are less than or equal to 10 
>>> our second condition is to add a + b + 4 if both the values are more than 10 
>>> if both the above conditions are not met then we add both the values to 3
>>> a + b + 3 
> in the second example we declare a function addWithSurcharge
>>> in the second example we declare a variable surcharge
>>> we initialize it with a value of 0
>>> we create two if / else statements to execute a block of code within addWithSurcharge
>>> our first condition within the first if / else statement is to add surcharge + 1 
>>>>> if 'a' is less than or equal to 10 and initialize the value to the variable 'surcharge'
>>>>>  or else add surcharge + 2 
>>> our second condition within the second if / else statement is to add surcharge + 1 
>>>>> if 'b' is less than or equal to 10 and initialize the value to the variable 'surcharge'
>>>>>  or else add surcharge + 2
>  in the second example, when we call the function with numbers 
> the function will start executing and updating the surcharge amount 
> it will first check if a is less than or equal to 10
> based on the number it will add original surcharge value 0 + 1 or 2 
> it will then store the value to the variable surcharge
> after it has assessed the parameter a, then it will move to parameter b
> it will perform the same function and will add the surcharge value to the value stored in the variable 'surcharge'; surcharge = surcharge + 1 or 2
> finally when both 'a' and 'b' are analyzed we return the final value of surcharge added to the 'a' and 'b' parameters

Javascript Practice 47: JS Hero - Two returns

 
Question: 

Write a function repdigit that determines whether a two-digit decimal is a repdigit or not. If the decimal is a repdigit, 'Repdigit!' should be returned, otherwise 'No Repdigit!'.

Example: repdigit(22) should return 'Repdigit!' and repdigit(23) should return 'No Repdigit!'.




Answer: 

function repdigit (n) {

if (Number.parseInt(n/10) === (n/11)) {

return 'Repdigit!';

return  'No Repdigit!';

};

or

function repdigit(n) {

  let ones = n % 10;
  let tens = Math.floor(n / 10);
  
if (ones === tens) {

    return 'Repdigit!';

  }

  return 'No Repdigit!';

};


> in the first example we have used the parseInt function to convert the result of n/10 into an integer
>>> then once it is converted to an integer we check its equality with the result of n/11 
>>> if both the results are equal then we are returned the Repdigit output 
>>> or else we are returned the No  Repdigit output
> in the second example we declare a variable 'ones' 
>>> we initialize it with a value 
>>> like this n % 10; we use the modulo operator
>>> we get the digit in the units place when we use the modulo operator
>>> for eg 58 % 10 = 8; 8 is the remainder when we divide 58 by 10
>>> we then create another variable 'tens' 
>>> we initialize it with a value
>>> like this Math.floor(n/10)
>>> we use the Math.floor in order to round down the value of n/10 to the nearest integer
>>> for eg (20.56589 / 10) = 2.056589 >>>> check in console
>>> Math.floor(2.056589) = 2 >>>> check in console
>>> we use the if / else statement to execute the code 
>>> if the digits in the ones place is strictly equal to the digits in the tens place we shall get Repdigit 
>>> else we get No Repdigit

Javascript Practice 46: JS Hero - if

 
Question: 

Write a function equals that checks two values for strict equality. If the two values are equal, the string 'EQUAL' should be returned. If they are unequal, you should get 'UNEQUAL'.

Example: equals(1, 1) should return 'EQUAL' and equals(1, 2) should return 'UNEQUAL'.




Answer: 

function equals (a,b) {

if (a === b) {

return 'EQUAL';

} else {

return 'UNEQUAL';}

}; 

> declare a function equals 
> it has 2 parameters
> it uses if / else statements to execute a block of code
> if a is strictly equal to b then the function would return 'Equal' or else 'Unequal

Javascript Practice 45: JS Hero - Compare numbers

 
Question: 

Write a function isThreeDigit that checks if a number is greater than or equal to 100 and less than 1000.

Example: isThreeDigit(500) should return true and isThreeDigit(50) should return false.




Answer: 

function isThreeDigit (n) { 

return n >= 100 && n < 1000; 

}; 


> create a function isThreeDigit
> has one parameter
> return statement is: n >= 100 && n < 1000
> two conditions passed for result to come true
> n has to be greater then or equal to 100 & less than 1000 

Javascript Practice 44: JS Hero - Strict inequality

 
Question: 

Write a function unequal that checks 3 values for strict inequality. The function should return true if all three parameters are strict unequal. Otherwise false.

Example: unequal(1, 2, 3) should return true and unequal(1, 1, 2) should return false.




Answer: 

function unequal (a,b,c) {

return a !== b && b !== c && a !== c; 

}; 

> declare a function unequal 
> it has 3 parameters
> return statement is: a !== b && b !== c && a !== c
> it checks for strict inequality between the 3 parameters
> it will return true of all parameters are strictly unequal
> it will return false if any 2 or all 3 of them are equal

Javascript Practice 43: JS Hero - Even numbers

 
Question: 

Write a function isEven that checks if a passed number is even. If the given number is even, true should be returned, otherwise false.

Example: isEven(2) should return true and isEven(3) should return false.




Answer: 

function isEven (n) {

return n % 2 === 0;

}; 

> declare a function isEven
> it has 1 parameter
> return statement is: n % 2 === 0
> % = modulo operator gives the remainder obtained by dividing two numbers 
∴ if n is divided by 2 and the remainder is 0 then n is an even number
> we shall get true if n is even and false if n is odd by using the modulo operator and the strict equality operator 

Javascript Practice 42: JS Hero - Three identical values

 
Question: 

Write a function equals that checks 3 values for strict equality. The function should only return true if all 3 values are equal.

Example: equals(1, 1, 1) should return true and equals(1, 2, 1) should return false.




Answer: 

function equals (a,b,c) {

return a === b && a === c;

}; 

> declare a function equals
> it has 3 parameters
> the return statement is: a === b && a === c
> so the expression above will first check if a is strictly equal to b 
> then it will check if a is strictly equal to c
> if a is strictly equal to b and a is strictly equal to c then it will give a true statement 
> or else it will return false

Javascript Practice 41: JS Hero - Strict equality

 
Question: 

Write a function equals that checks two values for strict equality.

Example: equals(1, 1) should return true and equals(1, 2) should return false.




Answer: 

function equals (a,b) {

let x = a === b; 

return x
};  


> create a variable x 
> initialize it with a value 
> like this a === b
> the '===' or strict equality operator checks if the values a & b are equal 
> the strict equality operator also checks if the data type of a & b are equal
> we then return the variable 'x'

Sunday, May 9, 2021

Javascript Practice 40: JS Hero - XOR

 
Question: 

Write a function xor that takes two Boolean values. If both values are different, the result should be true. If both values are the same, the result should be false.

I.e.: The calls xor(true, false) and xor(false, true) should return true. The calls xor(true, true) and xor(false, false) should return false.




Answer: 

function xor (boo1, boo2) {

let xor = (boo1 || boo2) && (!boo1 || !boo2);

return xor; 

}; 

> in this post, I will code a XOR Gate (eXclusive OR)
> we declare a variable 'xor' 
> we initialize it with a value of both our Boolean parameters
> like this (boo1 || boo2) && (!boo2 || !boo1);
> so if boo1 & boo2 are both true (or both are false) then variable 'xor' will store the value false and in all other cases it will store the value of true
>> xor(true, true) = false >>>> (true || true) && (false || false) >>>> check in console
>> xor(false, false) = false >>>> (false || false) && (true || true) >>>> check in console
>> xor(true, false) = true >>>> (true || false) && (false || true) >>>> check in console
>> xor(false, true) = true >>>> (false || true) && (true || false) >>>> check in console

Thursday, May 6, 2021

Javascript Practice 39: JS Hero - NOR

 
Question: 

Write a function nor that takes two Boolean values. If both values are false, the result should be true. In the other cases the return should be false.

I.e.: The call nor(false, false) should return true. The calls nor(true, false), nor(false, true) and nor(true, true) should return false.




Answer: 

function nor (boo1, boo2) {

let or = boo1 || boo2; 

return !or; 

}; 

> in the last post, I coded a NAND Gate (not and, !and) 
> in this post, I will code a NOR Gate (not or, !or)
> we declare a variable or
> we initialize it with a value of both our Boolean parameters
> like this boo1 || boo2
> so if boo1 or boo2, any one of them is true then variable 'or' will store the value true and in all other cases it will store the value of false
>> nor(true, false) = true
>> nor(false, true) = true
>> nor(true, true) = true
>> nor(false, false) = false
> but we need nor(false, false) to return true
> so instead of 'or' if we return '!or' (not or) then we shall get the value false

Javascript Practice 38: JS Hero - Boolean

 
Question: 

Write a function nand that takes two Boolean values. If both values are true, the result should be false. In the other cases the return should be true.

I.e.: The call nand(true, true) should return false. The calls nand(true, false), nand(false, true) and nand(false, false) should return true.




Answer: 

function nand (boo1, boo2) {

if (boo1 === true && boo2 === true) {
return false;} else {return true}

}; 


or 


function nand (b1, b2) {

let and = b1 && b2; 

return !and

};


> what is a Boolean
> a Boolean is a value that either represents true or false
> the reason we use Booleans, is to evaluate certain circumstances 
> it is not a string but a Boolean (keyword)
> in the question we have to write a function 'nand' that takes two Boolean values as parameters
> we then evaluate them 
> if both values are true then our result should be false
> the first solution is fairly simple with the use of if and else statements
>>> we clearly mention that if both the values are true then the function should return false
>>> else it should return true for all other scenarios
> the second solution is a bit complicated but this will help you understand the usage of Booleans much better
>>> JS has three Boolean operators: &&, || and !
>>> && = and    
>>> || = or
>>> ! = not 
>>> && links two Boolean values; if both values are true, then result is true or else in all other cases it is false
>>> || is true if at least one of the two input values is true; if both values are false then the result is false
>>>  ! is applied to a single Boolean value and inverts this value; !true (not true) = false and !false (not false) = true
>>> in our second solution we first declare a variable 'and'
>>> we initialize it with a value of both our Boolean parameters
>>> like this b1 && b2
>>> so if b1 and b2 are true, then variable 'and' will store the value true and in all other cases it will store the value of false
>>> so if we return the variable 'and' then we shall get the value 'true'
>>> but we need the returned value to be 'false' if both the values are true 
>>> so instead of 'and' if we return '!and' (not and) then we shall get the value false 
> finally we have created a function called nand but in coding it is called a NAND gate 

Javascript Practice 37: JS Hero - parseInt

 
Question: 

Write a function add that takes a string with a summation task and returns its result as a number. Two natural numbers should be added. The summation task is a string of the form '102+17'.

Example: add('102+17') should return 119.




Answer: 

function add (string) { 

let firstNumber = parseInt(string); 
let plusSignPosition = string.indexOf('+'); 
let extractSecondNumber = string.substr(plusSignPosition + 1); 
let secondNumber = parseInt(extractSecondNumber);
let totalValue = firstNumber + secondNumber; 
return totalValue; 

}; 

> let us understand what we are getting in a string for this question
> a summation expression in a string object
> for eg. '2+3' or '256+351', '15985 + 65', etc
        -check in the console by simply typing typeof '65+9' and pressing 'enter'
> these are not numbers but they are strings as they are wrapped in quotes ' ' 
> the summation task could have completed by itself if they were numbers 
        -check in the console by simply typing 65+9 and pressing 'enter'
> the summation task cannot complete by itself as they are strings
         -check in the console by simply typing '65+9' and pressing 'enter', don't forget the quotes
> in order to add the numbers in the string we will need the two numbers and simply add them
> we do this by first finding the first number in the string
> then we find the index position of the plus sign in the string
> based on the position of the plus sign, we extract the number that is placed after the plus sign
> after retrieving both the numbers, we add them to get our result
> so our first step is to find the first number in the string and convert it to a number 
>>> we do that by declaring a variable firstNumber
>>> we use the function parseInt
>>> parseInt function parses a string argument and returns an integer
>>> if the parseInt function encounters a character that is not a number then it ignores it and all the succeeding characters and only returns the integer value parsed up to that point
>>> so if we use parseInt function in the case of '100+5' our return shall be 100 only
        -check in console by typing parseInt('100+5') and pressing 'enter', don't forget the quotes
>>> parseInt not only accessed all the characters which are numbers before the plus sign 
>>> but also returned only the numbers in those characters
>>> and more importantly it converted the returned numbers from characters of a string into  integers that could be used to perform arithmetic operations on literals
> after finding our first number we come to the second step of finding the position of the plus sign 
>>> we declare a variable plusSignPosition
>>> we use the indexOf method to find the position of the '+' sign in the string
>>> we store the returned value in the plusSignPosition variable
> based on the returned value we get, of the position of the plus sign, which is stored in the variable plusSignPosition, we can move to the third step which involves extracting the part of a string, in which we are interested and that is the extractSecondNumber
>>> we declare a variable extractSecondNumber
>>> we use the substr method that extracts part of a string
>>> syntax of substr: string.substr(start, length)
>>> providing the length is optional and we shall not be providing it as we know that our strings are in the form of summation tasks of two natural numbers only  
>>> we provide the starting point from where we need the extraction to happen from the string
>>> our starting point is the plusSignPosition 
>>> however we do not want the plus sign to be extracted with the numbers 
>>> we only need the numbers
>>> by providing just the plusSignPosition as our starting point we shall get the plus sign returned as well because the extraction happens from the starting point itself
>>> in order to omit the plus sign we add +1 to plusSignPosition
>>> like this string.substr(plusSignPosition + 1)
>>> the returned value is stored in the variable extractSecondNumber
>>> these values are not numbers but are strings 
>>> as we have just extracted them and not parsed them 
> in order for us to perform arithmetic operations on numbers / integers / literals we need to convert extractSecondNumber which is a string to a number
>>> we do the conversion by first declaring a variable secondNumber
>>> we use the function parseInt to convert the string to a number
>>> like this: parseInt(extractSecondNumber)
> finally we declare a variable totalValue that simply adds the two variables
>>> firstNumber + secondNumber
>>> the result is stored in the variable totalValue which in the end we return

Wednesday, May 5, 2021

Javascript Practice 36: JS Hero - Random numbers

 
Question: 

Write a function dice that returns like a dice a random number between 1 and 6.




Answer: 

function dice () {

return (Math.floor(Math.random() * 6)) + 1;

}; 

> function dice has to return a random number between 1 and 6 
> random numbers can be generated using the Math.random method
> Math.random returns a floating-point, pseudo-random number
> random number is usually between 0 (inclusive) and 1 (exclusive)
> let me repeat - random number generated will be between 0 & 1
> 0 will be inclusive & 1 will be exclusive
> 0 will be included and 1 will not be included 
> we shall be generating numbers with decimal points (real numbers) and not a whole number
> for eg 0.75 or 0.89 or 0.9998898988898552 etc
> but we need to get a random whole number between two values i.e. 1 and 6 
> so first we need to use Math.random() to generate a number between 0 & 1
> we then multiply that with 6 like this: (Math.random() * 6)
> (Math.random() * 6) will generate random real numbers (not whole numbers) btw 0 & 6
> 0 will be included and 6 will not be included
> for eg 0.256, 1.536, 3.589 or 5.99958565
> then we wrap the result of (Math.random()*6) inside the Math.floor function to round it 
> like this: Math.floor(Math.random() * 6)
> Math.floor will round the number down to the closest whole number 
> this will generate whole numbers from 0 to 5 
> in order to ensure that our random numbers fall between 1 and 6 we simply add 1 
> like this: (Math.floor(Math.random()*6)) + 1; 
> the resulting numbers will always be between 1 and 6 

Javascript Practice 35: JS Hero - Rounding

 
Question: 

Write a function round100 that rounds a number to the nearest hundred.

Example: round100(1749) should return 1700 and round100(856.12) should return 900.




Answer: 

function round100 (number) { 

return Math.round (number / 100) * 100; 

}; 

> this was a bit tough for me
> i spent almost an hour understanding the logic behind this
> however I did a lot of googling to understand this
> its fairly simple in excel, i checked the function Round in excel
> i also realized that I can always check and experiment on the console to get some hints
> however you are supposed to be good not only in math but mainly in logic to execute this in JS
> this question needed me to round off any number to the nearest 100 
> lets say the number is 149
> lets break the above equation Math.round (number / 100) * 100
number / 100: 149 / 100 = 1.49
Math.round(1.49) =  1 (check this in the debugging console)
Math.round(1.49)*100 =  100
> this maybe easy for a lot of you but I was and am still very weak with Maths & Logic