Skip to content

Commit 855e909

Browse files
committed
Add javaScript solution to Beginner-POPGATES
1 parent ba95fde commit 855e909

File tree

1 file changed

+50
-0
lines changed
  • Beginner/At the Gates (POPGATES)

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//initalise testCase#s - t from process input.
2+
// Test case engine clearly uses old NodeJS stdin stream mode.
3+
// Assume from js solutions to other tasks: Stdin is initially paused. must call .resume() to resume stream.
4+
// process.stdin.resume();
5+
// process.stdin.setEncoding("utf8");
6+
// Assume: readline is supported
7+
const rl = require('readline').createInterface({
8+
input: process.stdin,
9+
output: process.stdout
10+
});
11+
// t # of test cases: number , n array containing number of coins in test case, k array containing number of ops
12+
// coins array of arrays containing coin states for each testcase.
13+
let t, nArr = [], kArr = [], coinStatesArr = [];
14+
// assign variables
15+
const variable = {
16+
lineCount : 1,
17+
getVars(input) {
18+
if (this.lineCount === 1) {t = parseInt(input); // initialise t once.
19+
} else if(this.lineCount % 3 === 0) {
20+
let line = input.split(' ')
21+
coinStatesArr[this.lineCount / 3 - 1] = line.map(coin => coin === 'H' ? true : false); //remap coin values => H = true, T = false or easier flipping
22+
} else if (this.lineCount % 2 === 0) {
23+
let line = input.split(' ');
24+
nArr[this.lineCount / 2 - 1] = line[0]
25+
kArr[this.lineCount / 2 - 1] = line[1]
26+
}
27+
this.lineCount ++
28+
}
29+
};
30+
// assume: synchronous process.stdin
31+
rl.on('line', variable.getVars)
32+
rl.resume()
33+
// Get variables in order.
34+
35+
let nHeads
36+
for (let i = 0; i<t; i++) {
37+
coinStates = coinStatesArr[i]
38+
n = nArr[i] - 1 // -1 to align to 0 start index.
39+
k = kArr[i]
40+
for (let j = 0; j<k; j++) {
41+
// if last value of coinStates === true, remove last value & flip all coin states.
42+
if (coinsStates[n]) {
43+
coinStates.pop(); // remove last value of coinstates
44+
coinsStates.map(coinState => coinState ? false : true); // flip coin states true <=> false.
45+
} else coinstates.pop();
46+
}
47+
nHeads = 0; //reinitialise nheads after each loop
48+
coinstates.forEach(state => state ? nHeads ++ : null);
49+
console.log(nHeads); //output nHeads
50+
}

0 commit comments

Comments
 (0)