How to Use Javascript in Hackerrank and Hackerearth?

Let’s take a simple example from HackerEarth:
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-factorial/

To provide the solution, you need to do this:

function main(input) {
    //Enter your code here
    var num = parseInt(input, 10);//This line expects input to be a string so convert to an int as per problem
    var res=1;
    for(var i=num;i>1;i--) {
        res *= i; 
    }
    process.stdout.write(res);//This is how you write output.
} 

EDIT:

Here is how you could do it in hackerrank:

function main() {
    var n = parseInt(readLine());
    var strN = n.toString();//<-- Convert int n to string
    for(var i=1;i<=10;i++) {
        process.stdout.write(strN+" x "+i+" = "+n*i);//<-- formatting the 
                                                     //question requires
        process.stdout.write("\n");//<-- newline
    }
}

The difference seems to be that in HackerRank, you need to convert the output to string yourself.
Hope it helps!

EDIT2:

For multiline input like:

5 1
1 2 3 4 1

You can do this:

function main(input) {
    //Enter your code here
    var data = input.split('\n');
    var firstLine = data[0].split(' ');
    var len = firstLine[0];
    //process.stdout.write('length:'+len);
    var toFind = firstLine[1];
    //process.stdout.write('toFind:'+toFind);
    //process.stdout.write('\n');
    var arr = data[1].split(' '); 
    //process.stdout.write(arr);
    for(var i=len-1;i>=0;i--) {
        if(arr[i] == toFind){
            process.stdout.write(i+1);
            return;
        }
    }
    process.stdout.write(-1);
}

Notice that input is multi-line, so first you need to split it into lines by doing var data = input.split('\n');.
Each split will give you string with spaces in between. So, to get individual characters, you have to split again but this time with space like var firstLine = data[0].split(' ');.
Once you have all the input, you are left with writing your own algorithm.
Notice that I have left comments too so that you know how to debug in the editor itself.

By the way this solution also works and is an accepted solution.

Hope this helps too!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)