3 ms·
I'd probably reach for node.js for something like this... var fs = require('fs'); var lines = fs.readFileSync('./somefile.txt','utf8') .trim().sp
by tracker1 13y ago
I'd probably reach for node.js for something like this...
var fs = require('fs');
var lines = fs.readFileSync('./somefile.txt','utf8')
.trim().split(/\r\n|\r|\n/g);
for (var i=0; i<lines.length; i++) {
lines[i] = i * +lines[i];
}
fs.writeFileSync(
'./outfile.txt'
,'urf8'
,lines.join('\n')
);
Easy peasy. That's off the top of my head so fs syntax may not be correct. I'd probably give it a quick run through in the node repl to start with.
Why JS, I find that this type of scenario begs for a language that does coercion well... say what you will about JS, it does do that.
- benhoyt 13y agoReally, that's easy peasy? Looks terrible to a Python programmer. :-) with open('input') as fin, open('output', 'w') as fout: for line_num, line in enumerate(fin, 1): fout.write('{0}\n'.format(int(line) * line_num))
- biscarch 13y agoI would've went with Haskell myself ;) main :: IO () main = writeListAsLines . toDoubleList . lines =<< readFile "nums.txt" where toDoubleList y = zipWith (*) (map read y) [1..length y] writeListAsLines z = writeFile "output.txt" (concat $ intersperse "\n" $ map show z)
- deckiedan 13y agoI think you would really enjoy learning some other languages. You obviously understand programming concepts really well... but, node.js for this? really? Even C is less verbose than that JS...: #include <stdio.h> int main(void){ unsigned int lineno=0; char line[1000]; unsigned int number; while (fgets(line, 999, stdin)) { sscanf(line, "%u", &number); printf("%u\n", number * lineno++); } return(0); } which reads stdin, and writes to stdout. I'm sure the C may not be perfect, I've not really used it in years. Node for a task like this is a bit like using a Nimitz Class Aircraft Carrier to hammer in a nail...
- tracker1 13y agostdin/out for node.js var i=0 ,stream = require("stream") ,rl = require('readline').createInterface({ input: process.stdin ,output: new stream.Writable() }); rl.on('line',function(line){ process.stdout.write(((+line || 0) * ++i) + '\n'); }); process.stdin.resume(); I actually know several languages... ;-) Just find that node is my go to tool these days.