Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

10 Days of Javascript - Day 3: Arrays - HackerRank [duplicate]

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?

like image 650
Benjamín Cáceres Ramirez Avatar asked Jun 20 '20 03:06

Benjamín Cáceres Ramirez


2 Answers

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

like image 86
BadPiggie Avatar answered Oct 12 '22 02:10

BadPiggie


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]));
like image 41
sibabrat swain Avatar answered Oct 12 '22 03:10

sibabrat swain