How to Use Javascript in Hackerrank and Hackerearth? - javascript

I am a newbie to competitive programming. The only language I know is Javascript but if I select javascript option I couldn't even understand how to get input and how to print output in both the sites for some problems is Hackerrank the code looks like this
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
And in the same Hackerrank for some problems the initial code looks like this
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var n = parseInt(readLine());
}
Whereas in Hackerearth the initial code look like this
function main(input) {
//Enter your code here
process.stdout.write("Hello World!");
}
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input;
});
process.stdin.on("end", function () {
main(stdin_input);
});
If someone gives me an example of a program how to get the inputs and print output in those sites or any solved program of those sites using javascript also will do I guess.

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!

function main(input) {
let [first, second] = [...input.split("\n")];
// do what ever you want here with inputs.
}
As Simple as that :) Happy coding.

Let's take a simple example from HackerEarth:
https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/tutorial/
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data",function(input){
stdin_input += input;
});
process.stdin.on("end",function (){
main(stdin_input);
});
function main(input){
var data = input.split('\n');
var num = parseInt(data[0],10);
var str = data[1];
process.stdout.write(num *2 + "\n" + data[1]);
}
sample input:
5
helloworld
sample output:
10
helloworld
first we read the input in the form of string then we convert into array with and assign to new variable data and these look like ["5", "helloworld"]

// Sample code to perform I/O:
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input; // Reading input from STDIN
});
process.stdin.on("end", function () {
main(stdin_input);
});
function main(input) {
var data = input.split('\n');
var firstLine = data[0].split(' ');
var secondLine = (data[1].split(' '));
let arr = [];
for(let i=0;i<secondLine.length;i++){
arr.push(parseInt(secondLine[i]));
}
findMininimum(arr);
//process.stdout.write("Hi, " + input + ".\n"); // Writing output to STDOUT
}
// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
// Write your code here
function findMininimum(input){
console.log(Math.min(...input));
}

I was recently stuck with the same kind of problem and have solved it using like this, hopefully it helps:
PS: Uncomment what is commented in the editor. After that add this:
/*Generally the Question Format is in
2 //TestCases
3 //N
1 3 5 //Array
5
3 6 11 22 12
*/
/*
Javascript accepts only string hence you need to parse it into integers and break the input lines
*/
function solve(arr){
//Code Here
}
function main(input){
var data = input.split('\n'); //split based on line
var t = parseInt(data[0],split(' ')); //based on space
var ind=0;
while(ind<t){
var n = parseInt(data[2*ind+1].split(' '));
for(let i=0;i<n;i++){
var val = data[2*ind+2].split(' ');
var arr=[];
for(let j=0;j<val.length;j++){
arr.push(parseInt(val[j]));
}
}
console.log(solve(arr));
ind++;
}
}

Add process.stdout.write at end of main as needed like so:
function myFunction(input) {
//Enter your code here
}
function main() {
//stuff
process.stdout.write(myFunction(input))
}

Handling 2D Array Input in NodeJs in Hackerearth
// Sample code to perform I/O:
// input we are taking
// 2 no. of test cases
// 3 2D array size
// 1 2 3
// 4 5 6
// 7 8 9
// 2 2D array size
// 4 3
// 1 4
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input = input.split("\n"); // Reading input from STDIN and splitting it
});
// now the stdin_input will contain
// stdin_input = ['2', '3', '1 2 3', '4 5 6', '7 8 9', '2', '4 3', '1 4']
process.stdin.on("end", function () {
main(stdin_input);
});
function main(input) {
let t =parseInt(input[0]) //string -> integer | no. of test cases
let index = 1 // we have already consumed 0th index value so we are starting from 1
while(t--){
// we need to increase index value each time when we consume input
n = parseInt(input[index])
index++
let arr= []
for(let i=0;i<n;i++){
arr.push([])
temp = input[index].split(" ")
for(let j=0;j<n;j++){
arr[i].push(parseInt(temp[j]))
}
index++
process.stdout.write(arr[i].toString()); // we can only print string
process.stdout.write("\n");
}
// write you logic here
process.stdout.write("------\n");
}
}
// output
// 1,2,3
// 4,5,6
// 7,8,9
// ------
// 4,3
// 1,4
// ------

process.stdin.resume(); // A Readable Stream that points to a standard input stream (stdin)
process.stdin.setEncoding("utf-8"); // so that the input doesn't transform
let inputString1 = "";
let inputString = "";
let currentLine = 0;
process.stdin.on("data", function (userInput) {
inputString1 = inputString1 + userInput; // taking the input string
});
process.stdin.on("end", function (x) {
inputString1.trim();
inputString1 = inputString1.split("\n"); // end line
for (let i = 0; i < inputString1.length; i++) {
inputString += inputString1[i].trim() + " ";
}
inputString = inputString.split(" ");
main();
});
function readline() {
let result = inputString[currentLine++];
return parseInt(result); // change when you want to use strings, according to the problem
}
// ---------------------------------------------
// use readline() to read individual integers/strings
function main() {
let t = readline();
for (let i = 0; i < t; i++) {
let n = readline();
let arr1 = [];
for (let i = 0; i < n ; i++) {
arr1[i] = readline();
}
console.log(n,arr1)
}
}
**This is for taking input where number of testcase are given **
2
2
2 4
3
1 2 3

Related

How to read line-by-line of a single parameter (input) from a JavaScript function?

I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank
Hce akr
Rn ak
Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
What I have tried without success:
function processData(input) {
let myArray = input.split("\n");
let even_indexed = "";
let odd_indexed = "";
for (let i = 1; i <= myArray.length; i++) {
let str = myArray[i];
let len = str.length;
for (let j = 0; j < len; j++){
if (j % 2 == 0) { //check if the index is even;
even_indexed.concat(str[j]);
}
else {
odd_indexed.concat(str[j]);
}
}
}
console.log("%s %s", even_indexed, odd_indexed);
}
Can't you just use split() method with a newline operator?
<script>
let x= `Hey
I'm
a
multiline
string`
console.log(x.split("\n"))
</script>
The result will be an array on which every element represents a line of your input.
I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.
let input = `This
is
a
multiline
string`
let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
currentLine = {evenIndex: [], oddIndex: []}
for(let i = 0; i < e.length; i++){
if((i + 1)%2 === 0){
currentLine.evenIndex.push(e[i]);
}
else{
currentLine.oddIndex.push(e[i]);
}
}
splitWords.push(currentLine);
});
splitWords.forEach(function(e){
console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});

Recursive parser using split in javascript

I have an algorithm where the user will enter a string and I will parse it into an array of 2+ dimensions. So, for example, the user can enter 1,2,3;4,5,6 and set the text to be parsed by the semicolon and the comma. The first pass through will create an array with 2 entries. The second pass through will create a 3 entry array in both prior spots.
The user can add or remove the number of text items to be used to parse the original string such as the semicolon or comma, meaning the resulting array can have as many dimensions as parsing items.
This doesn't seem like a difficult problem, but I have run into some snags.
Here is my code so far.
vm.parsers = [';', ','];
vm.inputString = "1,2,3,4,5;6,7,8,9,10";
function parseDatasetText( )
{
vm.real = vm.parseMe( vm.inputString, 0);
};
function parseMe( itemToParse, indexToParse )
{
if ( indexToParse < vm.parsers.length )
{
console.log('Parsing *'+itemToParse+'* with '+vm.parsers[indexToParse]);
var tempResults = itemToParse.split( vm.parsers[indexToParse] );
for (var a=0; a<tempResults.length; a++)
{
console.log('Pushing '+tempResults[a]);
tempResults[a] = vm.parseMe( tempResults[a], parseInt( indexToParse ) + 1 )
console.log('This value is '+tempResults[a]);
}
}else
{
console.log('Returning '+itemToParse);
return itemToParse
}
};
As you can see from the console logs, the algorithm spits out an undefined after the last parse, and the final answer is undefined.
Maybe I just haven't slept enough, but I was thinking that the array would recursively populate via the splits?
Thanks
function parseDatasetText(){
//composing parser from right to left into a single function
//that applies them from left to right on the data
var fn = vm.parsers.reduceRight(
(nextFn, delimiter) => v => String(v).split(delimiter).map(nextFn),
v => v
);
return fn( vm.inputString );
}
Don't know what else to add.
You can use a simple recursive function like the following (here an example with 3 different delimiters):
function multiSplit(xs, delimiters) {
if (!delimiters.length) return xs;
return xs.split(delimiters[0]).map(x => multiSplit(x, delimiters.slice(1)));
}
data = '1:10,2:20,3:30;4:40,5:50,6:60';
res = multiSplit(data, [';', ',', ':']);
console.log(res)
The following function should suit your requirements, please let me know if not
var parsers = [';', ',', ':'],
inputString = "1:a,2:b,3:c,4:d,5:e;6:f,7:g,8:h,9:i,10:j",
Result = [];
function Split(incoming) {
var temp = null;
for (var i = 0; i < parsers.length; i++)
if (incoming.indexOf(parsers[i]) >= 0) {
temp = incoming.split(parsers[i]);
break;
}
if (temp == null) return incoming;
var outgoing = [];
for (var i = 0; i < temp.length; i++)
outgoing[outgoing.length] = Split(temp[i])
return outgoing;
}
Result = Split(inputString);
try it on https://jsfiddle.net/cgy7nre1/
Edit 1 -
Added another inputString and another set of parsers: https://jsfiddle.net/cgy7nre1/1/
Did you mean this?
var inputString = "1,2,3,4,5;6,7,8,9,10";
var array=inputString.split(';');
for (var i=0;i<array.length;i++){
array[i]=array[i].split(',');
}
console.log(array);

How to split and change to different format in javascript

I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);

How do I remove "undefined" from the beginning of JavaScript array items?

I'm trying to generate an array of random digits, but I'm getting "undefined" at the beginning of each row. I've been searching online for a couple of hours, but haven't been able to figure it out.
The expected output should be 5 rows of 2 random digits like this:
87
57
81
80
02
but the actual output looks like this:
undefined87
undefined57
undefined81
undefined80
undefined02
This is a modified excerpt that produces the result shown above:
function NumberSet() {
// generate all the digits
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
}
return random_digits;
}
}
randomnumbers1 = new NumberSet();
mynums = randomnumbers1.generate();
jQuery.each(mynums, function(i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
The final version won't be using this method to display the digits. I'm just trying to troubleshoot where the "undefined" is coming from.
Initialize your variables
random_digits[i] = "";
for(z=0; z<2; z++) {
random_digit = Math.floor(Math.random()*10).toString();
random_digits[i] +=random_digit;
}
Declare the variables properly with var.
var random_digit, random_digits = [];
Declare random_digit in the first for loop and assign an empty string.
Go through the inner for loop appending your random numbers, and then push() to the array back in the outer for loop.
function NumberSet() {
// generate all the digits -a meme should be attached here-
this.generate = function() {
random_digits = [];
// create 5 rows of 2 random digits
for(i=0; i<5; i++) {
var random_digit = ""; //Declare it out here
for(z=0; z<2; z++) {
// use .toString() in order to concatenate digits to
// the array without adding them together
random_digit += Math.floor(Math.random()*10).toString(); //Append it here
}
random_digits.push(random_digit); //Push it back here
}
return random_digits;
}
}
Fiddle-dee-dee
OR Forget the inner loop and use recursion
function NumberSet() {
// generate all the digits
this.generate = function () {
random_digits = [];
// create 5 rows of 2 random digits
// Use i for how many numbers you want returned!
var random_digit = function (i) {
var getRand = function() {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand()+random_digit(i-1) : "";
};
for (i = 0; i < 5; i++) {
random_digits.push(random_digit(2)); //In this case, you want 2 numbers
}
return random_digits;
}
}
Fiddle-do-do
And the final version because I'm bored
function NumberSet(elNum, numLen) {
this.random_digits = []; //Random digits array
this.elNum = elNum; //Number of elements to add to the array
this.numLen = numLen; //Length of each element in the array
// generate all the digits
this.generate = function () {
// create 5 rows of 2 random digits
var random_digit = function (i) {
var getRand = function () {
return (Math.floor(Math.random() * 10).toString());
}
return (i > 0) ? getRand() + random_digit(i - 1) : "";
};
for (i = 0; i < this.elNum; i++) {
this.random_digits.push(random_digit(this.numLen));
}
return this.random_digits;
}
}
randomnumbers1 = new NumberSet(5, 2).generate();
jQuery.each(randomnumbers1, function (i, l) {
// display output in a div#nums
$('#nums').append(l + '<br>');
});
Fiddle on the roof
Replace
random_digits[i] +=random_digit;
With
random_digits[i] = (random_digits[i] == undefined ? '' : random_digits[i]) + random_digit;
Demo: Fiddle
Your function can be simplified to:
function NumberSet() {
this.generate = function() {
var random_digits = new Array();
for (i = 0; i < 5; i++) {
randnum = Math.floor(Math.random() * 99);
random_digits[i] = (randnum < 10 ? '0' : 0) + randnum;
}
return random_digits;
}
}
Live Demo

Adding commas, decimal to number output javascript

I'm using the following code to count up from a starting number. What I need is to insert commas in the appropriate places (thousands) and put a decimal point in front of the last two digits.
function createCounter(elementId,start,end,totalTime,callback)
{
var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function(){
jTarget.text(current);
if(current==end)
{
clearInterval(intervalId);
if(callback)
{
callback();
}
}
++current;
}
intervalId=setInterval(f,interval);
f();
}
jQuery(document).ready(function(){
createCounter("counter",12714086+'',9999999999,10000000000000,function(){
alert("finished")
})
})
Executed here: http://jsfiddle.net/blackessej/TT8BH/3/
var s = 121221;
Use the function insertDecimalPoints(s.toFixed(2));
and you get 1,212.21
function insertDecimalPoints(s) {
var l = s.length;
var res = ""+s[0];
console.log(res);
for (var i=1;i<l-1;i++)
{
if ((l-i)%3==0)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res = res.replace(',.','.');
return res;
}
Check out this page for explanations on slice(), split(), and substring(), as well as other String Object functions.
var num = 3874923.12 + ''; //converts to a string
numArray = num.split('.'); //numArray[0] = 3874923 | numArray[1] = 12;
commaNumber = '';
i = numArray[0].length;
do
{
//we don't want to start slicing from a negative number. The following line sets sliceStart to 0 if i < 0. Otherwise, sliceStart = i
sliceStart = (i-3 >= 0) ? i-3 : 0;
//we're slicing from the right side of numArray[0] because i = the length of the numArray[0] string.
var setOf3 = numArray[0].slice(sliceStart, i);
commaNumber = setOf3 + ',' + commaNumber; //prepend the new setOf3 in front, along with that comma you want
i -= 3; //decrement i by 3 so that the next iteration of the loop slices the next set of 3 numbers
}
while(i >= 0)
//result at this point: 3,874,923,
//remove the trailing comma
commaNumber = commaNumber.substring(0,commaNumber.length-1);
//add the decimal to the end
commaNumber += '.' + numArray[1];
//voila!
This function can be used for if not working locale somite
number =1000.234;
number=insertDecimalPoints(number.toFixed(3));
function insertDecimalPoints(s) {
console.log(s);
var temaparray = s.split(".");
s = temaparray[0];
var l = s.length;
var res = ""//+s[0];
console.log(res);
for (var i=0;i<l-1;i++)
{
if ((l-i)%3==0 && l>3)
res+= ",";
res+=s[i];
}
res+=s[l-1];
res =res +"."+temaparray[1];
return res;
}
function convertDollar(number) {
var num =parseFloat(number);
var n = num.toFixed(2);
var q =Math.floor(num);
var z=parseFloat((num).toFixed(2)).toLocaleString();
var p=(parseFloat(n)-parseFloat(q)).toFixed(2).toString().replace("0.", ".");
return z+p;
}

Categories