-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
128 lines (100 loc) · 3.18 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import { strictEqual } from 'assert';
import { readFileToArray } from '../utils';
class Screen {
w: number
h: number
pixels: string[][]
instructions: string[]
constructor(instructions: string[], w = 50, h = 6) {
this.instructions = instructions;
this.w = w;
this.h = h;
this.pixels = [];
for (let y = 0; y < this.h; y += 1) {
this.pixels[y] = (new Array(this.w)).fill('.');
}
}
private run() {
this.instructions.forEach((line) => {
const rectMatches = line.match(/^rect ([0-9]+)x([0-9]+)$/);
const rotateMatches = line.match(/^rotate (?:column|row) (x|y)=([0-9]+) by ([0-9]+)$/);
if (rectMatches) {
this.addRect(Number(rectMatches[1]), Number(rectMatches[2]));
} else if (rotateMatches) {
this.rotate(rotateMatches[1], Number(rotateMatches[2]), Number(rotateMatches[3]));
}
});
}
getPixelCount() {
this.run();
return this.pixels.reduce((acc, line) => acc + line.filter((char) => char === '#').length, 0);
}
printScreen() {
this.run();
this.pixels.forEach((line) => {
console.log(line.join(''));
});
}
private getY(index: number) {
let newIndex = index + 1;
if (newIndex < 1) {
newIndex += this.h;
} else if (index > this.h) {
newIndex -= this.h;
}
return newIndex - 1;
}
private getX(index: number) {
let newIndex = index + 1;
if (newIndex < 1) {
newIndex += this.w;
} else if (index > this.w) {
newIndex -= this.w;
}
return newIndex - 1;
}
private addRect(width: number, height: number) {
// console.log('addRect', width, height);
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
this.pixels[y][x] = '#';
}
}
}
private rotate(direction: string, index: number, by: number) {
for (let b = 0; b < by; b += 1) {
const clone: string[][] = JSON.parse(JSON.stringify(this.pixels));
if (direction === 'x') {
for (let y = 0; y < this.h; y += 1) {
this.pixels[y][index] = clone[this.getY(y - 1)][index];
}
} else if (direction === 'y') {
for (let x = 0; x < this.w; x += 1) {
this.pixels[index][x] = clone[index][this.getX(x - 1)];
}
}
}
}
}
function part1(data: string[]): number {
return (new Screen(data)).getPixelCount();
}
function part2(data: string[]) {
(new Screen(data)).printScreen();
}
try {
readFileToArray('./8/input.txt').then((data) => {
const testData = [
'rect 3x2',
'rotate column x=1 by 1',
'rotate row y=0 by 4',
'rotate column x=1 by 1',
];
strictEqual((new Screen(testData, 7, 3)).getPixelCount(), 6);
console.log('Part 1', part1(data));
console.log('Part 2');
part2(data);
});
} catch (err) {
console.log(err);
}