-
Notifications
You must be signed in to change notification settings - Fork 0
/
day05.chpl
68 lines (52 loc) · 1.71 KB
/
day05.chpl
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
/*
day05
usage:
chpl day04-solution1.chpl
./day04-solution1 < input04a.txt
See associated blog post at
https://chapel-lang.org/blog/posts/aoc2022-day04-ranges/.
*/
use IO, List;
param charsPerStack = 4; // number of characters per stack in input
// read and yield lines until we get to the blank one
iter readInitState() {
var line: string;
while (readLine(line) && line.size > 1) do
yield line;
}
// Procedure that initializes the crate stacks from the input.
proc initStacks() {
// array of strings with initial crate stack configuration
const initState = readInitState();
// use the last line (with all the stack numbers) to compute the # of stacks
var numStacks = initState.last.size / charsPerStack;
// Represent our stacks with an array of lists of strings
var crateStacks : [1..numStacks] list(string);
// iterate over the lines representing crates backwards (bottom up),
// skipping over the line with the stack numbers
for i in 0..<initState.size-1 by -1 {
// do a zippered iteration over the stack IDs and
// offsets where crate names will be
for (s,off) in zip(1..numStacks, 1.. by charsPerStack) {
const char = initState[i][off];
if (char != " ") { // blank means no crate here
crateStacks[s].append(char);
}
}
}
return crateStacks;
}
var crateStacks = initStacks();
writeln(crateStacks);
// read in and execute all of the move operations
var num, from, to : int;
while readf("move %i from %i to %i\n", num, from, to) {
for count in 1..num {
crateStacks[to].append(crateStacks[from].pop());
}
}
var topOfStacks : string;
for stack in crateStacks {
topOfStacks += stack.pop();
}
writeln("topOfStacks = ", topOfStacks);