97 lines
2.3 KiB
TypeScript
97 lines
2.3 KiB
TypeScript
import 'mocha';
|
|
import assert from 'assert';
|
|
import { readFileSync } from 'fs';
|
|
|
|
|
|
let input = readFileSync('./input/2020-day-06.txt', 'utf-8')
|
|
let example: string =
|
|
`abc
|
|
|
|
a
|
|
b
|
|
c
|
|
|
|
ab
|
|
ac
|
|
|
|
a
|
|
a
|
|
a
|
|
a
|
|
|
|
b
|
|
`;
|
|
let tasksResults: any[] = ['N/A', 'N/A'];
|
|
|
|
describe('Day 04', () => {
|
|
before(() => {
|
|
})
|
|
describe('task01', () => {
|
|
it('Calculate', () => {
|
|
assert.strictEqual(task01(example), 11);
|
|
tasksResults[0] = task01(input);;
|
|
})
|
|
});
|
|
describe('test02', () => {
|
|
it('Calculate', () => {
|
|
assert.strictEqual(task02(example), 6);
|
|
tasksResults[1] = task02(input);
|
|
});
|
|
});
|
|
after(() => {
|
|
console.log('\ntask 01:', tasksResults[0]);
|
|
console.log('\ntask 02:', tasksResults[1]);
|
|
});
|
|
});
|
|
|
|
type Group = {ppl: number; results: any};
|
|
function task01(input: string): number {
|
|
let groups = parseData(input);
|
|
let data = reduce(groups, (g: Group, k: string) => !!g.results[k]);
|
|
let counts: any[] = count(data);
|
|
return sum(counts);
|
|
}
|
|
|
|
function task02(input: string) {
|
|
let groups: Group[] = parseData(input);
|
|
let data = reduce(groups, (g: Group, k: string) => {
|
|
return g.results[k] === g.ppl
|
|
});
|
|
let counts: any[] = count(data);
|
|
return sum(counts);
|
|
}
|
|
|
|
function parseData(input: string): any[] {
|
|
let groups: Group[] = [];
|
|
let results: any = {};
|
|
let ppl: number = 0;
|
|
input.split('\n').forEach((line: string) => {
|
|
if (!line.length) {
|
|
groups.push({ results, ppl});
|
|
ppl = 0;
|
|
results = {};
|
|
return;
|
|
}
|
|
ppl++;
|
|
line.split('').forEach(i => {
|
|
results[i] = results.hasOwnProperty(i)
|
|
? results[i] + 1
|
|
: 1;
|
|
});
|
|
});
|
|
|
|
return groups;
|
|
}
|
|
|
|
const reduce = (data: Group[], predicate: (group: any, key: string) => boolean): boolean[] => {
|
|
return data.map((group: Group) => {
|
|
let results: any = {};
|
|
Object.keys(group.results).forEach((key: string) => {
|
|
results[key] = predicate(group, key);
|
|
});
|
|
return (results);
|
|
});
|
|
};
|
|
const count = (a: any[]) => a.map((i: any) => Object.keys(i).filter((x: string) => !!i[x]).length);
|
|
const sum = (a: number[]) => a.reduce((t: number, i: number) => t += i, 0);
|