-
Notifications
You must be signed in to change notification settings - Fork 1
/
day-06.ts
66 lines (59 loc) · 2.16 KB
/
day-06.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
interface ISpaceObject {
source: string;
orbit: string;
}
interface ISpaceObjectTreeNode {
level: number;
object: string;
}
export const getOrbitalTransfers = (path1: string[], path2: string[]) => {
const firstMatchingOrbit = path1.find((orbit) => path2.includes(orbit));
if (!firstMatchingOrbit) {
return Infinity;
}
const index1 = path1.findIndex((orbit) => orbit === firstMatchingOrbit);
const index2 = path2.findIndex((orbit) => orbit === firstMatchingOrbit);
return index1 + index2;
};
export const getOrbitPath = (spaceObjects: ISpaceObject[], orbit: string) => {
const orbitPath: string[] = [];
let sourceForOrbit: string | undefined = orbit;
while (sourceForOrbit !== 'COM') {
sourceForOrbit = getSourceForOrbit(spaceObjects, sourceForOrbit);
if (!sourceForOrbit) {
return;
}
orbitPath.push(sourceForOrbit);
}
return orbitPath;
};
export const getNumberOfOrbits = (orbits: string[]): number => {
const spaceObjects = transformList(orbits);
const spaceObjectQueue = [];
const origin = spaceObjects.find((spaceObject) => spaceObject.source === 'COM') as ISpaceObject;
spaceObjectQueue.push({ level: 1, object: origin.orbit });
let orbitCount = 1;
while (spaceObjectQueue.length) {
const nextSpaceObjectFromQueue = spaceObjectQueue.shift() as ISpaceObjectTreeNode;
const orbitsForSource = getOrbitsForSource(spaceObjects, nextSpaceObjectFromQueue.object).map((orbit) => {
orbitCount += nextSpaceObjectFromQueue.level + 1;
return { level: nextSpaceObjectFromQueue.level + 1, object: orbit };
});
spaceObjectQueue.push(...orbitsForSource);
}
return orbitCount;
};
export const transformList = (orbitList: string[]): ISpaceObject[] => {
return orbitList.map((orbitMapping) => {
const [source, orbit] = orbitMapping.split(')');
return { source, orbit };
});
};
export const getOrbitsForSource = (spaceObjects: ISpaceObject[], source: string) => {
return spaceObjects.filter((spaceObject) => {
return spaceObject.source === source;
}).map((spaceObject) => spaceObject.orbit);
};
export const getSourceForOrbit = (spaceObjects: ISpaceObject[], orbit: string) => {
return spaceObjects.find((spaceObject) => spaceObject.orbit === orbit)?.source;
};