Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not expected .map()/.match(regex) output

First line of the input contains an integer, N. Then N lines follow.
From the second line onwards, each line contains a set of W words separated by a single space.
For every line,
Print (console.log()) 1 if the conversation starts with hackerrank
Print 2 if the conversation ends with hackerrank
Print 0 if the conversation starts and ends with hackerrank
Print -1 if none of the above.

Code (JavaScript)

const processData = (input) =>
  input
    .split("\n")
    .slice(1)
    .map((line) => line.match(/^(hackerrank)\b.*(?<!\bhackerrank)$/g) ? console.log(1) : line.match(/ hackerrank$/g) ? console.log(2) : line.match(/^(hackerrank)\b(.*(?<!\bhackerrank))?$/g) ? console.log(0) : console.log(-1));

Input

4
i love hackerrank
hackerrank is an awesome place for programmers
hackerrank
i think hackerrank is a great place to hangout

Expected output

2 1 0 -1
(one number by line… im having a hard time with my markdown)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output I get

2 1 0 -1 -1
(one number by line… im having a hard time with my md)

what’s going on with this last -1?
i’ve tested this code on codepen and it works but it doesn’t work on hackerrank

thank you

>Solution :

You can remove empty lines before parsing with filter.

input.split("\n").slice(1).filter(Boolean)

Alternatively, remove leading and trailing whitespace from the input with String#trim before splitting.

input.trim().split("\n")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading