WeixiangYan/CodeTransOcean huggingface dataset:
Task: Optional parameters







Python: >>> def printtable(data):
    for row in data:
        print ' '.join('%-5s' % ('"%s"' % cell) for cell in row)

        
>>> import operator
>>> def sorttable(table, ordering=None, column=0, reverse=False):
    return sorted(table, cmp=ordering, key=operator.itemgetter(column), reverse=reverse)

>>> data = [["a", "b", "c"], ["", "q", "z"], ["zap", "zip", "Zot"]]
>>> printtable(data)
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data) )
""    "q"   "z"  
"a"   "b"   "c"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=2) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>> printtable( sorttable(data, column=1) )
"a"   "b"   "c"  
""    "q"   "z"  
"zap" "zip" "Zot"
>>> printtable( sorttable(data, column=1, reverse=True) )
"zap" "zip" "Zot"
""    "q"   "z"  
"a"   "b"   "c"  
>>> printtable( sorttable(data, ordering=lambda a,b: cmp(len(b),len(a))) )
"zap" "zip" "Zot"
"a"   "b"   "c"  
""    "q"   "z"  
>>>





Ada: package Tables is

   type Table is private;

   type Ordering is (Lexicographic, Psionic, ...); 

   procedure Sort (It               : in out Table;
                   Order_By         : in Ordering := Lexicographic;
                   Column           : in Positive := 1;
                   Reverse_Ordering : in Boolean  := False);

private
   ... 
end Tables;
Task: Trabb Pardo–Knuth algorithm







Python: Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3

>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
	           for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))

11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>





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

procedure Trabb_Pardo_Knuth is

   type Real is digits 6 range -400.0 .. 400.0;

   package TIO renames Ada.Text_IO;
   package FIO is new TIO.Float_IO(Real);
   package Math is new  Ada.Numerics.Generic_Elementary_Functions(Real);

   function F(X: Real) return Real is
   begin
      return (Math.Sqrt(abs(X)) + 5.0 * X**3);
   end F;

   Values: array(1 .. 11) of Real;

begin
   TIO.Put("Please enter 11 Numbers:");
   for I in Values'Range loop
      FIO.Get(Values(I));
   end loop;

   for I in reverse Values'Range loop
      TIO.Put("f(");
      FIO.Put(Values(I), Fore => 2, Aft => 3, Exp => 0);
      TIO.Put(")=");
      begin
         FIO.Put(F(Values(I)), Fore=> 4, Aft => 3, Exp => 0);
      exception
         when Constraint_Error => TIO.Put("
      end;
      TIO.New_Line;
   end loop;

end Trabb_Pardo_Knuth;
Task: Dice game probabilities







Python: from itertools import product

def gen_dict(n_faces, n_dice):
    counts = [0] * ((n_faces + 1) * n_dice)
    for t in product(range(1, n_faces + 1), repeat=n_dice):
        counts[sum(t)] += 1
    return counts, n_faces ** n_dice

def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2):
    c1, p1 = gen_dict(n_sides1, n_dice1)
    c2, p2 = gen_dict(n_sides2, n_dice2)
    p12 = float(p1 * p2)

    return sum(p[1] * q[1] / p12
               for p, q in product(enumerate(c1), enumerate(c2))
               if p[0] > q[0])

print beating_probability(4, 9, 6, 6)
print beating_probability(10, 5, 7, 6)





Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Main is
   package real_io is new Float_IO (Long_Float);
   use real_io;

   type Dice is record
      Faces    : Positive;
      Num_Dice : Positive;
   end record;

   procedure Roll_Dice (The_Dice : in Dice; Count : out Natural) is
      subtype Faces is Integer range 1 .. The_Dice.Faces;
      package Die_Random is new Ada.Numerics.Discrete_Random (Faces);
      use Die_Random;
      Seed : Generator;
   begin
      Reset (Seed);
      Count := 0;
      for I in 1 .. The_Dice.Num_Dice loop
         Count := Count + Random (Seed);
      end loop;
   end Roll_Dice;

   function Win_Prob
     (Dice_1 : Dice; Dice_2 : Dice; Tries : Positive) return Long_Float
   is
      Count_1      : Natural := 0;
      Count_2      : Natural := 0;
      Count_1_Wins : Natural := 0;
   begin
      for I in 1 .. Tries loop
         Roll_Dice (Dice_1, Count_1);
         Roll_Dice (Dice_2, Count_2);
         if Count_1 > Count_2 then
            Count_1_Wins := Count_1_Wins + 1;
         end if;
      end loop;
      return Long_Float (Count_1_Wins) / Long_Float (Tries);
   end Win_Prob;

   D1 : Dice := (Faces => 4, Num_Dice => 9);
   D2 : Dice := (Faces => 6, Num_Dice => 6);
   D3 : Dice := (Faces => 10, Num_Dice => 5);
   D4 : Dice := (Faces => 7, Num_Dice => 6);

   P1 : Long_Float := Win_Prob (D1, D2, 1_000_000);
   P2 : Long_Float := Win_Prob (D3, D4, 1_000_000);
begin
   Put ("Dice D1 wins = ");
   Put (Item => P1, Fore => 1, Aft => 7, Exp => 0);
   New_Line;
   Put ("Dice D2 wins = ");
   Put (Item => P2, Fore => 1, Aft => 7, Exp => 0);
   New_Line;
end Main;
Task: Metronome







Python: 
import time

def main(bpm = 72, bpb = 4):
    sleep = 60.0 / bpm
    counter = 0
    while True:
        counter += 1
        if counter % bpb:
            print 'tick'
        else:
            print 'TICK'
        time.sleep(sleep)
        


main()





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

 
with Ada.Calendar;  use Ada.Calendar;

 
with Ada.Characters.Latin_1;

procedure Main is

begin

   Put_Line ("Hello, this is 60 BPM");
   
   loop

      Ada.Text_IO.Put (Ada.Characters.Latin_1.BEL);
      delay 0.9; 
      
   end loop;

end Main;
Task: Sum of elements below main diagonal of matrix







Python: from numpy import array, tril, sum

A = [[1,3,7,8,10],
    [2,4,16,14,4],
    [3,1,9,18,11],
    [12,14,17,18,20],
    [7,1,3,9,5]]

print(sum(tril(A, -1)))   





Ada: with Ada.Text_Io;
with Ada.Numerics.Generic_Real_Arrays;

procedure Sum_Below_Diagonals is

   type Real is new Float;

   package Real_Arrays
   is new Ada.Numerics.Generic_Real_Arrays (Real);

   function Sum_Below_Diagonal (M : Real_Arrays.Real_Matrix) return Real
   with Pre => M'Length (1) = M'Length (2)
   is
      Sum : Real := 0.0;
   begin
      for Row in 0 .. M'Length (1) - 1 loop
         for Col in 0 .. Row - 1 loop
            Sum := Sum + M (M'First (1) + Row,
                            M'First (2) + Col);
         end loop;
      end loop;
      return Sum;
   end Sum_Below_Diagonal;

   M : constant Real_Arrays.Real_Matrix :=
     (( 1.0,  3.0,  7.0,  8.0, 10.0),
      ( 2.0,  4.0, 16.0, 14.0,  4.0),
      ( 3.0,  1.0,  9.0, 18.0, 11.0),
      (12.0, 14.0, 17.0, 18.0, 20.0),
      ( 7.0,  1.0,  3.0,  9.0,  5.0));
   Sum : constant Real := Sum_Below_Diagonal (M);

   package Real_Io is new Ada.Text_Io.Float_Io (Real);
   use Ada.Text_Io, Real_Io;
begin
   Put ("Sum below diagonal: ");
   Put (Sum, Exp => 0, Aft => 1);
   New_Line;
end Sum_Below_Diagonals;
Task: Rep-string







Python: def is_repeated(text):
    'check if the first part of the string is repeated throughout the string'
    for x in range(len(text)//2, 0, -1):
        if text.startswith(text[x:]): return x
    return 0

matchstr = 
for line in matchstr.split():
    ln = is_repeated(line)
    print('%r has a repetition length of %i i.e. %s' 
           % (line, ln, repr(line[:ln]) if ln else '*not* a rep-string'))





Ada: with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed;

procedure Rep_String is
   
   function Find_Largest_Rep_String(S:String) return String is
      L: Natural := S'Length;
   begin
      for I in reverse 1 .. L/2 loop
	 declare
	    use Ada.Strings.Fixed;
	    T: String := S(S'First .. S'First + I-1); 
	    U: String := (1+(L/I)) * T; 
	 begin 
	    if U(U'First .. U'First + S'Length -1) = S then
	       return T; 
	    end if;
	 end;
      end loop;
      return ""; 
   end Find_Largest_Rep_String;
   
   X: String := Ada.Command_Line.Argument(1);
   Y: String := Find_Largest_Rep_String(X);
   
begin
   if Y="" then
      Ada.Text_IO.Put_Line("No rep-string for """ & X & """");
   else
      Ada.Text_IO.Put_Line("Longest rep-string for """& X &""": """& Y &"""");
   end if;
end Rep_String;
Task: File size distribution







Python: import sys, os
from collections import Counter

def dodir(path):
    global h

    for name in os.listdir(path):
        p = os.path.join(path, name)

        if os.path.islink(p):
            pass
        elif os.path.isfile(p):
            h[os.stat(p).st_size] += 1
        elif os.path.isdir(p):
            dodir(p)
        else:
            pass

def main(arg):
    global h
    h = Counter()
    for dir in arg:
        dodir(dir)

    s = n = 0
    for k, v in sorted(h.items()):
        print("Size %d -> %d file(s)" % (k, v))
        n += v
        s += k * v
    print("Total %d bytes for %d files" % (s, n))

main(sys.argv[1:])





Ada: with Ada.Numerics.Elementary_Functions;
with Ada.Directories;    use Ada.Directories;
with Ada.Strings.Fixed;  use Ada.Strings;
with Ada.Command_Line;   use Ada.Command_Line;
with Ada.Text_IO;        use Ada.Text_IO;

with Dir_Iterators.Recursive;

procedure File_Size_Distribution is

   type Exponent_Type is range 0 .. 18;
   type File_Count    is range 0 .. Long_Integer'Last;
   Counts         : array (Exponent_Type) of File_Count := (others => 0);
   Non_Zero_Index : Exponent_Type   := 0;
   Directory_Name : constant String := (if Argument_Count = 0
                                        then "."
                                        else Argument (1));
   Directory_Walker : Dir_Iterators.Recursive.Recursive_Dir_Walk
     := Dir_Iterators.Recursive.Walk (Directory_Name);
begin
   if not Exists (Directory_Name) or else Kind (Directory_Name) /= Directory then
      Put_Line ("Directory does not exist");
      return;
   end if;

   for Directory_Entry of Directory_Walker loop
      declare
         use Ada.Numerics.Elementary_Functions;
         Size_Of_File : File_Size;
         Exponent     : Exponent_Type;
      begin
         if Kind (Directory_Entry) = Ordinary_File then
            Size_Of_File := Size (Directory_Entry);
            if Size_Of_File = 0 then
               Counts (0) := Counts (0) + 1;
            else
               Exponent := Exponent_Type (Float'Ceiling (Log (Float (Size_Of_File),
                                                              Base => 10.0)));
               Counts (Exponent) := Counts (Exponent) + 1;
            end if;
         end if;
      end;
   end loop;

   for I in reverse Counts'Range loop
      if Counts (I) /= 0 then
         Non_Zero_Index := I;
         exit;
      end if;
   end loop;

   for I in Counts'First .. Non_Zero_Index loop
      Put ("Less than 10**");
      Put (Fixed.Trim (Exponent_Type'Image (I), Side => Left));
      Put (": ");
      Put (File_Count'Image (Counts (I)));
      New_Line;
   end loop;
end File_Size_Distribution;
Task: Topswops







Python: >>> from itertools import permutations
>>> def f1(p):
	i = 0
	while True:
		p0  = p[0]
		if p0 == 1: break
		p[:p0] = p[:p0][::-1]
		i  += 1
	return i

>>> def fannkuch(n):
	return max(f1(list(p)) for p in permutations(range(1, n+1)))

>>> for n in range(1, 11): print(n,fannkuch(n))

1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
9 30
10 38
>>>





Ada: with Ada.Integer_Text_IO, Generic_Perm;

procedure Topswaps is
   
   function Topswaps(Size: Positive) return Natural is
      package Perms is new Generic_Perm(Size);
      P: Perms.Permutation;
      Done: Boolean;
      Max: Natural;
      
      function Swapper_Calls(P: Perms.Permutation) return Natural is
	 Q: Perms.Permutation := P;
	 I: Perms.Element := P(1);
      begin
	 if I = 1 then 
	    return 0;
	 else
	    for Idx in 1 .. I loop
	       Q(Idx) := P(I-Idx+1);
	    end loop;
	    return 1 + Swapper_Calls(Q);
	 end if;
      end Swapper_Calls;
      
   begin
      Perms.Set_To_First(P, Done);
      Max:= Swapper_Calls(P);
      while not Done loop
	 Perms.Go_To_Next(P, Done);
	 Max := natural'Max(Max, Swapper_Calls(P));
      end loop;
      return Max;
   end Topswaps;
   
begin
   for I in 1 .. 10 loop
      Ada.Integer_Text_IO.Put(Item => Topswaps(I), Width => 3);
   end loop;
end Topswaps;
Task: Sequence_ smallest number greater than previous term with exactly n divisors







Python: def divisors(n):
    divs = [1]
    for ii in range(2, int(n ** 0.5) + 3):
        if n % ii == 0:
            divs.append(ii)
            divs.append(int(n / ii))
    divs.append(n)
    return list(set(divs))


def sequence(max_n=None):
    previous = 0
    n = 0
    while True:
        n += 1
        ii = previous
        if max_n is not None:
            if n > max_n:
                break
        while True:
            ii += 1
            if len(divisors(ii)) == n:
                yield ii
                previous = ii
                break


if __name__ == '__main__':
    for item in sequence(15):
        print(item)





Ada: with Ada.Text_IO;

procedure Show_Sequence is

   function Count_Divisors (N : in Natural) return Natural is
      Count : Natural := 0;
      I     : Natural;
   begin
      I := 1;
      while I**2 <= N loop
         if N mod I = 0 then
            if I = N / I then
               Count := Count + 1;
            else
               Count := Count + 2;
            end if;
         end if;
         I := I + 1;
      end loop;

      return Count;
   end Count_Divisors;

   procedure Show (Max : in Natural) is
      use Ada.Text_IO;
      N : Natural := 1;
   Begin
      Put_Line ("The first" & Max'Image & "terms of the sequence are:");
      for Divisors in 1 .. Max loop
         while Count_Divisors (N) /= Divisors loop
            N := N + 1;
         end loop;
         Put (N'Image);
      end loop;
      New_Line;
   end Show;

begin
   Show (15);
end Show_Sequence;
Task: McNuggets problem







Python: >>> from itertools import product
>>> nuggets = set(range(101))
>>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)):
	nuggets.discard(6*s + 9*n + 20*t)

	
>>> max(nuggets)
43
>>>





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

procedure McNugget is
   Limit : constant                      := 100;
   List  : array (0 .. Limit) of Boolean := (others => False);
   N     : Integer;
begin
   for A in 0 .. Limit / 6 loop
      for B in 0 .. Limit / 9 loop
         for C in 0 .. Limit / 20 loop
            N := A * 6 + B * 9 + C * 20;
            if N <= 100 then
               List (N) := True;
            end if;
         end loop;
      end loop;
   end loop;
   for N in reverse 1 .. Limit loop
      if not List (N) then
         Put_Line ("The largest non McNugget number is:" & Integer'Image (N));
         exit;
      end if;
   end loop;
end McNugget;
Task: Idiomatically determine all the lowercase and uppercase letters







Python: classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
           str.isspace, str.istitle)

for stringclass in classes:
    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
    print('\nString class %s has %i characters the first of which are:\n  %r'
          % (stringclass.__name__, len(chars), chars[:100]))





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

procedure Main is
   subtype Lower is Character range 'a' .. 'z';
   subtype Upper is Character range 'A' .. 'Z';
begin
   Put ("Lower: ");
   for c in Lower'range loop
      Put (c);
   end loop;
   New_Line;
   Put ("Upper: ");
   for c in Upper'range loop
      Put (c);
   end loop;
   New_Line;
end Main;
Task: Superellipse







Python: 


import matplotlib.pyplot as plt
from math import sin, cos, pi

def sgn(x):
	return ((x>0)-(x<0))*1

a,b,n=200,200,2.5 
na=2/n
step=100 
piece=(pi*2)/step
xp=[];yp=[]

t=0
for t1 in range(step+1):
	
	x=(abs((cos(t)))**na)*a*sgn(cos(t))
	y=(abs((sin(t)))**na)*b*sgn(sin(t))
	xp.append(x);yp.append(y)
	t+=piece

plt.plot(xp,yp) 
plt.title("Superellipse with parameter "+str(n))
plt.show()





Ada: with Ada.Numerics.Elementary_Functions;

with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;

procedure Superelipse is

   Width  : constant := 600;
   Height : constant := 600;
   A      : constant := 200.0;
   B      : constant := 200.0;
   N      : constant := 2.5;

   Window   : SDL.Video.Windows.Window;
   Renderer : SDL.Video.Renderers.Renderer;
   Event    : SDL.Events.Events.Events;

   procedure Draw_Superelipse
   is
      use type SDL.C.int;
      use Ada.Numerics.Elementary_Functions;
      Xx, Yy : Float;
      subtype Legal_Range is Float range 0.980 .. 1.020;
   begin
      for Y in 0 .. Height loop
         for X in 0 .. Width loop
            Xx := Float (X - Width  / 2);
            Yy := Float (Y - Height / 2);
            if (abs (Xx / A)) ** N + (abs (Yy / B)) ** N in Legal_Range then
               Renderer.Draw (Point => (X => Width  / 2 + SDL.C.int (Xx),
                                        Y => Height / 2 - SDL.C.int (Yy)));
            end if;

         end loop;
      end loop;
   end Draw_Superelipse;

   procedure Wait is
      use type SDL.Events.Event_Types;
   begin
      loop
         while SDL.Events.Events.Poll (Event) loop
            if Event.Common.Event_Type = SDL.Events.Quit then
               return;
            end if;
         end loop;
         delay 0.100;
      end loop;
   end Wait;

begin
   if not SDL.Initialise (Flags => SDL.Enable_Screen) then
      return;
   end if;

   SDL.Video.Windows.Makers.Create (Win      => Window,
                                    Title    => "Superelipse",
                                    Position => SDL.Natural_Coordinates'(X => 10, Y => 10),
                                    Size     => SDL.Positive_Sizes'(Width, Height),
                                    Flags    => 0);
   SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);
   Renderer.Set_Draw_Colour ((0, 0, 0, 255));
   Renderer.Fill (Rectangle => (0, 0, Width, Height));
   Renderer.Set_Draw_Colour ((0, 220, 0, 255));

   Draw_Superelipse;
   Window.Update_Surface;

   Wait;
   Window.Finalize;
   SDL.Finalise;
end Superelipse;
Task: Mutex







Python: import threading
from time import sleep



res = 2
sema = threading.Semaphore(res)

class res_thread(threading.Thread):
    def run(self):
        global res
        n = self.getName()
        for i in range(1, 4):
            
            
            
            sema.acquire()
            res = res - 1
            print n, "+  res count", res
            sleep(2)

                        
            res = res + 1
            print n, "-  res count", res
            sema.release()


for i in range(1, 5):
    t = res_thread()
    t.start()





Ada: protected type Mutex is
   entry Seize;
   procedure Release;
private
   Owned : Boolean := False;
end Mutex;
Task: Odd word problem







Python: from sys import stdin, stdout

def char_in(): return stdin.read(1)
def char_out(c): stdout.write(c)

def odd(prev = lambda: None):
	a = char_in()
	if not a.isalpha():
		prev()
		char_out(a)
		return a != '.'

	
	def clos():
		char_out(a)
		prev()

	return odd(clos)

def even():
	while True:
		c = char_in()
		char_out(c)
		if not c.isalpha(): return c != '.'

e = False
while odd() if e else even():
	e = not e





Ada: with Ada.Text_IO;
 
procedure Odd_Word_Problem is
 
   use Ada.Text_IO; 
 
   function Current return Character is
      
      End_Of_Line: Boolean;
      C: Character;
   begin
      Look_Ahead(C, End_Of_Line);
      if End_Of_Line then
         raise Constraint_Error with "end of line before the terminating '.'";
      end if;
      return C;
   end Current;
 
   procedure Skip is
      
      C: Character;
   begin
      Get(C);
   end Skip;
 
   function Is_Alpha(Ch: Character) return Boolean is
   begin
      return (Ch in  'a' .. 'z') or (Ch in 'A' .. 'Z');
   end Is_Alpha;
 
   procedure Odd_Word(C: Character) is
   begin
      if Is_Alpha(C) then
         Skip;
         Odd_Word(Current);
         Put(C);
      end if;
   end Odd_Word;
 
begin 
   Put(Current);
   while Is_Alpha(Current) loop 
      Skip;
      Put(Current);
   end loop;
   if Current /= '.' then 
      Skip;
      Odd_Word(Current);
      Put(Current);
      if Current /= '.' then 
         Skip;
         Odd_Word_Problem;
      end if;
   end if;
end Odd_Word_Problem;
Task: Pseudo-random numbers_PCG32







Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005


class PCG32():
    
    def __init__(self, seed_state=None, seed_sequence=None):
        if all(type(x) == int for x in (seed_state, seed_sequence)):
            self.seed(seed_state, seed_sequence)
        else:
            self.state = self.inc = 0
    
    def seed(self, seed_state, seed_sequence):
        self.state = 0
        self.inc = ((seed_sequence << 1) | 1) & mask64
        self.next_int()
        self.state = (self.state + seed_state)
        self.next_int()
        
    def next_int(self):
        "return random 32 bit unsigned int"
        old = self.state
        self.state = ((old * CONST) + self.inc) & mask64
        xorshifted = (((old >> 18) ^ old) >> 27) & mask32
        rot = (old >> 59) & mask32
        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
        answer = answer &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 = PCG32()
    random_gen.seed(42, 54)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321, 1)
    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;

package random_pcg32 is
   function Next_Int return Unsigned_32;
   function Next_Float return Long_Float;
   procedure Seed (seed_state : Unsigned_64; seed_sequence : Unsigned_64);
end random_pcg32;
Task: Memory layout of a data structure







Python: from ctypes import Structure, c_int

rs232_9pin  = "_0 CD RD TD DTR SG DSR RTS CTS RI".split()
rs232_25pin = ( "_0  PG  TD  RD  RTS CTS DSR SG  CD  pos neg"
                "_11 SCD SCS STD TC  SRD RC"
                "_18 SRS DTR SQD RI DRS XTC" ).split()

class RS232_9pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_9pin]

	
class RS232_25pin(Structure):
    _fields_ = [(__, c_int, 1) for __ in rs232_25pin]





Ada: type Bit is mod 2;
type Rs_232_Layout is record
   Carrier_Detect      : Bit;
   Received_Data       : Bit;
   Transmitted_Data    : Bit;
   Data_Terminal_ready : Bit;
   Signal_Ground       : Bit;
   Data_Set_Ready      : Bit;
   Request_To_Send     : Bit;
   Clear_To_Send       : Bit;
   Ring_Indicator      : Bit;
end record;

for Rs_232_Layout use record
   Carrier_Detect      at 0 range 0..0;
   Received_Data       at 0 range 1..1;
   Transmitted_Data    at 0 range 2..2;
   Data_Terminal_Ready at 0 range 3..3;
   Signal_Ground       at 0 range 4..4;
   Data_Set_Ready      at 0 range 5..5;
   Request_To_Send     at 0 range 6..6;
   Clear_To_Send       at 0 range 7..7;
   Ring_Indicator      at 0 range 8..8;
end record;
Task: Largest proper divisor of n







Python: def lpd(n):
    for i in range(n-1,0,-1):
        if n%i==0: return i
    return 1

for i in range(1,101):
    print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')





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

procedure Main is
   subtype param_type is Integer range 1 .. 100;
   function lpd (n : in param_type) return param_type is
      result : param_type := 1;
   begin
      for divisor in reverse 1 .. n / 2 loop
         if n rem divisor = 0 then
            result := divisor;
            exit;
         end if;
      end loop;
      return result;
   end lpd;

begin
   for I in param_type loop
      Put (Item => lpd (I), Width => 3);
      if I rem 10 = 0 then
         New_Line;
      end if;
   end loop;
end Main;