WeixiangYan/CodeTransOcean huggingface dataset:
Task: Longest increasing subsequence




Go: package main

import (
  "fmt"
  "sort"
)

type Node struct {
    val int
    back *Node
}

func lis (n []int) (result []int) {
  var pileTops []*Node
  
  for _, x := range n {
    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
    node := &Node{ x, nil }
    if j != 0 { node.back = pileTops[j-1] }
    if j != len(pileTops) {
      pileTops[j] = node
    } else {
      pileTops = append(pileTops, node)
    }
  }

  if len(pileTops) == 0 { return []int{} }
  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
    result = append(result, node.val)
  }
  
  for i := 0; i < len(result)/2; i++ {
    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
  }
  return
}

func main() {
    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
        fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
    }
}
Task: Metaprogramming




Go: package main

import "fmt"

type person struct{
    name string
    age int
}

func copy(p person) person {
    return person{p.name, p.age}
}

func main() {
    p := person{"Dave", 40}
    fmt.Println(p)
    q := copy(p)
    fmt.Println(q)
     
}
Task: Odd and square numbers




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    pow := 1
    for p := 0; p < 5; p++ {
        low := int(math.Ceil(math.Sqrt(float64(pow))))
        if low%2 == 0 {
            low++
        }
        pow *= 10
        high := int(math.Sqrt(float64(pow)))
        var oddSq []int
        for i := low; i <= high; i += 2 {
            oddSq = append(oddSq, i*i)
        }
        fmt.Println(len(oddSq), "odd squares from", pow/10, "to", pow, "\b:")
        for i := 0; i < len(oddSq); i++ {
            fmt.Printf("%d ", oddSq[i])
            if (i+1)%10 == 0 {
                fmt.Println()
            }
        }
        fmt.Println("\n")
    }
}
Task: Words from neighbour ones




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) >= 9 {
            words = append(words, s)
        }
    }
    count := 0
    var alreadyFound []string
    le := len(words)
    var sb strings.Builder
    for i := 0; i < le-9; i++ {
        sb.Reset()
        for j := i; j < i+9; j++ {
            sb.WriteByte(words[j][j-i])
        }
        word := sb.String()
        ix := sort.SearchStrings(words, word)
        if ix < le && word == words[ix] {
            ix2 := sort.SearchStrings(alreadyFound, word)
            if ix2 == len(alreadyFound) {
                count++
                fmt.Printf("%2d: %s\n", count, word)
                alreadyFound = append(alreadyFound, word)
            }
        }
    }
}
Task: Sum of square and cube digits of an integer are primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    for i := 1; i < 100; i++ {
        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {
            continue
        }
        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {
            fmt.Printf("%d ", i)
        }
    }
    fmt.Println()
}
Task: Dynamic variable names




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
    "strings"
)

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

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    for n < 1 || n > 5 {
        fmt.Print("How many integer variables do you want to create (max 5) : ")
        scanner.Scan()
        n, _ = strconv.Atoi(scanner.Text())
        check(scanner.Err())
    }
    vars := make(map[string]int)
    fmt.Println("OK, enter the variable names and their values, below")
    for i := 1; i <= n; {
        fmt.Println("\n  Variable", i)
        fmt.Print("    Name  : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if _, ok := vars[name]; ok {
            fmt.Println("  Sorry, you've already created a variable of that name, try again")
            continue
        }
        var value int
        var err error
        for {
            fmt.Print("    Value : ")
            scanner.Scan()
            value, err = strconv.Atoi(scanner.Text())
            check(scanner.Err())
            if err != nil {
                fmt.Println("  Not a valid integer, try again")
            } else {
                break
            }
        }
        vars[name] = value
        i++
    }
    fmt.Println("\nEnter q to quit")
    for {
        fmt.Print("\nWhich variable do you want to inspect : ")
        scanner.Scan()
        name := scanner.Text()
        check(scanner.Err())
        if s := strings.ToLower(name); s == "q" {
            return
        }
        v, ok := vars[name]
        if !ok {
            fmt.Println("Sorry there's no variable of that name, try again")
        } else {
            fmt.Println("It's value is", v)
        }
    }
}
Task: Odd squarefree semiprimes




Go: package main

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

func main() {
    primes := rcu.Primes(333)
    var oss []int
    for i := 1; i < len(primes)-1; i++ {
        for j := i + 1; j < len(primes); j++ {
            n := primes[i] * primes[j]
            if n >= 1000 {
                break
            }
            oss = append(oss, n)
        }
    }
    sort.Ints(oss)
    fmt.Println("Odd squarefree semiprimes under 1,000:")
    for i, n := range oss {
        fmt.Printf("%3d ", n)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\n%d such numbers found.\n", len(oss))
}
Task: Square root by hand




Go: package main

import (
    "fmt"
    "math/big"
)

var one = big.NewInt(1)
var ten = big.NewInt(10)
var twenty = big.NewInt(20)
var hundred = big.NewInt(100)

func sqrt(n float64, limit int) {
    if n < 0 {
        log.Fatal("Number cannot be negative")
    }
    count := 0
    for n != math.Trunc(n) {
        n *= 100
        count--
    }
    i := big.NewInt(int64(n))
    j := new(big.Int).Sqrt(i)
    count += len(j.String())
    k := new(big.Int).Set(j)
    d := new(big.Int).Set(j)
    t := new(big.Int)
    digits := 0
    var sb strings.Builder
    for digits < limit {
        sb.WriteString(d.String())
        t.Mul(k, d)
        i.Sub(i, t)
        i.Mul(i, hundred)
        k.Mul(j, twenty)
        d.Set(one)
        for d.Cmp(ten) <= 0 {
            t.Add(k, d)
            t.Mul(t, d)
            if t.Cmp(i) > 0 {
                d.Sub(d, one)
                break
            }
            d.Add(d, one)
        }
        j.Mul(j, ten)
        j.Add(j, d)
        k.Add(k, d)
        digits = digits + 1
    }
    root := strings.TrimRight(sb.String(), "0")
    if len(root) == 0 {
        root = "0"
    }
    if count > 0 {
        root = root[0:count] + "." + root[count:]
    } else if count == 0 {
        root = "0." + root
    } else {
        root = "0." + strings.Repeat("0", -count) + root
    }
    root = strings.TrimSuffix(root, ".")
    fmt.Println(root)
}

func main() {
    numbers := []float64{2, 0.2, 10.89, 625, 0.0001}
    digits := []int{500, 80, 8, 8, 8}
    for i, n := range numbers {
        fmt.Printf("First %d significant digits (at most) of the square root of %g:\n", digits[i], n)
        sqrt(n, digits[i])
        fmt.Println()
    }
}
Task: Primes with digits in nondecreasing order




Go: package main

import (
    "fmt"
    "rcu"
)

func nonDescending(p int) bool {
    var digits []int
    for p > 0 {
        digits = append(digits, p%10)
        p = p / 10
    }
    for i := 0; i < len(digits)-1; i++ {
        if digits[i+1] > digits[i] {
            return false
        }
    }
    return true
}

func main() {
    primes := rcu.Primes(999)
    var nonDesc []int
    for _, p := range primes {
        if nonDescending(p) {
            nonDesc = append(nonDesc, p)
        }
    }
    fmt.Println("Primes below 1,000 with digits in non-decreasing order:")
    for i, n := range nonDesc {
        fmt.Printf("%3d ", n)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n%d such primes found.\n", len(nonDesc))
}
Task: Brilliant numbers




Go: package main

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

var primes = rcu.Primes(1e8 - 1)

type res struct {
    bc   interface{}
    next int
}

func getBrilliant(digits, limit int, countOnly bool) res {
    var brilliant []int
    count := 0
    pow := 1
    next := math.MaxInt
    for k := 1; k <= digits; k++ {
        var s []int
        for _, p := range primes {
            if p >= pow*10 {
                break
            }
            if p > pow {
                s = append(s, p)
            }
        }
        for i := 0; i < len(s); i++ {
            for j := i; j < len(s); j++ {
                prod := s[i] * s[j]
                if prod < limit {
                    if countOnly {
                        count++
                    } else {
                        brilliant = append(brilliant, prod)
                    }
                } else {
                    if next > prod {
                        next = prod
                    }
                    break
                }
            }
        }
        pow *= 10
    }
    if countOnly {
        return res{count, next}
    }
    return res{brilliant, next}
}

func main() {
    fmt.Println("First 100 brilliant numbers:")
    brilliant := getBrilliant(2, 10000, false).bc.([]int)
    sort.Ints(brilliant)
    brilliant = brilliant[0:100]
    for i := 0; i < len(brilliant); i++ {
        fmt.Printf("%4d ", brilliant[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println()
    for k := 1; k <= 13; k++ {
        limit := int(math.Pow(10, float64(k)))
        r := getBrilliant(k, limit, true)
        total := r.bc.(int)
        next := r.next
        climit := rcu.Commatize(limit)
        ctotal := rcu.Commatize(total + 1)
        cnext := rcu.Commatize(next)
        fmt.Printf("First >= %18s is %14s in the series: %18s\n", climit, ctotal, cnext)
    }
}
Task: Calkin-Wilf sequence




Go: package main

import (
    "fmt"
    "math"
    "math/big"
    "strconv"
    "strings"
)

func calkinWilf(n int) []*big.Rat {
    cw := make([]*big.Rat, n+1)
    cw[0] = big.NewRat(1, 1)
    one := big.NewRat(1, 1)
    two := big.NewRat(2, 1)
    for i := 1; i < n; i++ {
        t := new(big.Rat).Set(cw[i-1])
        f, _ := t.Float64()
        f = math.Floor(f)
        t.SetFloat64(f)
        t.Mul(t, two)
        t.Sub(t, cw[i-1])
        t.Add(t, one)
        t.Inv(t)
        cw[i] = new(big.Rat).Set(t)
    }
    return cw
}

func toContinued(r *big.Rat) []int {
    a := r.Num().Int64()
    b := r.Denom().Int64()
    var res []int
    for {
        res = append(res, int(a/b))
        t := a % b
        a, b = b, t
        if a == 1 {
            break
        }
    }
    le := len(res)
    if le%2 == 0 { 
        res[le-1]--
        res = append(res, 1)
    }
    return res
}

func getTermNumber(cf []int) int {
    b := ""
    d := "1"
    for _, n := range cf {
        b = strings.Repeat(d, n) + b
        if d == "1" {
            d = "0"
        } else {
            d = "1"
        }
    }
    i, _ := strconv.ParseInt(b, 2, 64)
    return int(i)
}

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() {
    cw := calkinWilf(20)
    fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
    for i := 1; i <= 20; i++ {
        fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
    }
    fmt.Println()
    r := big.NewRat(83116, 51639)
    cf := toContinued(r)
    tn := getTermNumber(cf)
    fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}
Task: Order disjoint list items




Go: package main

import (
	"fmt"
	"sort"
	"strings"
)

type indexSort struct {
	val sort.Interface
	ind []int
}

func (s indexSort) Len() int           { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
	s.val.Swap(s.ind[i], s.ind[j])
	s.ind[i], s.ind[j] = s.ind[j], s.ind[i]
}

func disjointSliceSort(m, n []string) []string {
	s := indexSort{sort.StringSlice(m), make([]int, 0, len(n))}
	used := make(map[int]bool)
	for _, nw := range n {
		for i, mw := range m {
			if used[i] || mw != nw {
				continue
			}
			used[i] = true
			s.ind = append(s.ind, i)
			break
		}
	}
	sort.Sort(s)
	return s.val.(sort.StringSlice)
}

func disjointStringSort(m, n string) string {
	return strings.Join(
		disjointSliceSort(strings.Fields(m), strings.Fields(n)), " ")
}

func main() {
	for _, data := range []struct{ m, n string }{
		{"the cat sat on the mat", "mat cat"},
		{"the cat sat on the mat", "cat mat"},
		{"A B C A B C A B C", "C A C A"},
		{"A B C A B D A B E", "E A D A"},
		{"A B", "B"},
		{"A B", "B A"},
		{"A B B A", "B A"},
	} {
		mp := disjointStringSort(data.m, data.n)
		fmt.Printf("%s → %s » %s\n", data.m, data.n, mp)
	}

}
Task: Prime words




Go: package main

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

func isPrime(n int) bool {
    if n < 2 {
        return false
    }
    if n%2 == 0 {
        return n == 2
    }
    if n%3 == 0 {
        return n == 3
    }
    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() {
    
    var primeRunes []rune
    for i := 33; i < 256; i += 2 {
        if isPrime(i) {
            primeRunes = append(primeRunes, rune(i))
        }
    }
    primeString := string(primeRunes)
    wordList := "unixdict.txt"
    b, err := ioutil.ReadFile(wordList)
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    fmt.Println("Prime words in", wordList, "are:")
    for _, bword := range bwords {
        word := string(bword)
        ok := true
        for _, c := range word {
            if !strings.ContainsRune(primeString, c) {
                ok = false
                break
            }
        }
        if ok {
            fmt.Println(word)
        }
    }
}
Task: Palindromic primes




Go: package main

import (
    "fmt"
    "rcu"
)

func reversed(n int) int {
    rev := 0
    for n > 0 {
        rev = rev*10 + n%10
        n /= 10
    }
    return rev
}

func main() {
    primes := rcu.Primes(99999)
    var pals []int
    for _, p := range primes {
        if p == reversed(p) {
            pals = append(pals, p)
        }
    }
    fmt.Println("Palindromic primes under 1,000:")
    var smallPals, bigPals []int
    for _, p := range pals {
        if p < 1000 {
            smallPals = append(smallPals, p)
        } else {
            bigPals = append(bigPals, p)
        }
    }
    rcu.PrintTable(smallPals, 10, 3, false)
    fmt.Println()
    fmt.Println(len(smallPals), "such primes found.")

    fmt.Println("\nAdditional palindromic primes under 100,000:")
    rcu.PrintTable(bigPals, 10, 6, true)
    fmt.Println()
    fmt.Println(len(bigPals), "such primes found,", len(pals), "in all.")
}
Task: Duffinian numbers




Go: package main

import (
    "fmt"
    "math"
    "rcu"
)

func isSquare(n int) bool {
    s := int(math.Sqrt(float64(n)))
    return s*s == n
}

func main() {
    limit := 200000 
    d := rcu.PrimeSieve(limit-1, true)
    d[1] = false
    for i := 2; i < limit; i++ {
        if !d[i] {
            continue
        }
        if i%2 == 0 && !isSquare(i) && !isSquare(i/2) {
            d[i] = false
            continue
        }
        sigmaSum := rcu.SumInts(rcu.Divisors(i))
        if rcu.Gcd(sigmaSum, i) != 1 {
            d[i] = false
        }
    }

    var duff []int
    for i := 1; i < len(d); i++ {
        if d[i] {
            duff = append(duff, i)
        }
    }
    fmt.Println("First 50 Duffinian numbers:")
    rcu.PrintTable(duff[0:50], 10, 3, false)

    var triplets [][3]int
    for i := 2; i < limit; i++ {
        if d[i] && d[i-1] && d[i-2] {
            triplets = append(triplets, [3]int{i - 2, i - 1, i})
        }
    }
    fmt.Println("\nFirst 56 Duffinian triplets:")
    for i := 0; i < 14; i++ {
        s := fmt.Sprintf("%6v", triplets[i*4:i*4+4])
        fmt.Println(s[1 : len(s)-1])
    }
}
Task: Sylvester's sequence




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewInt(1)
    two := big.NewInt(2)
    next := new(big.Int)
    sylvester := []*big.Int{two}
    prod := new(big.Int).Set(two)
    count := 1
    for count < 10 {
        next.Add(prod, one)
        sylvester = append(sylvester, new(big.Int).Set(next))
        count++
        prod.Mul(prod, next)
    }
    fmt.Println("The first 10 terms in the Sylvester sequence are:")
    for i := 0; i < 10; i++ {
        fmt.Println(sylvester[i])
    }

    sumRecip := new(big.Rat)
    for _, s := range sylvester {
        sumRecip.Add(sumRecip, new(big.Rat).SetFrac(one, s))
    }
    fmt.Println("\nThe sum of their reciprocals as a rational number is:")
    fmt.Println(sumRecip)
    fmt.Println("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
    fmt.Println(sumRecip.FloatString(211))
}
Task: Harmonic series




Go: package main

import (
    "fmt"
    "math/big"
)

func harmonic(n int) *big.Rat {
    sum := new(big.Rat)
    for i := int64(1); i <= int64(n); i++ {
        r := big.NewRat(1, i)
        sum.Add(sum, r)
    }
    return sum
}

func main() {
    fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:")
    numbers := make([]int, 21)
    for i := 1; i <= 20; i++ {
        numbers[i-1] = i
    }
    numbers[20] = 100
    for _, i := range numbers {
        fmt.Printf("%3d : %s\n", i, harmonic(i))
    }

    fmt.Println("\nThe first harmonic number to exceed the following integers is:")
    const limit = 10
    for i, n, h := 1, 1, 0.0; i <= limit; n++ {
        h += 1.0 / float64(n)
        if h > float64(i) {
            fmt.Printf("integer = %2d  -> n = %6d  ->  harmonic number = %9.6f (to 6dp)\n", i, n, h)
            i++
        }
    }
}
Task: Runtime evaluation_In an environment




Go: package main

import (
    "bitbucket.org/binet/go-eval/pkg/eval"
    "fmt"
    "go/parser"
    "go/token"
)

func main() {
    
    squareExpr := "x*x"

    
    fset := token.NewFileSet()
    squareAst, err := parser.ParseExpr(squareExpr)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    w := eval.NewWorld()

    
    wVar := new(intV)

    
    err = w.DefineVar("x", eval.IntType, wVar)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    squareCode, err := w.CompileExpr(fset, squareAst)
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar = 5
    
    r0, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    *wVar--
    
    r1, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    
    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}


type intV int64

func (v *intV) String() string              { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64      { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
    *v = intV(o.(eval.IntValue).Get(t))
}
Task: Reverse the gender of a string




Go: package main

import (
    "fmt"
    "strings"
)

func reverseGender(s string) string {
    if strings.Contains(s, "She") {
        return strings.Replace(s, "She", "He", -1)
    } else if strings.Contains(s, "He") {
        return strings.Replace(s, "He", "She", -1)
    }
    return s
}

func main() {
    s := "She was a soul stripper. She took my heart!"
    t := reverseGender(s)
    fmt.Println(t)
    fmt.Println(reverseGender(t))
}
Task: Runtime evaluation




Go: package main
import (
	"fmt"
	"bitbucket.org/binet/go-eval/pkg/eval"
	"go/token"
)

func main() {
	w := eval.NewWorld();
	fset := token.NewFileSet();

	code, err := w.Compile(fset, "1 + 2")
	if err != nil {
		fmt.Println("Compile error");
		return
	}

	val, err := code.Run();
	if err != nil {
		fmt.Println("Run time error");
		return;
	}
	fmt.Println("Return value:", val) 

}
Task: Index finite lists of positive integers




Go: package main

import (
    "fmt"
    "math/big"
)

func rank(l []uint) (r big.Int) {
    for _, n := range l {
        r.Lsh(&r, n+1)
        r.SetBit(&r, int(n), 1)
    }
    return
}

func unrank(n big.Int) (l []uint) {
    m := new(big.Int).Set(&n)
    for a := m.BitLen(); a > 0; {
        m.SetBit(m, a-1, 0)
        b := m.BitLen()
        l = append(l, uint(a-b-1))
        a = b
    }
    return
}

func main() {
    var b big.Int
    for i := 0; i <= 10; i++ {
        b.SetInt64(int64(i))
        u := unrank(b)
        r := rank(u)
        fmt.Println(i, u, &r)
    }
    b.SetString("12345678901234567890", 10)
    u := unrank(b)
    r := rank(u)
    fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r)
}
Task: Generate random numbers without repeating a value




Go: package main

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




func generate(from, to int64) {
    if to < from || from < 0 {
        log.Fatal("Invalid range.")
    }
    span := to - from + 1
    generated := make([]bool, span) 
    count := span
    for count > 0 {
        n := from + rand.Int63n(span) 
        if !generated[n-from] {
            generated[n-from] = true
            fmt.Printf("%2d ", n)
            count--
        }
    }
    fmt.Println()
}

func main() {
    rand.Seed(time.Now().UnixNano())

    
    for i := 1; i <= 5; i++ {
        generate(1, 20)
    }
}
Task: Safe and Sophie Germain primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    var sgp []int
    p := 2
    count := 0
    for count < 50 {
        if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) {
            sgp = append(sgp, p)
            count++
        }
        if p != 2 {
            p = p + 2
        } else {
            p = 3
        }
    }
    fmt.Println("The first 50 Sophie Germain primes are:")
    for i := 0; i < len(sgp); i++ {
        fmt.Printf("%5s ", rcu.Commatize(sgp[i]))
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Conjugate a Latin verb




Go: package main

import (
    "fmt"
    "log"
)

var endings = [][]string{
    {"o", "as", "at", "amus", "atis", "ant"},
    {"eo", "es", "et", "emus", "etis", "ent"},
    {"o", "is", "it", "imus", "itis", "unt"},
    {"io", "is", "it", "imus", "itis", "iunt"},
}

var infinEndings = []string{"are", "ēre", "ere", "ire"}

var pronouns = []string{"I", "you (singular)", "he, she or it", "we", "you (plural)", "they"}

var englishEndings = []string{"", "", "s", "", "", ""}

func conjugate(infinitive, english string) {
    letters := []rune(infinitive)
    le := len(letters)
    if le < 4 {
        log.Fatal("Infinitive is too short for a regular verb.")
    }
    infinEnding := string(letters[le-3:])
    conj := -1
    for i, s := range infinEndings {
        if s == infinEnding {
            conj = i
            break
        }
    }
    if conj == -1 {
        log.Fatalf("Infinitive ending -%s not recognized.", infinEnding)
    }
    stem := string(letters[:le-3])
    fmt.Printf("Present indicative tense, active voice, of '%s' to '%s':\n", infinitive, english)
    for i, ending := range endings[conj] {
        fmt.Printf("    %s%-4s  %s %s%s\n", stem, ending, pronouns[i], english, englishEndings[i])
    }
    fmt.Println()
}

func main() {
    pairs := [][2]string{{"amare", "love"}, {"vidēre", "see"}, {"ducere", "lead"}, {"audire", "hear"}}
    for _, pair := range pairs {
        conjugate(pair[0], pair[1])
    }
}