#How can I get the maximum value in an ArrayList of integers (i32)?
1 messages · Page 1 of 1 (latest)
There may be a convenience method, but I use https://ziglang.org/documentation/master/std/#root;sort.sort
So you use it like this:
// (May not actually be descending order, 50/50 odds
fn sortDescending(context: void, a: u16, b: u16) bool {
_ = context;
return a > b;
}
...
pub fn main() !void {
...
std.sort.sort(u16, some_arraylist.items, {}, sortFn);
const max = some_arraylist.items[0];
...
}
Off to bed but hopefully that helps!
ooh nice. i did it in a super dumb way that also worked but this is much nicer, thanks 😄
sorting the array is a bit much if you are just interested in the maximum value
I don't think there is a convenience function in the ArrayList type itself, but it's easy enough to write one yourself like so:
pub inline fn max(items: anytype) switch (@typeInfo(@TypeOf(items))) {
.Array => |arr| arr.child,
.Pointer => |ptr| ptr.child,
else => @compileError("max: Unsupported type: " ++ @typeName(@TypeOf(items))),
}
{
const T = @TypeOf(items[0]);
const type_info = @typeInfo(T);
comptime assert(type_info == .Int or type_info == .ComptimeInt);
var m: T = std.math.minInt(T);
for (items) |item| {
if (item > m) m = item;
}
return m;
}
this would work on integer arrays and slices, so if you want to get the maximum value of an ArrayList, you would have to pass array_list.items
not sure if it was already mentioned, but there also std.mem.max/min
const max = std.mem.max(u16, array_list.items)
cool, that's good to know
sorting is definitely not the way to go, that's O(n log n) whereas std.mem.min is O(n)