Card 1 / 11
Compute prefix sums: each element of the result is the sum of all input elements up to that point. The caller owns the returned slice and must free it with allocator.free(result).
items |
result |
|---|---|
[1, 2, 3, 4] |
[1, 3, 6, 10] |
[5] |
[5] |
[] |
[] |
The result always contains exactly items.len elements, so allocate that slice directly with allocator.alloc(i32, items.len).
Iterate over the input and output together with for (items, result) |item, *output|. Update the running sum, then store it through output.*.
/// Return prefix sums of the input slice
fn prefixSums(
allocator: std.mem.Allocator,
items: []const i32,
) std.mem.Allocator.Error![]i32 {
const result = try allocator.alloc(i32, items.len);
var running: i32 = 0;
for (items, result) |item, *output| {
running += item;
output.* = running;
}
return result;
}Card 2 / 11
Return a newly allocated slice containing only the even numbers from items.
items |
result |
|---|---|
[1, 2, 3, 4, 5, 6] |
[2, 4, 6] |
[1, 3, 5] |
[] |
[] |
[] |