I've a simple problem from Hacker Rank.
There are N strings. Each string's length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurred previously. The first line contains , the number of strings. The next N lines each contain a string. The N + 2nd line contains , the number of queries.
The following Q lines each contain a query string.
Sample Input
4
aba
baba
aba
xzxb
3
aba
xzxb
ab
Sample Output
2
1
0
Here's the provided code,
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);
});
The solution to the problem is simple.
Initialize a hashmap. Enter the values in the N strings in the hashmap against occurence count.
var map = {};
if(!map[input])map[input]++;
else map[input] = 1;
And then for each query return the get on the respective key.
The issue is I'm new to javascript and have no clue about node. Can someone help me understand the code and help me in figuring out the scopes in which the respective data structures will have to instantiated.
You need to put your code in :
function processData(input) {
// split your input and access it
//your logic
var map = {};
if(!map[input])map[input]=1;
else map[input] +=1;
//your output
console.log('...');
}
Explaination
Start reading from stdin so we don't exit.
process.stdin.resume();
Reads the input data
process.stdin.on("data", function (input) {
_input += input;
});
On completion of data calls the end event is fired.
process.stdin.on("end", function () {
processData(_input);
});
Related
Is anybody here who solves problems on HackerEarth? I am confused with the way they supply the input data.
I have been using Leetcode to date to solve problems and I am pretty happy with them but unfortunately, some people prefer HackerEarth to host coding challenges and I have issues trying to read the input test case properly.
Take this for example https://www.hackerearth.com/practice/algorithms/searching/ternary-search/practice-problems/algorithm/small-factorials/submissions/
I did my research and found their "solution guide" which has the wrong info: https://www.hackerearth.com/docs/wiki/developers/solution-guide/
How would I read the individual lines and output the results in JS (Node v10) judge?
Thank you.
Just logged into and looked it up here.
Seems to be similar to HackerRank which I'm not fond of. (LeetCode's UI is fun and much easier to use.)
On LeetCode, we don't have to print things out, here it seems we have to print the output (for instance in JavaScript we would use console.log not to mention printing inside methods is generally a bad practice coding).
This solution (copied from one of those activities) seems to be passing based on which you can figure things out:
/*
// 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) {
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
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) {
input = input.split('\n');
input.shift();
input.forEach(n => {
n = parseInt(n);
let fact = BigInt(1);
while(n){
fact = BigInt(fact) * BigInt(n);
n--;
}
console.log(String(fact).replace('n',''));
});
}
in accessing inputs HackerEarth bit different compare to leetcode and Hacker Rank here you will have to extract inputs from standard input (STDIN) by line number you can find more details here
for example, if the format of the input given as below
Input format:
First line contains integer N.
Second line contains string S.
then you will split the STDIN by new line("\n") and access each input line-wise
below is a sample of how would you access inputs in JavaScript
var input1 = 0;
var input2 = "";
var stdin_input = ""
process.stdin.on("data", function (input) {
// Reading input from STDIN
stdin_input += input;
input1 = stdin_input.split("\n")[0]
input2 = stdin_input.split("\n")[1]
console.log("input1 = ", input1)
console.log("input2 = ", input2)
});
1- First step --> Find the first occurrence of a number using Regex \d+ (No need to add the global flag as the problem stated that the first line always contains a number, thus we are looking for the first number). The + flag is to always match more than one occurrence of a digit like 2,12,21,234, and so on.
2-Second Step --> Cast the matched string to a number to multiply it by two (double it), then cast it back to a string and make the replacement using the regex replace methods.
More about the method can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
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) {
const regex = /(\d+)/g;
let expr = input.replace(regex,(match) => {
return String(Number(match) * 2);
});
process.stdout.write(expr);
}
I'm doing a beginner-level programming challenge. I understand the algorithm part, but I don't understand how it takes input.
I know it takes input in three lines. There is some pre-written code that puts the input into an "input" variable. How do I process this "input" variable to get the data in individual lines?
input line 1: number of items ordered, index of item Anna did not eat
input line 2: price of each item
input line 3: cost to Anna
Sample input:
4 1
3 10 2 9
12
Expected output: 5
here is my code that is messed up, which I am trying to fix:
function processData(input) {
var input_temp = input.split("\n");
var allergyIndex = input_temp[0][1];
var array = input_temp[1].split(" ");
var annaCharged = input_temp[2];
var annaMealsCost = 0;
for (var i = 0; i < array.length; i++){
if (i !== allergyIndex){
annaMealsCost += array[i];
}
}
if (annaMealsCost / 2 === annaCharged){
console.log("Bon Appetit");
} else {
console.log(annaCharged - annaMealsCost / 2);
} }
// below is the code that is pre-written, which I don't understand at all:
process.stdin.resume(); process.stdin.setEncoding("ascii");
_input = ""; process.stdin.on("data", function (input) {
_input += input; });
process.stdin.on("end", function () { processData(_input); });
When the program runs, it will listen for the data to be entered in until an EOF character. At that point, processData will be called with all lines entered up until that point.
If you normally run the program (node my-program.js) it will wait for input. You can enter the data, and finally trigger the process.stdin end event by manually entering Cmd + D which will be interpreted as an EOF character.
Piping
Another option is to just put the input as you would enter it into a text file.
By default printing a file will go to process.stdout. But you may redirect the print to go to process.stdin by using the pipe character (|).
input.txt
4 1
3 10 2 9
12
terminal prompt
cat input.txt | node my-program.js
The output of the command cat input.txt will be used as input to node my-program.js.
So im trying to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
123456
23456
3456
456
56
6
I am trying to understand the solution of this question as below:
function pattern(n){
var output="";
for(i=1;i<n+1;i++){
for(j=i;j<n+1;j++){ //what is the purpose of this j loop?
output += j;
}
if(i!=n) output +="\n"; //I know \n can jump to next line, but what does this if statement mean? why I!=n?
}
return output;
}
// function definition
function pattern(n){
// declare a variable to collect the lines
var output="";
// there are n lines
for(i=1;i<n+1;i++){
// each line starts with the linenumber and ends with n
// so take a loop from i to n
for(j=i;j<n+1;j++){
// collect the numbers of each line as a string in the declared variable
output += j;
}
// if i!=n means: not the last line
if(i!=n) output +="\n";
}
// return the result of this function
return output;
}
UPDATE
But please let me point out, that the given solution is not very smart. Take a look at the following code:
Array.range = function(start, end) {
return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}
function pattern(n){
var startValues = Array.range(1,n);
return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}
http://jsfiddle.net/afmchdwp/
First we define the static Method Array.range which helps us to define number ranges in javascript.
The pattern function can now use this ranges to create the numbers you need.
The first line of the function create a range from 1..n (the startnumbers of the lines).
The second line walks throu this array and transform every value 1..n into a range from the linenumber to n. With .join(), you can combine the characters of each line and combine the lines itself.
UPDATE 2
Here a updated fiddle without comma separated numbers (using join inside the closure): http://jsfiddle.net/afmchdwp/1/
Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);
I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}