WeixiangYan/CodeTransOcean huggingface dataset:
Task: Rep-string








VB: Function rep_string(s)
	max_len = Int(Len(s)/2)
	tmp = ""
	If max_len = 0 Then
		rep_string = "No Repeating String"
		Exit Function
	End If
	For i = 1 To max_len
		If InStr(i+1,s,tmp & Mid(s,i,1))Then
			tmp = tmp & Mid(s,i,1)
		Else
			Exit For
		End If
	Next
	Do While Len(tmp) > 0
		If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then
			rep_string = tmp
			Exit Do
		Else
			tmp = Mid(tmp,1,Len(tmp)-1)
		End If
	Loop
	If Len(tmp) > 0 Then
		rep_string = tmp
	Else
		rep_string = "No Repeating String"
	End If
End Function


arr = Array("1001110011","1110111011","0010010010","1010101010",_
		"1111111111","0100101101","0100100","101","11","00","1")

For n = 0 To UBound(arr)
	WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n))
	WScript.StdOut.WriteLine
Next




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: Odd word problem








VB: Private Function OddWordFirst(W As String) As String
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
   count = 1
   Do
      flag = Not flag
      l = FindNextPunct(i, W) - count + 1
      If flag Then
         temp = temp & ExtractWord(W, count, l)
      Else
         temp = temp & ReverseWord(W, count, l)
      End If
   Loop While count < Len(W)
   OddWordFirst = temp
End Function

Private Function FindNextPunct(d As Integer, W As String) As Integer
Const PUNCT As String = ",;:."
   Do
      d = d + 1
   Loop While InStr(PUNCT, Mid(W, d, 1)) = 0
   FindNextPunct = d
End Function

Private Function ExtractWord(W As String, c As Integer, i As Integer) As String
   ExtractWord = Mid(W, c, i)
   c = c + Len(ExtractWord)
End Function

Private Function ReverseWord(W As String, c As Integer, i As Integer) As String
Dim temp As String, sep As String
   temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1)
   sep = Right(Mid(W, c, i), 1)
   ReverseWord = StrReverse(temp) & sep
   c = c + Len(ReverseWord)
End Function




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: Self-describing numbers








VB: Function IsSelfDescribing(n)
	IsSelfDescribing = False
	Set digit = CreateObject("Scripting.Dictionary")
	For i = 1 To Len(n)
		k = Mid(n,i,1)
		If digit.Exists(k) Then
			digit.Item(k) = digit.Item(k) + 1
		Else
			digit.Add k,1
		End If	
	Next
	c = 0
	For j = 0 To Len(n)-1
		l = Mid(n,j+1,1)
		If digit.Exists(CStr(j)) Then
			If digit.Item(CStr(j)) = CInt(l) Then
				c = c + 1
			End If
		ElseIf l = 0 Then
			c = c + 1
		Else
			Exit For
		End If
	Next
	If c = Len(n) Then
		IsSelfDescribing = True
	End If
End Function


start_time = Now
s = ""
For m = 1 To 100000000
	If 	IsSelfDescribing(m) Then
		WScript.StdOut.WriteLine m
	End If
Next
end_time = Now
WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds"




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: Longest substrings without repeating characters








VB: function nrls(byval s1)
  dim i,x
  if len(s1)<2 then nlrs=s :exit function
  s=lcase(replace(s1," ",""))
    redim a(127)
  dim ls:ls=len(s)
  start=1
  so=""
  ml=1
  a(asc(left(s,1)))=1
  for i=2 to ls+1
    if i>ls then
       rep=true
    else   
      x=asc(mid(s,i,1))
      rep=a(x)<>0
    end if
    if a(x)<>0 then 
      if (i-start)>ml then  
           so=  mid(s,start,i-start)  
           ml=(i-start)
      elseif   (i-start)=ml  then          
           so=so & " " & mid(s,start,i-start)
      end if  
      xx=a(x)
      for j= 96 to 122: 
        if a(j)<=x then a(j)=0
      next         
      start=xx+1
    end if
    a(x)=i
  next
  nrls=trim(so)
  erase a
end function

sub test (f)
  wscript.stdout.writeline "Original:   "&f
  wscript.stdout.writeline "Substrings: "&nrls(f)&vbcrlf  
end sub 

test "dabale arroz a la zorra el abad"
test "The quick brown fox jumps over the lazy dog"
test "ae"
test "aa"
test "abdefghij"




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;
Task: Words containing _the_ substring








VB: Sub Main_Contain()
Dim ListeWords() As String, Book As String, i As Long, out() As String, count As Integer
    Book = Read_File("C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt")
    ListeWords = Split(Book, vbNewLine)
    For i = LBound(ListeWords) To UBound(ListeWords)
        If Len(ListeWords(i)) > 11 Then
            If InStr(ListeWords(i), "the") > 0 Then
                ReDim Preserve out(count)
                out(count) = ListeWords(i)
                count = count + 1
            End If
        End If
    Next
    Debug.Print "Found : " & count & " words : " & Join(out, ", ")
End Sub
Private Function Read_File(Fic As String) As String
Dim Nb As Integer
    Nb = FreeFile
    Open Fic For Input As #Nb
        Read_File = Input(LOF(Nb), #Nb)
    Close #Nb
End Function




Ada: with Ada.Text_IO;            use Ada.Text_IO;
with Ada.Strings.Fixed;      use Ada.Strings.Fixed;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;

procedure Main is
   type col_count is mod 6;
   package AF renames Ada.Strings.Fixed;

   file_name : String             := "unixdict.txt";
   The_File  : File_Type;
   Inpt_Str  : String (1 .. 40);
   Length    : Natural;
   pattern   : String             := "the";
   Columns   : col_count          := 0;
   Tally     : Natural            := 0;
   sep       : constant Character := HT;
begin

   Open (File => The_File, Mode => In_File, Name => file_name);

   while not End_Of_File (The_File) loop
      Get_Line (File => The_File, Item => Inpt_Str, Last => Length);

      if Length > 11
        and then
          AF.Count (Source => Inpt_Str (1 .. Length), Pattern => pattern) > 0
      then
         Tally   := Tally + 1;
         Columns := Columns + 1;
         Put (Inpt_Str (1 .. Length) & sep);
         if Columns = 0 then
            New_Line;
         end if;
      end if;
   end loop;
   New_Line;
   Put_Line ("Found" & Tally'Image & " ""the"" words");
   Close (The_File);
end Main;
Task: Address of a variable








VB: Dim TheAddress as long
Dim SecVar as byte
Dim MyVar as byte
    MyVar = 10


TheAddress = varptr(MyVar)


MEMSET(TheAddress, 102, SizeOf(byte))


showmessage "MyVar = " + str$(MyVar)


MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte))


showmessage "SecVar = " + str$(SecVar)




Ada: The_Address : System.Address;
I : Integer;
The_Address := I'Address;
Task: Find words whose first and last three letters are equal








VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

set d= createobject("Scripting.Dictionary")
for each aa in a
  x=trim(aa)
  l=len(x)
  if l>5 then
   d.removeall
   for i=1 to 3
     m=mid(x,i,1)
     if not d.exists(m) then d.add m,null
   next
   res=true
   for i=l-2 to l
     m=mid(x,i,1)
     if not d.exists(m) then 
       res=false:exit for 
      else
        d.remove(m)
      end if        
   next 
   if res then 
     wscript.stdout.write left(x & space(15),15)
     if left(x,3)=right(x,3) then  wscript.stdout.write "*"
     wscript.stdout.writeline
    end if 
  end if
next




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








VB: with createobject("ADODB.Stream")
  .charset ="UTF-8"
  .open
  .loadfromfile("unixdict.txt")
  s=.readtext
end with  
a=split (s,vblf)

dim b(25)  
dim c(128) 

with new regexp
  .pattern="([^aeiou])"
  .global=true
for each i in a
  if len(trim(i))>10 then
   set matches= .execute(i)   
   rep=false
   for each m in matches  
     x=asc(m)  
     c(x)=c(x)+1
     if c(x)>1 then rep=true :exit for
   next
   erase c
   if not rep then   
     x1=matches.count
     b(x1)=b(x1)&" "&i  
   end if    
  end if
next
end with 


for i=25 to 0 step -1
  if b(i)<>"" then  wscript.echo i & "  "& b(i) & vbcrlf
next




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: Juggler sequence




Go: package main

import (
    "fmt"
    "log"
    
    big "github.com/ncw/gmp"
    "rcu"
)

var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)

func juggler(n int64) (int, int, *big.Int, int) {
    if n < 1 {
        log.Fatal("Starting value must be a positive integer.")
    }
    count := 0
    maxCount := 0
    a := big.NewInt(n)
    max := big.NewInt(n)
    tmp := new(big.Int)
    for a.Cmp(one) != 0 {
        if tmp.Rem(a, two).Cmp(zero) == 0 {
            a.Sqrt(a)
        } else {
            tmp.Mul(a, a)
            tmp.Mul(tmp, a)
            a.Sqrt(tmp)
        }
        count++
        if a.Cmp(max) > 0 {
            max.Set(a)
            maxCount = count
        }
    }
    return count, maxCount, max, len(max.String())
}

func main() {
    fmt.Println("n    l[n]  i[n]  h[n]")
    fmt.Println("-----------------------------------")
    for n := int64(20); n < 40; n++ {
        count, maxCount, max, _ := juggler(n)
        cmax := rcu.Commatize(int(max.Int64()))
        fmt.Printf("%2d    %2d   %2d    %s\n", n, count, maxCount, cmax)
    }
    fmt.Println()
    nums := []int64{
        113, 173, 193, 2183, 11229, 15065, 15845, 30817, 48443, 275485, 1267909,
        2264915, 5812827, 7110201, 56261531, 92502777, 172376627, 604398963,
    }
    fmt.Println("       n      l[n]   i[n]   d[n]")
    fmt.Println("-------------------------------------")
    for _, n := range nums {
        count, maxCount, _, digits := juggler(n)
        cn := rcu.Commatize(int(n))
        fmt.Printf("%11s   %3d    %3d    %s\n", cn, count, maxCount, rcu.Commatize(digits))
    }
}
Task: Modified random distribution




Go: package main

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

func rng(modifier func(x float64) float64) float64 {
    for {
        r1 := rand.Float64()
        r2 := rand.Float64()
        if r2 < modifier(r1) {
            return r1
        }
    }
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    rand.Seed(time.Now().UnixNano())
    modifier := func(x float64) float64 {
        if x < 0.5 {
            return 2 * (0.5 - x)
        }
        return 2 * (x - 0.5)
    }
    const (
        N              = 100000
        NUM_BINS       = 20
        HIST_CHAR      = "■"
        HIST_CHAR_SIZE = 125
    )
    bins := make([]int, NUM_BINS) 
    binSize := 1.0 / NUM_BINS
    for i := 0; i < N; i++ {
        rn := rng(modifier)
        bn := int(math.Floor(rn / binSize))
        bins[bn]++
    }

    fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n")
    fmt.Println("    Range           Number of samples within that range")
    for i := 0; i < NUM_BINS; i++ {
        hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE)))
        fi := float64(i)
        fmt.Printf("%4.2f ..< %4.2f  %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i]))
    }
}
Task: Deming's funnel




Go: package main

import (
    "fmt"
    "math"
)

type rule func(float64, float64) float64

var dxs = []float64{
    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,
     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,
    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,
     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,
    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,
    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,
     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,
    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,
     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,
    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,
     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,
     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,
     0.443, -0.521, -0.799,  0.087,
}

var dys = []float64{
     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,
     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,
     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,
     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,
    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,
     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,
     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,
     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,
    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,
     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,
    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,
     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,
    -0.947, -1.424, -0.542, -1.032,
}

func funnel(fa []float64, r rule) []float64 {
    x := 0.0
    result := make([]float64, len(fa))
    for i, f := range fa {
        result[i] = x + f
        x = r(x, f)
    }
    return result
}

func mean(fa []float64) float64 {
    sum := 0.0
    for _, f := range fa {
        sum += f
    }
    return sum / float64(len(fa))
}

func stdDev(fa []float64) float64 {
    m := mean(fa)
    sum := 0.0
    for _, f := range fa {
        sum += (f - m) * (f - m)
    }
    return math.Sqrt(sum / float64(len(fa)))
}

func experiment(label string, r rule) {
    rxs := funnel(dxs, r)
    rys := funnel(dys, r)
    fmt.Println(label, " :      x        y")
    fmt.Printf("Mean    :  %7.4f, %7.4f\n", mean(rxs), mean(rys))
    fmt.Printf("Std Dev :  %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
    fmt.Println()
}

func main() {
    experiment("Rule 1", func(_, _ float64) float64 {
        return 0.0
    })
    experiment("Rule 2", func(_, dz float64) float64 {
        return -dz
    })
    experiment("Rule 3", func(z, dz float64) float64 {
        return -(z + dz)
    })
    experiment("Rule 4", func(z, dz float64) float64 {
        return z + dz
    })
}
Task: Exponentiation with infix operators in (or operating on) the base




Go: package main

import (
    "fmt"
    "math"
)

type float float64

func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }

func main() {
    ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"}
    for _, x := range []float{float(-5), float(5)} {
        for _, e := range []float{float(2), float(3)} {
            fmt.Printf("x = %2.0f e = %0.0f | ", x, e)
            fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e))
            fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e))
            fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e))
            fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e)))
        }
    }
}
Task: Concatenate two primes is also prime




Go: package main

import (
    "fmt"
    "rcu"
    "sort"
)

func main() {
    const LIMIT = 99
    primes := rcu.Primes(LIMIT)
    rmap := make(map[int]bool)
    for _, p := range primes {
        for _, q := range primes {
            var pq int
            if q < 10 {
                pq = p*10 + q
            } else {
                pq = p*100 + q
            }
            if rcu.IsPrime(pq) {
                rmap[pq] = true
            }
        }
    }
    results := make([]int, len(rmap))
    i := 0
    for k := range rmap {
        results[i] = k
        i++
    }
    sort.Ints(results)
    fmt.Println("Two primes under 100 concatenated together to form another prime:")
    for i, p := range results {
        fmt.Printf("%5s ", rcu.Commatize(p))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n\nFound", len(results), "such concatenated primes.")
}
Task: Reverse the order of lines in a text file while preserving the contents of each line




Go: package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "log"
    "runtime"
)

func main() {
    fileName1 := "rodgers.txt"
    fileName2 := "rodgers_reversed.txt"
    lineBreak := "\n"
    if runtime.GOOS == "windows" {
        lineBreak = "\r\n"
    }
    
    b, err := ioutil.ReadFile(fileName1)
    if err != nil {
        log.Fatal(err)
    }
    lines := bytes.Split(b, []byte(lineBreak))
    
    if len(lines[len(lines)-1]) == 0 {
        lines = lines[:len(lines)-1]
    }

    
    for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 {
        lines[i], lines[j] = lines[j], lines[i]
    }
    b = bytes.Join(lines, []byte(lineBreak))
    if err = ioutil.WriteFile(fileName2, b, 0o666); err != nil {
        log.Fatal(err)
    }
    
    b, err = ioutil.ReadFile(fileName2)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(b))
}
Task: Assertions in design by contract




Go: func assert(t bool, s string) {
	if !t {
		panic(s)
	}
}

	assert(c == 0, "some text here")
Task: Colour pinstripe_Printer




Go: package main
 
import (
    "github.com/fogleman/gg"
    "log"
    "os/exec"
    "runtime"
)

var palette = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}
 
func pinstripe(dc *gg.Context) {
    w := dc.Width()
    h := dc.Height() / 7
    for b := 1; b <= 11; b++ {
        for x, ci := 0, 0; x < w; x, ci = x+b, ci+1 {
            dc.SetHexColor(palette[ci%8])
            y := h * (b - 1)
            dc.DrawRectangle(float64(x), float64(y), float64(b), float64(h))
            dc.Fill()
        }
    }
}
 
func main() {
    dc := gg.NewContext(842, 595)
    pinstripe(dc)
    fileName := "color_pinstripe.png"
    dc.SavePNG(fileName)
    var cmd *exec.Cmd
    if runtime.GOOS == "windows" {
        cmd = exec.Command("mspaint", "/pt", fileName)
    } else {
        cmd = exec.Command("lp", fileName)
    }
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }   
}