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);
});
Related
My aim is for a string passed into dna will be converted using the lookup table traslateDna and returned.
For a single character this works fine but multiple characters and empty strings breaks this.
I can get it to work running it through a loop but is there a way of not requiring a loop?
Sample dna = ACGTGGT
const traslateDna = {
'G':'C',
'C':'G',
'T':'A',
'A':'U'
}
export const toRna = (dna) => {
let rnaStr = ''
for(let i =0; i < dna.length; i++){
rnaStr+=(traslateDna[dna[i]])
}
return rnaStr;
};
Below is the closest I can come, which is pretty awful. Is there a way of using the replace()method for this.
const traslateDna = {
'G':'C',
'C':'G',
'T':'A',
'A':'U'
}
export const toRna = (dna) => {
let rnaStr = '';
rnaStr = traslateDna[dna.replace()]);
}
return rnaStr;
};
Your second example is still incorrect. You should put it into codepen and try to parse it. It should not run.
To answer your question tho, You could use recursion I suppose.
const dna = 'ACGTGGT';
const traslateDna = {
'G':'C',
'C':'G',
'T':'A',
'A':'U'
}
const toRna = (dna, offset = 0) => {
if (offset == dna.length) return dna;
let rnaStr = '';
rnaStr = dna.substring(0, offset) + traslateDna[dna[offset]] + dna.substring(offset + 1, dna.length);
return toRna(rnaStr, offset + 1);
};
console.log(toRna(dna));
Although, functionally, this method and a loop are equivilant.
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*$/, '')
);
});
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
test.csv file has:
"Id","UserName","Age"
"01","Sam Smith","33"
"02","Fred Frankly","44"
"03","Zachary Zupers","55"
acpected output: as Json File
[{"id":01,"User Name": " Sam Smith", "Age":"33"},
{"id":03,"User Name": " Fred Frankly", "Age":"44"}
{"id":03,"User Name": "Aachary Zupers", "Age":"55"}
]
I tried to solve like this using node.js
var fs = require("fs");
var data = fs.readFileSync('test.csv');
var stringData=data.toString();
console.log(stringData);
var arrayOne= stringData.split('\r\n');
var header=arrayOne[0].split(',');
var noOfRow=arrayOne.length;
var noOfCol=header.length;
var jArray=[];
var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {
for (j = 0; j< noOfCol; j++) {
var myNewLine=arrayOne[i].split(',');
jArray.push( '{'+header[j]+':'+myNewLine[j]+'}');
};
};
console.log( jArray);
this is the output I got when I run the above code:
output Image
In the above code I have just tried to show in json script. But If you can do that. Please provide the code to convert the displayed output into a .json file.
Please help me I shall be thankful to you.
As ShanShan mentioned you can leverage an external library for this in a real project, but I've made some modifications to your code that should do what you want in case you're doing this as a learning experience.
I've tried to keep the code roughly the same. There are two major changes. First, rather than construct a string with the content I'm creating an object that stores the data that you're interested in for each row. Because this object is on a per-row level, this is in the outer loop that handles rows. Second, I'm stripping out the first and last character of the header and value text (the quotes). Because you're interepreting the CSV as a string and splitting based on that, it still contains the quotes. In the real world you might want to extract this with a regex or a replace function, but I tried to keep it simple so it uses substring instead.
The code below:
var fs = require("fs");
var data = fs.readFileSync('test.csv');
var stringData=data.toString();
console.log(stringData);
var arrayOne= stringData.split('\r\n');
var header=arrayOne[0].split(',');
var noOfRow=arrayOne.length;
var noOfCol=header.length;
var jArray=[];
var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {
var obj = {};
var myNewLine=arrayOne[i].split(',');
for (j = 0; j< noOfCol; j++) {
var headerText = header[j].substring(1,header[j].length-1);
var valueText = myNewLine[j].substring(1,myNewLine[j].length-1);
obj[headerText] = valueText;
};
jArray.push(obj);
};
console.log( jArray);
try this:
...
var jArray=[];
var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {
for (j = 0; j< noOfCol; j++) {
var myNewLine=arrayOne[i].split(',');
jArray.push(JSON.parse( '{'+header[j]+':'+myNewLine[j]+'}'));
};
};
fs.writeFile('test.json', JSON.stringify(jArray), function (err) {
if (err) return console.log(err);
console.log('ok');
});
console.log( jArray);
This should work
var fs = require('fs');
var data = fs.readFileSync('test.csv');
var parsed = data.toString().split('\r\n').splice(1).map(function(d) {
var splitted = d.split(',');
return {
id: parseInt(JSON.parse(splitted[0])),
user_name: JSON.parse(splitted[1]),
age: parseInt(JSON.parse(splitted[2]))
};
});
console.log(parsed);
If you care to not re invent the wheel,
Given a csv such
NAME, AGE
Daffy Duck, 24
Bugs Bunny, 22
you could do like this
var csv = require('csv-parser')
var fs = require('fs')
fs.createReadStream('some-csv-file.csv')
.pipe(csv())
.on('data', function (data) {
console.log('Name: %s Age: %s', data.NAME, data.AGE)
})
see more here
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