WeixiangYan/CodeTransOcean huggingface dataset:
Task: Numbers with equal rises and falls




Go: package main

import "fmt"

func risesEqualsFalls(n int) bool {
    if n < 10 {
        return true
    }
    rises := 0
    falls := 0
    prev := -1
    for n > 0 {
        d := n % 10
        if prev >= 0 {
            if d < prev {
                rises = rises + 1
            } else if d > prev {
                falls = falls + 1
            }
        }
        prev = d
        n /= 10   
    }
    return rises == falls
}

func main() {
    fmt.Println("The first 200 numbers in the sequence are:")
    count := 0
    n := 1
    for {
        if risesEqualsFalls(n) {
            count++
            if count <= 200 {
                fmt.Printf("%3d ", n)
                if count%20 == 0 {
                    fmt.Println()
                }
            }
            if count == 1e7 {
                fmt.Println("\nThe 10 millionth number in the sequence is ", n)
                break
            }
        }
        n++
    }
}








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

procedure Equal_Rise_Fall is
   use Ada.Text_Io;

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

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




Go: package main

import (
    "fmt"
    "log"
    "math"
)

var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}

const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1


func mod(x, y int64) int64 {
    m := x % y
    if m < 0 {
        if y < 0 {
            return m - y
        } else {
            return m + y
        }
    }
    return m
}

type MRG32k3a struct{ x1, x2 [3]int64 }

func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }

func (mrg *MRG32k3a) seed(seedState int64) {
    if seedState <= 0 || seedState >= d {
        log.Fatalf("Argument must be in the range [0, %d].\n", d)
    }
    mrg.x1 = [3]int64{seedState, 0, 0}
    mrg.x2 = [3]int64{seedState, 0, 0}
}

func (mrg *MRG32k3a) nextInt() int64 {
    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} 
    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} 
    return mod(x1i-x2i, m1) + 1
}

func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }

func main() {
    randomGen := MRG32k3aNew()
    randomGen.seed(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}








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

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




Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)


func sdn(n int64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatInt(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}


func main() {
    for n := int64(0); n < 1e10; n++ {
        if sdn(n) {
            fmt.Println(n)
        }
    }
}








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

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

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




Go: package main

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

func hammingDist(s1, s2 string) int {
    r1 := []rune(s1) 
    r2 := []rune(s2) 
    if len(r1) != len(r2) {
        return 0
    }
    count := 0
    for i := 0; i < len(r1); i++ {
        if r1[i] != r2[i] {
            count++
            if count == 2 {
                break 
            }
        }
    }
    return count
}

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) > 11 {
            words = append(words, s)
        }
    }
    count := 0
    fmt.Println("Changeable words in", wordList, "\b:")
    for _, word1 := range words {
        for _, word2 := range words {
            if word1 != word2 && hammingDist(word1, word2) == 1 {
                count++
                fmt.Printf("%2d: %-14s -> %s\n", count, word1, word2)
            }
        }
    }
}








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

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

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

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

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




Go: package main

import "fmt"

func main() {
    lists := [][]int{
        {9, 3, 3, 3, 2, 1, 7, 8, 5},
        {5, 2, 9, 3, 3, 7, 8, 4, 1},
        {1, 4, 3, 6, 7, 3, 8, 3, 2},
        {1, 2, 3, 4, 5, 6, 7, 8, 9},
        {4, 6, 8, 7, 2, 3, 3, 3, 1},
        {3, 3, 3, 1, 2, 4, 5, 1, 3},
        {0, 3, 3, 3, 3, 7, 2, 2, 6},
        {3, 3, 3, 3, 3, 4, 4, 4, 4},
    }
    for d := 1; d <= 4; d++ {
        fmt.Printf("Exactly %d adjacent %d's:\n", d, d)
        for _, list := range lists {
            var indices []int
            for i, e := range list {
                if e == d {
                    indices = append(indices, i)
                }
            }
            adjacent := false
            if len(indices) == d {
                adjacent = true
                for i := 1; i < len(indices); i++ {
                    if indices[i]-indices[i-1] != 1 {
                        adjacent = false
                        break
                    }
                }
            }
            fmt.Printf("%v -> %t\n", list, adjacent)
        }
        fmt.Println()
    }
}








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

procedure Exactly_3 is

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

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

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

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

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

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

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




Go: package main

import (
    "errors"
    "fmt"
    "os"
)

type dtText struct {
    rules, text string
}

var ptText = []dtText{
    {"YYYYNNNN", "Printer does not print"},
    {"YYNNYYNN", "A red light is flashing"},
    {"YNYNYNYN", "Printer is unrecognised"},
    {"--------", ""},
    {"  X     ", "Check the power cable"},
    {"X X     ", "Check the printer-computer cable"},
    {"X X X X ", "Ensure printer software is installed"},
    {"XX  XX  ", "Check/replace ink"},
    {" X X    ", "Check for paper jam"},
}

type dtMap map[string][]string

func compileDT(t []dtText) (dtMap, error) {
    if len(t) == 0 {
        return nil, errors.New("Empty decision table")
    }
    var conditions, actions []dtText
    ruleColumns := len(t[0].rules)
    for i, row := range t {
        if len(row.rules) != ruleColumns {
            return nil, errors.New("Inconsistent number of rule columns")
        }
        if len(row.text) == 0 {
            if conditions != nil {
                return nil, errors.New("Multple separator lines")
            }
            if i == 0 {
                return nil, errors.New("No conditions specified")
            }
            if i == len(t)-1 {
                return nil, errors.New("No actions specified")
            }
            conditions = t[:i]
            actions = t[i+1:]
        }
    }
    if conditions == nil {
        return nil, errors.New("Missing separator line")
    }
    m := make(map[string][]string, ruleColumns)
    kb := make([]byte, len(conditions))
    for col := 0; col < ruleColumns; col++ {
        for i, c := range conditions {
            kb[i] = c.rules[col]
        }
        key := string(kb)
        for _, a := range actions {
            if a.rules[col] != ' ' {
                m[key] = append(m[key], a.text)
            }
        }
    }
    return m, nil
}

func init() {
    var err error
    if ptMap, err = compileDT(ptText); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

var ptMap dtMap

func main() {
    for _, a := range ptMap["NYY"] {
        fmt.Println(a)
    }
}








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

package Generic_Decision_Table is

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

   procedure React(Rules: Rule_A);

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




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "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
outer:
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) >= 4 {
            for _, c := range s {
                if strings.ContainsRune("aiou", c) {
                    continue outer
                }
            }
            words = append(words, s)
        }
    }
    wcount := 0
    for _, word := range words {
        ecount := 0
        for _, c := range word {
            if c == 'e' {
                ecount++
            }
        }
        if ecount > 3 {
            wcount++
            fmt.Printf("%2d: %s\n", wcount, word)
        }
    }
}








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

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

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




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    numbers1 := [5]int{5, 45, 23, 21, 67}
    numbers2 := [5]int{43, 22, 78, 46, 38}
    numbers3 := [5]int{9, 98, 12, 98, 53}
    numbers := [5]int{}
    for n := 0; n < 5; n++ {
        numbers[n] = rcu.Min(rcu.Min(numbers1[n], numbers2[n]), numbers3[n])
    }
    fmt.Println(numbers)
}








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

procedure Minimum_Three_Lists is

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

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

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

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




Go: package main

import "fmt"

func mosaicMatrix(n uint) {
    for i := uint(0); i < n; i++ {
        for j := uint(0); j < n; j++ {
            if (i+j)%2 == 0 {
                fmt.Printf("%s ", "1")
            } else {
                fmt.Printf("%s ", ".")
            }
        }
        fmt.Println()
    }
}

func main() {
    mosaicMatrix(7)
    fmt.Println()
    mosaicMatrix(8)
}








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

procedure Mosaic_Matrix is

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

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

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

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

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

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




Go: package main
 
import (
    "fmt"
    "strconv"
    "strings"
)
 
func main() {
    const decimal = "0123456789"
    c := 0
    for i := int64(1); i < 500; i++ {
        hex := strconv.FormatInt(i, 16)
        if !strings.ContainsAny(decimal, hex) {
            fmt.Printf("%3d ", i)
            c++
            if c%14 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Printf("\n%d such numbers found.\n", c)
}








Ada: with Ada.Text_IO;

procedure Numbers_In_Base_16 is

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

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

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




Go: package main

import "fmt"

func substrings(s string) []string {
    n := len(s)
    if n == 0 {
        return []string{""}
    }
    var ss []string
    for i := 0; i < n; i++ {
        for le := 1; le <= n-i; le++ {
            ss = append(ss, s[i:i+le])
        }
    }
    return ss
}

func distinctRunes(chars []rune) []rune {
    m := make(map[rune]bool)
    for _, char := range chars {
        m[char] = true
    }
    var l []rune
    for k := range m {
        l = append(l, k)
    }
    return l
}

func distinctStrings(strings []string) []string {
    m := make(map[string]bool)
    for _, str := range strings {
        m[str] = true
    }
    var l []string
    for k := range m {
        l = append(l, k)
    }
    return l
}

func main() {
    fmt.Println("The longest substring(s) of the following without repeating characters are:\n")
    strs := []string{"xyzyabcybdfd", "xyzyab", "zzzzz", "a", ""}
    for _, s := range strs {
        var longest []string
        longestLen := 0
        for _, ss := range substrings(s) {
            if len(distinctRunes([]rune(ss))) == len(ss) {
                if len(ss) >= longestLen {
                    if len(ss) > longestLen {
                        longest = longest[:0]
                        longestLen = len(ss)
                    }
                    longest = append(longest, ss)
                }
            }
        }
        longest = distinctStrings(longest)
        fmt.Printf("String = '%s'\n", s)
        fmt.Println(longest)
        fmt.Printf("Length = %d\n\n", len(longest[0]))
    }
}








Ada: with Ada.Text_IO;

procedure Longest_Substring is

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

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

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

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

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

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