-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode-jam.js
More file actions
94 lines (78 loc) · 1.91 KB
/
code-jam.js
File metadata and controls
94 lines (78 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const fs = require('fs');
class Input {
constructor(input) {
this.input = input;
}
readLine() {
const index = this.input.indexOf('\n');
const line = this.input.substr(0, index);
this.input = this.input.substr(index + 1);
return line;
}
readWord() {
const result = /(\S+)\s*/.exec(this.input);
if (result) {
this.input = this.input.substr(result[0].length);
return result[1];
}
}
readNumber() {
return +this.readWord();
}
readN(n, f) {
const res = [];
for (let i = 0; i < n; i++) {
res.push(f.call(this, this));
}
return res;
}
readLines(n) {
return this.readN(n, this.readLine);
}
readWords(n) {
return this.readN(n, this.readWord);
}
readNumbers(n) {
return this.readN(n, this.readNumber);
}
}
function outputSolutions(input, solution, options) {
const caseOutputNewline = options && options.caseOutputNewline;
input = new Input(input);
const T = +input.readLine();
let output = '';
for (let t = 1; t <= T; t++) {
output += `Case #${t}:${caseOutputNewline ? '\n' : ' '}${solution(input)}\n`;
}
console.log(output);
return output;
}
function solve(options, solution) {
if (!solution) {
solution = options;
options = undefined;
}
const inputFile = process.argv[2];
if (inputFile) {
// From file
fs.readFile(inputFile, 'utf8', (err, input) => {
if (err) throw err;
const output = outputSolutions(input, solution, options);
if (inputFile) {
const outputFile = inputFile.replace('.in', '.out');
fs.writeFile(outputFile, output, (err) => {
if (err) throw err;
});
}
});
}
else {
// From stdin
let input = '';
process.stdin.resume();
process.stdin.on('data', chunk => input += chunk);
process.stdin.on('end', () => outputSolutions(input, solution, options));
}
};
module.exports = {solve};