Board logo
Exo 6: Tab1 en séquence dans Tab2

ftbass - 27/02/2004 à 22:02

Verifier si le contenu de Tab1 est retrouvé en séquence dans Tab2 :

code:
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

with Nombres_aleatoires; use Nombres_aleatoires;

procedure Tab1EnSequenceDansTab2 is

Long1 : constant := 3;
Tab1 : array(1 .. Long1) of integer := (1, 2, 3);
Long2 : constant := 10;
Tab2 : array(1 .. Long2) of integer := (4, 3, 1, 2, 3, 9, 2, 1, 1, 2);
Trouve : boolean := false;
i : integer := 1;
j : integer;

begin
  while (i <= Long1) and (Trouve = false) loop
     if Tab2(i) /= Tab1(1) then
        i := i + 1;
       else
          Trouve := true;
          j := 1;
     end if;
     while (j < Long1) and (i <= Long2 - j) and (Trouve = true) loop
        if Tab2(i + j) = Tab1(j + 1) then
           j := j + 1;
        else
           Trouve := false;
           i := i + 1;
        end if;
     end loop;
  end loop;
  if (Trouve = true) and (j > Long1) then
     Trouve := false;
  end if;
  if Trouve = true then
     put("Trouve");
  else
     put("Pas trouve");
  end if;
end;


[Edité le 10/03/2004 à 09:12 par ftbass]


bouba - 28/09/2006 à 09:34

1. Il n'est jamais bon de s'amuser a faire soi-meme ce que le language peut faire pour nous.
Ada gere tres bien les comparaisons de donnees de type tableau, donc autant le laisser faire, cela simplifie
le code. ;)
2. De plus, on connait parfaitement la taille des donnees, donc il est preferable d'utiliser une boucle for plutot
qu'une boucle while.
3. Cette version est plus generale car elle autorise tout range entier valide pour indexer le tableau.
4. Si tab1 est plus grand que tab2, la boucle n'est pas executee, contrairement a la version precedente. D'ailleurs, si vous essayez de faire ce test, vous verrez que le compilo levera un warning car en verifiant les bornes du for, il s'en est apercu. ;) ... Si ce n'est pas le cas, changez de compilo, le votre est une bouze. ^^

code:

with Text_Io; use Text_Io;

procedure Tab is
 type Table is array(Integer range <>) of Integer;
 
 Tab1        : constant Table( 1 .. 3) := (1 , 2 , 3);
 Tab2        : constant Table(-3 .. 6) := (4, 3, 1, 2, 3, 9, 2, 1, 1, 2);
 Max         : constant Integer := Tab2'Last - Tab1'Length + 1;  
 
 type Result_T(Match_Found : Boolean := False) is
   record
     case Match_Found is
       when True  =>
         Index : Integer;
       when False =>
         null;
     end case;
   end record;
 
 Result : Result_T;
begin
 
 for Index in Tab2'First .. Max
 loop
   if Tab2(Index .. Index+Tab1'Length-1) = Tab1 then      
     Result := (Match_Found => True,
                Index       => Index);
     exit;
   end if;
 end loop;
 
 if Result.Match_Found then
   Put_Line("Tab1 trouve a partir de l'index " & Integer'Image(Result.Index));
 else
   Put_Line("Tab1 non trouve");
 end if;
end Tab;