-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.ts
40 lines (32 loc) · 960 Bytes
/
common.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
import * as fs from 'fs';
export interface Coords {
row: number;
col: number;
}
export interface MatrixEntry<T> extends Coords {
value: T;
}
export function readString(name: string): string {
return fs.readFileSync(name, { encoding: 'utf8' });
}
export function readLines(name: string): Array<string> {
return readString(name).split('\r\n');
}
export function parseNumbersFromLine(str: string): number[] {
return str.split(' ').filter(x => x !== '').map(x => parseInt(x));
}
export function getMatrixEntries<T>(matrix: T[][]): Array<MatrixEntry<T>> {
return Object
.entries(matrix)
.flatMap(([row, x]) => Object.entries(x).map(([col, ch]) => ({
row: parseInt(row),
col: parseInt(col),
value: ch
})));
};
export function sum(numbers: Iterable<number>): number {
return [...numbers].reduce((acc, v) => acc + v, 0);
}
export function lastElement<T>(arr: ReadonlyArray<T>): T {
return arr[arr.length - 1];
}