I’m working on a challenge called Compare the Triplets in Hacker Rank where the function takes in two arrays as parameters and you are meant to compare the indexes and award a point to the group with a higher number and return the score for each array.
my code is as follows:
let aTemp = readLine().split(' ');
let a0 = parseInt(aTemp[0]);
let a1 = parseInt(aTemp[1]);
let a2 = parseInt(aTemp[2]);
let bTemp = readLine().split(' ');
let b0 = parseInt(bTemp[0]);
let b1 = parseInt(bTemp[1]);
let b2 = parseInt(bTemp[2]);
let aScore = 0;
let bScore = 0;
if(a0 > b0){
a++;
};
if (a0 < b0){
b++;
};
if(a1 > b1){
a++;
};
if (a1 < b1){
b++;
};
if(a2 > b2){
a++;
};
if (a2 < b2){
b++;
};
console.log(aScore + ' ' + bScore);
I am getting the error:
TypeError: Cannot read properties of undefined (reading ‘split’)
I have tried searching this error to get more information but do not seem to see anything relevant to my issue.
2
Answers
You’re missing one argument in the
readLine
function. You can just usereadLine('Write something divided by spaces')
.Also you can refactor your code to be a bit more simple. Here’s my take.
The undefined you get from
readLine
means you are reading more lines from the input than is given as input. This typically happens when the input was already read, and you are trying to read it again.The template that HackerRank offers before you start entering your code, is this:
Note how the code in
main
already reads the necessary input, callingreadLine
, so you shouldn’t do that in your implementation. Instead you should put your code inside thecompareTriplets
function. That function is called frommain
(which you shouldn’t touch!), and gets the two arrays as arguments. It should not performconsole.log
, but return the result as a 2-element array. It ismain
that takes care of outputting that result in the required format.Not your question, but you can avoid the repetition of similar code you have for
a0
,a1
anda2
, by making use of arrays.Here is how it could be done:
Don’t touch the rest of the template code you get to start with. Only define the body of the
compareTriplets
function.