I am still new to nodeJs, and I am trying to create a stream of inputs but my code is not working once I launch the app in the terminal by calling node fileName .
My input format is like this:
- N the number of queries.
- second line represent a string containing two words separated by a space.
- N lines of a string containing two words separated by a space.
for some reason, the terminal doesn't show a thing.
This is my code :
'use strict';
const fs = require('fs');
var n = 0;
var position = '';
var destination = '';
var array = [];
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*$/, '')
.split('\n')
.map(str => str.replace(/\s*$/, ''));
main();
});
function readLine() {
return inputString[currentLine++];
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const s = parseInt(readLine(), 10);
const input= readLine().split(' ');
position = input[0] ;
destination = input[1];
console.log('our number is',s, 'and our position and destination:', position, destination);
ws.end();
}
You can simplify this whole thing by allowing readline to buffer the input:
'use strict';
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('line', line => {
rl.write(
line.replace(/\s*$/, '')
);
});
Related
I have big file almost 2GB and text also includes so many countries, sometimes twise and more. I should create script what will write to stdout all countries from the file and also will show how many times the country name was used. for example if there is germany five times in file code Should show us: Germany: 5 (something like that)
const fs = require("fs");
readline = require("readline");
stream = require("stream");
const filename = process.argv[2];
const instream = fs.createReadStream(filename);
const outstream = new stream();
outstream.readable = true;
outstream.writable = true;
const rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false,
});
rl.on("line", function (line) {
const [country] = line.split(",", 1);
Str = country;
var obj = new Object();
for (var i = 0; i < Str.length; i++) {
if (obj[Str] != null) {
obj[Str] += 1;
} else {
obj[Str] = 1;
}
}
console.log(obj);
});
I wrote this but it shows the number of letters in word.
Thank you (link for download file is in comments)
Here is a part of text:
united
states,2001,dinner-and-a-murder-mystery-games,retail,linkedin.com/company/dinner-and-a-murder-mystery-games,"",dinner
and a murder mystery games,tennessee,1-10,dinnerandamurder.com
netherlands,2013,jennifer-campbell,management
consulting,linkedin.com/company/jennifer-campbell,houten,jennifer
campbell,utrecht,1-10,jennifercampbell.com united
states,"",imtec-corp,marketing and
advertising,linkedin.com/company/imtec-corp,ardmore,imtec corp
italy,1977,bo.ma-s.r.l.,research,linkedin.com/company/bo.ma-s.r.l.
Your problem is probably, that you have a variable "country" that contains the country as string and then you store it to Str and do:
"for (var i = 0; i < Str.length; i++) {
this loops over every char in the stream.
Also you need to define the "obj" outside of the callback otherwise it gets recreated for every line.
Just try:
var obj = {};
rl.on("line", function (line) {
const [country] = line.split(",", 1);
if (obj[country]) {
obj[country]++;
} else {
obj[country] = 1;
}
console.log(obj);
});
//I can split a string in the following way without problem
var string1 = "abc def ghi";
var res = string1.split(" ");
var split1 = res[1]; // abc
var split2 = res[2]; // def
var split3 = res[3]; // ghi
//But my string that has to be split is coming from reading a textfile (text)
//Unfortunately this is not working
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
var res = text.split(" ");
var split1 = res[1];
var split2 = res[2];
var split3 = res[3];
Assuming this is Javascript and not Java code, the problem is that you're trying to access the text variable outside of the callback function. The value from the readFile will only be available inside of its callback function.
You should use fs.readFileSync to get the value directly and work with it. See documentation for more details on using the function, but this should work:
var fs = require("fs")
var text = fs.readFileSync("./mytext.txt")
var textByLine = text.split("\n")
console.log("first line:",textByLine[0])
Suppose I want to generate a string base on some incremental no and a specified string.
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
Now want to replace the originalStr from last without changing its size like
//for str1 my expected output is 'activa100'
//for str2 my expected output is 'activ4569'
//for str3 my expected output is 'acti12345'
//for str4 my expected output is '123456789'
How I do this using JS?
I tried the following method:
Is their any better method than this? How to ensure result size always 9
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
const str5 = 'sizeWillChanged'
console.log(str1.padStart(9,originalStr)); //'activa100'
console.log(str2.padStart(9,originalStr)); //'activ4659'
console.log(str3.padStart(9,originalStr)); //'acti12345'
console.log(str4.padStart(9,originalStr)); //'123456789'
console.log(str5.padStart(9,originalStr)); //'sizeWillChanged'
You can use slice() to remove n characters from originalStr from the end. So that the new characters can be prefixed to originalStr without affecting the original length of originalStr.
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
function replacing(str, token) {
return (str.slice(0, -token.length) + token);
}
console.log(replacing(originalStr, str1));
console.log(replacing(originalStr, str2));
console.log(replacing(originalStr, str3));
console.log(replacing(originalStr, str4));
const originalStr = 'activator'
const str1= '100';
const str2= '4659';
const str3 = '12345';
const str4 = '123456789'
function replaceFromEnd(string1, string2){
return string1.substr(0, string1.length - string2.length) + string2;
}
console.log(replaceFromEnd(originalStr, str1));
console.log(replaceFromEnd(originalStr, str2));
console.log(replaceFromEnd(originalStr, str3));
console.log(replaceFromEnd(originalStr, str4));
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
I need help in this. I've been trying out codes for days regarding about regular expression to extract sentences using NYP as the keyword, the outcome doesn't turn out to be what i expect. what I needed was sentence that contain NYP in it, please help guys its for my project. ! my codes are in the comment box.
//readline
var fs = require('fs'),
readline = require('readline');
//reading the file
var rd = readline.createInterface({
input: fs.createReadStream('nyptweets38.out'),
output: process.stdout,
terminal: false
});
//because its a JSON file so I just want the necessary information. the date and text
rd.on('line', function (line) {
/*console.log(JSON.parse(line));
create JSON object */
var TEMP = JSON.parse(line);
console.log(TEMP.created_at + " : (" + TEMP.text + ")\n\n\n");
})
//here is where the filter starts
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun /*, thisp*/ ) {
var len = this.length;
if (typeof fun != "function") throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (filtered.length > 0) {
console.log(filtered);
return (filtered.length != -1);
}
};
Regex is overkill here; how about text.toLowerCase().indexOf('nyp') > -1;? JSFiddle