Simple Array Sum
reads in input like so:
6 // first # is represents how many #s there are
1 2 3 4 10 11 // your output should be 31
use Array’s reduce.
1 2 3 4 5 |
const data = [1,2,3,4,5]; data.reduce((total, element, index) => { console.log(index, element); return total + element; }, 0); |
output:
0 1
1 2
2 3
3 4
4 5
15
answer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function simpleArraySum(ar) { return ar.reduce(function(total, num) { return total + num; }); } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); let input = readLine(); const arCount = parseInt(input, 10); // # of numbers const ar = readLine().split(' ').map(arTemp => { return parseInt(arTemp, 10) }); let result = simpleArraySum(ar); ws.write(result + "\n"); ws.end(); } |
Compare the Triplets
Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from 1 to 100 for three categories: problem clarity, originality, and difficulty.
The rating for Alice’s challenge is the triplet a = (a[0], a[1], a[2]), and the rating for Bob’s challenge is the triplet b = (b[0], b[1], b[2]).
The task is to find their comparison points by comparing a[0] with b[0], a[1] with b[1], and a[2] with b[2].
If a[i] > b[i], then Alice is awarded 1 point.
If a[i] < b[i], then Bob is awarded 1 point.
If a[i] = b[i], then neither person receives a point.
Comparison points is the total points a person earned.
Given a and b, determine their respective comparison points.
Sample Input 1
17 28 30
99 16 8
bob wins on first compare 17 vs 99
alice wins on second compare 28 vs 16
alice wins on third compare 30 vs 8
Thus output should be alice’s score first, then bob’s score:
2 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Complete the compareTriplets function below. function compareTriplets(a, b) { let aliceScore = 0; let bobScore = 0; if (a.length === b.length) { for (let index = 0; index < a.length; index++) { if (a[index] > b[index]) { aliceScore = aliceScore + 1; } else if (a[index] < b[index]) { bobScore = bobScore + 1; } } } return [aliceScore, bobScore]; } |
Diagonal Difference
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
input:
3
11 2 4
4 5 6
10 8 -12
so diagonal starting from top left and going down right: 11 + 5 + -12 = 4
diagonal starting from bottom left and going up right: 10 + 5 + 4 = 19
output:
|19-4| = 15
Keep in mind that the matrix can vary in length.
1 2 3 4 5 6 7 8 9 10 11 12 |
function diagonalDifference(arr) { // Write your code here let leftDiagonal = 0; let rightDiagonal = 0; let matrixLength = arr.length-1; for (let i = 0; i < arr.length; i++) { leftDiagonal = leftDiagonal + arr[i][i]; rightDiagonal = rightDiagonal + arr[i][matrixLength-i]; } return Math.abs(leftDiagonal - rightDiagonal); } |
Plus Minus
See how many
positives,
negatives, and
0s
there are in an array.
Calculate their ratio according to the array’s length.
Make sure the results is in 6 decimal places.
Sample Input
6
-4 3 -9 0 4 1
Sample Output
3, 4, 1, so three positives. 3/6 = 0.500000
-4, -9, so two negatives. 2/6 = 0.333333
0, so 1 zero. 1/6 = 0.166667
0.500000
0.333333
0.166667
For rounding to n-th place we use toFixed(n)
The rest, we simply keep counters and keep track of when one of them happens.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Complete the plusMinus function below. function plusMinus(arr) { let posCounter = 0; let zeroCounter = 0; let negCounter = 0; let total = arr.length; for (let i = 0; i < arr.length; i++ ) { let num = arr[i]; posCounter += (num > 0) ? 1 : 0; negCounter += (num < 0) ? 1 : 0; zeroCounter += (num === 0) ? 1 : 0; } console.log((posCounter/total).toFixed(6)); console.log((negCounter/total).toFixed(6)); console.log((zeroCounter/total).toFixed(6)); } |
another solution:
1 2 3 |
function eval(expr) { return expr ? 1 : 0; } |
eval(1 > 0) // 1
eval(-5 < 0) // 1
eval(2 > 5) // -1
eval(0===0) // 1
1 2 3 4 5 6 7 8 9 10 |
const data = [2,3,4,2,5,2,4,-1,0]; let posCounter = 0; let negCounter = 0; let zeros = 0; data.forEach((item) => { posCounter += eval(item>0) negCounter += eval(item<0) zeros += eval(item === 0) }); |
posCounter is 7
negCounter is 1
zeros is 1
Staircase
input:
4
output:
#
##
###
####
note the spaces in front. Make sure the # appears in the end.
Our solution is to use recursion.
approach is
print backwards
1 2 3 4 5 6 7 |
function recursion(n) { console.log(n); if (n==1) { // base case return n; } recursion(n-1); // recursion } |
print forward
1 2 3 4 5 6 7 8 |
function recursion(n) { if (n==1) { // base case console.log(1); return n; } recursion(n-1); // recursion console.log(n); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
let gTotal; function staircase(n) { if (n === 1) { // base let spaces = ''; for (let i = 0; i < gTotal-n; i++) { spaces = spaces.concat(' '); } console.log(spaces + '#'); // print base case return; } staircase(n-1); // recursion let output = ''; for (let j = 0; j < gTotal - n; j++) { output = output.concat(' '); } for (let i = 0; i < n; i++) { output = output.concat('#'); } console.log(output); // print the other cases } function main() { const n = parseInt(readLine(), 10); gTotal = n; staircase(n); } |
Min Max Sum
Get the sum of 4 of the 5 items in an array.
Then console out the min and max of it.
Sample Input
1 2 3 4 5
Sample Output
10 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function miniMaxSum(arr) { let total = 0; let storage = []; for (let j = 0; j < arr.length; j++) { for (let i = 0; i < arr.length; i++) { if (j != i) { total += arr[i]; } } storage.push(total); total = 0; } storage.sort(function(a,b) { return a > b; }); console.log(`${storage[0]} ${storage[storage.length-1]}`); } function main() { const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10)); miniMaxSum(arr); } |
Workers and jobs
Given an array of orders [10, 20, 30], where each order takes one robot to complete, we have a starting # of robots, say 60.
Calculate how many orders can be completed.
We send 10 to do the first one. 20 to do the second one. We have 30 robots left. The last job takes 30 robots so works out perfectly.
In this case, the answer is (3) where all three orders can be completed.
Let’s say we have an array of orders [20, 20, 40, 10]. We only have 50 robots this time. The return answers should be 3. Because we can only afford to do 3 jobs. Job 1, 2, and 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let orders = [20, 20, 40, 10]; let workerRobots = 50; function doIt(orders, workerRobots) { let maxPossibleFulfilledOrders = 0; for(let i = 0; i < orders.length; i++) { let numOfOrders = orders[i]; console.log(`processing index ${i}, orders - ${numOfOrders}, workerRobots - ${workerRobots}`); if (workerRobots >= numOfOrders) { // can subtract from index i because there is enough robot workers to complete the orders workerRobots = workerRobots - numOfOrders; maxPossibleFulfilledOrders++; } else { console.log(`skipping order at index ${i}. It overlaps # of workerRobots`); } } console.log('maxPossibleFulfilledOrders', maxPossibleFulfilledOrders); } doIt(orders, workerRobots); |