Files
ziglings/exercises/005_arrays2.zig
T
it3x 98b831aec4 Refresh 005_arrays2 exercise
Updated the exercise to use SIMD. This allows us to
cross-reference the concept from 112_vectors back to 005_arrays2,
introducing a handy feature of vectors early on.

See #430
2026-06-29 18:48:05 +02:00

70 lines
1.8 KiB
Zig

//
// Zig has one array operator.
//
// You can use '++' to concatenate two arrays:
//
// const a = [_]u8{ 1,2 };
// const b = [_]u8{ 3,4 };
// const c = a ++ b ++ [_]u8{ 5 }; // equals 1 2 3 4 5
//
// Note that '++' only operates on arrays while your program is
// _being compiled_. This special time is known in Zig
// parlance as "comptime" and we'll learn plenty more about that
// later.
//
const std = @import("std");
pub fn main() void {
const le = [_]u8{ 1, 3 };
const et = [_]u8{ 3, 7 };
// (Problem 1)
// Please set this array concatenating the two arrays above.
// It should result in: 1 3 3 7
const leet = ???;
// (Problem 2)
// Please set this array using repetition.
// It should result in: 1 0 0 1 1 0 0 1 1 0 0 1
const bit_pattern_unit = ???;
// How long should the bit pattern be?
const len = ???;
// For now, don't worry about the use of SIMD.
const bit_pattern: [len]u8 = std.simd.repeat(len, bit_pattern_unit);
// Okay, that's all of the problems. Let's see the results.
//
// We could print these arrays with leet[0], leet[1],...but let's
// have a little preview of Zig 'for' loops instead:
//
// for (<item array>) |item| { <do something with item> }
//
// Don't worry, we'll cover looping properly in upcoming
// lessons.
//
std.debug.print("LEET: ", .{});
for (leet) |n| {
std.debug.print("{}", .{n});
}
std.debug.print(", Bits: ", .{});
for (bit_pattern) |n| {
std.debug.print("{}", .{n});
}
std.debug.print("\n", .{});
}
// For the curious:
//
// The `std.simd.repeat` function takes a target length and a pattern,
// and returns a vector filled with that pattern repeated to the
// desired length.
//
// For example, `repeat(5, [_]u8{1, 2})` will return a vector
// equivalent to `.{1, 2, 1, 2, 1}`.