| ... | @@ -3527,21 +3527,33 @@ test "max" { | ... | @@ -3527,21 +3527,33 @@ test "max" { |
| 3527 | /// Finds the smallest and largest number in a slice. O(n). | 3527 | /// Finds the smallest and largest number in a slice. O(n). |
| 3528 | /// Returns an anonymous struct with the fields `min` and `max`. | 3528 | /// Returns an anonymous struct with the fields `min` and `max`. |
| 3529 | /// `slice` must not be empty. | 3529 | /// `slice` must not be empty. |
| 3530 | pub fn minMax(comptime T: type, slice: []const T) struct { min: T, max: T } { | 3530 | pub fn minMax(comptime T: type, slice: []const T) struct { T, T } { |
| 3531 | assert(slice.len > 0); | 3531 | assert(slice.len > 0); |
| 3532 | var minVal = slice[0]; | 3532 | var running_minimum = slice[0]; |
| 3533 | var maxVal = slice[0]; | 3533 | var running_maximum = slice[0]; |
| 3534 | for (slice[1..]) |item| { | 3534 | for (slice[1..]) |item| { |
| 3535 | minVal = @min(minVal, item); | 3535 | running_minimum = @min(running_minimum, item); |
| 3536 | maxVal = @max(maxVal, item); | 3536 | running_maximum = @max(running_maximum, item); |
| 3537 | } | 3537 | } |
| 3538 | return .{ .min = minVal, .max = maxVal }; | 3538 | return .{ running_minimum, running_maximum }; |
| 3539 | } | 3539 | } |
| 3540 | | 3540 | |
| 3541 | test "minMax" { | 3541 | test minMax { |
| 3542 | try testing.expectEqual(minMax(u8, "abcdefg"), .{ .min = 'a', .max = 'g' }); | 3542 | { |
| 3543 | try testing.expectEqual(minMax(u8, "bcdefga"), .{ .min = 'a', .max = 'g' }); | 3543 | const actual_min, const actual_max = minMax(u8, "abcdefg"); |
| 3544 | try testing.expectEqual(minMax(u8, "a"), .{ .min = 'a', .max = 'a' }); | 3544 | try testing.expectEqual(@as(u8, 'a'), actual_min); |
| | 3545 | try testing.expectEqual(@as(u8, 'g'), actual_max); |
| | 3546 | } |
| | 3547 | { |
| | 3548 | const actual_min, const actual_max = minMax(u8, "bcdefga"); |
| | 3549 | try testing.expectEqual(@as(u8, 'a'), actual_min); |
| | 3550 | try testing.expectEqual(@as(u8, 'g'), actual_max); |
| | 3551 | } |
| | 3552 | { |
| | 3553 | const actual_min, const actual_max = minMax(u8, "a"); |
| | 3554 | try testing.expectEqual(@as(u8, 'a'), actual_min); |
| | 3555 | try testing.expectEqual(@as(u8, 'a'), actual_max); |
| | 3556 | } |
| 3545 | } | 3557 | } |
| 3546 | | 3558 | |
| 3547 | /// Returns the index of the smallest number in a slice. O(n). | 3559 | /// Returns the index of the smallest number in a slice. O(n). |