WeixiangYan/CodeTransOcean huggingface dataset:
Task: Unique characters







Python: 

from itertools import chain, groupby



def uniques(xs):
    
    return [
        h for h, (_, *tail) in
        groupby(sorted(chain(*xs)))
        if not tail
    ]




def main():
    
    print(
        uniques([
            "133252abcdeeffd",
            "a6789798st",
            "yxcdfgxcyz"
        ])
    )



if __name__ == '__main__':
    main()





Ada: with Ada.Text_Io;

procedure Unique_Characters is

   List : array (Character) of Natural := (others => 0);

   procedure Count (Item : String) is
   begin
      for C of Item loop
         List (C) := List (C) + 1;
      end loop;
   end Count;

   procedure Put_Only_Once is
      use Ada.Text_Io;
   begin
      for C in List'Range loop
         if List (C) = 1 then
            Put (C);
            Put (' ');
         end if;
      end loop;
      New_Line;
   end Put_Only_Once;

begin
   Count ("133252abcdeeffd");
   Count ("a6789798st");
   Count ("yxcdfgxcyz");
   Put_Only_Once;
end Unique_Characters;
Task: Day of the week of Christmas and New Year







Python: import datetime

weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
thisXMas  = datetime.date(2021,12,25)
thisXMasDay = thisXMas.weekday()
thisXMasDayAsString = weekDays[thisXMasDay]
print("This year's Christmas is on a {}".format(thisXMasDayAsString))

nextNewYear = datetime.date(2022,1,1)
nextNewYearDay = nextNewYear.weekday()
nextNewYearDayAsString = weekDays[nextNewYearDay]
print("Next new year is on a {}".format(nextNewYearDayAsString))





Ada: with Ada.Text_Io;
with Ada.Calendar.Formatting;

procedure Weekdays is
   use Ada.Text_Io;
   use Ada.Calendar.Formatting;

   subtype Time is Ada.Calendar.Time;

   procedure Info (Date : Time) is
   begin
      Put (Image (Date));
      Put (" is a ");
      Put (Day_Name'Image (Day_Of_Week (Date)));
      Put (".");
      New_Line;
   end Info;

   Christmas_Day : constant Time := Time_Of (Year => 2021, Month => 12, Day => 25);
   New_Years_Day : constant Time := Time_Of (Year => 2022, Month => 01, Day => 01);

begin
   Info (Christmas_Day);
   Info (New_Years_Day);
end Weekdays;
Task: Here document







Python: print()





Ada: with Ada.Containers.Indefinite_Vectors, Ada.Text_IO;

procedure Here_Doc is

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

   use type String_Vec.Vector;

   Document: String_Vec.Vector := String_Vec.Empty_Vector
    & "This is a vector of strings with the following properties:"
    & "  - indention is preserved, and"
    & "  - a quotation mark '""' must be ""escaped"" by a double-quote '""""'.";
begin
   Document := Document & "Have fun!";
   for I in Document.First_Index .. Document.Last_Index loop
      Ada.Text_IO.Put_Line(Document.Element(I));
   end loop;
end Here_Doc;
Task: Abelian sandpile model_Identity







Python: from itertools import product
from collections import defaultdict


class Sandpile():
    def __init__(self, gridtext):
        array = [int(x) for x in gridtext.strip().split()]
        self.grid = defaultdict(int,
                                {(i //3, i % 3): x 
                                 for i, x in enumerate(array)})

    _border = set((r, c) 
                  for r, c in product(range(-1, 4), repeat=2) 
                  if not 0 <= r <= 2 or not 0 <= c <= 2
                  )
    _cell_coords = list(product(range(3), repeat=2))
    
    def topple(self):
        g = self.grid
        for r, c in self._cell_coords:
            if g[(r, c)] >= 4:
                g[(r - 1, c)] += 1
                g[(r + 1, c)] += 1
                g[(r, c - 1)] += 1
                g[(r, c + 1)] += 1
                g[(r, c)] -= 4
                return True
        return False
    
    def stabilise(self):
        while self.topple():
            pass
        
        g = self.grid
        for row_col in self._border.intersection(g.keys()):
            del g[row_col]
        return self
    
    __pos__ = stabilise     
    
    def __eq__(self, other):
        g = self.grid
        return all(g[row_col] == other.grid[row_col]
                   for row_col in self._cell_coords)

    def __add__(self, other):
        g = self.grid
        ans = Sandpile("")
        for row_col in self._cell_coords:
            ans.grid[row_col] = g[row_col] + other.grid[row_col]
        return ans.stabilise()
       
    def __str__(self):
        g, txt = self.grid, []
        for row in range(3):
            txt.append(' '.join(str(g[(row, col)]) 
                                for col in range(3)))
        return '\n'.join(txt)
    
    def __repr__(self):
        return f'{self.__class__.__name__}()'
        

unstable = Sandpile()
s1 = Sandpile()
s2 = Sandpile()
s3 = Sandpile("3 3 3  3 3 3  3 3 3")
s3_id = Sandpile("2 1 2  1 0 1  2 1 2")





Ada: 

package Abelian_Sandpile is
   Limit : constant Integer := 4;

   type Sandpile is array (0 .. 2, 0 .. 2) of Natural with
      Default_Component_Value => 0;

   procedure Stabalize (Pile : in out Sandpile);
   function Is_Stable (Pile : in Sandpile) return Boolean;
   procedure Topple (Pile : in out Sandpile);
   function "+" (Left, Right : Sandpile) return Sandpile;
   procedure Print(PIle : in Sandpile);

end Abelian_Sandpile;
Task: Base 16 numbers needing a to f







Python: 



def p(n):
    
    return 9 < n and (9 < n % 16 or p(n // 16))




def main():
    
    xs = [
        str(n) for n in range(1, 1 + 500)
        if p(n)
    ]
    print(f'{len(xs)} matches for the predicate:\n')
    print(
        table(6)(xs)
    )





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def table(n):
    
    def go(xs):
        w = len(xs[-1])
        return '\n'.join(
            ' '.join(row) for row in chunksOf(n)([
                s.rjust(w, ' ') for s in xs
            ])
        )
    return go



if __name__ == '__main__':
    main()





Ada: with Ada.Text_Io;

procedure Base_16_Numbers is
   Columns : constant := 24;
   Base    : constant := 16;

   function Has_A_To_F (N : Positive) return Boolean is
      C : Natural := N;
   begin
      while C > 0 loop
         if C mod Base in 16#A# .. 16#F# then
            return True;
         end if;
         C := C / Base;
      end loop;
      return False;
   end Has_A_To_F;

   package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
   use Ada.Text_Io;
   Count : Natural := 0;
begin
   for N in 1 .. 500 loop
      if Has_A_To_F (N) then
         Count := Count + 1;
         Natural_Io.Put (N, Width => 5);
         if Count mod Columns = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line (2);
   Put ("Total count: "); Natural_Io.Put (Count, Width => 3); New_Line;
end Base_16_Numbers;
Task: Address of a variable







Python: var num = 12
var pointer = ptr(num) 

print pointer 

@unsafe 
pointer.addr = 0xFFFE 





Ada: The_Address : System.Address;
I : Integer;
The_Address := I'Address;
Task: Juggler sequence







Python: from math import isqrt

def juggler(k, countdig=True, maxiters=1000):
    m, maxj, maxjpos = k, k, 0
    for i in range(1, maxiters):
        m = isqrt(m) if m % 2 == 0 else isqrt(m * m * m)
        if m >= maxj:
            maxj, maxjpos  = m, i
        if m == 1:
            print(f"{k: 9}{i: 6,}{maxjpos: 6}{len(str(maxj)) if countdig else maxj: 20,}{' digits' if countdig else ''}")
            return i

    print("ERROR: Juggler series starting with $k did not converge in $maxiters iterations")


print("       n    l(n)  i(n)       h(n) or d(n)\n-------------------------------------------")
for k in range(20, 40):
    juggler(k, False)

for k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909]:
    juggler(k)





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

procedure Juggler is

   subtype Number  is Long_Long_Integer;
   type Index_Type is new Natural;

   subtype Initial_Values is Number range 20 .. 39;

   generic
      Initial : Number;
   package Generic_Juggler is
      procedure Next (Value : out Number; Index : out Index_Type);
   end Generic_Juggler;

   package body Generic_Juggler is

      type Real is new Long_Long_Float;

      package Real_Math is
        new Ada.Numerics.Generic_Elementary_Functions (Real);

      K   : Index_Type := 0;
      A_K : Real       := Real (Initial);

      procedure Next (Value : out Number; Index : out Index_Type) is
         use Real_Math;
      begin
         Value := Number (A_K);
         Index := K;
         A_K := (if Number (A_K) mod 2 = 0
                 then Real'Floor (A_K ** 0.5)
                 else Real'Floor (A_K ** 1.5));
         K := K + 1;
      end Next;

   end Generic_Juggler;

   procedure Statistics (N   : Number;     L_N : out Index_Type;
                         H_N : out Number; I_N : out Index_Type)
   is
      package Juggler_Generator is new Generic_Juggler (Initial => N);
      use Juggler_Generator;
      Value : Number;
   begin
      H_N := 0;
      I_N := 0;
      loop
         Next (Value, L_N);
         if Value > H_N then
            H_N := Value;
            I_N := L_N;
         end if;
         exit when Value = 1;
      end loop;
   end Statistics;

   procedure Put_Table is
      package Number_IO is new Ada.Text_IO.Integer_IO (Number);
      package Index_IO  is new Ada.Text_IO.Integer_IO (Index_Type);
      use Ada.Text_IO, Number_IO, Index_IO;
      L_N : Index_Type;
      H_N : Number;
      I_N : Index_Type;
   begin
      Put_Line ("  N   L(N)            H(N)   I(N)");
      Put_Line ("
      for N in Initial_Values loop
         Statistics (N, L_N, H_N, I_N);
         Put (N, Width => 3);     Put (L_N, Width => 7);
         Put (H_N, Width => 16);  Put (I_N, Width => 7);  New_Line;
      end loop;
   end Put_Table;

begin
   Put_Table;
end Juggler;
Task: Fixed length records







Python: infile = open('infile.dat', 'rb')
outfile = open('outfile.dat', 'wb')

while True:
    onerecord = infile.read(80)
    if len(onerecord) < 80:
        break
    onerecordreversed = bytes(reversed(onerecord))
    outfile.write(onerecordreversed)

infile.close()
outfile.close()





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

procedure Main is
   subtype Block is String (1 .. 80);
   Infile_Name  : String := "infile.dat";
   outfile_Name : String := "outfile.dat";
   Infile       : File_Type;
   outfile      : File_Type;

   Line : Block := (Others => ' ');
begin
   Open (File => Infile, Mode => In_File, Name => Infile_Name);
   Create (File => outfile, Mode => Out_File, Name => outfile_Name);

   Put_Line("Input data:");
   New_Line;
   while not End_Of_File (Infile) loop
      Get (File => Infile, Item => Line);
      Put(Line);
      New_Line;
      for I in reverse Line'Range loop
         Put (File => outfile, Item => Line (I));
      end loop;
   end loop;
   
   Close (Infile);
   Close (outfile);

   Open(File => infile,
        Mode => In_File,
        Name => outfile_name);
   New_Line;
   Put_Line("Output data:");
   New_Line;
   while not End_Of_File(Infile) loop
      Get(File => Infile,
          Item => Line);
      Put(Line);
      New_Line;
   end loop;
end Main;
Task: Find words whose first and last three letters are equal







Python: import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>5 and word[:3].lower()==word[-3:].lower():
        print(word)





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

procedure Find_Three_Equals is
   use Ada.Text_Io;
   use Ada.Strings.Fixed;

   Filename : constant String := "unixdict.txt";
   File     : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word  : constant String  := Get_Line (File);
         First : String renames Head (Word, 3);
         Last  : String renames Tail (Word, 3);
      begin
         if First = Last and Word'Length > 5 then
            Put_Line (Word);
         end if;
      end;
   end loop;
   Close (File);
end Find_Three_Equals;
Task: Find words which contain the most consonants







Python: print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in
      (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w)
      for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if len(l) > 10 and all(c >= 'a' and c <= 'z' for c in l)]
      if sorted(c := w.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')) == sorted(set(c))])[0]) else None)





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

procedure Most_Consonants is
   use Ada.Text_Io;

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

   function Is_Vowel (Letter : Character) return Boolean
   is (Ada.Strings.Fixed.Index ("aeiou", "" & Letter) /= 0);

   type Consonant_Count is range 0 .. 15;
   Filename : constant String := "unixdict.txt";
   File     : File_Type;
   Words    : array (Consonant_Count) of String_Vectors.Vector;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word  : constant String  := Get_Line (File);
         Found : array (Character) of Boolean := (others => False);
         Conso : Consonant_Count := 0;
         Bad   : Boolean         := False;
      begin
         for Letter of Word loop
            if Is_Vowel (Letter) then
               null;
            elsif Found (Letter) then
               Bad := True;
            else
               Found (Letter) := True;
               Conso := Conso + 1;
            end if;
         end loop;
         if not Bad and Word'Length > 10 then
            Words (Conso).Append (Word);
         end if;
      end;
   end loop;
   Close (File);


   for Cons in Words'Range loop
      if not Words (Cons).Is_Empty then
         Put (Cons'Image & " consonants: ");
         Put (Words (Cons).Length'Image & " words");
         New_Line;
      end if;
      declare
         Column : Natural := 0;
         Image  : String (1 .. 15);
      begin
         for Word of Words (Cons) loop
            Ada.Strings.Fixed.Move (Word, Image);
            Put (Image);
            Column := Column + 1;
            if Column mod 8 = 0 then
               New_Line;
            end if;
         end loop;
      end;
      if not Words (Cons).Is_Empty then
         New_Line;
      end if;
   end loop;

end Most_Consonants;
Task: Find words which contains all the vowels







Python: import urllib.request
from collections import Counter

urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

for word in wordList:
    if len(word)>10:
        frequency = Counter(word.lower())
        if frequency['a']==frequency['e']==frequency['i']==frequency['o']==frequency['u']==1:
            print(word)





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

procedure Find_All_Vowels is
   use Ada.Text_Io;
   use Ada.Strings;

   type Vowels     is ('a', 'e', 'i', 'o', 'u');
   type Count_Type is array (Vowels) of Natural;

   Filename : constant String := "unixdict.txt";
   Chars    : constant array (Vowels) of Character := "aeiou";
   File     : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word  : constant String  := Get_Line (File);
         Count : Count_Type;
      begin
         for Vowel in Vowels loop
            Count (Vowel) := Fixed.Count (Word, Maps.To_Set (Chars (Vowel)));
         end loop;

         if Count = Count_Type'(others => 1) and Word'Length > 10 then
            Put_Line (Word);
         end if;
      end;
   end loop;
   Close (File);
end Find_All_Vowels;
Task: Odd words







Python: 

import urllib.request
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")

dictionary = open("unixdict.txt","r")

wordList = dictionary.read().split('\n')

dictionary.close()

oddWordSet = set({})

for word in wordList:
    if len(word)>=9 and word[::2] in wordList:
        oddWordSet.add(word[::2])

[print(i) for i in sorted(oddWordSet)]





Ada: with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;

procedure Odd_Words is
   use Ada.Text_Io;

   package String_Maps is
     new Ada.Containers.Indefinite_Ordered_Maps (Key_Type     => String,
                                                 Element_Type => String);

   Filename : constant String := "unixdict.txt";
   Words    : String_Maps.Map;

   function Get_Odd (Word : String) return String is
      Odd : String (1 .. (Word'Length + 1) / 2);
   begin
      for Index in Odd'Range loop
         Odd (Index) := Word (1 + 2 * (Index - 1));
      end loop;
      return Odd;
   end Get_Odd;

   function Get_Even (Word : String) return String is
      Even : String (1 .. Word'Length / 2);
   begin
      for Index in Even'Range loop
         Even (Index) := Word (1 + 1 + 2 * (Index - 1));
      end loop;
      return Even;
   end Get_Even;

   generic
      with function Filter (Word : String) return String;
   procedure Iterate_Map;

   procedure Iterate_Map is
   begin
      for Word of Words loop
         declare
            Half : constant String := Filter (Word);
         begin
            if Half'Length > 4 and then Words.Contains (Half) then
               Put (Word); Set_Col (15); Put_Line (Half);
            end if;
         end;
      end loop;
   end Iterate_Map;

   procedure Put_Odd_Words  is new Iterate_Map (Get_Odd);
   procedure Put_Even_Words is new Iterate_Map (Get_Even);

   File : File_Type;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         Words.Insert (Word, Word);
      end;
   end loop;
   Close (File);

   Put_Line ("Odd words:");
   Put_Odd_Words;
   New_Line;

   Put_Line ("Even words:");
   Put_Even_Words;
end Odd_Words;
Task: Common list elements







Python: 

def common_list_elements(*lists):
    return list(set.intersection(*(set(list_) for list_ in lists)))


if __name__ == "__main__":
    test_cases = [
        ([2, 5, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 9, 8, 4], [1, 3, 7, 6, 9]),
        ([2, 2, 1, 3, 8, 9, 4, 6], [3, 5, 6, 2, 2, 2, 4], [2, 3, 7, 6, 2]),
    ]

    for case in test_cases:
        result = common_list_elements(*case)
        print(f"Intersection of {case} is {result}")





Ada: with Ada.Text_Io;
with Ada.Containers.Vectors;

procedure Common is

   package Integer_Vectors is
     new Ada.Containers.Vectors (Index_Type   => Positive,
                                 Element_Type => Integer);
   use Integer_Vectors;

   function Common_Elements (Left, Right : Vector) return Vector is
      Res : Vector;
   begin
      for E of Left loop
         if Has_Element (Right.Find (E)) then
            Res.Append (E);
         end if;
      end loop;
      return Res;
   end Common_Elements;

   procedure Put (Vec : Vector) is
      use Ada.Text_Io;
   begin
      Put ("[");
      for E of Vec loop
         Put (E'Image);  Put (" ");
      end loop;
      Put ("]");
      New_Line;
   end Put;

   A : constant Vector := 2 & 5 & 1 & 3 & 8 & 9 & 4 & 6;
   B : constant Vector := 3 & 5 & 6 & 2 & 9 & 8 & 4;
   C : constant Vector := 1 & 3 & 7 & 6 & 9;
   R : Vector;
begin
   R := Common_Elements (A, B);
   R := Common_Elements (R, C);
   Put (R);
end Common;
Task: Maze solving







Python: 

def Dijkstra(Graph, source):
    
    
    infinity = float('infinity')
    n = len(graph)
    dist = [infinity]*n   
    previous = [infinity]*n 
    dist[source] = 0        
    Q = list(range(n)) 
    while Q:           
        u = min(Q, key=lambda n:dist[n])                 
        Q.remove(u)
        if dist[u] == infinity:
            break 
        for v in range(n):               
            if Graph[u][v] and (v in Q): 
                alt = dist[u] + Graph[u][v]
                if alt < dist[v]:       
                    dist[v] = alt
                    previous[v] = u
    return dist,previous

def display_solution(predecessor):
    cell = len(predecessor)-1
    while cell:
        print(cell,end='<')
        cell = predecessor[cell]
    print(0)





Ada: with Ada.Text_IO;

procedure Maze_Solver is

   X_Size: constant Natural := 45;
   Y_Size: constant Natural := 17;

   subtype X_Range is Natural range 1 .. X_Size;
   subtype Y_Range is Natural range 1 .. Y_Size;

   East:  constant X_Range := 2;
   South: constant Y_Range := 1;

   X_Start: constant X_Range  := 3; 
   Y_Start: constant Y_Range  := 1;
   X_Finish: constant X_Range := X_Size-East; 
   Y_Finish: constant Y_Range := Y_Size; 

   type Maze_Type is array (Y_Range) of String(X_Range);

   function Solved(X: X_Range; Y: Y_Range) return Boolean is
   begin
      return (X = X_Finish) and (Y = Y_Finish);
   end Solved;

   procedure Output_Maze(M: Maze_Type; Message: String := "") is
   begin
      if Message /= "" then
         Ada.Text_IO.Put_Line(Message);
      end if;
      for I in M'Range loop
         Ada.Text_IO.Put_Line(M(I));
      end loop;
   end Output_Maze;

   procedure Search(M: in out Maze_Type; X: X_Range; Y:Y_Range) is
   begin
      M(Y)(X) := '*';
      if Solved(X, Y) then
         Output_Maze(M, "Solution found!");
      else
         if Integer(Y)-South >= 1 and then M(Y-South)(X) = ' ' then
            Search(M, X, Y-South);
         end if;
         if Integer(Y)+South <= Y_Size and then M(Y+South)(X) = ' ' then
            Search(M, X, Y+South);
         end if;
         if Integer(X)-East >= 1 and then M(Y)(X-East) = ' ' then
            Search(M, X-East, Y);
         end if;
         if Integer(Y)+East <= Y_Size and then M(Y)(X+East) = ' ' then
            Search(M, X+East, Y);
         end if;
      end if;
      M(Y)(X) := ' ';
   end Search;

   Maze: Maze_Type;
   X: X_Range := X_Start;
   Y: Y_Range := Y_Start;

begin
   for I in 1 .. Y_Size loop
      Maze(I) := Ada.Text_IO.Get_Line;
   end loop;
   Maze(Y_Start)(X_Start)   := ' '; 
   Maze(Y_Finish)(X_Finish) := ' '; 
   Output_Maze(Maze, "The Maze:");
   Ada.Text_IO.New_Line;

   Search(Maze, X, Y) ; 
                        
end Maze_Solver;