-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08.ts
91 lines (80 loc) · 2.34 KB
/
08.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
import {loadData} from '../shared/utils';
/*
https://adventofcode.com/2019/day/7
*/
export const part1 = (image: Array<Array<Array<number>>>): number => {
let leastEmptyPixelsCount = Infinity;
let leastEmptyPixelsIndex = -1;
image.forEach((layer, index) => {
let emptyPixels = countPixels(layer, 0);
if (emptyPixels < leastEmptyPixelsCount) {
leastEmptyPixelsCount = emptyPixels;
leastEmptyPixelsIndex = index;
}
});
return (
countPixels(image[leastEmptyPixelsIndex]!, 1) *
countPixels(image[leastEmptyPixelsIndex]!, 2)
);
};
export const part2 = (image: Array<Array<Array<number>>>): string => {
const flat = flattenImage(image);
return flat.map(row => row.map(p => (p ? 'X' : ' ')).join('')).join('\n');
};
const countPixels = (layer: Array<Array<number>>, pixel: number): number => {
return layer.reduce((count, row) => {
return row.filter(p => p === pixel).length + count;
}, 0);
};
export const flattenImage = (
image: Array<Array<Array<number>>>
): Array<Array<number>> => {
const height = image[0]!.length;
const width = image[0]![0]!.length;
const flattened: Array<Array<number>> = [];
for (let y = 0; y < height; y += 1) {
const row: Array<number> = [];
for (let x = 0; x < width; x += 1) {
let pixel = 2;
for (let l = 0; l < image.length; l += 1) {
pixel = image[l]![y]![x]!;
if (pixel !== 2) {
break;
}
}
row.push(pixel);
}
flattened.push(row);
}
return flattened;
};
export const parseImageString = (
data: string,
width: number,
height: number
): Array<Array<Array<number>>> => {
const pixels = data.split('').map(p => parseInt(p, 10));
const numLayers = pixels.length / (width * height);
const image: Array<Array<Array<number>>> = [];
for (let l = 0; l < numLayers; l += 1) {
const layer = [];
const layerPixels = pixels.slice(
l * (width * height),
(l + 1) * (width * height)
);
for (let y = 0; y < height; y += 1) {
layer.push(layerPixels.slice(y * width, (y + 1) * width));
}
image.push(layer);
}
return image;
};
/**
* Parse the puzzle input file ready for processing
*/
/* istanbul ignore next */
export const parse = async (
width: number,
height: number
): Promise<Array<Array<Array<number>>>> =>
parseImageString(await loadData(2019, 8), width, height);