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
|
const std = @import("std");
/// Returns the sum of a slice of i32 values.
pub fn sum(values: []const i32) i64 {
var total: i64 = 0;
for (values) |v| total += v;
return total;
}
/// Returns the product of a slice of i32 values.
/// Returns 1 for an empty slice (identity element).
pub fn product(values: []const i32) i64 {
var result: i64 = 1;
for (values) |v| result *= v;
return result;
}
/// Returns the minimum value, or null for an empty slice.
pub fn min(values: []const i32) ?i32 {
if (values.len == 0) return null;
var m = values[0];
for (values[1..]) |v| {
if (v < m) m = v;
}
return m;
}
/// Returns the maximum value, or null for an empty slice.
pub fn max(values: []const i32) ?i32 {
if (values.len == 0) return null;
var m = values[0];
for (values[1..]) |v| {
if (v > m) m = v;
}
return m;
}
test "sum empty" {
try std.testing.expectEqual(@as(i64, 0), sum(&.{}));
}
test "sum positive values" {
try std.testing.expectEqual(@as(i64, 15), sum(&.{ 1, 2, 3, 4, 5 }));
}
test "sum with negatives" {
try std.testing.expectEqual(@as(i64, 0), sum(&.{ -3, -2, -1, 0, 1, 2, 3 }));
}
test "product empty" {
try std.testing.expectEqual(@as(i64, 1), product(&.{}));
}
test "product small" {
try std.testing.expectEqual(@as(i64, 120), product(&.{ 1, 2, 3, 4, 5 }));
}
test "min and max" {
const data = [_]i32{ 3, 1, 4, 1, 5, 9, 2, 6 };
try std.testing.expectEqual(@as(?i32, 1), min(&data));
try std.testing.expectEqual(@as(?i32, 9), max(&data));
}
test "min max empty" {
try std.testing.expectEqual(@as(?i32, null), min(&.{}));
try std.testing.expectEqual(@as(?i32, null), max(&.{}));
}
|