Given a square matrix, calculate the absolute difference between the sums of its diagonals.
function diagonalDifference(arr) {
// arr eg: [ [ 11, 2, 4 ], [ 4, 5, 6 ], [ 10, 8, -12 ] ]
const arrLength = arr.length
let leftDiagonal = 0, rightDiagonal = 0
for(let i = 0; i < arrLength; i++){
leftDiagonal += arr[i][i]
rightDiagonal += arr[arrLength - 1 - i][i]
}
return Math.abs(leftDiagonal - rightDiagonal);
}
Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero.
function plusMinus(arr) {
const total = arr.length
let zeroCount = 0, positiveCount = 0, negativeCount = 0
for(let i = 0; i < arr.length; i++){
arr[i] < 0 ? negativeCount++ : arr[i] > 0 ? positiveCount++ : zeroCount++
}
console.log(eval(positiveCount/total))
console.log(eval(negativeCount/total))
console.log(eval(zeroCount/total))
}
input: 4
expected output:
#
##
###
####
function staircase(n) {
let count = 0
while(count < n){
let hashArray = Array(count + 1).fill('#')
console.log(' '.repeat(n - count -1) + hashArray.join(''))
count++
}
}
input: [1,4,2,3,4]
expected output: 2
function birthdayCakeCandles(candles) {
// **Simple ES6 Way**
// const maxValue = Math.max(...candles)
// const count = candles.filter(val => val == maxValue).length
// return count
// **Classic "algorithm challenge" way**
// [1,2,3,4,4]
let count = 0
let maxValue = 0
for(let i = 0; i < candles.length; i++){
if(candles[i] == maxValue){
count++
}
if(candles[i] > maxValue){
maxValue = candles[i]
count = 1
}
}
return count
}
input: 07:05:45PM expected output: 19:05:45
function timeConversion(s) {
const timeAsArray = s.slice(0,8).split(":")
timeAsArray[0] = (s.indexOf('PM') > -1) ? (timeAsArray[0] == 12 ? '12' : Number(timeAsArray[0]) + 12) : (timeAsArray[0] == 12 ? '00' : timeAsArray[0]);
return timeAsArray.join(':');
}