WeixiangYan/CodeTransOcean huggingface dataset:
Task: ABC words


C++: #include <cstdlib>
#include <fstream>
#include <iostream>

bool is_abc_word(const std::string& word) {
    bool a = false;
    bool b = false;
    for (char ch : word) {
        switch (ch) {
        case 'a':
            if (!a)
                a = true;
            break;
        case 'b':
            if (!b) {
                
                if (!a)
                    return false;
                b = true;
            }
            break;
        case 'c':
            
            return b;
        }
    }
    return false;
}

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string word;
    int n = 1;
    while (getline(in, word)) {
        if (is_abc_word(word))
            std::cout << n++ << ": " << word << '\n';
    }
    return EXIT_SUCCESS;
}










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

procedure Abc_Words is
   use Ada.Text_Io;

   function Is_Abc_Word (Word : String) return Boolean is
      use Ada.Strings.Fixed;
      Pos_A : constant Natural := Index (Word, "a");
      Pos_B : constant Natural := Index (Word, "b");
      Pos_C : constant Natural := Index (Word, "c");
   begin
      return
        Pos_B > Pos_A and Pos_C > Pos_B and
        Pos_A /= 0 and Pos_B /= 0 and Pos_C /= 0;
   end Is_Abc_Word;

   Filename : constant String := "unixdict.txt";
   File     : File_Type;
   Column   : Ada.Text_Io.Count := 0;
begin
   Open (File, In_File, Filename);
   while not End_Of_File (File) loop
      declare
         Word : constant String := Get_Line (File);
      begin
         if Is_Abc_Word (Word) then
            Set_Col (1 + Column);
            Column := (Column + 15) mod 120;
            Put (Word);
         end if;
      end;
   end loop;
   Close (File);
end Abc_Words;
Task: Two identical strings


C++: #include <iostream>
#include <string>



void base2_increment(std::string& s) {
    size_t z = s.rfind('0');
    if (z != std::string::npos) {
        s[z] = '1';
        size_t count = s.size() - (z + 1);
        s.replace(z + 1, count, count, '0');
    } else {
        s.assign(s.size() + 1, '0');
        s[0] = '1';
    }
}

int main() {
    std::cout << "Decimal\tBinary\n";
    std::string s("1");
    for (unsigned int n = 1; ; ++n) {
        unsigned int i = n + (n << s.size());
        if (i >= 1000)
            break;
        std::cout << i << '\t' << s << s << '\n';
        base2_increment(s);
    }
}










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

procedure Two_Identical is
   package Integer_Io is
     new Ada.Text_Io.Integer_Io (Integer);
   use Integer_Io;

   Image : String (1 .. 16);
   Pos_1, Pos_2 : Natural;
   Mid  : Natural;
begin
   for N in 1 .. 1000 loop
      Put (Image, N, Base => 2);
      Pos_1 := Index (Image, "#");
      Pos_2 := Index (Image, "#", Pos_1 + 1);
      Mid := (Pos_1 + Pos_2) / 2;
      if Image (Pos_1 + 1 .. Mid) = Image (Mid + 1 .. Pos_2 - 1) then
         Put (N, Width => 3); Put ("  "); Put (Image); New_Line;
      end if;
   end loop;
end Two_Identical;
Task: Sum of first n cubes


C++: #include <array>
#include <cstdio>
#include <numeric>

void PrintContainer(const auto& vec)
{
    int count = 0;
    for(auto value : vec)
    {
        printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' ');
    }
}

int main()
{
    
    auto cube = [](auto x){return x * x * x;};

    
    std::array<int, 50> a;
    std::iota(a.begin(), a.end(), 0);

    
    
    
    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);
    PrintContainer(a);    
}










Ada: with Ada.Text_Io;

procedure Sum_Of_First_N_Cubes is

   Columns : constant := 10;
   Width   : constant := 8;

   package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
   use Ada.Text_Io, Natural_Io;

   Sum : Natural := 0;
begin
   for N in 0 .. 49 loop
      Sum := Sum + N ** 3;
      Put (Sum, Width => Width);
      if N mod Columns = Columns - 1 then
         New_Line;
      end if;
   end loop;
   New_Line;
end Sum_Of_First_N_Cubes;
Task: CSV to HTML translation


C++: #include <string>
#include <boost/regex.hpp>
#include <iostream>

std::string csvToHTML( const std::string & ) ;

int main( ) {
   std::string text = "Character,Speech\n" 
                            "The multitude,The messiah! Show us the messiah!\n" 
			    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n" 
	                    "The multitude,Who are you?\n" 
		            "Brians mother,I'm his mother; that's who!\n" 
		            "The multitude,Behold his mother! Behold his mother!\n" ;
  std::cout << csvToHTML( text ) ;
  return 0 ;
}

std::string csvToHTML( const std::string & csvtext ) {
   
   std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
   const char* replacements [ 5 ] = { "&lt;" , "&gt;" , "    <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n"  } ;  
   boost::regex e1( regexes[ 0 ] ) ; 
   std::string tabletext = boost::regex_replace( csvtext , e1 ,
     replacements[ 0 ] , boost::match_default | boost::format_all ) ;
   for ( int i = 1 ; i < 5 ; i++ ) {
      e1.assign( regexes[ i ] ) ;
      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
   }
   tabletext = std::string( "<TABLE>\n" ) + tabletext ;
   tabletext.append( "</TABLE>\n" ) ;
   return tabletext ;
}










Ada: with Ada.Strings.Fixed;
with Ada.Text_IO;
with Templates_Parser;

procedure Csv2Html is
   use type Templates_Parser.Vector_Tag;

   Chars : Templates_Parser.Vector_Tag;
   Speeches : Templates_Parser.Vector_Tag;

   CSV_File : Ada.Text_IO.File_Type;
begin
   
   Ada.Text_IO.Open (File => CSV_File,
                     Mode => Ada.Text_IO.In_File,
                     Name => "data.csv");

   
   while not Ada.Text_IO.End_Of_File (CSV_File) loop
      declare
         Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File);
         Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, ",");
      begin
         Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1);
         Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last);
      end;
   end loop;

   Ada.Text_IO.Close (CSV_File);

   
   declare
      Translations : constant Templates_Parser.Translate_Table :=
        (1 => Templates_Parser.Assoc ("CHAR", Chars),
         2 => Templates_Parser.Assoc ("SPEECH", Speeches));
   begin
      Ada.Text_IO.Put_Line
        (Templates_Parser.Parse ("table.tmplt", Translations));
   end;
end Csv2Html;
Task: Alternade words


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string line;
    std::set<std::string> dictionary;
    while (getline(in, line))
        dictionary.insert(line);
    std::cout << std::left;
    for (const std::string& word : dictionary) {
        size_t len = word.size();
        if (len < 6)
            continue;
        std::string word1, word2;
        for (size_t i = 0; i < len; i += 2) {
            word1 += word[i];
            if (i + 1 < len)
                word2 += word[i + 1];
        }
        if (dictionary.find(word1) != dictionary.end()
            && dictionary.find(word2) != dictionary.end()) {
            std::cout << std::setw(10) << word
                    << std::setw(6) << word1 << word2 << '\n';
        }
    }
    return EXIT_SUCCESS;
}










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

procedure Alternade_Words is
   use Ada.Text_Io;

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

   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;

   Filename : constant String := "unixdict.txt";
   Words    : String_Maps.Map;
   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);

   for Word of Words loop
      declare
         Odd  : constant String := Get_Odd  (Word);
         Even : constant String := Get_Even (Word);
      begin
         if
           Word'Length >= 6       and then
             Words.Contains (Odd) and then
             Words.Contains (Even)
         then
            Put (Word);
            Set_Col (15); Put (Odd);
            Set_Col (25); Put (Even);
            New_Line;
         end if;
      end;
   end loop;
end Alternade_Words;
Task: Pythagorean triples


C++: #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>

using namespace std;

auto CountTriplets(unsigned long long maxPerimeter)
{
    unsigned long long totalCount = 0;
    unsigned long long primitveCount = 0;
    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
    for(unsigned long long m = 2; m < max_M; ++m)
    {
        for(unsigned long long n = 1 + m % 2; n < m; n+=2)
        {
            if(gcd(m,n) != 1)
            {
                continue;
            }
            
            
            
            
            
            
            auto a = m * m - n * n;
            auto b = 2 * m * n;
            auto c = m * m + n * n;
            auto perimeter = a + b + c;
            if(perimeter <= maxPerimeter)
            {
                primitveCount++;
                totalCount+= maxPerimeter / perimeter;
            }
        }
    }
    
    return tuple(totalCount, primitveCount);
}


int main()
{
    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
        1000'000, 10'000'000, 100'000'000, 1000'000'000,
        10'000'000'000};  
    for(auto maxPerimeter : inputs)
    {
        auto [total, primitive] = CountTriplets(maxPerimeter);
        cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
    }
}










Ada: with Ada.Text_IO;

procedure Pythagorean_Triples is

   type Large_Natural is range 0 .. 2**63-1;
     

   procedure New_Triangle(A, B, C: Large_Natural;
                          Max_Perimeter: Large_Natural;
                          Total_Cnt, Primitive_Cnt: in out Large_Natural) is
      Perimeter: constant Large_Natural := A + B + C;
   begin
      if Perimeter <= Max_Perimeter then
         Primitive_Cnt := Primitive_Cnt + 1;
         Total_Cnt     := Total_Cnt + Max_Perimeter / Perimeter;
         New_Triangle(A-2*B+2*C,     2*A-B+2*C,    2*A-2*B+3*C,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
         New_Triangle(A+2*B+2*C,     2*A+B+2*C,    2*A+2*B+3*C,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
         New_Triangle(2*B+2*C-A,     B+2*C-2*A,    2*B+3*C-2*A,   Max_Perimeter, Total_Cnt, Primitive_Cnt);
      end if;
   end New_Triangle;

   T_Cnt, P_Cnt: Large_Natural;

begin
   for I in 1 .. 9 loop
      T_Cnt := 0;
      P_Cnt := 0;
      New_Triangle(3,4,5, 10**I, Total_Cnt => T_Cnt, Primitive_Cnt => P_Cnt);
      Ada.Text_IO.Put_Line("Up to 10 **" & Integer'Image(I) & " :" &
                             Large_Natural'Image(T_Cnt) & " Triples," &
                             Large_Natural'Image(P_Cnt) & " Primitives");
   end loop;
end Pythagorean_Triples;
Task: Call a foreign-language function


C++: FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y










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

procedure Test_C_Interface is
   function strdup (s1 : Char_Array) return Chars_Ptr;
   pragma Import (C, strdup, "_strdup");

   S1 : constant String := "Hello World!";
   S2 : Chars_Ptr;
begin
   S2 := strdup (To_C (S1));
   Put_Line (Value (S2));
   Free (S2);
end Test_C_Interface;
Task: Yellowstone sequence


C++: #include <iostream>
#include <numeric>
#include <set>

template <typename integer>
class yellowstone_generator {
public:
    integer next() {
        n2_ = n1_;
        n1_ = n_;
        if (n_ < 3) {
            ++n_;
        } else {
            for (n_ = min_; !(sequence_.count(n_) == 0
                && std::gcd(n1_, n_) == 1
                && std::gcd(n2_, n_) > 1); ++n_) {}
        }
        sequence_.insert(n_);
        for (;;) {
            auto it = sequence_.find(min_);
            if (it == sequence_.end())
                break;
            sequence_.erase(it);
            ++min_;
        }
        return n_;
    }
private:
    std::set<integer> sequence_;
    integer min_ = 1;
    integer n_ = 0;
    integer n1_ = 0;
    integer n2_ = 0;
};

int main() {
    std::cout << "First 30 Yellowstone numbers:\n";
    yellowstone_generator<unsigned int> ygen;
    std::cout << ygen.next();
    for (int i = 1; i < 30; ++i)
        std::cout << ' ' << ygen.next();
    std::cout << '\n';
    return 0;
}










Ada: with Ada.Text_IO;
with Ada.Containers.Ordered_Sets;

procedure Yellowstone_Sequence is

   generic  
   package Yellowstones is
      function Next return Integer;
      function GCD (Left, Right : Integer) return Integer;
   end Yellowstones;

   package body Yellowstones
   is
      package Sequences is
        new Ada.Containers.Ordered_Sets (Integer);

      
      N_0 : Integer := 0;
      N_1 : Integer := 0;
      N_2 : Integer := 0;
      Seq : Sequences.Set;
      Min : Integer := 1;

      function GCD (Left, Right : Integer) return Integer
      is (if Right = 0
          then Left
          else GCD (Right, Left mod Right));

      function Next return Integer is
      begin
         N_2 := N_1;
         N_1 := N_0;
         if N_0 < 3 then
            N_0 := N_0 + 1;
         else
            N_0 := Min;
            while
              not (not Seq.Contains (N_0)
                     and then GCD (N_1, N_0) = 1
                     and then GCD (N_2, N_0) > 1)
            loop
               N_0 := N_0 + 1;
            end loop;
         end if;
         Seq.Insert (N_0);
         while Seq.Contains (Min) loop
            Seq.Delete (Min);
            Min := Min + 1;
         end loop;
         return N_0;
      end Next;

   end Yellowstones;

   procedure First_30 is
      package Yellowstone is new Yellowstones;  
      use Ada.Text_IO;
   begin
      Put_Line ("First 30 Yellowstone numbers:");
      for A in 1 .. 30 loop
         Put (Yellowstone.Next'Image); Put (" ");
      end loop;
      New_Line;
   end First_30;

begin
   First_30;
end Yellowstone_Sequence;
Task: Gray code


C++: #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>

uint32_t gray_encode(uint32_t b)
{
    return b ^ (b >> 1);
}

uint32_t gray_decode(uint32_t g)
{
    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
    {
        if (g & bit) g ^= bit >> 1;
    }
    return g;
}

std::string to_binary(int value) 
{
    const std::bitset<32> bs(value);
    const std::string str(bs.to_string());
    const size_t pos(str.find('1'));
    return pos == std::string::npos ? "0" : str.substr(pos);
}

int main()
{
    std::cout << "Number\tBinary\tGray\tDecoded\n";
    for (uint32_t n = 0; n < 32; ++n)
    {
        uint32_t g = gray_encode(n);
        assert(gray_decode(g) == n);

        std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
    }
}










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

procedure Gray is

   Bits : constant := 5; 
   subtype Values is Unsigned_8 range 0 .. 2 ** Bits - 1;
   package Values_Io is new Ada.Text_IO.Modular_IO (Values);

   function Encode (Binary : Values) return Values is
   begin
      return Binary xor Shift_Right (Binary, 1);
   end Encode;
   pragma Inline (Encode);

   function Decode (Gray : Values) return Values is
      Binary, Bit : Values;
      Mask        : Values := 2 ** (Bits - 1);
   begin
      Bit    := Gray and Mask;
      Binary := Bit;
      for I in 2 .. Bits loop
         Bit    := Shift_Right (Bit, 1);
         Mask   := Shift_Right (Mask, 1);
         Bit    := (Gray and Mask) xor Bit;
         Binary := Binary + Bit;
      end loop;
      return Binary;
   end Decode;
   pragma Inline (Decode);

   HT : constant Character := Character'Val (9);
   J  : Values;
begin
   Put_Line ("Num" & HT & "Binary" & HT & HT & "Gray" & HT & HT & "decoded");
   for I in Values'Range loop
      J := Encode (I);
      Values_Io.Put (I, 4);
      Put (": " & HT);
      Values_Io.Put (I, Bits + 2, 2);
      Put (" =>" & HT);
      Values_Io.Put (J, Bits + 2, 2);
      Put (" => " & HT);
      Values_Io.Put (Decode (J), 4);
      New_Line;
   end loop;
end Gray;
Task: Knuth's algorithm S


C++: #include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <ctime>

template <typename T>
std::function<std::vector<T>(T)> s_of_n_creator(int n) {
  std::vector<T> sample;
  int i = 0;
  return [=](T item) mutable {
    i++;
    if (i <= n) {
      sample.push_back(item);
    } else if (std::rand() % i < n) {
      sample[std::rand() % n] = item;
    }
    return sample;
  };
}

int main() {
  std::srand(std::time(NULL));
  int bin[10] = {0};
  for (int trial = 0; trial < 100000; trial++) {
    auto s_of_n = s_of_n_creator<int>(3);
    std::vector<int> sample;
    for (int i = 0; i < 10; i++)
      sample = s_of_n(i);
    for (int s : sample)
      bin[s]++;
  }
  for (int x : bin)
    std::cout << x << std::endl;
  return 0;
}










Ada: generic
   Sample_Size: Positive;
   type Item_Type is private;
package S_Of_N_Creator is

   subtype Index_Type is Positive range 1 .. Sample_Size;
   type Item_Array is array (Index_Type) of Item_Type;

   procedure Update(New_Item: Item_Type);
   function Result return Item_Array;

end S_Of_N_Creator;
Task: Flow-control structures


C++: #include <iostream> 

int main()
{
 LOOP:
  std::cout << "Hello, World!\n";
 goto LOOP;
}










Ada: <<Top>>
   Put_Line("Hello, World");
   goto Top;
Task: Return multiple values


C++: #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>

std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
   const auto maximum = std::max_element(numbers, numbers + num);
   const auto minimum = std::min_element(numbers, numbers + num);
   return std::make_tuple(*minimum, *maximum) ;
}

int main( ) {
   const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
   int min{};
   int max{};
   std::tie(min, max) = minmax(numbers.data(), numbers.size());
   std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}










Ada: with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
   procedure SumAndDiff (x, y : Integer; sum, diff : out Integer) is begin
      sum := x + y;
      diff := x - y;
   end SumAndDiff;
   inta : Integer := 5;
   intb : Integer := 3;
   thesum, thediff : Integer;
begin
   SumAndDiff (inta, intb, thesum, thediff);
   Put_Line ("Sum:" & Integer'Image (thesum));
   Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;
Task: Change e letters to i in words


C++: #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <string>

int main(int argc, char** argv) {
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    const int min_length = 6;
    std::string word;
    std::set<std::string> dictionary;
    while (getline(in, word)) {
        if (word.size() >= min_length)
            dictionary.insert(word);
    }
    int count = 0;
    for (const std::string& word1 : dictionary) {
        if (word1.find('e') == std::string::npos)
            continue;
        std::string word2(word1);
        std::replace(word2.begin(), word2.end(), 'e', 'i');
        if (dictionary.find(word2) != dictionary.end()) {
            std::cout << std::right << std::setw(2) << ++count
                << ". " << std::left << std::setw(10) << word1
                << " -> " << word2 << '\n';
        }
    }

    return EXIT_SUCCESS;
}










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

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

   Filename : constant String := "unixdict.txt";
   Mapping  : constant Maps.Character_Mapping :=
     Maps.To_Mapping ("Ee", "Ii");

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

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

   for Word of Dict loop
      declare
         Trans : constant String := Fixed.Translate (Word, Mapping);
      begin
         if Word /= Trans and Dict.Contains (Trans) and Word'Length >= 6 then
            Put (Word); Put (" -> "); Put (Trans); New_Line;
         end if;
      end;
   end loop;
end Change_E_To_I;