-
Notifications
You must be signed in to change notification settings - Fork 0
/
One.re
68 lines (52 loc) · 1.8 KB
/
One.re
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
68
module IntSet = Set.Make(Int32);
type operation = char;
type amount = Int32.t;
type frequencyChange = (operation, amount);
exception UnknownOperation(string);
let inputLines = () =>
Node.Fs.readFileAsUtf8Sync("resources/one.txt")
|> Js.String.split("\n")
|> Array.to_list;
let lineToOperation = (line: string): operation => line.[0];
let lineToAmount = (line: string): Int32.t => {
let rangeEnd = String.length(line);
String.sub(line, 1, rangeEnd - 1) |> Int32.of_string;
};
let lineToFrequencyChange = (line: string): frequencyChange => (
lineToOperation(line),
lineToAmount(line),
);
let applyFrequencyChange = (total: Int32.t, change: frequencyChange): Int32.t =>
switch (change) {
| ('+', amount) => Int32.add(total, amount)
| ('-', amount) => Int32.sub(total, amount)
| (operation, _) =>
raise(
UnknownOperation("unknown operation: " ++ String.make(1, operation)),
)
};
let circularStream = (l: list('a)): Stream.t('a) => {
let length = List.length(l);
Stream.from(i => Some(List.nth(l, i mod length)));
};
let findFirstRepeatFrequency = l => {
let changes = circularStream(l);
let knownFrequencies = ref(IntSet.empty);
let frequency = ref(Int32.zero);
let break = ref(false);
while (! break^) {
frequency := applyFrequencyChange(frequency^, Stream.next(changes));
if (IntSet.mem(frequency^, knownFrequencies^)) {
break := true;
} else {
knownFrequencies := IntSet.add(frequency^, knownFrequencies^);
};
};
frequency^;
};
let processChanges = (changes: list('frequencyChange)) =>
List.fold_left(applyFrequencyChange, Int32.zero, changes);
let firstSolution = () =>
inputLines() |> List.map(lineToFrequencyChange) |> processChanges;
let secondSolution = () =>
inputLines() |> List.map(lineToFrequencyChange) |> findFirstRepeatFrequency;