WeixiangYan/CodeTransOcean huggingface dataset:
Task: Alternade words




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "unicode/utf8"
)

func main() {
    b, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    dict := make(map[string]bool, len(bwords))
    words := make([]string, len(bwords))
    for i, bword := range bwords {
        word := string(bword)
        dict[word] = true
        words[i] = word
    }
    fmt.Println("'unixdict.txt' contains the following alternades of length 6 or more:\n")
    count := 0
    for _, word := range words {
        if utf8.RuneCountInString(word) < 6 {
            continue
        }
        var w1 = ""
        var w2 = ""
        for i, c := range word {
            if i%2 == 0 {
                w1 += string(c)
            } else {
                w2 += string(c)
            }
        }
        _, ok1 := dict[w1]
        _, ok2 := dict[w2]
        if ok1 && ok2 {
            count++
            fmt.Printf("%2d: %-8s -> %-4s %-4s\n", count, word, w1, w2)
        }
    }
}








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: Count how many vowels and consonants occur in a string




Go: package main

import (
    "fmt"
    "strings"
)

func main() {
    const (
        vowels     = "aeiou"
        consonants = "bcdfghjklmnpqrstvwxyz"
    )
    strs := []string{
        "Forever Go programming language",
        "Now is the time for all good men to come to the aid of their country.",
    }
    for _, str := range strs {
        fmt.Println(str)
        str = strings.ToLower(str)
        vc, cc := 0, 0
        vmap := make(map[rune]bool)
        cmap := make(map[rune]bool)
        for _, c := range str {
            if strings.ContainsRune(vowels, c) {
                vc++
                vmap[c] = true
            } else if strings.ContainsRune(consonants, c) {
                cc++
                cmap[c] = true
            }
        }
        fmt.Printf("contains (total) %d vowels and %d consonants.\n", vc, cc)
        fmt.Printf("contains (distinct %d vowels and %d consonants.\n\n", len(vmap), len(cmap))
    }
}








Ada: 


with Ada.Text_IO; use Ada.Text_IO;

procedure count_vowels_and_consonants is
   subtype letter is Character with
        Static_Predicate => letter in 'A' .. 'Z' | 'a' .. 'z';
   subtype Vowel is Character with
        Static_Predicate => Vowel in 'A' | 'E' | 'I' | 'O' | 'U' | 'a' | 'e' |
            'i' | 'o' | 'u';
   subtype consonant is Character with
        Dynamic_Predicate => consonant in letter
        and then consonant not in Vowel;

   Input           : String (1 .. 1_024);
   length          : Natural;
   consonant_count : Natural := 0;
   vowel_count     : Natural := 0;
begin
   Put ("Enter a string: ");
   Get_Line (Item => Input, Last => length);
   
   for char of Input (1 .. length) loop
      if char in consonant then
         consonant_count := consonant_count + 1;
      elsif char in Vowel then
         vowel_count := vowel_count + 1;
      end if;
   end loop;
   Put_Line ('"' & Input (1 .. length) & '"');
   Put_Line
     ("contains" & vowel_count'Image & " vowels and" & consonant_count'Image &
      " consonants.");
end count_vowels_and_consonants;
Task: Pythagorean triples




Go: package main

import "fmt"

var total, prim, maxPeri int64

func newTri(s0, s1, s2 int64) {
    if p := s0 + s1 + s2; p <= maxPeri {
        prim++
        total += maxPeri / p
        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
    }
}

func main() {
    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
        prim = 0
        total = 0
        newTri(3, 4, 5)
        fmt.Printf("Up to %d:  %d triples, %d primitives\n",
            maxPeri, total, prim)
    }
}








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




Go: package main



import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    
    go1 := "hello C"
    
    c1 := C.CString(go1)
    
    go1 = ""
    
    c2 := C.strdup(c1)
    
    C.free(unsafe.Pointer(c1))
    
    go2 := C.GoString(c2)
    
    C.free(unsafe.Pointer(c2))
    
    fmt.Println(go2)
}








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




Go: package main

import (
    "fmt"
    "log"
    "os/exec"
)

func gcd(x, y int) int {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

func yellowstone(n int) []int {
    m := make(map[int]bool)
    a := make([]int, n+1)
    for i := 1; i < 4; i++ {
        a[i] = i
        m[i] = true
    }
    min := 4
    for c := 4; c <= n; c++ {
        for i := min; ; i++ {
            if !m[i] && gcd(a[c-1], i) == 1 && gcd(a[c-2], i) > 1 {
                a[c] = i
                m[i] = true
                if i == min {
                    min++
                }
                break
            }
        }
    }    
    return a[1:]
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    x := make([]int, 100)
    for i := 0; i < 100; i++ {
        x[i] = i + 1
    }
    y := yellowstone(100)
    fmt.Println("The first 30 Yellowstone numbers are:")
    fmt.Println(y[:30])
    g := exec.Command("gnuplot", "-persist")
    w, err := g.StdinPipe()
    check(err)
    check(g.Start())
    fmt.Fprintln(w, "unset key; plot '-'")
    for i, xi := range x {
        fmt.Fprintf(w, "%d %d\n", xi, y[i])
    }
    fmt.Fprintln(w, "e")
    w.Close()
    g.Wait()
}








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




Go: package main

import "fmt"

func enc(b int) int {
    return b ^ b>>1
}

func dec(g int) (b int) {
    for ; g != 0; g >>= 1 {
        b ^= g
    }
    return
}

func main() {
    fmt.Println("decimal  binary   gray    decoded")
    for b := 0; b < 32; b++ {
        g := enc(b)
        d := dec(g)
        fmt.Printf("  %2d     %05b   %05b   %05b  %2d\n", b, b, g, d, d)
    }
}








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: File extension is in extensions list




Go: package main

import (
    "fmt"
    "strings"
)

var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}

func fileExtInList(filename string) (bool, string) {
    filename2 := strings.ToLower(filename)
    for _, ext := range extensions {
        ext2 := "." + strings.ToLower(ext)
        if strings.HasSuffix(filename2, ext2) {
            return true, ext
        }
    }
    s := strings.Split(filename, ".")
    if len(s) > 1 {
        t := s[len(s)-1]
        if t != "" {
            return false, t
        } else {
            return false, "<empty>"
        }
    } else {
        return false, "<none>"
    }
}

func main() {
    fmt.Println("The listed extensions are:")
    fmt.Println(extensions, "\n")
    tests := []string{
        "MyData.a##", "MyData.tar.Gz", "MyData.gzip",
        "MyData.7z.backup", "MyData...", "MyData",
        "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
    }
    for _, test := range tests {
        ok, ext := fileExtInList(test)
        fmt.Printf("%-20s => %-5t  (extension = %s)\n", test, ok, ext)
    }
}








Ada: with Ada.Text_IO;                              use Ada.Text_IO;
with Ada.Strings.Fixed.Equal_Case_Insensitive; use Ada.Strings.Fixed;
with Ada.Strings.Bounded;

procedure Main is

   package B_String is new Ada.Strings.Bounded.Generic_Bounded_Length (30);
   use B_String;
   function is_equal (left, right : String) return Boolean renames
     Ada.Strings.Fixed.Equal_Case_Insensitive;

   type extension_list is array (Positive range <>) of Bounded_String;
   Ext_List : extension_list :=
     (To_Bounded_String ("zip"), To_Bounded_String ("rar"),
      To_Bounded_String ("7z"), To_Bounded_String ("gz"),
      To_Bounded_String ("archive"), To_Bounded_String ("A##"),
      To_Bounded_String ("tar.bz2"));
   type filename_list is array (Positive range <>) of Bounded_String;
   fnames : filename_list :=
     (To_Bounded_String ("MyData.a##"), To_Bounded_String ("MyData.tar.Gz"),
      To_Bounded_String ("MyData.gzip"), To_Bounded_String ("MyData..."),
      To_Bounded_String ("Mydata"), To_Bounded_String ("MyData_V1.0.tar.bz2"),
      To_Bounded_String ("MyData_v1.0.bz2"));
   Valid_Extension : Boolean;
begin
   for name of fnames loop
      Valid_Extension := False;
      Put (To_String (name));
      for ext of Ext_List loop
         declare
            S : String := "." & To_String (ext);
            T : String := Tail (Source => To_String (name), Count => S'Length);
         begin
            if is_equal (S, T) then
               Valid_Extension := True;
            end if;
         end;
      end loop;
      Set_Col (22);
      Put_Line (": " & Valid_Extension'Image);
   end loop;
end Main;
Task: Extreme floating point values




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    var zero float64                         
    var negZero, posInf, negInf, nan float64 
    negZero = zero * -1
    posInf = 1 / zero
    negInf = -1 / zero
    nan = zero / zero

    
    fmt.Println(negZero, posInf, negInf, nan)

    
    fmt.Println(math.Float64frombits(1<<63),
        math.Inf(1), math.Inf(-1), math.NaN())

    
    fmt.Println()
    validateNaN(negInf+posInf, "-Inf + Inf")
    validateNaN(0*posInf, "0 * Inf")
    validateNaN(posInf/posInf, "Inf / Inf")
    
    
    validateNaN(math.Mod(posInf, 1), "Inf % 1")
    validateNaN(1+nan, "1 + NaN")
    validateZero(1/posInf, "1 / Inf")
    validateGT(posInf, math.MaxFloat64, "Inf > max value")
    validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
    validateNE(nan, nan, "NaN != NaN")
    validateEQ(negZero, 0, "-0 == 0")
}

func validateNaN(n float64, op string) {
    if math.IsNaN(n) {
        fmt.Println(op, "-> NaN")
    } else {
        fmt.Println("!!! Expected NaN from", op, "  Found", n)
    }
}

func validateZero(n float64, op string) {
    if n == 0 {
        fmt.Println(op, "-> 0")
    } else {
        fmt.Println("!!! Expected 0 from", op, "  Found", n)
    }
}

func validateGT(a, b float64, op string) {
    if a > b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}

func validateNE(a, b float64, op string) {
    if a == b {
        fmt.Println("!!! Expected", op, "  Found not true.")
    } else {
        fmt.Println(op)
    }
}

func validateEQ(a, b float64, op string) {
    if a == b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}








Ada: subtype Consistent_Float is Float range Float'Range;
Task: Knuth's algorithm S




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}








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: Cousin primes




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func main() {
    count := 0
    fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
    for i := 3; i <= 995; i += 2 {
        if isPrime(i) && isPrime(i+4) {
            fmt.Printf("%3d:%3d  ", i, i+4)
            count++
            if count%7 == 0 {
                fmt.Println()
            }
            if i != 3 {
                i += 4
            } else {
                i += 2
            }
        }
    }
    fmt.Printf("\n\n%d pairs found\n", count)
}








Ada: with Ada.Text_Io;

procedure Cousin_Primes is

   type Number is new Long_Integer range 0 .. Long_Integer'Last;
   package Number_Io is new Ada.Text_Io.Integer_Io (Number);

   function Is_Prime (A : Number) return Boolean is
      D : Number;
   begin
      if A < 2       then return False; end if;
      if A in 2 .. 3 then return True;  end if;
      if A mod 2 = 0 then return False; end if;
      if A mod 3 = 0 then return False; end if;
      D := 5;
      while D * D <= A loop
         if A mod D = 0 then
            return False;
         end if;
         D := D + 2;
         if A mod D = 0 then
            return False;
         end if;
         D := D + 4;
      end loop;
      return True;
   end Is_Prime;

   use Ada.Text_Io;
   Count : Natural := 0;
begin
   for N in Number range 1 .. 999 - 4 loop
      if Is_Prime (N) and then Is_Prime (N + 4) then
         Count := Count + 1;
         Put("[");
         Number_Io.Put (N, Width => 3); Put (",");
         Number_Io.Put (N + 4, Width => 3);
         Put("]  ");
         if Count mod 8 = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line;
   Put_Line (Count'Image & " pairs.");
end Cousin_Primes;
Task: Return multiple values




Go: func addsub(x, y int) (int, int) {
  return x + y, x - y
}








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




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "sort"
    "strings"
    "unicode/utf8"
)

func main() {
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    var words []string
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 5 {
            words = append(words, s)
        }
    }
    count := 0
    le := len(words)
    for _, word := range words {
        if strings.ContainsRune(word, 'e') {
            repl := strings.ReplaceAll(word, "e", "i")
            ix := sort.SearchStrings(words, repl) 
            if ix < le && words[ix] == repl {
                count++
                fmt.Printf("%2d: %-9s -> %s\n", count, word, repl)
            }
        }
    }
}








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;