diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec..c30a17a 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,41 +1,110 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} - +// takes two numbers as arguments and returns the largest +function maxOfTwoNumbers(num1, num2) { + if (num1 >= num2) { + return num1; + } else{ + return num2; + } +} // Iteration #2: Find longest word +// takes as an argument an array of words and returns the longest one. If there are 2 with the same length, it should return the first occurrence. const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} +function findLongestWord(wordsArr) { + if (wordsArr.length===0){ + return null; + } + let longestWord = wordsArr[0]; + for (let i=1;ilongestWord.length){ + longestWord = wordsArr[i]; + } + } + return longestWord; +} // Iteration #3: Calculate the sum +// iterating over an array and adding each of the elements together. const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; -function sumNumbers() {} +function sumNumbers(numbersArr) { + if (numbersArr.length===0){ + return 0; + } + let sum=0; + for (let i=0;i maxProduct) { + maxProduct = product; + } + } + if (i + 3 < matrix.length) { + let product = matrix[i][j] * matrix[i + 1][j] * matrix[i + 2][j] * matrix[i + 3][j]; + if (product > maxProduct) { + maxProduct = product; + } + } + } + } + return maxProduct; +} +console.log(greatestProduct(matrix)); // 51267216 + +//Bonus - Iteration #8.1: Product of diagonals +// It takes a matrix as a parameter and returns the greatest product of any four values layed out diagonally, in either direction. +function greatestProductOfDiagonals(matrix){ + let maxProduct = 0; + for (let i = 0; i < matrix.length; i++) { + for (let j = 0; j < matrix[i].length; j++) { + if (i + 3 < matrix.length && j + 3 < matrix[i].length) { + let product = matrix[i][j] * matrix[i + 1][j + 1] * matrix[i + 2][j + 2] * matrix[i + 3][j + 3]; + if (product > maxProduct) { + maxProduct = product; + } + } + if (i - 3 >= 0 && j + 3 < matrix[i].length) { + let product = matrix[i][j] * matrix[i - 1][j + 1] * matrix[i - 2][j + 2] * matrix[i - 3][j + 3]; + if (product > maxProduct) { + maxProduct = product; + } + } + } + } + return maxProduct; +} +console.log(greatestProductOfDiagonals(matrix)); // 70600674 // The following is required to make unit tests work. /* Environment setup. Do not modify the below code. */