WeixiangYan/CodeTransOcean huggingface dataset:
Task: Earliest difference between prime gaps




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    limit := int(1e9)
    gapStarts := make(map[int]int)
    primes := rcu.Primes(limit * 5)
    for i := 1; i < len(primes); i++ {
        gap := primes[i] - primes[i-1]
        if _, ok := gapStarts[gap]; !ok {
            gapStarts[gap] = primes[i-1]
        }
    }
    pm := 10
    gap1 := 2
    for {
        for _, ok := gapStarts[gap1]; !ok; {
            gap1 += 2
        }
        start1 := gapStarts[gap1]
        gap2 := gap1 + 2
        if _, ok := gapStarts[gap2]; !ok {
            gap1 = gap2 + 2
            continue
        }
        start2 := gapStarts[gap2]
        diff := start2 - start1
        if diff < 0 {
            diff = -diff
        }
        if diff > pm {
            cpm := rcu.Commatize(pm)
            cst1 := rcu.Commatize(start1)
            cst2 := rcu.Commatize(start2)
            cd := rcu.Commatize(diff)
            fmt.Printf("Earliest difference > %s between adjacent prime gap starting primes:\n", cpm)
            fmt.Printf("Gap %d starts at %s, gap %d starts at %s, difference is %s.\n\n", gap1, cst1, gap2, cst2, cd)
            if pm == limit {
                break
            }
            pm *= 10
        } else {
            gap1 = gap2
        }
    }
}
Task: Monads_Writer monad




Go: package main

import (
    "fmt"
    "math"
)

type mwriter struct {
    value float64
    log   string
}

func (m mwriter) bind(f func(v float64) mwriter) mwriter {
    n := f(m.value)
    n.log = m.log + n.log
    return n
}

func unit(v float64, s string) mwriter {
    return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)}
}

func root(v float64) mwriter {
    return unit(math.Sqrt(v), "Took square root")
}

func addOne(v float64) mwriter {
    return unit(v+1, "Added one")
}

func half(v float64) mwriter {
    return unit(v/2, "Divided by two")
}

func main() {
    mw1 := unit(5, "Initial value")
    mw2 := mw1.bind(root).bind(addOne).bind(half)
    fmt.Println("The Golden Ratio is", mw2.value)
    fmt.Println("\nThis was derived as follows:-")
    fmt.Println(mw2.log)
}
Task: Word ladder




Go: package main

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

func contains(a []string, s string) bool {
    for _, e := range a {
        if e == s {
            return true
        }
    }
    return false
}

func oneAway(a, b string) bool {
    sum := 0
    for i := 0; i < len(a); i++ {
        if a[i] != b[i] {
            sum++
        }
    }
    return sum == 1
}

func wordLadder(words []string, a, b string) {
    l := len(a)
    var poss []string
    for _, word := range words {
        if len(word) == l {
            poss = append(poss, word)
        }
    }
    todo := [][]string{{a}}
    for len(todo) > 0 {
        curr := todo[0]
        todo = todo[1:]
        var next []string
        for _, word := range poss {
            if oneAway(word, curr[len(curr)-1]) {
                next = append(next, word)
            }
        }
        if contains(next, b) {
            curr = append(curr, b)
            fmt.Println(strings.Join(curr, " -> "))
            return
        }
        for i := len(poss) - 1; i >= 0; i-- {
            if contains(next, poss[i]) {
                copy(poss[i:], poss[i+1:])
                poss[len(poss)-1] = ""
                poss = poss[:len(poss)-1]
            }
        }
        for _, s := range next {
            temp := make([]string, len(curr))
            copy(temp, curr)
            temp = append(temp, s)
            todo = append(todo, temp)
        }
    }
    fmt.Println(a, "into", b, "cannot be done.")
}

func main() {
    b, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal("Error reading file")
    }
    bwords := bytes.Fields(b)
    words := make([]string, len(bwords))
    for i, bword := range bwords {
        words[i] = string(bword)
    }
    pairs := [][]string{
        {"boy", "man"},
        {"girl", "lady"},
        {"john", "jane"},
        {"child", "adult"},
    }
    for _, pair := range pairs {
        wordLadder(words, pair[0], pair[1])
    }
}
Task: Non-transitive dice




Go: package main

import (
    "fmt"
    "sort"
)

func fourFaceCombs() (res [][4]int) {
    found := make([]bool, 256)
    for i := 1; i <= 4; i++ {
        for j := 1; j <= 4; j++ {
            for k := 1; k <= 4; k++ {
                for l := 1; l <= 4; l++ {
                    c := [4]int{i, j, k, l}
                    sort.Ints(c[:])
                    key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)
                    if !found[key] {
                        found[key] = true
                        res = append(res, c)
                    }
                }
            }
        }
    }
    return
}

func cmp(x, y [4]int) int {
    xw := 0
    yw := 0
    for i := 0; i < 4; i++ {
        for j := 0; j < 4; j++ {
            if x[i] > y[j] {
                xw++
            } else if y[j] > x[i] {
                yw++
            }
        }
    }
    if xw < yw {
        return -1
    } else if xw > yw {
        return 1
    }
    return 0
}

func findIntransitive3(cs [][4]int) (res [][3][4]int) {
    var c = len(cs)
    for i := 0; i < c; i++ {
        for j := 0; j < c; j++ {
            for k := 0; k < c; k++ {
                first := cmp(cs[i], cs[j])
                if first == -1 {
                    second := cmp(cs[j], cs[k])
                    if second == -1 {
                        third := cmp(cs[i], cs[k])
                        if third == 1 {
                            res = append(res, [3][4]int{cs[i], cs[j], cs[k]})
                        }
                    }
                }
            }
        }
    }
    return
}

func findIntransitive4(cs [][4]int) (res [][4][4]int) {
    c := len(cs)
    for i := 0; i < c; i++ {
        for j := 0; j < c; j++ {
            for k := 0; k < c; k++ {
                for l := 0; l < c; l++ {
                    first := cmp(cs[i], cs[j])
                    if first == -1 {
                        second := cmp(cs[j], cs[k])
                        if second == -1 {
                            third := cmp(cs[k], cs[l])
                            if third == -1 {
                                fourth := cmp(cs[i], cs[l])
                                if fourth == 1 {
                                    res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return
}

func main() {
    combs := fourFaceCombs()
    fmt.Println("Number of eligible 4-faced dice", len(combs))
    it3 := findIntransitive3(combs)
    fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3))
    for _, a := range it3 {
        fmt.Println(a)
    }
    it4 := findIntransitive4(combs)
    fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4))
    for _, a := range it4 {
        fmt.Println(a)
    }
}
Task: Separate the house number from the street name




Go: package main

import (
    "fmt"
    "strings"
)

func isDigit(b byte) bool {
    return '0' <= b && b <= '9'
}

func separateHouseNumber(address string) (street string, house string) {
    length := len(address)
    fields := strings.Fields(address)
    size := len(fields)
    last := fields[size-1]
    penult := fields[size-2]
    if isDigit(last[0]) {
        isdig := isDigit(penult[0])
        if size > 2 && isdig && !strings.HasPrefix(penult, "194") {
            house = fmt.Sprintf("%s %s", penult, last)
        } else {
            house = last
        }
    } else if size > 2 {
        house = fmt.Sprintf("%s %s", penult, last)
    }
    street = strings.TrimRight(address[:length-len(house)], " ")
    return
}

func main() {
    addresses := [...]string{
        "Plataanstraat 5",
        "Straat 12",
        "Straat 12 II",
        "Dr. J. Straat   12",
        "Dr. J. Straat 12 a",
        "Dr. J. Straat 12-14",
        "Laan 1940 - 1945 37",
        "Plein 1940 2",
        "1213-laan 11",
        "16 april 1944 Pad 1",
        "1e Kruisweg 36",
        "Laan 1940-'45 66",
        "Laan '40-'45",
        "Langeloërduinen 3 46",
        "Marienwaerdt 2e Dreef 2",
        "Provincialeweg N205 1",
        "Rivium 2e Straat 59.",
        "Nieuwe gracht 20rd",
        "Nieuwe gracht 20rd 2",
        "Nieuwe gracht 20zw /2",
        "Nieuwe gracht 20zw/3",
        "Nieuwe gracht 20 zw/4",
        "Bahnhofstr. 4",
        "Wertstr. 10",
        "Lindenhof 1",
        "Nordesch 20",
        "Weilstr. 6",
        "Harthauer Weg 2",
        "Mainaustr. 49",
        "August-Horch-Str. 3",
        "Marktplatz 31",
        "Schmidener Weg 3",
        "Karl-Weysser-Str. 6",
    }
    fmt.Println("Street                   House Number")
    fmt.Println("---------------------    ------------")
    for _, address := range addresses {
        street, house := separateHouseNumber(address)
        if house == "" {
            house = "(none)"
        }
        fmt.Printf("%-22s   %s\n", street, house)
    }
}
Task: Geohash




Go: package main

import (
    "fmt"
    "strings"
)

type Location struct{ lat, lng float64 }

func (loc Location) String() string { return fmt.Sprintf("[%f, %f]", loc.lat, loc.lng) }

type Range struct{ lower, upper float64 }

var gBase32 = "0123456789bcdefghjkmnpqrstuvwxyz"

func encodeGeohash(loc Location, prec int) string {
    latRange := Range{-90, 90}
    lngRange := Range{-180, 180}
    var hash strings.Builder
    hashVal := 0
    bits := 0
    even := true
    for hash.Len() < prec {
        val := loc.lat
        rng := latRange
        if even {
            val = loc.lng
            rng = lngRange
        }
        mid := (rng.lower + rng.upper) / 2
        if val > mid {
            hashVal = (hashVal << 1) + 1
            rng = Range{mid, rng.upper}
            if even {
                lngRange = Range{mid, lngRange.upper}
            } else {
                latRange = Range{mid, latRange.upper}
            }
        } else {
            hashVal <<= 1
            if even {
                lngRange = Range{lngRange.lower, mid}
            } else {
                latRange = Range{latRange.lower, mid}
            }
        }
        even = !even
        if bits < 4 {
            bits++
        } else {
            bits = 0
            hash.WriteByte(gBase32[hashVal])
            hashVal = 0
        }
    }
    return hash.String()
}

func main() {
    locs := []Location{
        {51.433718, -0.214126},
        {51.433718, -0.214126},
        {57.64911, 10.40744},
    }
    precs := []int{2, 9, 11}

    for i, loc := range locs {
        geohash := encodeGeohash(loc, precs[i])
        fmt.Printf("geohash for %v, precision %-2d = %s\n", loc, precs[i], geohash)
    }
}
Task: Smallest numbers




Go: package main

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

func main() {
    var res []int64
    for n := 0; n <= 50; n++ {
        ns := strconv.Itoa(n)
        k := int64(1)
        for {
            bk := big.NewInt(k)
            s := bk.Exp(bk, bk, nil).String()
            if strings.Contains(s, ns) {
                res = append(res, k)
                break
            }
            k++
        }
    }
    fmt.Println("The smallest positive integers K where K ^ K contains N (0..50) are:")
    for i, n := range res {
        fmt.Printf("%2d ", n)
        if (i+1)%17 == 0 {
            fmt.Println()
        }
    }
}
Task: Ramanujan primes_twins




Go: package main

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

var count []int

func primeCounter(limit int) {
    count = make([]int, limit)
    for i := 0; i < limit; i++ {
        count[i] = 1
    }
    if limit > 0 {
        count[0] = 0
    }
    if limit > 1 {
        count[1] = 0
    }
    for i := 4; i < limit; i += 2 {
        count[i] = 0
    }
    for p, sq := 3, 9; sq < limit; p += 2 {
        if count[p] != 0 {
            for q := sq; q < limit; q += p << 1 {
                count[q] = 0
            }
        }
        sq += (p + 1) << 2
    }
    sum := 0
    for i := 0; i < limit; i++ {
        sum += count[i]
        count[i] = sum
    }
}

func primeCount(n int) int {
    if n < 1 {
        return 0
    }
    return count[n]
}

func ramanujanMax(n int) int {
    fn := float64(n)
    return int(math.Ceil(4 * fn * math.Log(4*fn)))
}

func ramanujanPrime(n int) int {
    if n == 1 {
        return 2
    }
    for i := ramanujanMax(n); i >= 2*n; i-- {
        if i%2 == 1 {
            continue
        }
        if primeCount(i)-primeCount(i/2) < n {
            return i + 1
        }
    }
    return 0
}

func rpc(p int) int { return primeCount(p) - primeCount(p/2) }

func main() {
    for _, limit := range []int{1e5, 1e6} {
        start := time.Now()
        primeCounter(1 + ramanujanMax(limit))
        rplim := ramanujanPrime(limit)
        climit := rcu.Commatize(limit)
        fmt.Printf("The %sth Ramanujan prime is %s\n", climit, rcu.Commatize(rplim))
        r := rcu.Primes(rplim)
        c := make([]int, len(r))
        for i := 0; i < len(c); i++ {
            c[i] = rpc(r[i])
        }
        ok := c[len(c)-1]
        for i := len(c) - 2; i >= 0; i-- {
            if c[i] < ok {
                ok = c[i]
            } else {
                c[i] = 0
            }
        }
        var fr []int
        for i, r := range r {
            if c[i] != 0 {
                fr = append(fr, r)
            }
        }
        twins := 0
        for i := 0; i < len(fr)-1; i++ {
            if fr[i]+2 == fr[i+1] {
                twins++
            }
        }
        fmt.Printf("There are %s twins in the first %s Ramanujan primes.\n", rcu.Commatize(twins), climit)
        fmt.Println("Took", time.Since(start))
        fmt.Println()
    }
}
Task: Polynomial derivative




Go: package main

import (
    "fmt"
    "strings"
)

func derivative(p []int) []int {
    if len(p) == 1 {
        return []int{0}
    }
    d := make([]int, len(p)-1)
    copy(d, p[1:])
    for i := 0; i < len(d); i++ {
        d[i] = p[i+1] * (i + 1)
    }
    return d
}

var ss = []string{"", "", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"}


func superscript(n int) string {
    if n < 10 {
        return ss[n]
    }
    if n < 20 {
        return ss[1] + ss[n-10]
    }
    return ss[2] + ss[0]
}

func abs(n int) int {
    if n < 0 {
        return -n
    }
    return n
}

func polyPrint(p []int) string {
    if len(p) == 1 {
        return fmt.Sprintf("%d", p[0])
    }
    var terms []string
    for i := 0; i < len(p); i++ {
        if p[i] == 0 {
            continue
        }
        c := fmt.Sprintf("%d", p[i])
        if i > 0 && abs(p[i]) == 1 {
            c = ""
            if p[i] != 1 {
                c = "-"
            }
        }
        x := "x"
        if i <= 0 {
            x = ""
        }
        terms = append(terms, fmt.Sprintf("%s%s%s", c, x, superscript(i)))
    }
    for i, j := 0, len(terms)-1; i < j; i, j = i+1, j-1 {
        terms[i], terms[j] = terms[j], terms[i]
    }
    s := strings.Join(terms, "+")
    return strings.Replace(s, "+-", "-", -1)
}

func main() {
    fmt.Println("The derivatives of the following polynomials are:\n")
    polys := [][]int{{5}, {4, -3}, {-1, 6, 5}, {-4, 3, -2, 1}, {1, 1, 0, -1, -1}}
    for _, poly := range polys {
        deriv := derivative(poly)
        fmt.Printf("%v -> %v\n", poly, deriv)
    }
    fmt.Println("\nOr in normal mathematical notation:\n")
    for _, poly := range polys {
        deriv := derivative(poly)
        fmt.Println("Polynomial : ", polyPrint(poly))
        fmt.Println("Derivative : ", polyPrint(deriv), "\n")
    }
}
Task: Doomsday rule




Go: package main

import (
    "fmt"
    "strconv"
)

var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}

func anchorDay(y int) int {
    return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}

func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }

var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}

func main() {
    dates := []string{
        "1800-01-06",
        "1875-03-29",
        "1915-12-07",
        "1970-12-23",
        "2043-05-14",
        "2077-02-12",
        "2101-04-02",
    }

    fmt.Println("Days of week given by Doomsday rule:")
    for _, date := range dates {
        y, _ := strconv.Atoi(date[0:4])
        m, _ := strconv.Atoi(date[5:7])
        m--
        d, _ := strconv.Atoi(date[8:10])
        a := anchorDay(y)
        f := firstDaysCommon[m]
        if isLeapYear(y) {
            f = firstDaysLeap[m]
        }
        w := d - f
        if w < 0 {
            w = 7 + w
        }
        dow := (a + w) % 7
        fmt.Printf("%s -> %s\n", date, days[dow])
    }
}
Task: Gauss-Jordan matrix inversion




Go: package main

import "fmt"

type vector = []float64
type matrix []vector

func (m matrix) inverse() matrix {
    le := len(m)
    for _, v := range m {
        if len(v) != le {
            panic("Not a square matrix")
        }
    }
    aug := make(matrix, le)
    for i := 0; i < le; i++ {
        aug[i] = make(vector, 2*le)
        copy(aug[i], m[i])
        
        aug[i][i+le] = 1
    }
    aug.toReducedRowEchelonForm()
    inv := make(matrix, le)
    
    for i := 0; i < le; i++ {
        inv[i] = make(vector, le)
        copy(inv[i], aug[i][le:])
    }
    return inv
}


func (m matrix) toReducedRowEchelonForm() {
    lead := 0
    rowCount, colCount := len(m), len(m[0])
    for r := 0; r < rowCount; r++ {
        if colCount <= lead {
            return
        }
        i := r

        for m[i][lead] == 0 {
            i++
            if rowCount == i {
                i = r
                lead++
                if colCount == lead {
                    return
                }
            }
        }

        m[i], m[r] = m[r], m[i]
        if div := m[r][lead]; div != 0 {
            for j := 0; j < colCount; j++ {
                m[r][j] /= div
            }
        }

        for k := 0; k < rowCount; k++ {
            if k != r {
                mult := m[k][lead]
                for j := 0; j < colCount; j++ {
                    m[k][j] -= m[r][j] * mult
                }
            }
        }
        lead++
    }
}

func (m matrix) print(title string) {
    fmt.Println(title)
    for _, v := range m {
        fmt.Printf("% f\n", v)
    }
    fmt.Println()
}

func main() {
    a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}
    a.inverse().print("Inverse of A is:\n")

    b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
    b.inverse().print("Inverse of B is:\n")
}
Task: Numerical integration_Adaptive Simpson's method




Go: package main

import (
    "fmt"
    "math"
)

type F = func(float64) float64


func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
    
    m = (a + b) / 2
    fm = f(m)
    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
    return
}

func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
    
    
    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
    delta := left + right - whole
    if math.Abs(delta) <= eps*15 {
        return left + right + delta/15
    }
    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}

func quadAsr(f F, a, b, eps float64) float64 {
    
    fa, fb := f(a), f(b)
    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}

func main() {
    a, b := 0.0, 1.0
    sinx := quadAsr(math.Sin, a, b, 1e-09)
    fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)   
}
Task: Colorful numbers




Go: package main

import (
    "fmt"
    "rcu"
    "strconv"
)

func isColorful(n int) bool {
    if n < 0 {
        return false
    }
    if n < 10 {
        return true
    }
    digits := rcu.Digits(n, 10)
    for _, d := range digits {
        if d == 0 || d == 1 {
            return false
        }
    }
    set := make(map[int]bool)
    for _, d := range digits {
        set[d] = true
    }
    dc := len(digits)
    if len(set) < dc {
        return false
    }
    for k := 2; k <= dc; k++ {
        for i := 0; i <= dc-k; i++ {
            prod := 1
            for j := i; j <= i+k-1; j++ {
                prod *= digits[j]
            }
            if ok := set[prod]; ok {
                return false
            }
            set[prod] = true
        }
    }
    return true
}

var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0

func countColorful(taken int, n string) {
    if taken == 0 {
        for digit := 0; digit < 10; digit++ {
            dx := digit + 1
            used[dx] = true
            t := 1
            if digit < 2 {
                t = 9
            }
            countColorful(t, string(digit+48))
            used[dx] = false
        }
    } else {
        nn, _ := strconv.Atoi(n)
        if isColorful(nn) {
            ln := len(n)
            count[ln]++
            if nn > largest {
                largest = nn
            }
        }
        if taken < 9 {
            for digit := 2; digit < 10; digit++ {
                dx := digit + 1
                if !used[dx] {
                    used[dx] = true
                    countColorful(taken+1, n+string(digit+48))
                    used[dx] = false
                }
            }
        }
    }
}

func main() {
    var cn []int
    for i := 0; i < 100; i++ {
        if isColorful(i) {
            cn = append(cn, i)
        }
    }
    fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
    for i := 0; i < len(cn); i++ {
        fmt.Printf("%2d ", cn[i])
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }

    countColorful(0, "")
    fmt.Println("\n\nThe largest possible colorful number is:")
    fmt.Println(rcu.Commatize(largest))

    fmt.Println("\nCount of colorful numbers for each order of magnitude:")
    pow := 10
    for dc := 1; dc < len(count); dc++ {
        cdc := rcu.Commatize(count[dc])
        pc := 100 * float64(count[dc]) / float64(pow)
        fmt.Printf("  %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
        if pow == 10 {
            pow = 90
        } else {
            pow *= 10
        }
    }

    sum := 0
    for _, c := range count {
        sum += c
    }
    fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}