049_quiz6.zig 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. pub fn getTrunk(self: *Elephant) *Elephant{
  25. return self.trunk.?; // Remember, this means "orelse unreachable"
  26. }
  27. pub fn hasTrunk(self: *Elephant) bool{
  28. return (self.trunk != null);
  29. }
  30. // ---------------------------------------------------
  31. pub fn visit(self: *Elephant) void{
  32. self.visited = true;
  33. }
  34. pub fn print(self: *Elephant) void{
  35. // Prints elephant letter and [v]isited
  36. const v: u8 = if(self.visited) 'v' else ' ';
  37. std.debug.print("{u}{u} ", .{ self.letter, v });
  38. }
  39. };
  40. pub fn main() void{
  41. var elephantA = Elephant{ .letter = 'A' };
  42. var elephantB = Elephant{ .letter = 'B' };
  43. var elephantC = Elephant{ .letter = 'C' };
  44. // We link the elephants so that each tail "points" to the next.
  45. elephantA.tail = &elephantB;
  46. elephantB.tail = &elephantC;
  47. // And link the elephants so that each trunk "points" to the previous.
  48. elephantB.trunk = &elephantA;
  49. elephantC.trunk = &elephantB;
  50. visitElephants(&elephantA);
  51. std.debug.print("\n", .{});
  52. }
  53. // This function visits all elephants twice, tails to trunks.
  54. fn visitElephants(first_elephant: *Elephant) void{
  55. var e = first_elephant;
  56. // We follow the tails!
  57. while(true){
  58. e.print();
  59. e.visit();
  60. // This gets the next elephant or stops.
  61. if(e.hasTail()){
  62. e = e.getTail();
  63. }else{
  64. break;
  65. }
  66. }
  67. // We follow the trunks!
  68. while(true){
  69. e.print();
  70. // This gets the previous elephant or stops.
  71. if(e.hasTrunk()){
  72. e = e.getTrunk();
  73. }else{
  74. break;
  75. }
  76. }
  77. }