WeixiangYan/CodeTransOcean huggingface dataset:
Task: SHA-256 Merkle tree

C: #include <glib.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

guchar* sha256_merkle_tree(FILE* in, size_t block_size) {
    gchar* buffer = g_malloc(block_size);
    GPtrArray* hashes = g_ptr_array_new_with_free_func(g_free);
    gssize digest_length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
    GChecksum* checksum = g_checksum_new(G_CHECKSUM_SHA256);
    size_t bytes;
    while ((bytes = fread(buffer, 1, block_size, in)) > 0) {
        g_checksum_reset(checksum);
        g_checksum_update(checksum, (guchar*)buffer, bytes);
        gsize len = digest_length;
        guchar* digest = g_malloc(len);
        g_checksum_get_digest(checksum, digest, &len);
        g_ptr_array_add(hashes, digest);
    }
    g_free(buffer);
    guint hashes_length = hashes->len;
    if (hashes_length == 0) {
        g_ptr_array_free(hashes, TRUE);
        g_checksum_free(checksum);
        return NULL;
    }
    while (hashes_length > 1) {
        guint j = 0;
        for (guint i = 0; i < hashes_length; i += 2, ++j) {
            guchar* digest1 = g_ptr_array_index(hashes, i);
            guchar* digest_out = g_ptr_array_index(hashes, j);
            if (i + 1 < hashes_length) {
                guchar* digest2 = g_ptr_array_index(hashes, i + 1);
                g_checksum_reset(checksum);
                g_checksum_update(checksum, digest1, digest_length);
                g_checksum_update(checksum, digest2, digest_length);
                gsize len = digest_length;
                g_checksum_get_digest(checksum, digest_out, &len);
            } else {
                memcpy(digest_out, digest1, digest_length);
            }
        }
        hashes_length = j;
    }
    guchar* result = g_ptr_array_steal_index(hashes, 0);
    g_ptr_array_free(hashes, TRUE);
    g_checksum_free(checksum);
    return result;
}

int main(int argc, char** argv) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s filename\n", argv[0]);
        return EXIT_FAILURE;
    }
    FILE* in = fopen(argv[1], "rb");
    if (in) {
        guchar* digest = sha256_merkle_tree(in, 1024);
        fclose(in);
        if (digest) {
            gssize length = g_checksum_type_get_length(G_CHECKSUM_SHA256);
            for (gssize i = 0; i < length; ++i)
                printf("%02x", digest[i]);
            printf("\n");
            g_free(digest);
        }
    } else {
        perror(argv[1]);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Task: Write to Windows event log








VB: Sub write_event(event_type,msg)
	Set objShell = CreateObject("WScript.Shell")
	Select Case event_type
		Case "SUCCESS"
			n = 0
		Case "ERROR"
			n = 1
		Case "WARNING"
			n = 2
		Case "INFORMATION"
			n = 4
		Case "AUDIT_SUCCESS"
			n = 8
		Case "AUDIT_FAILURE"
			n = 16
	End Select
	objShell.LogEvent n, msg
	Set objShell = Nothing
End Sub

Call write_event("INFORMATION","This is a test information.")
Task: ASCII control characters








VB: Enum AsciiControlChar
    NUL = &H00  
    SOH = &H01  
    STX = &H02  
    ETX = &H03  
    EOT = &H04  
    ENQ = &H05  
    ACK = &H06  
    BEL = &H07  
    BS = &H08   
    HT = &H09   
    LF = &H0A   
    VT = &H0B   
    FF = &H0C   
    CR = &H0D   
    SO = &H0E   
    SI = &H0F   
    DLE = &H10  
    DC1 = &H11  
    DC2 = &H12  
    DC3 = &H13  
    DC4 = &H14  
    NAK = &H15  
    SYN = &H16  
    ETB = &H17  
    CAN = &H18  
    EM = &H19   
    SUB_ = &H1A 
    ESC = &H1B  
    FS = &H1C   
    GS = &H1D   
    RS = &H1E   
    US = &H1F   
    SP = &H20   
    DEL = &H7F  
End Enum

Print(Hex(AsciiControlChar.CR))
Print(Hex(AsciiControlChar.DEL))
Sleep
Task: Data Encryption Standard








VB: Imports System.IO
Imports System.Security.Cryptography

Module Module1

    
    Function ByteArrayToString(ba As Byte()) As String
        Return BitConverter.ToString(ba).Replace("-", "")
    End Function

    
    
    Function Encrypt(messageBytes As Byte(), passwordBytes As Byte()) As Byte()
        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

        
        Dim provider As New DESCryptoServiceProvider
        Dim transform = provider.CreateEncryptor(passwordBytes, iv)
        Dim mode = CryptoStreamMode.Write

        
        Dim memStream As New MemoryStream
        Dim cryptoStream As New CryptoStream(memStream, transform, mode)
        cryptoStream.Write(messageBytes, 0, messageBytes.Length)
        cryptoStream.FlushFinalBlock()

        
        Dim encryptedMessageBytes(memStream.Length - 1) As Byte
        memStream.Position = 0
        memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length)

        Return encryptedMessageBytes
    End Function

    
    
    Function Decrypt(encryptedMessageBytes As Byte(), passwordBytes As Byte()) As Byte()
        Dim iv As Byte() = {&H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

        
        Dim provider As New DESCryptoServiceProvider
        Dim transform = provider.CreateDecryptor(passwordBytes, iv)
        Dim mode = CryptoStreamMode.Write

        
        Dim memStream As New MemoryStream
        Dim cryptoStream As New CryptoStream(memStream, transform, mode)
        cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length)
        cryptoStream.FlushFinalBlock()

        
        Dim decryptedMessageBytes(memStream.Length - 1) As Byte
        memStream.Position = 0
        memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length)

        Return decryptedMessageBytes
    End Function

    Sub Main()
        Dim keyBytes As Byte() = {&HE, &H32, &H92, &H32, &HEA, &H6D, &HD, &H73}
        Dim plainBytes As Byte() = {&H87, &H87, &H87, &H87, &H87, &H87, &H87, &H87}

        Dim encStr = Encrypt(plainBytes, keyBytes)
        Console.WriteLine("Encoded: {0}", ByteArrayToString(encStr))

        Dim decStr = Decrypt(encStr, keyBytes)
        Console.WriteLine("Decoded: {0}", ByteArrayToString(decStr))
    End Sub

End Module
Task: CalmoSoft primes








VB: #include "isprime.bas"

Dim As Integer Primes(100), PrimeSums(100)
Dim As Integer i, n, Size, Head, Tail, Longest, Sum, SaveHead, SaveTail
i = 0                         
For n = 2 To 100-1
    If isPrime(n) Then Primes(i) = n : i += 1
Next
Size = i                       
PrimeSums(0) = Primes(0)
For i = 1 To Size-1
    PrimeSums(i) = PrimeSums(i-1) + Primes(i)
Next
Longest = 0                    
For Head = Size-1 To 0 Step -1
    Sum = PrimeSums(Head)
    For Tail = 0 To Head
        If Head-Tail > Longest Then
            If IsPrime(Sum) Then
                Longest = Head-Tail
                SaveHead = Head
                SaveTail = Tail
            End If
            Sum -= Primes(Tail)
        End If
    Next
Next

Print "[";
For i = SaveTail To SaveHead
    Print Primes(i); ",";
Next
Print Chr$(8); Chr$(8); " ]"

Sum = 0
For i = SaveTail To SaveHead
    Sum += Primes(i)
    Print Primes(i);
    If i <> SaveHead Then Print " +";
Next
Print Chr$(8); " ="; Sum; " is prime number" 
Print "The longest sequence of CalmoSoft primes ="; Longest+1
Sleep
Task: Worthwhile task shaving








VB: 


Dim As Integer shaved(0 To 8) = {1, 5, 30, 60, 300, 1800, 3600, 21600, 86400}
Dim As String columns(0 To 8) = {" 1 SECOND", " 5 SECONDS", "30 SECONDS", _
" 1 MINUTE", " 5 MINUTES", "30 MINUTES", " 1 HOUR", " 6 HOURS", " 1 DAY"}
Dim As Single diy = 365.25
Dim As Integer minuto = 60
Dim As Integer hora = minuto * 60
Dim As Integer dia = hora * 24
Dim As Integer semana = dia * 7
Dim As Integer mes = dia * diy \ 12
Dim As Integer anno = dia * diy

Dim As Integer freq(0 To 5) = {50 * diy, 5 * diy, diy, diy\7, 12, 1}
Dim As Integer y, x, t, mult = 5

Sub fmtTime(t As Single, interval As String)
    t = Int(t + .5)
    Dim As String pl = Iif(t = 1, "", "S")
    Print Using " ## \       \"; t; interval & pl;
End Sub

Print Spc(34); "HOW OFTEN YOU DO THE TASK"
Print " SHAVED OFF   | 50/DAY        5/DAY       DAILY        WEEKLY       MONTHLY      YEARLY"
Print String (92, "-")
For y = 0 To Ubound(columns)
    Print Using "\        \    |"; columns(y);
    For x = 0 To Ubound(freq)
        t = freq(x) * shaved(y) * mult
        If (t < minuto) Then
            fmtTime (t, "SECOND")
        Elseif (t < hora) Then
            fmtTime (t/minuto, "MINUTE")
        Elseif (t < dia) Then
            fmtTime (t/hora, "HOUR")
        Elseif (t < 14 * dia) Then
            fmtTime (t/dia, "DAY")
        Elseif (t < 9 * semana) Then
            fmtTime (t/semana, "WEEK")
        Elseif (t < anno) Then
            fmtTime (t/mes, "MONTH")
        Else
            Print String (13, " ");
        End If
    Next
    Print
Next
Task: Hello world_Line printer






PHP: <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
Task: Sutherland-Hodgman polygon clipping






PHP: <?php
function clip ($subjectPolygon, $clipPolygon) {

    function inside ($p, $cp1, $cp2) {
        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);
    }
    
    function intersection ($cp1, $cp2, $e, $s) {
        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];
        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];
        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];
        $n2 = $s[0] * $e[1] - $s[1] * $e[0];
        $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]);

        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];
    }
    
    $outputList = $subjectPolygon;
    $cp1 = end($clipPolygon);
    foreach ($clipPolygon as $cp2) {
        $inputList = $outputList;
        $outputList = [];
        $s = end($inputList);
        foreach ($inputList as $e) {
            if (inside($e, $cp1, $cp2)) {
                if (!inside($s, $cp1, $cp2)) {
                    $outputList[] = intersection($cp1, $cp2, $e, $s);
                }
                $outputList[] = $e;
            }
            else if (inside($s, $cp1, $cp2)) {
                $outputList[] = intersection($cp1, $cp2, $e, $s);
            }
            $s = $e;
        }
        $cp1 = $cp2;
    }
    return $outputList;
}

$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];
$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
$clippedPolygon = clip($subjectPolygon, $clipPolygon);

echo json_encode($clippedPolygon);
echo "\n";
?>
Task: Copy a string






PHP: $src = "Hello";
$dst = $src;
Task: Sorting algorithms_Stooge sort


C++: #include <iostream>
#include <time.h>


using namespace std;


class stooge
{
public:
    void sort( int* arr, int start, int end )
    {
        if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
	int n = end - start; if( n > 2 )
	{
	    n /= 3; sort( arr, start, end - n );
	    sort( arr, start + n, end ); sort( arr, start, end - n );
        }
    }
};

int main( int argc, char* argv[] )
{
    srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; 
    cout << "before:\n";
    for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20;  cout << a[x] << " "; }
    s.sort( a, 0, m ); cout << "\n\nafter:\n"; 
    for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; 
    return system( "pause" );
}
Task: Idoneal numbers



C#: using System;

class Program {

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int a, b, c, i, n, s3, ab; var res = new int[65];
    for (n = 1, i = 0; n < 1850; n++) {
      bool found = true;
      for (a = 1; a < n; a++)
         for (b = a + 1, ab = a * b + a + b; b < n; b++, ab += a + 1) {
            if (ab > n) break;
            for (c = b + 1, s3 = ab + (b + a) * b; c < n; c++, s3 += b + a) {
                if (s3 == n) found = false;
                if (s3 >= n) break;
            }
         }
      if (found) res[i++] = n;
    }
    sw.Stop();
    Console.WriteLine("The 65 known Idoneal numbers:");
    for (i = 0; i < res.Length; i++)
      Console.Write("{0,5}{1}", res[i], i % 13 == 12 ? "\n" : "");
    Console.Write("Calculations took {0} ms", sw.Elapsed.TotalMilliseconds);
  }
}
Task: Numbers which are not the sum of distinct squares



C#: using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
 
  
  static bool soms(int n, IEnumerable<int> f) {
    if (n <= 0) return false;
    if (f.Contains(n)) return true;
    switch(n.CompareTo(f.Sum())) {
      case 1: return false;
      case 0: return true;
      case -1:
        var rf = f.Reverse().Skip(1).ToList();
        return soms(n - f.Last(), rf) || soms(n, rf);
    }
    return false;
  }

  static void Main() {
    var sw = System.Diagnostics.Stopwatch.StartNew();
    int c = 0, r, i, g; var s = new List<int>(); var a = new List<int>();
    var sf = "stopped checking after finding {0} sequential non-gaps after the final gap of {1}";
    for (i = 1, g = 1; g >= (i >> 1); i++) {
      if ((r = (int)Math.Sqrt(i)) * r == i) s.Add(i);
      if (!soms(i, s)) a.Add(g = i);
    }
    sw.Stop();
    Console.WriteLine("Numbers which are not the sum of distinct squares:");
    Console.WriteLine(string.Join(", ", a));
    Console.WriteLine(sf, i - g, g);
    Console.Write("found {0} total in {1} ms",
      a.Count, sw.Elapsed.TotalMilliseconds);
  }
}
Task: Common sorted list




Go: package main

import (
    "fmt"
    "sort"
)

func distinctSortedUnion(ll [][]int) []int {
    var res []int
    for _, l := range ll {
        res = append(res, l...)
    }
    set := make(map[int]bool)
    for _, e := range res {
        set[e] = true
    }
    res = res[:0]
    for key := range set {
        res = append(res, key)
    }
    sort.Ints(res)
    return res
}

func main() {
    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}
    fmt.Println("Distinct sorted union of", ll, "is:")
    fmt.Println(distinctSortedUnion(ll))
}
Task: Numeric error propagation




Go: package main

import (
    "fmt"
    "math"
)




type unc struct {
    n float64 
    s float64 
}


func newUnc(n, s float64) *unc {
    return &unc{n, s * s}
}



func (z *unc) errorTerm() float64 {
    return math.Sqrt(z.s)
}









func (z *unc) addC(a *unc, c float64) *unc {
    *z = *a
    z.n += c
    return z
}

func (z *unc) subC(a *unc, c float64) *unc {
    *z = *a
    z.n -= c
    return z
}

func (z *unc) addU(a, b *unc) *unc {
    z.n = a.n + b.n
    z.s = a.s + b.s
    return z
}
func (z *unc) subU(a, b *unc) *unc {
    z.n = a.n - b.n
    z.s = a.s + b.s
    return z
}


func (z *unc) mulC(a *unc, c float64) *unc {
    z.n = a.n * c
    z.s = a.s * c * c
    return z
}

func (z *unc) divC(a *unc, c float64) *unc {
    z.n = a.n / c
    z.s = a.s / (c * c)
    return z
}

func (z *unc) mulU(a, b *unc) *unc {
    prod := a.n * b.n
    z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
    return z
}

func (z *unc) divU(a, b *unc) *unc {
    quot := a.n / b.n
    z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
    return z
}


func (z *unc) expC(a *unc, c float64) *unc {
    f := math.Pow(a.n, c)
    g := f * c / a.n
    z.n = f
    z.s = a.s * g * g
    return z
}

func main() {
    x1 := newUnc(100, 1.1)
    x2 := newUnc(200, 2.2)
    y1 := newUnc(50, 1.2)
    y2 := newUnc(100, 2.3)
    var d, d2 unc
    d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)
    fmt.Println("d:    ", d.n)
    fmt.Println("error:", d.errorTerm())
}
Task: Trabb Pardo–Knuth algorithm




Go: package main

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

func main() {
    
    fmt.Print("Enter 11 numbers: ")
    
    var s [11]float64
    for i := 0; i < 11; {
        if n, _ := fmt.Scan(&s[i]); n > 0 {
            i++
        }
    }
    
    for i, item := range s[:5] {
        s[i], s[10-i] = s[10-i], item
    }
    
    for _, item := range s {
        if result, overflow := f(item); overflow {
            
            log.Printf("f(%g) overflow", item)
        } else {
            
            fmt.Printf("f(%g) = %g\n", item, result)
        }
    }
}

func f(x float64) (float64, bool) {
    result := math.Sqrt(math.Abs(x)) + 5*x*x*x
    return result, result > 400
}
Task: Rate counter




Go: package main

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


type rateStateS struct {
    lastFlush time.Time
    period    time.Duration
    tickCount int
}

func ticRate(pRate *rateStateS) {
    pRate.tickCount++
    now := time.Now()
    if now.Sub(pRate.lastFlush) >= pRate.period {
        
        tps := 0.
        if pRate.tickCount > 0 {
            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
        }
        fmt.Println(tps, "tics per second.")

        
        pRate.tickCount = 0
        pRate.lastFlush = now
    }
}

func somethingWeDo() {
    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) 
}

func main() {
    start := time.Now()

    rateWatch := rateStateS{
        lastFlush: start,
        period:    5 * time.Second,
    }

    
    latest := start
    for latest.Sub(start) < 20*time.Second {
        somethingWeDo()
        ticRate(&rateWatch)
        latest = time.Now()
    }
}
Task: Dice game probabilities




Go: package main

import(
    "math"
    "fmt"
)

func minOf(x, y uint) uint {
    if x < y {
        return x
    }
    return y
}

func throwDie(nSides, nDice, s uint, counts []uint) {
    if nDice == 0 {
        counts[s]++
        return
    }
    for i := uint(1); i <= nSides; i++ {
        throwDie(nSides, nDice - 1, s + i, counts)
    }
}

func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
    len1 := (nSides1 + 1) * nDice1
    c1 := make([]uint, len1)  
    throwDie(nSides1, nDice1, 0, c1)

    len2 := (nSides2 + 1) * nDice2
    c2 := make([]uint, len2)
    throwDie(nSides2, nDice2, 0, c2)
    p12 := math.Pow(float64(nSides1), float64(nDice1)) *
           math.Pow(float64(nSides2), float64(nDice2))

    tot := 0.0
    for i := uint(0); i < len1; i++ {
        for j := uint(0); j < minOf(i, len2); j++ {
            tot += float64(c1[i] * c2[j]) / p12
        }
    }
    return tot
}

func main() {
    fmt.Println(beatingProbability(4, 9, 6, 6))
    fmt.Println(beatingProbability(10, 5, 7, 6))
}
Task: Metronome




Go: package main

import (
	"fmt"
	"time"
)

func main() {
	var bpm = 72.0 
	var bpb = 4    

	d := time.Duration(float64(time.Minute) / bpm)
	fmt.Println("Delay:", d)
	t := time.NewTicker(d)
	i := 1
	for _ = range t.C {
		i--
		if i == 0 {
			i = bpb
			fmt.Printf("\nTICK ")
		} else {
			fmt.Printf("tick ")
		}
	}
}
Task: Sum of elements below main diagonal of matrix




Go: package main

import (
    "fmt"
    "log"
)

func main() {
    m := [][]int{
        {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},
    }
    if len(m) != len(m[0]) {
        log.Fatal("Matrix must be square.")
    }
    sum := 0
    for i := 1; i < len(m); i++ {
        for j := 0; j < i; j++ {
            sum = sum + m[i][j]
        }
    }
    fmt.Println("Sum of elements below main diagonal is", sum)
}
Task: Rep-string




Go: package main

import (
    "fmt"
    "strings"
)

func rep(s string) int {
    for x := len(s) / 2; x > 0; x-- {
        if strings.HasPrefix(s, s[x:]) {
            return x
        }
    }
    return 0
}

const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`

func main() {
    for _, s := range strings.Fields(m) {
        if n := rep(s); n > 0 {
            fmt.Printf("%q  %d rep-string %q\n", s, n, s[:n])
        } else {
            fmt.Printf("%q  not a rep-string\n", s)
        }
    }
}
Task: Idiomatically determine all the lowercase and uppercase letters




Go: package main

import (
	"fmt"
	"unicode"
)

const (
	lcASCII = "abcdefghijklmnopqrstuvwxyz"
	ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)

func main() {
	fmt.Println("ASCII lower case:")
	fmt.Println(lcASCII)
	for l := 'a'; l <= 'z'; l++ {
		fmt.Print(string(l))
	}
	fmt.Println()

	fmt.Println("\nASCII upper case:")
	fmt.Println(ucASCII)
	for l := 'A'; l <= 'Z'; l++ {
		fmt.Print(string(l))
	}
	fmt.Println()

	fmt.Println("\nUnicode version " + unicode.Version)
	showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
	showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
	showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
	showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}

func showRange16(hdr string, rList []unicode.Range16) {
	fmt.Print("\n", hdr, "\n")
	fmt.Printf("%d ranges:\n", len(rList))
	for _, rng := range rList {
		fmt.Printf("%U: ", rng.Lo)
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			fmt.Printf("%c", r)
		}
		fmt.Println()
	}
}

func showRange32(hdr string, rList []unicode.Range32) {
	fmt.Print("\n", hdr, "\n")
	fmt.Printf("%d ranges:\n", len(rList))
	for _, rng := range rList {
		fmt.Printf("%U: ", rng.Lo)
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			fmt.Printf("%c", r)
		}
		fmt.Println()
	}
}
Task: Shift list elements to left by 3




Go: package main

import "fmt"


func lshift(l []int) {
    n := len(l)
    if n < 2 {
        return
    }
    f := l[0]
    for i := 0; i < n-1; i++ {
        l[i] = l[i+1]
    }
    l[n-1] = f
}

func main() {
    l := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println("Original list     :", l)
    for i := 0; i < 3; i++ {
        lshift(l)
    }
    fmt.Println("Shifted left by 3 :", l)
}
Task: Words containing _the_ substring




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
    for _, bword := range bwords {
        s := string(bword)
        if utf8.RuneCountInString(s) > 11 {
            words = append(words, s)
        }
    }
    count := 0
    fmt.Println("Words containing 'the' having a length > 11 in", wordList, "\b:")
    for _, word := range words {
        if strings.Contains(word, "the") {
            count++
            fmt.Printf("%2d: %s\n", count, word)
        }
    }
}
Task: Continued fraction_Arithmetic_G(matrix ng, continued fraction n)




Go: package cf





















type NG4 struct {
	A1, A int64
	B1, B int64
}

func (ng NG4) needsIngest() bool {
	if ng.isDone() {
		panic("b₁==b==0")
	}
	return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}

func (ng NG4) isDone() bool {
	return ng.B1 == 0 && ng.B == 0
}

func (ng *NG4) ingest(t int64) {
	
	
	ng.A1, ng.A, ng.B1, ng.B =
		ng.A+ng.A1*t, ng.A1,
		ng.B+ng.B1*t, ng.B1
}

func (ng *NG4) ingestInfinite() {
	
	
	ng.A, ng.B = ng.A1, ng.B1
}

func (ng *NG4) egest(t int64) {
	
	
	ng.A1, ng.A, ng.B1, ng.B =
		ng.B1, ng.B,
		ng.A1-ng.B1*t, ng.A-ng.B*t
}



func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
	return func() NextFn {
		next := cf()
		done := false
		return func() (int64, bool) {
			if done {
				return 0, false
			}
			for ng.needsIngest() {
				if t, ok := next(); ok {
					ng.ingest(t)
				} else {
					ng.ingestInfinite()
				}
			}
			t := ng.A1 / ng.B1
			ng.egest(t)
			done = ng.isDone()
			return t, true
		}
	}
}