-
Notifications
You must be signed in to change notification settings - Fork 0
/
05.js
67 lines (50 loc) · 2.36 KB
/
05.js
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
/* eslint-disable no-continue */
/* eslint-disable unicorn/prevent-abbreviations */
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {readInput} from '../../../util.js';
const directoryPath = path.dirname(fileURLToPath(import.meta.url));
const fileContent = await readInput(directoryPath);
const [stacks, rearrangements] = fileContent
.split('\n\n')
.map(part => part.split('\n').filter(line => line !== ''));
const arrangedStacks = {};
stacks.reverse();
for (const stack of stacks.slice(1)) {
for (let counter = 1, i = 1; i < stack.length; i += 4, counter++) {
if (stack[i] === ' ') continue;
// Create array if not set already
if (arrangedStacks[counter] === undefined) arrangedStacks[counter] = [];
arrangedStacks[counter].push(stack[i]);
}
}
for (const rearrangement of rearrangements) {
const amount = Number(rearrangement.split('move ')[1].split(' ')[0]);
const from = rearrangement.split('from ')[1].split(' ')[0];
const to = rearrangement.split('to ')[1].split(' ')[0];
for (let i = 0; i < amount; i++) {
const element = arrangedStacks[from].pop();
arrangedStacks[to].push(element);
}
}
const rearrangedTopCrates = Object.values(arrangedStacks).map(stack => stack.at(-1)).join('');
console.log('Rearranged top crates:', rearrangedTopCrates);
const multipleArrangedStacks = {};
for (const stack of stacks.slice(1)) {
for (let counter = 1, i = 1; i < stack.length; i += 4, counter++) {
if (stack[i] === ' ') continue;
// Create array if not set already
if (multipleArrangedStacks[counter] === undefined) multipleArrangedStacks[counter] = [];
multipleArrangedStacks[counter].push(stack[i]);
}
}
for (const rearrangement of rearrangements) {
const amount = Number(rearrangement.split('move ')[1].split(' ')[0]);
const from = rearrangement.split('from ')[1].split(' ')[0];
const to = rearrangement.split('to ')[1].split(' ')[0];
const movingElements = multipleArrangedStacks[from].slice(multipleArrangedStacks[from].length - amount, multipleArrangedStacks[from].length);
multipleArrangedStacks[to].push(...movingElements);
multipleArrangedStacks[from].splice(multipleArrangedStacks[from].length - amount, multipleArrangedStacks[from].length);
}
const multipleRearrangedTopCrates = Object.values(multipleArrangedStacks).map(stack => stack.at(-1)).join('');
console.log('Multiple rearranged top crates:', multipleRearrangedTopCrates);