Okay so I'm learning Javascript with HackerRank's 10 days of Javascript, I'm at Day 3: which consists in Array problems. The current problem consists of returning the second-highest value from two inputs, the first is the amount of items on the array, and the second is an amount of values which will be saved at the 'nums' array. I made it with the code below, but only with the following input case, if I try the same code for different inputs (see at the end) it return to me 'Wrong Answer'. Here you can read more about the problem: https://www.hackerrank.com/challenges/js10-arrays/problem
'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(string => {
return string.trim();
});
main();
});
function readLine() {
return inputString[currentLine++];
}
/* This is the code that I wrote */
function getSecondLargest(nums) {
nums.sort();
let maxValue = Math.max(...nums);
let count = 0;
for (let i=0;i<nums.length;i++){
if (nums[i]==maxValue){
count++;
}
}
let secondMaxValue = nums[(nums.lastIndexOf(maxValue)-count)];
return secondMaxValue;
}
function main() {
const n = +(readLine());
const nums = readLine().split(' ').map(Number);
console.log(getSecondLargest(nums));
}
5
2 3 6 6 5
But when I try the same code with the following inputs I get "Wrong Answer"
10
1 2 3 4 5 6 7 8 9 10
Any explanation or maybe an advice please?
The problem is sort()
function. The javascript's sort()
method will order the integer array in following way.
[1,10,2,3,4,5,6,7,8,9]
You need to use following method to sort it,
nums = nums.sort(function(a,b) {
return (+a) - (+b);
});
The sorting problem already asked here
You just need to sort the numbers and get the second index. Follow the code.
function getSecondLargest(nums) {
nums.sort((a, b) => {
return b - a;
});
return nums[1]
}
function getSecondLargest(nums) {
nums.sort((a, b) => Math.sign(b - a));
return nums[1]
}
console.log(getSecondLargest([1,2,3,4,5,6,7,8,9,10]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With