mull_it_over.adb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
  2. with GNAT.Regpat; use GNAT.Regpat;
  3. with Ada.Text_IO; use Ada.Text_IO;
  4. with Ada.Strings.Fixed; use Ada.Strings.Fixed;
  5. -- This code reads its input from standard input
  6. -- Use cat _input.txt | Mull_It_Over_ to get the result
  7. procedure Mull_It_Over is
  8. subtype Operand is Positive;
  9. -- Use pattern to match mul operations
  10. Mul_Pattern : constant Pattern_Matcher :=
  11. Compile ("mul\(([0-9]+),([0-9]+)\)");
  12. Sum : Natural := 0;
  13. begin
  14. while not End_Of_File loop
  15. declare
  16. Line : constant String := Get_Line;
  17. Remaining : String := Line;
  18. Matches : Match_Array (0 .. Paren_Count (Mul_Pattern));
  19. begin
  20. Match (Mul_Pattern, Remaining, Matches);
  21. -- Iterate on all match of the line
  22. while Matches (0) /= No_Match loop
  23. declare
  24. Operand_1 : Operand;
  25. Operand_2 : Operand;
  26. Last : Positive;
  27. begin
  28. Get
  29. (Remaining (Matches (1).First .. Matches (1).Last), Operand_1,
  30. Last);
  31. Get
  32. (Remaining (Matches (2).First .. Matches (2).Last), Operand_2,
  33. Last);
  34. Sum := Sum + Operand_1 * Operand_2;
  35. end;
  36. -- Copy without last parenthesis
  37. Move
  38. (Remaining (Matches (2).Last + 2 .. Remaining'Last), Remaining);
  39. Match (Mul_Pattern, Remaining, Matches);
  40. end loop;
  41. end;
  42. end loop;
  43. Put_Line ("The sum is " & Sum'Image);
  44. end Mull_It_Over;