049_quiz6.zig 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // "Trunks and tails
  3. // Are handy things"
  4. // from Holding Hands
  5. // by Lenore M. Link
  6. //
  7. // Now that we have tails all figured out, can you implement trunks?
  8. //
  9. const std = @import("std");
  10. const Elephant = struct {
  11. letter: u8,
  12. tail: ?*Elephant = null,
  13. trunk: ?*Elephant = null,
  14. visited: bool = false,
  15. // Elephant tail methods!
  16. pub fn getTail(self: *Elephant) *Elephant {
  17. return self.tail.?; // Remember, this means "orelse unreachable"
  18. }
  19. pub fn hasTail(self: *Elephant) bool {
  20. return (self.tail != null);
  21. }
  22. // Your Elephant trunk methods go here!
  23. // ---------------------------------------------------
  24. ???
  25. // ---------------------------------------------------
  26. pub fn visit(self: *Elephant) void {
  27. self.visited = true;
  28. }
  29. pub fn print(self: *Elephant) void {
  30. // Prints elephant letter and [v]isited
  31. const v: u8 = if (self.visited) 'v' else ' ';
  32. std.debug.print("{u}{u} ", .{ self.letter, v });
  33. }
  34. };
  35. pub fn main() void {
  36. var elephantA = Elephant{ .letter = 'A' };
  37. var elephantB = Elephant{ .letter = 'B' };
  38. var elephantC = Elephant{ .letter = 'C' };
  39. // We link the elephants so that each tail "points" to the next.
  40. elephantA.tail = &elephantB;
  41. elephantB.tail = &elephantC;
  42. // And link the elephants so that each trunk "points" to the previous.
  43. elephantB.trunk = &elephantA;
  44. elephantC.trunk = &elephantB;
  45. visitElephants(&elephantA);
  46. std.debug.print("\n", .{});
  47. }
  48. // This function visits all elephants twice, tails to trunks.
  49. fn visitElephants(first_elephant: *Elephant) void {
  50. var e = first_elephant;
  51. // We follow the tails!
  52. while (true) {
  53. e.print();
  54. e.visit();
  55. // This gets the next elephant or stops.
  56. if (e.hasTail()) {
  57. e = e.getTail();
  58. } else {
  59. break;
  60. }
  61. }
  62. // We follow the trunks!
  63. while (true) {
  64. e.print();
  65. // This gets the previous elephant or stops.
  66. if (e.hasTrunk()) {
  67. e = e.getTrunk();
  68. } else {
  69. break;
  70. }
  71. }
  72. }