Last active
January 1, 2025 23:19
-
-
Save steinelu/2f0e88a22a4f701bf64d2fef22d6cc95 to your computer and use it in GitHub Desktop.
zig argsort example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const std = @import("std"); | |
| const builtin = @import("builtin"); | |
| pub fn main() !void { | |
| const n = 20; | |
| var idx : [n]u8 = undefined; | |
| for (&idx, 0..) |*id, i| { | |
| id.* = @intCast(i); | |
| } | |
| var prng = std.rand.DefaultPrng.init(0); | |
| const rand = prng.random(); | |
| var vals : [n]u8 = undefined; | |
| for (&vals) |*val| { | |
| val.* = rand.intRangeAtMost(u8, 0, 10); | |
| } | |
| const Thingy = struct { | |
| fn argcomp (context: []u8, a:u8, b:u8) bool { | |
| const one = context[a]; | |
| const two = context[b]; | |
| return one < two; | |
| } | |
| }; | |
| const slice: []u8 = @as([]u8, &vals)[0..vals.len]; | |
| std.mem.sort(u8, &idx, slice, Thingy.argcomp); | |
| std.debug.print("{any}\n", .{vals}); | |
| for (idx) |i| { | |
| std.debug.print("{}\t -> {}\n", .{i, slice[i]}); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment