//Exercises Level 1 //Exercise 1 -- Declare a function fullName and it print out your full name. function fullName() { return ('Brendan Klein'); } console.log(fullName()); //Exercise 2 -- Declare a function fullName and now it takes firstName, lastName as a parameter and it returns your full - name. function fullName(first,last) { return first+" "+last; } console.log(fullName(`Brendan`,`Klein`)); //Exercise 3 -- Declare a function addNumbers and it takes two two parameters and it returns sum. function addNumbers(firstNum, secondNum) { var sum = firstNum + secondNum; return sum; } console.log(addNumbers(1,2)); //Exercise 4 -- An area of a rectangle is calculated as follows: area = length x width. Write a function which calculates areaOfRectangle. function areaOfRectangle(length, width) { var area = length*width; return area; } console.log(areaOfRectangle(7,5)); //Exercise 5 -- A perimeter of a rectangle is calculated as follows: perimeter= 2x(length + width). Write a function which calculates perimeterOfRectangle. function perimeterOfRectangle(length, width) { var perimeter= 2*(length + width) return perimeter; } console.log(perimeterOfRectangle(1,2)); //Exercise 6 -- A volume of a rectangular prism is calculated as follows: volume = length x width x height. Write a function which calculates volumeOfRectPrism. function volumeOfRectPrism(length, width, height) { var volume = length*width*height return volume; } console.log(volumeOfRectPrism(1,2,3)); //Exercise 7 -- Area of a circle is calculated as follows: area = π x r x r. Write a function which calculates areaOfCircle function areaOfCircle(r) { var area = (Math.PI)*r*r; return area; } console.log(areaOfCircle(24)); //Exercise 8 -- Circumference of a circle is calculated as follows: circumference = 2πr. Write a function which calculates circumOfCircle function circumOfCircle(r) { var circumference = 2*Math.PI*r; return circumference; } console.log(circumOfCircle(5)); //Exercise 9 -- Density of a substance is calculated as follows:density= mass/volume. Write a function which calculates density. function calculateDensity(mass, volume) { var density = (mass/volume); return density; } console.log(3000, 1500); //Exercise 10 -- Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, speed. function calculateSpeed(distance, time) { var speed = distance/time; return speed; } console.log(100, 5000); //Exercise 11 -- Weight of a substance is calculated as follows: weight = mass x gravity. Write a function which calculates weight. function calculateWeight(mass, gravity) { var weight = mass*gravity; return weight; } console.log(calculateWeight(1000,9.023)); //Exercise 12 -- Temperature in oC can be converted to oF using this formula: oF = (oC x 9/5) + 32. Write a function which convert oC to oF convertCelsiusToFahrenheit. function convertCelsiusToFahrenheit(oC) { var oF = (oC*(9/5)) + 32; return oF; } console.log(convertCelsiusToFahrenheit(100)); //Exercise 13 -- Body mass index(BMI) is calculated as follows: bmi = weight in Kg / (height x height) in inches squared. Write a function which calculates bmi. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is underweight, normal, overweight or obese based the information given below. // The same groups apply to both men and women. // Underweight: BMI is less than 18.5 // Normal weight: BMI is 18.5 to 24.9 // Overweight: BMI is 25 to 29.9 // Obese: BMI is 30 or more function bmiCalculator(weight, height) { var bmi = (weight/(height*height)); var result=0; if(bmi<18.5) result = "Underweight"; else if(bmi>=18.5 && bmi<=24.9) result = "Normal weight"; else if(bmi>=25 && bmi<=29.9) result = "Overweight"; else if(bmi>=30) result = "Obese"; else result = "Invalid entry, please use valid numbers and try again" return result; } console.log(bmiCalculator(62,68)); //Exercise 14 -- Write a function called checkSeason, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer. function checkSeason(month){ month=month.toLowerCase(); if(month == "december" | month=="january" | month=="february") return "Winter"; else if(month =="march" | month=="april" | month=="may") return "Spring"; else if(month =="june" | month=="july" | month=="august") return "Summer"; else if(month =="september" | month=="october" | month=="november") return "Autumn"; else return "Input not valid, please enter a valid month"; } console.log(checkSeason("april")); //Exercise 15 -- Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method. //console.log(findMax(0, 10, 5)) //10 //console.log(findMax(0, -10, -2)) //0 function findMax(a,b,c){ var max=0; if(a>max) max=a; if(b>max) max=b; if(c>max) max=c; return max; } console.log(findMax(6001,6050,1)); //Exercises Level 2 //Exercise 1 -- Linear equation is calculated as follows: ax + by + c = 0. Write a function which calculates value of a linear equation, solveLinEquation. function solveLinEquation(a,b,c,x,y) { var result = (a*x + b*y +c); return result; } //Exercise 2 -- Quadratic equation is calculated as follows: ax2 + bx + c = 0. Write a function which calculates value or values of a quadratic equation, solveQuadEquation. //console.log(solveQuadratic()) // {0} // console.log(solveQuadratic(1, 4, 4)) // {-2} // console.log(solveQuadratic(1, -1, -2)) // {2, -1} // console.log(solveQuadratic(1, 7, 12)) // {-3, -4} // console.log(solveQuadratic(1, 0, -4)) //{2, -2} // console.log(solveQuadratic(1, -1, 0)) //{1, 0} function solveQuadEquation(a,b,c) { let root1, root2; // calculate discriminant let discriminant = b * b - 4 * a * c; // condition for real and different roots if (discriminant > 0) { root1 = (-b + Math.sqrt(discriminant)) / (2 * a); root2 = (-b - Math.sqrt(discriminant)) / (2 * a); // result console.log(`The roots of quadratic equation are ${root1} and ${root2}`); } // condition for real and equal roots else if (discriminant == 0) { root1 = root2 = -b / (2 * a); // result console.log(`The roots of quadratic equation are ${root1} and ${root2}`); } // if roots are not real else { let realPart = (-b / (2 * a)).toFixed(2); let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2); // result console.log(`The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`); } } solveQuadEquation(1,2,3); //Exercise 3 -- Declare a function name printArray. It takes array as a parameter and it prints out each value of the array. function printArray(array) { for(var a=0;a 4, y=>3 // swapValues(4, 5) // x = 5, y = 4 function swapValues(x,y) { return (`(${y},${x})`); } console.log(swapValues(2,3)); //Exercise 6 -- Declare a function name reverseArray. It takes array as a parameter and it returns the reverse of the array (don't use method). // console.log(reverseArray([1, 2, 3, 4, 5])) // //[5, 4, 3, 2, 1] // console.log(reverseArray(['A', 'B', 'C'])) // //['C', 'B', 'A'] function reverseArray(arr) { var newArray = []; for (var i = arr.length - 1; i >= 0; i--) newArray.push(arr[i]); return newArray; } console.log(reverseArray([1,2,3,4,5])); //Exercise 7 -- Declare a function name capitalizeArray. It takes array as a parameter and it returns the - capitalizedarray. function capitalizeArray(array) { for(var x=0; x 6 // sum(1, 2, 3, 4) // -> 10 const sumAllNums = (...args) => { let sum = 0 for (const element of args) { sum += element } return sum } console.log(sumAllNums(1,2,3,4,5,6,7,8,9)); //Exercise 15 -- Write a function which generates a randomUserIp. function randomUserIp() { var ip = (Math.floor(Math.random() * 255) + 1)+"."+(Math.floor(Math.random() * 255))+"."+(Math.floor(Math.random() * 255))+"."+(Math.floor(Math.random() * 255)); return ip; } console.log(randomUserIp()); //Exercise 16 -- Write a function which generates a randomMacAddress function randomMacAddress() { return "XX:XX:XX:XX:XX:XX".replace(/X/g, function() { return "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16)) }); } console.log(randomMacAddress()); //Exercise 17 -- Declare a function name randomHexaNumberGenerator. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number. // console.log(randomHexaNumberGenerator()); // '#ee33df' function randomHexaNumberGenerator() { let resultID = ""; const characters = '0123456789abcdef'; const charLength = characters.length; var counter = 0; while (counter<6) { resultID = resultID + characters.charAt(Math.floor(Math.random() * charLength)); counter = counter + 1; } return ('#'+resultID); } console.log(randomHexaNumberGenerator()); //Exercise 18 -- Declare a function name userIdGenerator. When this function is called it generates seven character id. //The function return the id. // console.log(userIdGenerator()); // 41XTDbE function userIdGenerator() { let resultID = ""; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charLength = characters.length; var counter = 0; while (counter<7) { resultID = resultID + characters.charAt(Math.floor(Math.random() * charLength)); counter = counter + 1; } return resultID; } console.log(userIdGenerator()); //Exercises Level 3 //Exercise 1 -- Modify the userIdGenerator function. Declare a function name userIdGeneratedByUser. It doesn’t take any parameter but it takes two inputs using prompt(). //One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. // userIdGeneratedByUser() // 'kcsy2 // SMFYb // bWmeq // ZXOYh // 2Rgxf // ' // userIdGeneratedByUser() // '1GCSgPLMaBAVQZ26 // YD7eFwNQKNs7qXaT // ycArC5yrRupyG00S // UbGxOFI7UXSWAyKN // dIV0SSUTgAdKwStr // ' function userIdGeneratedByUserHelper(length) { let resultID = ""; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charLength = characters.length; var counter = 0; while (counter { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); // return {r, g, b} return (`rgb(${r},${g},${b})`); } console.log(convertHexaToRgb("#ff33ff")); //Exercise 6 -- Write a function convertRgbToHexa which converts rgb to hexa color and it returns an hexa color. const convertRgbToHexaHelper = (c) => { const hex = c.toString(16); return hex.length == 1 ? "0" + hex : hex; } const convertRgbToHexa = (r, g, b) => { return "#" + convertRgbToHexaHelper(r) + convertRgbToHexaHelper(g) + convertRgbToHexaHelper(b); } console.log(convertRgbToHexa(255, 51, 255)); // #ff33ff //Exercise 7 -- Write a function generateColors which can generate any number of hexa or rgb colors. // console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b'] // console.log(generateColors('hexa', 1)) // '#b334ef' // console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)'] // console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)' // Uses generate array of rgb numbers from Exercises Level 3, Exercise 4 function generateColors(type, num) { if(type == 'rgb') return arrayOfRgbColors(num); else if(type == 'hexa') return arrayOfHexaColors(num); } console.log(generateColors('hexa',3)); console.log(generateColors('rgb',4)); //Exercise 8 -- Call your function shuffleArray, it takes an array as a parameter and it returns a shuffled array function shuffle(array) { let currentIndex = array.length, randomIndex; // While there remain elements to shuffle. while (currentIndex > 0) { // Pick a remaining element. randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; // And swap it with the current element. [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]; } return array; } var thisIsMyArray = [2, 11, 37, 42]; shuffle(thisIsMyArray); console.log(thisIsMyArray); //Exercise 9 -- Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number function factorial(num) { // If the number is less than 0, reject it. if (num < 0) return -1; // If the number is 0, its factorial is 1. else if (num == 0) return 1; // Otherwise, call the recursive procedure again else return (num * factorial(num - 1)); } console.log(factorial(2)); //Exercise 10 -- Call your function isEmpty, it takes a parameter and it checks if it is empty or not function isEmpty(arr) { if(arr.length==0) return 'true'; else return 'false'; } console.log(isEmpty([])); //Exercise 11 -- Call your function sum, it takes any number of arguments and it returns the sum. const sum = (...args) => { let sum = 0 for (const element of args) { sum += element } return sum } console.log(sum(1, 2, 3)); //Exercise 12 -- Write a function called sumOfArrayItems, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not give return reasonable feedback. function sumOfArrayItems(array) { var invalidIndexes = []; var summation = 0; for(var a=0; a=5) { for(var a=0; a 1; } console.log(isPrime(23)); //Exercise 16 -- Write a functions which checks if all items are unique in the array. function areDistinct(arr) { let n = arr.length; // Puts all array elements in a map let s = new Set(); for (let i = 0; i < n; i++) s.add(arr[i]); // If all elements are distinct, size of // set should be same array. if(s.size == arr.length) return true; else return false; } console.log(areDistinct([ 1, 2, 3, 2 ])); //Exercise 17 -- Write a function which checks if all the items of the array are the same data type. function sameDataType(array) { for(var a=0; a= 0; a--) { reversedArray.push(array[a]); } return reversedArray; } console.log(reverseCountries([1,2,3,4,5,6,7,8,9,10]));