#How can I sort arrays of variable lengths?

1 messages · Page 1 of 1 (latest)

slim flint
#

error: array literal requires address-of operator (&) to coerce to slice type '[]i64'

const levels = [_][]i64{
    [_]i64{ 87, 90, 92, 95, 96, 93 },
    [_]i64{ 12, 15, 16, 17, 17 },
    [_]i64{ 26, 27, 29, 31, 34, 36, 40 },
};

for (levels) |level| {
  ...

  var ascLevel = level;
  
  std.mem.sort(i64, &ascLevel, {}, comptime std.sort.asc(i64));
#

Sorting arrays of variable lengths

#

How can I sort arrays of variable lengths?

tepid helm
#

ascLevel[0..]

spare blaze
#

[_]i64 is an array literal, not a slice literal, so you can't put it inside an array of slices [_][]i64

#

change them to &[_]i64{ ... } (or even shorter &.{ ... }) to coerce them to slices

prisma girder
#

The next problem is that&literal creates a const temporary, which won't work in for slice to non-const i64.
The next problem is that var ascLevel = level is assigning a slice, which does not copy the underlying memory, so it's still pointing to const i64 and can't be sorted.

#

taking these in order,

const std = @import("std");
test {
    const allocator = std.testing.allocator;
    const levels = [_][]const i64{
        &[_]i64{ 87, 90, 92, 95, 96, 93 },
        &[_]i64{ 12, 15, 16, 17, 17 },
        &[_]i64{ 26, 27, 29, 31, 34, 36, 40 },
    };

    for (levels) |level| {
        const ascLevel = try allocator.dupe(i64, level);
        defer allocator.free(ascLevel);
        std.mem.sort(i64, ascLevel, {}, comptime std.sort.asc(i64));
        std.debug.print("{any}\n", .{ascLevel});
    }
}