-
Notifications
You must be signed in to change notification settings - Fork 1
/
max.hid
53 lines (48 loc) · 1.39 KB
/
max.hid
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
// Compare these two inputs. This algorithm returns early as soon as it
// finds the max value, so it is much faster if the max value is at the
// beginning of the array.
// const int[] default = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const int[] default = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
int @max(const int[] arr) {
try {
int max_val = arr[0];
for (int i = 1; i < arr.length; i += 1) {
if (arr[i] > max_val) {
max_val = arr[i];
preempt {
// There are no larger values, so return early.
return max_val;
}
}
}
// Reaching the end of the array without returning is defeat
!is_defeat();
} undo {
// First item was the max, return it
// The typechecker knows !is_defeat() is guaranteed defeat, so
// we can put the return here without it complaining.
return arr[0];
}
}
empty write_array(const int[] arr) {
write('[');
for (int i = 0; i < arr.length; i += 1) {
if (i != 0) {
write(", ");
}
write(arr[i]);
}
write(']');
}
empty @is_you(int[] nums) {
if (nums) {
write("Max value: ");
writeln(@max(nums));
} else {
write("Array: ");
write_array(default);
writeln();
write("Max value: ");
writeln(@max(default));
}
}