005_arrays2.zig 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // Zig has some fun array operators.
  3. //
  4. // You can use '++' to concatenate two arrays:
  5. //
  6. // const a = [_]u8{ 1,2 };
  7. // const b = [_]u8{ 3,4 };
  8. // const c = a ++ b ++ [_]u8{ 5 }; // equals 1 2 3 4 5
  9. //
  10. // You can use '**' to repeat an array:
  11. //
  12. // const d = [_]u8{ 1,2,3 } ** 2; // equals 1 2 3 1 2 3
  13. //
  14. // Note that both '++' and '**' only operate on arrays while your
  15. // program is _being compiled_. This special time is known in Zig
  16. // parlance as "comptime" and we'll learn plenty more about that
  17. // later.
  18. //
  19. const std = @import("std");
  20. pub fn main() void {
  21. const le = [_]u8{ 1, 3 };
  22. const et = [_]u8{ 3, 7 };
  23. // (Problem 1)
  24. // Please set this array concatenating the two arrays above.
  25. // It should result in: 1 3 3 7
  26. const leet = ???;
  27. // (Problem 2)
  28. // Please set this array using repetition.
  29. // It should result in: 1 0 0 1 1 0 0 1 1 0 0 1
  30. const bit_pattern = [_]u8{ ??? } ** 3;
  31. // Okay, that's all of the problems. Let's see the results.
  32. //
  33. // We could print these arrays with leet[0], leet[1],...but let's
  34. // have a little preview of Zig 'for' loops instead:
  35. //
  36. // for (<item array>) |item| { <do something with item> }
  37. //
  38. // Don't worry, we'll cover looping properly in upcoming
  39. // lessons.
  40. //
  41. std.debug.print("LEET: ", .{});
  42. for (leet) |n| {
  43. std.debug.print("{}", .{n});
  44. }
  45. std.debug.print(", Bits: ", .{});
  46. for (bit_pattern) |n| {
  47. std.debug.print("{}", .{n});
  48. }
  49. std.debug.print("\n", .{});
  50. }