WeixiangYan/CodeTransOcean huggingface dataset:
Task: Koch curve







Python: l = 300

def setup():
    size(400, 400)
    background(0, 0, 255)
    stroke(255)
    
    translate(width / 2.0, height / 2.0)
    
    translate(-l / 2.0, l * sqrt(3) / 6.0)
    for i in range(4):
        kcurve(0, l)
        rotate(radians(120))
        translate(-l, 0)


def kcurve(x1, x2):
    s = (x2 - x1) / 3.0
    if s < 5:
        pushMatrix()
        translate(x1, 0)
        line(0, 0, s, 0)
        line(2 * s, 0, 3 * s, 0)
        translate(s, 0)
        rotate(radians(60))
        line(0, 0, s, 0)
        translate(s, 0)
        rotate(radians(-120))
        line(0, 0, s, 0)
        popMatrix()
        return

    pushMatrix()
    translate(x1, 0)
    kcurve(0, s)
    kcurve(2 * s, 3 * s)
    translate(s, 0)
    rotate(radians(60))
    kcurve(0, s)
    translate(s, 0)
    rotate(radians(-120))
    kcurve(0, s)
    popMatrix()





Ada: with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
with PDF_Out;

procedure Koch_Curve is

   package Real_Math is
     new Ada.Numerics.Generic_Elementary_Functions (PDF_Out.Real);
   use Real_Math, PDF_Out, Ada.Command_Line, Ada.Text_IO;

   subtype Angle_Deg  is Real;
   type    Level_Type is range 0 .. 7;

   Purple : constant Color_Type := (0.7, 0.0, 0.5);
   Length : constant Real       := 400.0;
   Corner : constant Point      := (90.0, 580.0);

   Level     : Level_Type;
   Current   : Point      := (0.0, 0.0);
   Direction : Angle_Deg  := Angle_Deg'(60.0);
   Doc       : PDF_Out_File;

   procedure Koch (Level : Level_Type; Length : Real) is
   begin
      if Level = 0 then
         Current := Current + Length * Point'(Sin (Direction, 360.0),
                                              Cos (Direction, 360.0));
         Doc.Line (Corner + Current);
      else
         Koch (Level - 1, Length / 3.0);  Direction := Direction -  60.0;
         Koch (Level - 1, Length / 3.0);  Direction := Direction + 120.0;
         Koch (Level - 1, Length / 3.0);  Direction := Direction -  60.0;
         Koch (Level - 1, Length / 3.0);
      end if;
   end Koch;

begin
   if Argument_Count /= 1 then
      Put_Line ("koch_curve <level>");
      Put_Line ("  <level>   0 .. 7");
      Put_Line ("open koch.pdf to view ouput");
      return;
   end if;
   Level := Level_Type'Value (Argument (1));

   Doc.Create ("koch.pdf");
   Doc.Page_Setup (A4_Portrait);
   Doc.Margins (Margins_Type'(Left   => Cm_2_5,
                              others => One_cm));
   Doc.Color (Purple);
   Doc.Move (Corner);
   for A in 1 .. 3 loop
      Koch (Level, Length);
      Direction := Direction + 120.0;
   end loop;
   Doc.Finish_Path (Close_Path => True,
                    Rendering  => Fill,
                    Rule       => Even_Odd);
   Doc.Close;
end Koch_Curve;
Task: Pseudo-random numbers_Xorshift star







Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D



class Xorshift_star():
    
    def __init__(self, seed=0):
        self.state = seed & mask64

    def seed(self, num):
        self.state =  num & mask64
    
    def next_int(self):
        "return random int between 0 and 2**32"
        x = self.state
        x = (x ^ (x >> 12)) & mask64
        x = (x ^ (x << 25)) & mask64
        x = (x ^ (x >> 27)) & mask64
        self.state = x
        answer = (((x * const) & mask64) >> 32) & mask32 
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = Xorshift_star()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)





Ada: with Interfaces;  use Interfaces;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   const : constant Unsigned_64 := 16#2545_F491_4F6C_DD1D#;
   state : Unsigned_64          := 0;
   Unseeded_Error : exception;

   procedure seed (num : Unsigned_64) is
   begin
      state := num;
   end seed;

   function Next_Int return Unsigned_32 is
      x : Unsigned_64 := state;
   begin
      if state = 0 then
         raise Unseeded_Error;
      end if;

      x     := x xor (x / 2**12);
      x     := x xor (x * 2**25);
      x     := x xor (x / 2**27);
      state := x;
      return Unsigned_32 ((x * const) / 2**32);
   end Next_Int;

   function Next_Float return Long_Float is
   begin
      return Long_Float (Next_Int) / 2.0**32;
   end Next_Float;

   counts : array (0 .. 4) of Natural := (others => 0);
   J      : Natural;
begin
   seed (1_234_567);
   for I in 1 .. 5 loop
      Put_Line (Unsigned_32'Image (Next_Int));
   end loop;

   seed (987_654_321);
   for I in 1 .. 100_000 loop
      J          := Natural (Long_Float'Floor (Next_Float * 5.0));
      counts (J) := counts (J) + 1;
   end loop;

   New_Line;
   for I in counts'Range loop
      Put_Line (I'Image & " :" & counts (I)'Image);
   end loop;

end Main;
Task: Numbers with equal rises and falls







Python: import itertools

def riseEqFall(num):
    
    height = 0
    d1 = num % 10
    num //= 10
    while num:
        d2 = num % 10
        height += (d1<d2) - (d1>d2)
        d1 = d2
        num //= 10
    return height == 0
    
def sequence(start, fn):
    
    num=start-1
    while True:
        num += 1
        while not fn(num): num += 1
        yield num

a296712 = sequence(1, riseEqFall)


print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))


print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))







Ada: with Ada.Text_Io;
with Ada.Integer_Text_Io;

procedure Equal_Rise_Fall is
   use Ada.Text_Io;

   function Has_Equal_Rise_Fall (Value : Natural) return Boolean is
      Rises : Natural := 0;
      Falls : Natural := 0;
      Image : constant String := Natural'Image (Value);
      Last  : Character := Image (Image'First + 1);
   begin
      for Pos in Image'First + 2 .. Image'Last loop
         if Image (Pos) > Last then
            Rises := Rises + 1;
         elsif Image (Pos) < Last then
            Falls := Falls + 1;
         end if;
         Last := Image (Pos);
      end loop;
      return Rises = Falls;
   end Has_Equal_Rise_Fall;

   Value : Natural := 1;
   Count : Natural := 0;
begin
   loop
      if Has_Equal_Rise_Fall (Value) then
         Count := Count + 1;
         if Count <= 200 then
            Ada.Integer_Text_Io.Put (Value, Width => 5);
            if Count mod 20 = 0 then
               New_Line;
            end if;
         end if;
         if Count = 10_000_000 then
            New_Line;
            Put_Line ("The 10_000_000th: " & Natural'Image (Value));
            exit;
         end if;
      end if;
      Value := Value + 1;
   end loop;
end Equal_Rise_Fall;
Task: Pseudo-random numbers_Combined recursive generator MRG32k3a







Python: 
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209

a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853

d = m1 + 1

class MRG32k3a():
    
    def __init__(self, seed_state=123):
        self.seed(seed_state)
    
    def seed(self, seed_state):
        assert 0 <seed_state < d, f"Out of Range 0 x < {d}"
        self.x1 = [seed_state, 0, 0]
        self.x2 = [seed_state, 0, 0]
        
    def next_int(self):
        "return random int in range 0..d"
        x1i = sum(aa * xx  for aa, xx in zip(a1, self.x1)) % m1
        x2i = sum(aa * xx  for aa, xx in zip(a2, self.x2)) % m2
        self.x1 = [x1i] + self.x1[:2]
        self.x2 = [x2i] + self.x2[:2]

        z = (x1i - x2i) % m1
        answer = (z + 1)
        
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / d
    

if __name__ == '__main__':
    random_gen = MRG32k3a()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)





Ada: package MRG32KA is
   type I64 is range -2**63..2**63 - 1;
   m1 : constant I64 := 2**32 - 209;
   m2 : constant I64 := 2**32 - 22853;

   subtype state_value is I64 range 1..m1;
   
   procedure Seed (seed_state : state_value);
   function Next_Int return I64;
   function Next_Float return Long_Float;
end MRG32KA;
Task: Self-describing numbers







Python: >>> def isSelfDescribing(n):
	s = str(n)
	return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))

>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]





Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure SelfDesc is
   subtype Desc_Int is Long_Integer range 0 .. 10**10-1;

   function isDesc (innum : Desc_Int) return Boolean is
      subtype S_Int is Natural range 0 .. 10;
      type S_Int_Arr is array (0 .. 9) of S_Int;
      ref, cnt : S_Int_Arr := (others => 0);
      n, digit : S_Int := 0;  num : Desc_Int := innum;
   begin
      loop
         digit := S_Int (num mod 10);
         ref (9 - n) := digit;  cnt (digit) := cnt (digit) + 1;
         num := num / 10; exit when num = 0; n := n + 1;
      end loop;
      return ref (9 - n .. 9) = cnt (0 .. n);
   end isDesc;

begin
   for i in Desc_Int range 1 .. 100_000_000 loop
      if isDesc (i) then
         Put_Line (Desc_Int'Image (i));
      end if;
   end loop;
end SelfDesc;
Task: Changeable words







Python: from collections import defaultdict, Counter


def getwords(minlength=11, fname='unixdict.txt'):
    "Return set of lowercased words of > given number of characters"
    with open(fname) as f:
        words = f.read().strip().lower().split()
    return {w for w in words if len(w) > minlength}

words11 = getwords()
word_minus_1 = defaultdict(list)    
minus_1_to_word = defaultdict(list) 

for w in words11:
    for i in range(len(w)):
        minus_1 = w[:i] + w[i+1:]
        word_minus_1[minus_1].append((w, i))   
        if minus_1 in words11:
            minus_1_to_word[minus_1].append(w)
    
cwords = set()  
for _, v in word_minus_1.items():
    if len(v) >1:
        change_indices = Counter(i for wrd, i in v)
        change_words = set(wrd for wrd, i in v)
        words_changed = None
        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
            words_changed = [wrd for wrd, i in v
                             if change_indices[i] > 1]
        if words_changed:
            cwords.add(tuple(sorted(words_changed)))

print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
    print(f"  {k:12} From {', '.join(v)}")

print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
    print(f"  {v[0]:12} From {', '.join(v[1:])}")





Ada: with Ada.Text_Io;
with Ada.Strings.Fixed;
with Ada.Containers.Indefinite_Vectors;

procedure Changeable is
   use Ada.Text_Io, Ada.Strings.Fixed;

   package String_Vectors is
     new Ada.Containers.Indefinite_Vectors (Index_Type   => Positive,
                                            Element_Type => String);

   Filename : constant String := "unixdict.txt";
   File     : File_Type;
   Words    : String_Vectors.Vector;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         if Word'Length > 11 then
            Words.Append (Word);
         end if;
      end;
   end loop;
   Close (File);

   for Word_Index_1 in Words.First_Index .. Words.Last_Index loop
      for Word_Index_2 in Word_Index_1 + 1 .. Words.Last_Index loop
         declare
            Image  : String (1 .. 14);
            Word_1 : String renames Words (Word_Index_1);
            Word_2 : String renames Words (Word_Index_2);
            Match  : Natural := 0;
         begin
            if Word_1'Length = Word_2'Length then
               for Index in Word_1'Range loop
                  if Word_1 (Index) = Word_2 (Index) then
                     Match := Match + 1;
                  end if;
               end loop;
               if Match = Word_1'Length - 1 then
                  Move (Word_1, Image);
                  Put (Image); Put (" <-> ");
                  Move (Word_2, Image);
                  Put_Line (Image);
               end if;
            end if;
         end;
      end loop;
   end loop;
end Changeable;
Task: Exactly three adjacent 3 in lists







Python: 

from itertools import dropwhile, takewhile



def nnPeers(n):
    
    def p(x):
        return n == x

    def go(xs):
        fromFirstMatch = list(dropwhile(
            lambda v: not p(v),
            xs
        ))
        ns = list(takewhile(p, fromFirstMatch))
        rest = fromFirstMatch[len(ns):]

        return p(len(ns)) and (
            not any(p(x) for x in rest)
        )

    return go




def main():
    
    print(
        '\n'.join([
            f'{xs} -> {nnPeers(3)(xs)}' for xs in [
                [9, 3, 3, 3, 2, 1, 7, 8, 5],
                [5, 2, 9, 3, 3, 7, 8, 4, 1],
                [1, 4, 3, 6, 7, 3, 8, 3, 2],
                [1, 2, 3, 4, 5, 6, 7, 8, 9],
                [4, 6, 8, 7, 2, 3, 3, 3, 1]
            ]
        ])
    )



if __name__ == '__main__':
    main()





Ada: with Ada.Text_Io;  use Ada.Text_Io;

procedure Exactly_3 is

   type List_Type is array (Positive range <>) of Integer;

   function Has_3_Consecutive (List : List_Type) return Boolean is
      Conseq : constant Natural := 3;
      Match  : constant Integer := 3;
      Count  : Natural := 0;
   begin
      for Element of List loop
         if Element = Match then
            Count := Count + 1;
         else
            if Count = Conseq then
               return True;
            else
               Count := 0;
            end if;
         end if;
      end loop;
      return (Count = Conseq);
   end Has_3_Consecutive;

   procedure Put (List : List_Type) is
   begin
      Put ("[");
      for Element of List loop
         Put (Integer'Image (Element));
         Put (" ");
      end loop;
      Put ("]");
   end Put;

   procedure Test (List : List_Type) is
      Result : constant Boolean := Has_3_Consecutive (List);
   begin
      Put (List);
      Put (" -> ");
      Put (Boolean'Image (Result));
      New_Line;
   end Test;

begin
   Test ((9,3,3,3,2,1,7,8,5));
   Test ((5,2,9,3,3,7,8,4,1));
   Test ((1,4,3,6,7,3,8,3,2));
   Test ((1,2,3,4,5,6,7,8,9));
   Test ((4,6,8,7,2,3,3,3,1));

   Test ((4,6,8,7,2,3,3,3,3)); 
   Test ((4,6,8,7,2,1,3,3,3)); 
   Test ((1,3,3,3,3,4,5,8,9));

   Test ((3,3,3,3));
   Test ((3,3,3));
   Test ((3,3));
   Test ((1 => 3));        
   Test ((1 .. 0 => <>));  
end Exactly_3;
Task: Decision tables







Python: 

def dt_creator():
    print("\n\nCREATING THE DECISION TABLE\n")
    conditions = input("Input conditions, in order, separated by commas: ")
    conditions = [c.strip() for c in conditions.split(',')]
    print( ("\nThat was %s conditions:\n  " % len(conditions))
           + '\n  '.join("%i: %s" % x for x in enumerate(conditions, 1)) )
    print("\nInput an action, a semicolon, then a list of tuples of rules that trigger it. End with a blank line")
    action2rules, action = [], ' '
    while action:
        action = input("%i: " % (len(action2rules) + 1)).strip()
        if action:
            name, _, rules = [x.strip() for x in action.partition(';')]
            rules = eval(rules)
            assert all(len(rule) == len(conditions) for rule in rules), \
                   "The number of conditions in a rule to trigger this action is wrong" 
            action2rules.append((name, rules))
    actions = [x[0] for x in action2rules]
    
    rule2actions = dict((y,[]) for y in set(sum((x[1] for x in action2rules), [])))
    for action, rules in action2rules:
        for r in rules:
            rule2actions[r].append( action )
    return conditions, rule2actions

def dt_user(dt, default=['Pray!']):
    conditions, rule2actions = dt
    print("\n\nUSING THE DECISION TABLE\n")
    rule = tuple(int('y' == input("%s? (Answer y if statement is true or n): " % c)) for c in conditions)
    print("Try this:\n  " + '\n  '.join(rule2actions.get(rule, default)))

if __name__ == '__main__':
    dt = dt_creator()
    dt_user(dt)
    dt_user(dt)
    dt_user(dt)





Ada: generic
   type Condition is (<>);
   type Action is (<>);
   with function Ask_Question (Cond: Condition) return Boolean;
   with procedure Give_Answer (Act:  Action);
   with procedure No_Answer;

package Generic_Decision_Table is

   type Answers is array(Condition) of Boolean;
   type Rule_R is record
      If_Then: Answers;
      Act:     Action;
   end record;
   type Rule_A is array(Positive range <>) of Rule_R;

   procedure React(Rules: Rule_A);

end Generic_Decision_Table;
Task: Find words which contains more than 3 e vowels







Python: with open('unixdict.txt', 'rt') as f:
    for line in f.readlines():
        if not any(c in 'aiou' for c in line) and sum(c=='e' for c in line)>3:
            print(line.strip())





Ada: with Ada.Text_Io;
with Ada.Strings.Maps;
with Ada.Strings.Fixed;

procedure Find_Three_E is
   use Ada.Text_Io;
   use Ada.Strings;
   use type Ada.Strings.Maps.Character_Set;

   Filename   : constant String  := "unixdict.txt";
   Y_Is_Vowel : constant Boolean := False;
   Set_E      : constant Maps.Character_Set := Maps.To_Set ("eE");
   Set_Y      : constant Maps.Character_Set := Maps.To_Set ("yY");
   Set_Others : constant Maps.Character_Set :=
     Maps.To_Set ("aiouAIOU") or (if Y_Is_Vowel then Set_Y else Maps.Null_Set);
   File       : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word         : constant String  := Get_Line (File);
         Count_E      : constant Natural := Fixed.Count (Word, Set_E);
         Count_Others : constant Natural := Fixed.Count (Word, Set_Others);
      begin
         if Count_E > 3 and Count_Others = 0 then
            Put_Line (Word);
         end if;
      end;
   end loop;
   Close (File);
end Find_Three_E;
Task: Minimum numbers of three lists







Python: numbers1 = [5,45,23,21,67]
numbers2 = [43,22,78,46,38]
numbers3 = [9,98,12,98,53]

numbers = [min(numbers1[i],numbers2[i],numbers3[i]) for i in range(0,len(numbers1))]

print(numbers)





Ada: with Ada.Text_Io; use Ada.Text_Io;

procedure Minimum_Three_Lists is

   type Number_Array is array (Positive range 1 .. 5) of Integer;

   Numbers_1 : constant Number_Array := (5,45,23,21,67);
   Numbers_2 : constant Number_Array := (43,22,78,46,38);
   Numbers_3 : constant Number_Array := (9,98,12,98,53);

   Result : Number_Array;
begin
   for A in Number_Array'Range loop
      declare
         R   : Integer renames Result    (A);
         N_1 : Integer renames Numbers_1 (A);
         N_2 : Integer renames Numbers_2 (A);
         N_3 : Integer renames Numbers_3 (A);
      begin
         R := Integer'Min (N_1, Integer'Min (N_2, N_3));
      end;
   end loop;

   for R of Result loop
      Put (R'Image);
   end loop;
   New_Line;
end Minimum_Three_Lists;
Task: Mosaic matrix







Python: size = 9
for Row in range(size):
    for Col in range(size):
        if (Row % 2 == 1 and Col % 2 == 1) or (Row % 2 == 0 and Col % 2 == 0):
            print("1", end=" ")
        else:
            print("0", end=" ")
    print()





Ada: with Ada.Text_Io; use Ada.Text_Io;
with Ada.Command_Line;

procedure Mosaic_Matrix is

   type Matrix_Type is array (Positive range <>, Positive range <>) of Character;

   function Mosaic (Length : Natural) return Matrix_Type is
   begin
      return M : Matrix_Type (1 .. Length, 1 .. Length) do
         for Row in M'Range (1) loop
            for Col in M'Range (2) loop
               M (Row, Col) := (if (Row + Col) mod 2 = 0
                                then '1' else '.');
            end loop;
         end loop;
      end return;
   end Mosaic;

   procedure Put (M : Matrix_Type) is
   begin
      for Row in M'Range (1) loop
         for Col in M'Range (2) loop
            Put (' ');
            Put (M (Row, Col));
         end loop;
         New_Line;
      end loop;
   end Put;

begin
   Put (Mosaic (Length => Natural'Value (Ada.Command_Line.Argument (1))));

exception
   when others =>
      Put_Line ("Usage: ./mosaic_matrix <side-length>");

end Mosaic_Matrix;
Task: Numbers in base-16 representation that cannot be written with decimal digits







Python: [print(16*q + r,end=' ') for q in range(0,16) for r in range(10,16)]





Ada: with Ada.Text_IO;

procedure Numbers_In_Base_16 is

   package Natural_IO is new Ada.Text_IO.Integer_IO (Natural);
   use Ada.Text_IO, Natural_IO;

   function Is_Hex_Only (Value : Natural) return Boolean
   is (Value = 0 or
         (Value mod 16 >= 10 and then Is_Hex_Only (Value / 16)));

   subtype Test_Range is Natural range 1 .. 499;
   Count : Natural := 0;
begin
   for A in Test_Range loop
      if Is_Hex_Only (A) then
         Count := Count + 1;
         Put (A, Width => 3); Put (" = ");
         Put (A, Width => 6, Base => 16); Put ("   ");
         if Count mod 5 = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line;
   Default_Width := 0;
   Put ("There are "); Put (Count);
   Put (" numbers in range ");
   Put (Test_Range'First); Put (" .. ");
   Put (Test_Range'Last);
   Put (" without decimal digits in hex representation.");
   New_Line;
end Numbers_In_Base_16;
Task: Longest substrings without repeating characters







Python: def longest_substring(s = "xyzyab"):
    substr = [s[x:y] for x in range(len(s)) for y in range(x+1, len(s) + 1)]
    no_reps = []
    for sub in substr:
        if len(sub) == len(set(sub)) and sub not in no_reps:
            no_reps.append(sub)
    max_len = max(len(sub) for sub in no_reps) if no_reps else 0
    max_subs = [sub for sub in no_reps if len(sub) == max_len]
    return max_subs

if __name__ == '__main__':
    for s in ["xyzyabcybdfd", "xyzyab", "zzzzz", "a", "α⊆϶α϶", "",
              [1, 2, 3, 4, 1, 2, 5, 6, 1, 7, 8, 1, 0]]:
        print(f"{s} => {longest_substring(s)}")





Ada: with Ada.Text_IO;

procedure Longest_Substring is

   function Longest (Item : String) return String is
      Hist  : array (Character) of Natural := (others => 0);
      First         : Natural := Item'First;
      Last          : Natural := Item'First - 1;
      Longest_First : Natural := Item'First;
      Longest_Last  : Natural := Item'First - 1;

      procedure Adjust is
      begin
         if Last - First > Longest_Last - Longest_First then
            Longest_First := First;
            Longest_Last  := Last;
         end if;
      end Adjust;

   begin
      if Item = "" then
         return Item;
      end if;
      for Index in Item'Range loop
         Last := Index;
         Hist (Item (Index)) := Hist (Item (Index)) + 1;
         if Hist (Item (Index)) = 1 then
            Adjust;
         else
            for A in First .. Index loop
               if (for all E of Hist => E <= 1) then
                  First := A;
                  Adjust;
                  exit;
               end if;

               Hist (Item (A)) := Hist (Item (A)) - 1;
            end loop;
         end if;
      end loop;
      return Item (Longest_First .. Longest_Last);
   end Longest;

   procedure Test (Item : String) is
      use Ada.Text_IO;
   begin
      Put ("original : '");  Put (Item);            Put_Line ("'");
      Put ("longest  : '");  Put (Longest (Item));  Put_Line ("'");
   end Test;

begin
   Test ("");
   Test ("a");
   Test ("xyzyabcybdfd");
   Test ("thisisastringtest");
   Test ("zzzzz");
end Longest_Substring;