WeixiangYan/CodeTransOcean huggingface dataset:
Task: Find Chess960 starting position identifier




Go: package main

import (
    "fmt"
    "log"
    "strings"
)

var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔")
var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"}
var g2lMap = map[rune]string{
    '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K",
    '♖': "R", '♘': "N", '♗': "B", '♕': "Q", '♔': "K",
}

var ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9}

func g2l(pieces string) string {
    lets := ""
    for _, p := range pieces {
        lets += g2lMap[p]
    }
    return lets
}

func spid(pieces string) int {
    pieces = g2l(pieces) 

    
    if len(pieces) != 8 {
        log.Fatal("There must be exactly 8 pieces.")
    }
    for _, one := range "KQ" {
        count := 0
        for _, p := range pieces {
            if p == one {
                count++
            }
        }
        if count != 1 {
            log.Fatalf("There must be one %s.", names[one])
        }
    }
    for _, two := range "RNB" {
        count := 0
        for _, p := range pieces {
            if p == two {
                count++
            }
        }
        if count != 2 {
            log.Fatalf("There must be two %s.", names[two])
        }
    }
    r1 := strings.Index(pieces, "R")
    r2 := strings.Index(pieces[r1+1:], "R") + r1 + 1
    k := strings.Index(pieces, "K")
    if k < r1 || k > r2 {
        log.Fatal("The king must be between the rooks.")
    }
    b1 := strings.Index(pieces, "B")
    b2 := strings.Index(pieces[b1+1:], "B") + b1 + 1
    if (b2-b1)%2 == 0 {
        log.Fatal("The bishops must be on opposite color squares.")
    }

    
    piecesN := strings.ReplaceAll(pieces, "Q", "")
    piecesN = strings.ReplaceAll(piecesN, "B", "")
    n1 := strings.Index(piecesN, "N")
    n2 := strings.Index(piecesN[n1+1:], "N") + n1 + 1
    np := fmt.Sprintf("%d%d", n1, n2)
    N := ntable[np]

    piecesQ := strings.ReplaceAll(pieces, "B", "")
    Q := strings.Index(piecesQ, "Q")

    D := strings.Index("0246", fmt.Sprintf("%d", b1))
    L := strings.Index("1357", fmt.Sprintf("%d", b2))
    if D == -1 {
        D = strings.Index("0246", fmt.Sprintf("%d", b2))
        L = strings.Index("1357", fmt.Sprintf("%d", b1))
    }

    return 96*N + 16*Q + 4*D + L
}

func main() {
    for _, pieces := range []string{"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♖♕♘♗♗♔♖♘", "♖♘♕♗♗♔♖♘"} {
        fmt.Printf("%s or %s has SP-ID of %d\n", pieces, g2l(pieces), spid(pieces))
    }
}
Task: Terminal control_Restricted width positional input_No wrapping




Go: package main


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

var conOut = C.GetStdHandle(C.STD_OUTPUT_HANDLE)

func setCursor(p C.COORD) {
    C.SetConsoleCursorPosition(conOut, p)
}

func cls() {
    cmd := exec.Command("cmd", "/c", "cls")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

func getInput(row, col, width int) string {
    if row < 0 || row > 20 || col < 0 || width < 1 || width > 78 || col > (79 - width) {
        panic("Invalid parameter(s) to getInput. Terminating program")
    }
    coord := C.COORD{C.short(col), C.short(row)}
    setCursor(coord)
    var sb []byte
    full := false
    loop:
    for {
        ch := C._getch()                         
        switch c := byte(ch); c {
        case 3, 13:
            break loop                           
        case 8:
            if len(sb) > 0 {                     
		fmt.Print("\b \b")
                sb = sb[:len(sb) - 1]
            }
        case 0, 224:
            C._getch()                           
        default:
            if c >= 32 && c <= 126 && !full {
                C._putch(ch)                     
                sb = append(sb, c)
            }
        }
        full = len(sb) == width                  
    }
    return string(sb)
}

func main() {
    cls() 
    s := getInput(2, 4, 8) 
    coord := C.COORD{0, 22}
    setCursor(coord)
    fmt.Printf("You entered '%s'\n", s)
}
Task: The ISAAC cipher




Go: package main

import "fmt"

const (
    msg = "a Top Secret secret"
    key = "this is my secret key"
)

func main() {
    var z state
    z.seed(key)
    fmt.Println("Message: ", msg)
    fmt.Println("Key    : ", key)
    fmt.Println("XOR    : ", z.vernam(msg))
}

type state struct {
    aa, bb, cc uint32
    mm         [256]uint32
    randrsl    [256]uint32
    randcnt    int
}

func (z *state) isaac() {
    z.cc++
    z.bb += z.cc
    for i, x := range z.mm {
        switch i % 4 {
        case 0:
            z.aa = z.aa ^ z.aa<<13
        case 1:
            z.aa = z.aa ^ z.aa>>6
        case 2:
            z.aa = z.aa ^ z.aa<<2
        case 3:
            z.aa = z.aa ^ z.aa>>16
        }
        z.aa += z.mm[(i+128)%256]
        y := z.mm[x>>2%256] + z.aa + z.bb
        z.mm[i] = y
        z.bb = z.mm[y>>10%256] + x
        z.randrsl[i] = z.bb
    }
}

func (z *state) randInit() {
    const gold = uint32(0x9e3779b9)
    a := [8]uint32{gold, gold, gold, gold, gold, gold, gold, gold}
    mix1 := func(i int, v uint32) {
        a[i] ^= v
        a[(i+3)%8] += a[i]
        a[(i+1)%8] += a[(i+2)%8]
    }
    mix := func() {
        mix1(0, a[1]<<11)
        mix1(1, a[2]>>2)
        mix1(2, a[3]<<8)
        mix1(3, a[4]>>16)
        mix1(4, a[5]<<10)
        mix1(5, a[6]>>4)
        mix1(6, a[7]<<8)
        mix1(7, a[0]>>9)
    }
    for i := 0; i < 4; i++ {
        mix()
    }
    for i := 0; i < 256; i += 8 {
        for j, rj := range z.randrsl[i : i+8] {
            a[j] += rj
        }
        mix()
        for j, aj := range a {
            z.mm[i+j] = aj
        }
    }
    for i := 0; i < 256; i += 8 {
        for j, mj := range z.mm[i : i+8] {
            a[j] += mj
        }
        mix()
        for j, aj := range a {
            z.mm[i+j] = aj
        }
    }
    z.isaac()
}

func (z *state) seed(seed string) {
    for i, r := range seed {
        if i == 256 {
            break
        }
        z.randrsl[i] = uint32(r)
    }
    z.randInit()
}

func (z *state) random() (r uint32) {
    r = z.randrsl[z.randcnt]
    z.randcnt++
    if z.randcnt == 256 {
        z.isaac()
        z.randcnt = 0
    }
    return
}

func (z *state) randA() byte {
    return byte(z.random()%95 + 32)
}

func (z *state) vernam(msg string) string {
    b := []byte(msg)
    for i := range b {
        b[i] ^= z.randA()
    }
    return fmt.Sprintf("%X", b)
}
Task: Terminal control_Restricted width positional input_With wrapping




Go: package main


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

var conOut = C.GetStdHandle(C.STD_OUTPUT_HANDLE)

func setCursor(p C.COORD) {
    C.SetConsoleCursorPosition(conOut, p)
}

func cls() {
    cmd := exec.Command("cmd", "/c", "cls")
    cmd.Stdout = os.Stdout
    cmd.Run()
}

func getInput(row, col, width int) string {
    if row < 0 || row > 20 || col < 0 || width < 1 || width > 78 || col > (79 - width) {
        panic("Invalid parameter(s) to getInput. Terminating program")
    }
    coord := C.COORD{C.short(col), C.short(row)}
    setCursor(coord)
    var sb []byte
    wlen := 0                                    
    full := false
    loop:
    for {
        ch := C._getch()                         
        switch c := byte(ch); c {
        case 3, 13:
            break loop                           
        case 8:
            if wlen > 0 {                        
		fmt.Print("\b \b")
                sb = sb[:len(sb) - 1]
                wlen--
            }
            if len(sb) > wlen {
		coord.X = C.short(col)
                coord.Y = C.short(row)
                setCursor(coord)
                fmt.Print(string(sb)[len(sb) - width:])
                wlen = width
            }
        case 0, 224:
            C._getch()                           
        default:
            if c >= 32 && c <= 126 {             
                sb = append(sb, c)
                if !full {
                    C._putch(ch)
                    wlen++
                } else if len(sb) > wlen {
		    coord.X = C.short(col)
                    coord.Y = C.short(row)
                    setCursor(coord)
                    fmt.Print(string(sb)[len(sb) - width:])
                }
            }
        }
        full = wlen == width                     
    }
    return string(sb)
}

func main() {
    cls() 
    s := getInput(2, 4, 8) 
    coord := C.COORD{0, 22}
    setCursor(coord)
    fmt.Printf("You entered '%s'\n", s)
}
Task: Gradient descent




Go: package main

import (
    "fmt"
    "math"
)

func steepestDescent(x []float64, alpha, tolerance float64) {
    n := len(x)
    g0 := g(x) 

    
    fi := gradG(x)

    
    delG := 0.0
    for i := 0; i < n; i++ {
        delG += fi[i] * fi[i]
    }
    delG = math.Sqrt(delG)
    b := alpha / delG

    
    for delG > tolerance {
        
        for i := 0; i < n; i++ {
            x[i] -= b * fi[i]
        }

        
        fi = gradG(x)

        
        delG = 0
        for i := 0; i < n; i++ {
            delG += fi[i] * fi[i]
        }
        delG = math.Sqrt(delG)
        b = alpha / delG

        
        g1 := g(x)

        
        if g1 > g0 {
            alpha /= 2
        } else {
            g0 = g1
        }
    }
}


func gradG(p []float64) []float64 {
    z := make([]float64, len(p))
    x := p[0]
    y := p[1]
    z[0] = 2*(x-1)*math.Exp(-y*y) - 4*x*math.Exp(-2*x*x)*y*(y+2)
    z[1] = -2*(x-1)*(x-1)*y*math.Exp(-y*y) + math.Exp(-2*x*x)*(y+2) + math.Exp(-2*x*x)*y
    return z
}


func g(x []float64) float64 {
    return (x[0]-1)*(x[0]-1)*
        math.Exp(-x[1]*x[1]) + x[1]*(x[1]+2)*
        math.Exp(-2*x[0]*x[0])
}

func main() {
    tolerance := 0.0000006
    alpha := 0.1
    x := []float64{0.1, -1} 

    steepestDescent(x, alpha, tolerance)
    fmt.Println("Testing steepest descent method:")
    fmt.Printf("The minimum is at x = %f, y = %f for which f(x, y) = %f.\n", x[0], x[1], g(x))
}
Task: Permutations_Rank of a permutation




Go: package main

import (
    "fmt"
    "math/rand"
)


func MRPerm(q, n int) []int {
    p := ident(n)
    var r int
    for n > 0 {
        q, r = q/n, q%n
        n--
        p[n], p[r] = p[r], p[n]
    }
    return p
}


func ident(n int) []int {
    p := make([]int, n)
    for i := range p {
        p[i] = i
    }
    return p
}


func MRRank(p []int) (r int) {
    p = append([]int{}, p...)
    inv := inverse(p)
    for i := len(p) - 1; i > 0; i-- {
        s := p[i]
        p[inv[i]] = s
        inv[s] = inv[i]
    }
    for i := 1; i < len(p); i++ {
        r = r*(i+1) + p[i]
    }
    return
}


func inverse(p []int) []int {
    r := make([]int, len(p))
    for i, x := range p {
        r[x] = i
    }
    return r
}


func fact(n int) (f int) {
    for f = n; n > 2; {
        n--
        f *= n
    }
    return
}

func main() {
    n := 3
    fmt.Println("permutations of", n, "items")
    f := fact(n)
    for i := 0; i < f; i++ {
        p := MRPerm(i, n)
        fmt.Println(i, p, MRRank(p))
    }
    n = 12
    fmt.Println("permutations of", n, "items")
    f = fact(n)
    m := map[int]bool{}
    for len(m) < 4 {
        r := rand.Intn(f)
        if m[r] {
            continue
        }
        m[r] = true
        fmt.Println(r, MRPerm(r, n))
    }
}
Task: First power of 2 that has leading decimal digits of 12




Go: package main

import (
    "fmt"
    "math"
    "time"
)

const ld10 = math.Ln2 / math.Ln10

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

func p(L, n uint64) uint64 {
    i := L
    digits := uint64(1)
    for i >= 10 {
        digits *= 10
        i /= 10
    }
    count := uint64(0)
    for i = 0; count < n; i++ {
        e := math.Exp(math.Ln10 * math.Mod(float64(i)*ld10, 1))
        if uint64(math.Trunc(e*float64(digits))) == L {
            count++            
        }
    }
    return i - 1
}

func main() {
    start := time.Now()
    params := [][2]uint64{{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}}
    for _, param := range params {
        fmt.Printf("p(%d, %d) = %s\n", param[0], param[1], commatize(p(param[0], param[1])))
    }
    fmt.Printf("\nTook %s\n", time.Since(start))
}
Task: Stirling numbers of the second kind




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    limit := 100
    last := 12
    s2 := make([][]*big.Int, limit+1)
    for n := 0; n <= limit; n++ {
        s2[n] = make([]*big.Int, limit+1)
        for k := 0; k <= limit; k++ {
            s2[n][k] = new(big.Int)
        }
        s2[n][n].SetInt64(int64(1))
    }
    var t big.Int
    for n := 1; n <= limit; n++ {
        for k := 1; k <= n; k++ {
            t.SetInt64(int64(k))
            t.Mul(&t, s2[n-1][k])
            s2[n][k].Add(&t, s2[n-1][k-1])
        }
    }
    fmt.Println("Stirling numbers of the second kind: S2(n, k):")
    fmt.Printf("n/k")
    for i := 0; i <= last; i++ {
        fmt.Printf("%9d ", i)
    }
    fmt.Printf("\n--")
    for i := 0; i <= last; i++ {
        fmt.Printf("----------")
    }
    fmt.Println()
    for n := 0; n <= last; n++ {
        fmt.Printf("%2d ", n)
        for k := 0; k <= n; k++ {
            fmt.Printf("%9d ", s2[n][k])
        }
        fmt.Println()
    }
    fmt.Println("\nMaximum value from the S2(100, *) row:")
    max := new(big.Int).Set(s2[limit][0])
    for k := 1; k <= limit; k++ {
        if s2[limit][k].Cmp(max) > 0 {
            max.Set(s2[limit][k])
        }
    }
    fmt.Println(max)
    fmt.Printf("which has %d digits.\n", len(max.String()))
}
Task: Cipolla's algorithm




Go: package main

import "fmt"

func c(n, p int) (R1, R2 int, ok bool) {
    
    powModP := func(a, e int) int {
        s := 1
        for ; e > 0; e-- {
            s = s * a % p
        }
        return s
    }
    
    ls := func(a int) int {
        return powModP(a, (p-1)/2)
    }
    
    if ls(n) != 1 {
        return
    }
    
    var a, ω2 int
    for a = 0; ; a++ {
        
        ω2 = (a*a + p - n) % p
        if ls(ω2) == p-1 {
            break
        }
    }
    
    type point struct{ x, y int }
    mul := func(a, b point) point {
        return point{(a.x*b.x + a.y*b.y*ω2) % p, (a.x*b.y + b.x*a.y) % p}
    }
    
    r := point{1, 0}
    s := point{a, 1}
    for n := (p + 1) >> 1 % p; n > 0; n >>= 1 {
        if n&1 == 1 {
            r = mul(r, s)
        }
        s = mul(s, s)
    }
    
    if r.y != 0 {
        return
    }
    
    if r.x*r.x%p != n {
        return
    }
    
    return r.x, p - r.x, true
}

func main() {
    fmt.Println(c(10, 13))
    fmt.Println(c(56, 101))
    fmt.Println(c(8218, 10007))
    fmt.Println(c(8219, 10007))
    fmt.Println(c(331575, 1000003))
}
Task: Pierpont primes




Go: package main

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

var (
    one   = new(big.Int).SetUint64(1)
    two   = new(big.Int).SetUint64(2)
    three = new(big.Int).SetUint64(3)
)

func pierpont(ulim, vlim int, first bool) []*big.Int {
    p := new(big.Int)
    p2 := new(big.Int).Set(one)
    p3 := new(big.Int).Set(one)   
    var pp []*big.Int
    for v := 0; v < vlim; v++ {
        for u := 0; u < ulim; u++ {
            p.Mul(p2, p3)
            if first {
                p.Add(p, one)
            } else {
                p.Sub(p, one)
            }
            if p.ProbablyPrime(10) {
                q := new(big.Int)
                q.Set(p)
                pp = append(pp, q)
            }
            p2.Mul(p2, two)
        }
        p3.Mul(p3, three)
        p2.Set(one)
    }
    sort.Slice(pp, func(i, j int) bool {
        return pp[i].Cmp(pp[j]) < 0
    })
    return pp
}
func main() {
    fmt.Println("First 50 Pierpont primes of the first kind:")
    pp := pierpont(120, 80, true)
    for i := 0; i < 50; i++ {
        fmt.Printf("%8d ", pp[i])
        if (i-9)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\nFirst 50 Pierpont primes of the second kind:")
    pp2 := pierpont(120, 80, false)
    for i := 0; i < 50; i++ {
        fmt.Printf("%8d ", pp2[i])
        if (i-9)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n250th Pierpont prime of the first kind:", pp[249])
    fmt.Println("\n250th Pierpont prime of the second kind:", pp2[249])
}
Task: N-smooth numbers




Go: package main

import (
    "fmt"
    "log"
    "math/big"
)

var (
    primes      []*big.Int
    smallPrimes []int
)


func init() {
    two := big.NewInt(2)
    three := big.NewInt(3)
    p521 := big.NewInt(521)
    p29 := big.NewInt(29)
    primes = append(primes, two)
    smallPrimes = append(smallPrimes, 2)
    for i := three; i.Cmp(p521) <= 0; i.Add(i, two) {
        if i.ProbablyPrime(0) {
            primes = append(primes, new(big.Int).Set(i))
            if i.Cmp(p29) <= 0 {
                smallPrimes = append(smallPrimes, int(i.Int64()))
            }
        }
    }
}

func min(bs []*big.Int) *big.Int {
    if len(bs) == 0 {
        log.Fatal("slice must have at least one element")
    }
    res := bs[0]
    for _, i := range bs[1:] {
        if i.Cmp(res) < 0 {
            res = i
        }
    }
    return res
}

func nSmooth(n, size int) []*big.Int {
    if n < 2 || n > 521 {
        log.Fatal("n must be between 2 and 521")
    }
    if size < 1 {
        log.Fatal("size must be at least 1")
    }
    bn := big.NewInt(int64(n))
    ok := false
    for _, prime := range primes {
        if bn.Cmp(prime) == 0 {
            ok = true
            break
        }
    }
    if !ok {
        log.Fatal("n must be a prime number")
    }

    ns := make([]*big.Int, size)
    ns[0] = big.NewInt(1)
    var next []*big.Int
    for i := 0; i < len(primes); i++ {
        if primes[i].Cmp(bn) > 0 {
            break
        }
        next = append(next, new(big.Int).Set(primes[i]))
    }
    indices := make([]int, len(next))
    for m := 1; m < size; m++ {
        ns[m] = new(big.Int).Set(min(next))
        for i := 0; i < len(indices); i++ {
            if ns[m].Cmp(next[i]) == 0 {
                indices[i]++
                next[i].Mul(primes[i], ns[indices[i]])
            }
        }
    }
    return ns
}

func main() {
    for _, i := range smallPrimes {
        fmt.Printf("The first 25 %d-smooth numbers are:\n", i)
        fmt.Println(nSmooth(i, 25), "\n")
    }
    for _, i := range smallPrimes[1:] {
        fmt.Printf("The 3,000th to 3,202nd %d-smooth numbers are:\n", i)
        fmt.Println(nSmooth(i, 3002)[2999:], "\n")
    }
    for _, i := range []int{503, 509, 521} {
        fmt.Printf("The 30,000th to 30,019th %d-smooth numbers are:\n", i)
        fmt.Println(nSmooth(i, 30019)[29999:], "\n")
    }
}
Task: Partition an integer x into n primes




Go: package main

import (
    "fmt"
    "log"
)

var (
    primes     = sieve(100000)
    foundCombo = false
)

func sieve(limit uint) []uint {
    primes := []uint{2}
    c := make([]bool, limit+1) 
    
    p := uint(3)
    for {
        p2 := p * p
        if p2 > limit {
            break
        }
        for i := p2; i <= limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    for i := uint(3); i <= limit; i += 2 {
        if !c[i] {
            primes = append(primes, i)
        }
    }
    return primes
}

func findCombo(k, x, m, n uint, combo []uint) {
    if k >= m {
        sum := uint(0)
        for _, c := range combo {
            sum += primes[c]
        }
        if sum == x {
            s := "s"
            if m == 1 {
                s = " "
            }
            fmt.Printf("Partitioned %5d with %2d prime%s: ", x, m, s)
            for i := uint(0); i < m; i++ {
                fmt.Print(primes[combo[i]])
                if i < m-1 {
                    fmt.Print("+")
                } else {
                    fmt.Println()
                }
            }
            foundCombo = true
        }
    } else {
        for j := uint(0); j < n; j++ {
            if k == 0 || j > combo[k-1] {
                combo[k] = j
                if !foundCombo {
                    findCombo(k+1, x, m, n, combo)
                }
            }
        }
    }
}

func partition(x, m uint) error {
    if !(x >= 2 && m >= 1 && m < x) {
        return fmt.Errorf("x must be at least 2 and m in [1, x)")
    }
    n := uint(0)
    for _, prime := range primes {
        if prime <= x {
            n++
        }
    }
    if n < m {
        return fmt.Errorf("not enough primes")
    }
    combo := make([]uint, m)
    foundCombo = false
    findCombo(0, x, m, n, combo)
    if !foundCombo {
        s := "s"
        if m == 1 {
            s = " "
        }
        fmt.Printf("Partitioned %5d with %2d prime%s: (impossible)\n", x, m, s)
    }
    return nil
}

func main() {
    a := [...][2]uint{
        {99809, 1}, {18, 2}, {19, 3}, {20, 4}, {2017, 24},
        {22699, 1}, {22699, 2}, {22699, 3}, {22699, 4}, {40355, 3},
    }
    for _, p := range a {
        err := partition(p[0], p[1])
        if err != nil {
            log.Println(err)
        }
    }
}
Task: Stirling numbers of the first kind




Go: package main

import (
    "fmt"
    "math/big"
)

func main() {
    limit := 100
    last := 12
    unsigned := true
    s1 := make([][]*big.Int, limit+1)
    for n := 0; n <= limit; n++ {
        s1[n] = make([]*big.Int, limit+1)
        for k := 0; k <= limit; k++ {
            s1[n][k] = new(big.Int)
        }
    }
    s1[0][0].SetInt64(int64(1))
    var t big.Int
    for n := 1; n <= limit; n++ {
        for k := 1; k <= n; k++ {
            t.SetInt64(int64(n - 1))
            t.Mul(&t, s1[n-1][k])            
            if unsigned {
                s1[n][k].Add(s1[n-1][k-1], &t)
            } else {
                s1[n][k].Sub(s1[n-1][k-1], &t)
            }           
        }
    }
    fmt.Println("Unsigned Stirling numbers of the first kind: S1(n, k):")
    fmt.Printf("n/k")
    for i := 0; i <= last; i++ {
        fmt.Printf("%9d ", i)
    }
    fmt.Printf("\n--")
    for i := 0; i <= last; i++ {
        fmt.Printf("----------")
    }
    fmt.Println()
    for n := 0; n <= last; n++ {
        fmt.Printf("%2d ", n)
        for k := 0; k <= n; k++ {
            fmt.Printf("%9d ", s1[n][k])
        }
        fmt.Println()
    }
    fmt.Println("\nMaximum value from the S1(100, *) row:")
    max := new(big.Int).Set(s1[limit][0])
    for k := 1; k <= limit; k++ {
        if s1[limit][k].Cmp(max) > 0 {
            max.Set(s1[limit][k])
        }
    }
    fmt.Println(max)
    fmt.Printf("which has %d digits.\n", len(max.String()))
}
Task: Ramer-Douglas-Peucker line simplification




Go: package main

import (
    "fmt"
    "math"
)

type point struct{ x, y float64 }

func RDP(l []point, ε float64) []point {
    x := 0
    dMax := -1.
    last := len(l) - 1
    p1 := l[0]
    p2 := l[last]
    x21 := p2.x - p1.x
    y21 := p2.y - p1.y
    for i, p := range l[1:last] {
        if d := math.Abs(y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax {
            x = i + 1
            dMax = d
        }
    }
    if dMax > ε {
        return append(RDP(l[:x+1], ε), RDP(l[x:], ε)[1:]...)
    }
    return []point{l[0], l[len(l)-1]}
}

func main() {
    fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1},
        {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1))
}