#How can I get the maximum value in an ArrayList of integers (i32)?

1 messages · Page 1 of 1 (latest)

indigo harbor
#

Very very new to Zig, trying some stuff out.
Do I have to do this manually by looping through the ArrayList or is there a convenient std function to retrieve the maximum numerical value out of an ArrayList (or array in general)?

dark sundial
#

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!

lucid spruce
#

btw you can just do std.sort.desc(i32) :)

#

instead of implementing sortDescending

indigo harbor
#

ooh nice. i did it in a super dumb way that also worked but this is much nicer, thanks 😄

stoic pumice
#

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

elfin plume
#

not sure if it was already mentioned, but there also std.mem.max/min

#

const max = std.mem.max(u16, array_list.items)

stoic pumice
#

cool, that's good to know

brisk tree
#

sorting is definitely not the way to go, that's O(n log n) whereas std.mem.min is O(n)