The Ada Program: dutch_flag.adb

  1 -- dutch_flag.adb:  sort command-line string into three colors
  2 
  3 with
  4   Ada.Command_Line,     -- Access to external execution env (Ada95 A.15)
  5   Ada.Text_IO;          -- Usual string oriented IO package
  6 use Ada;
  7 
  8 procedure Dutch_Flag is
  9 
 10    Flag_String : constant String := Command_Line.Argument (1);
 11 
 12    type Colors is (Red, White, Blue);
 13    package Color_IO is new Text_IO.Enumeration_IO (Colors);
 14 
 15    N : constant Positive := Flag_String'Length;
 16    subtype Index_Range is Positive range 1..N;
 17    Flag : array (Index_Range) of Colors;
 18    First_Blue, First_White : Index_Range := Flag'First;
 19 
 20 begin
 21 
 22    -- convert string to an array of colors
 23    for I in Flag_String'Range loop
 24       case Flag_String(I) is
 25         when 'R' | 'r' => Flag(I) := Red;
 26         when 'W' | 'w' => Flag(I) := White;
 27         when 'B' | 'b' => Flag(I) := Blue;
 28         when others    => Flag(I) := Blue;
 29       end case;
 30    end loop;
 31 
 32    -- sort array of colors into the color scheme of the Dutch flag
 33    for I in Flag'Range loop
 34       case Flag(I) is
 35          when Red =>
 36             Flag(I)           := Flag(First_Blue);
 37             Flag(First_Blue)  := Flag(First_White);
 38             Flag(First_White) := Red;
 39             First_Blue        := First_Blue + 1;
 40             First_White       := First_White + 1;
 41          when White =>
 42             Flag(I)           := Flag(First_Blue);
 43             Flag(First_Blue)  := White;
 44             First_Blue        := First_Blue + 1;
 45          when Blue =>
 46             null;
 47       end case;
 48    end loop;
 49 
 50    -- print result
 51    for I in Flag'Range loop
 52       Color_IO.Put (Flag(I)); Text_IO.New_Line;
 53    end loop;
 54 
 55 end Dutch_Flag;