-
Notifications
You must be signed in to change notification settings - Fork 0
/
Task1TS.ts
71 lines (71 loc) · 2.06 KB
/
Task1TS.ts
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
// Gets the input file's contents
function getInput(): string {
const fs = require("fs");
var inputContent = fs.readFileSync(
".\\Task 2. Input (1).txt",
"utf-8",
(err) => {
if (err) {
throw err;
}
}
);
return inputContent; // returns input file contents
}
// Checks if the character is upperCase
function isUpperCase(char: string): boolean {
return char === char.toUpperCase();
}
// Subtracts the unwanted pair of characters
function removeByIndex(str: string, index: number): string {
if (index === 0) {
return str.slice(2);
} else {
return str.substring(0, index) + str.substring(index + 2, str.length);
}
}
// Finds how many units of polymer remain after reaction
function findUnits() {
try {
var input: string = getInput();
var count = 0; // count how many reactions occured
for (let index = 0; index < input.length; index++) {
// if reaction occurs at index 0 or 1, the index will be negative
if (index < 0 && input.length > 0) {
index = 0;
}
// Check if it's the last index.
if (index === input.length - 1) {
break;
} else {
// Adjacent characters
const first = input[index];
const second = input[index + 1];
// Check if characters match
if (first.toLowerCase() === second.toLowerCase()) {
// Check character polarity
const UpperFirst = isUpperCase(first);
const UpperSecond = isUpperCase(second);
// If only one of them are uppercase, reaction occurs
if (
(UpperFirst && UpperSecond === false) ||
(UpperFirst === false && UpperSecond)
) {
input = removeByIndex(input, index);
count++;
index = index - 2; // set loop to -2 positions from the beginning to find newly formed polarities
}
}
}
}
console.log(
"Polarity units remaining:",
input.length,
"\nNumber of reactions occured: ",
count
);
} catch (error) {
console.log(error);
}
}
findUnits();