WeixiangYan/CodeTransOcean huggingface dataset:
Task: Magic squares of singly even order




Go: package main

import (
    "fmt"
    "log"
)

func magicSquareOdd(n int) ([][]int, error) {
    if n < 3 || n%2 == 0 {
        return nil, fmt.Errorf("base must be odd and > 2")
    }
    value := 1
    gridSize := n * n
    c, r := n/2, 0
    result := make([][]int, n)

    for i := 0; i < n; i++ {
        result[i] = make([]int, n)
    }

    for value <= gridSize {
        result[r][c] = value
        if r == 0 {
            if c == n-1 {
                r++
            } else {
                r = n - 1
                c++
            }
        } else if c == n-1 {
            r--
            c = 0
        } else if result[r-1][c+1] == 0 {
            r--
            c++
        } else {
            r++
        }
        value++
    }
    return result, nil
}

func magicSquareSinglyEven(n int) ([][]int, error) {
    if n < 6 || (n-2)%4 != 0 {
        return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2")
    }
    size := n * n
    halfN := n / 2
    subSquareSize := size / 4
    subSquare, err := magicSquareOdd(halfN)
    if err != nil {
        return nil, err
    }
    quadrantFactors := [4]int{0, 2, 3, 1}
    result := make([][]int, n)

    for i := 0; i < n; i++ {
        result[i] = make([]int, n)
    }

    for r := 0; r < n; r++ {
        for c := 0; c < n; c++ {
            quadrant := r/halfN*2 + c/halfN
            result[r][c] = subSquare[r%halfN][c%halfN]
            result[r][c] += quadrantFactors[quadrant] * subSquareSize
        }
    }

    nColsLeft := halfN / 2
    nColsRight := nColsLeft - 1

    for r := 0; r < halfN; r++ {
        for c := 0; c < n; c++ {
            if c < nColsLeft || c >= n-nColsRight ||
                (c == nColsLeft && r == nColsLeft) {
                if c == 0 && r == nColsLeft {
                    continue
                }
                tmp := result[r][c]
                result[r][c] = result[r+halfN][c]
                result[r+halfN][c] = tmp
            }
        }
    }
    return result, nil
}

func main() {
    const n = 6
    msse, err := magicSquareSinglyEven(n)
    if err != nil {
        log.Fatal(err)
    }
    for _, row := range msse {
        for _, x := range row {
            fmt.Printf("%2d ", x)
        }
        fmt.Println()
    }
    fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2)
}
Task: Weird numbers




Go: package main

import "fmt"

func divisors(n int) []int {
    divs := []int{1}
    divs2 := []int{}
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            divs = append(divs, i)
            if i != j {
                divs2 = append(divs2, j)
            }
        }
    }
    for i := len(divs) - 1; i >= 0; i-- {
        divs2 = append(divs2, divs[i])
    }
    return divs2
}

func abundant(n int, divs []int) bool {
    sum := 0
    for _, div := range divs {
        sum += div
    }
    return sum > n
}

func semiperfect(n int, divs []int) bool {
    le := len(divs)
    if le > 0 {
        h := divs[0]
        t := divs[1:]
        if n < h {
            return semiperfect(n, t)
        } else {
            return n == h || semiperfect(n-h, t) || semiperfect(n, t)
        }
    } else {
        return false
    }
} 

func sieve(limit int) []bool {
    
    
    w := make([]bool, limit)
    for i := 2; i < limit; i += 2 {
        if w[i] {
            continue
        }
        divs := divisors(i)
        if !abundant(i, divs) {
            w[i] = true
        } else if semiperfect(i, divs) {
            for j := i; j < limit; j += i {
                w[j] = true
            }
        }
    }
    return w
}

func main() {
    w := sieve(17000)
    count := 0
    const max = 25
    fmt.Println("The first 25 weird numbers are:")
    for n := 2; count < max; n += 2 {
        if !w[n] {
            fmt.Printf("%d ", n)
            count++
        }
    }
    fmt.Println()
}
Task: Peaceful chess queen armies




Go: package main

import "fmt"

const (
    empty = iota
    black
    white
)

const (
    bqueen  = 'B'
    wqueen  = 'W'
    bbullet = '•'
    wbullet = '◦'
)

type position struct{ i, j int }

func iabs(i int) int {
    if i < 0 {
        return -i
    }
    return i
}

func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool {
    if m == 0 {
        return true
    }
    placingBlack := true
    for i := 0; i < n; i++ {
    inner:
        for j := 0; j < n; j++ {
            pos := position{i, j}
            for _, queen := range *pBlackQueens {
                if queen == pos || !placingBlack && isAttacking(queen, pos) {
                    continue inner
                }
            }
            for _, queen := range *pWhiteQueens {
                if queen == pos || placingBlack && isAttacking(queen, pos) {
                    continue inner
                }
            }
            if placingBlack {
                *pBlackQueens = append(*pBlackQueens, pos)
                placingBlack = false
            } else {
                *pWhiteQueens = append(*pWhiteQueens, pos)
                if place(m-1, n, pBlackQueens, pWhiteQueens) {
                    return true
                }
                *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
                *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1]
                placingBlack = true
            }
        }
    }
    if !placingBlack {
        *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1]
    }
    return false
}

func isAttacking(queen, pos position) bool {
    if queen.i == pos.i {
        return true
    }
    if queen.j == pos.j {
        return true
    }
    if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) {
        return true
    }
    return false
}

func printBoard(n int, blackQueens, whiteQueens []position) {
    board := make([]int, n*n)
    for _, queen := range blackQueens {
        board[queen.i*n+queen.j] = black
    }
    for _, queen := range whiteQueens {
        board[queen.i*n+queen.j] = white
    }

    for i, b := range board {
        if i != 0 && i%n == 0 {
            fmt.Println()
        }
        switch b {
        case black:
            fmt.Printf("%c ", bqueen)
        case white:
            fmt.Printf("%c ", wqueen)
        case empty:
            if i%2 == 0 {
                fmt.Printf("%c ", bbullet)
            } else {
                fmt.Printf("%c ", wbullet)
            }
        }
    }
    fmt.Println("\n")
}

func main() {
    nms := [][2]int{
        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
    }
    for _, nm := range nms {
        n, m := nm[0], nm[1]
        fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n)
        var blackQueens, whiteQueens []position
        if place(m, n, &blackQueens, &whiteQueens) {
            printBoard(n, blackQueens, whiteQueens)
        } else {
            fmt.Println("No solution exists.\n")
        }
    }
}
Task: Sequence_ nth number with exactly n divisors




Go: package main

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

var bi = new(big.Int)

func isPrime(n int) bool {
    bi.SetUint64(uint64(n))
    return bi.ProbablyPrime(0)
}

func generateSmallPrimes(n int) []int {
    primes := make([]int, n)
    primes[0] = 2
    for i, count := 3, 1; count < n; i += 2 {
        if isPrime(i) {
            primes[count] = i
            count++
        }
    }
    return primes
}

func countDivisors(n int) int {
    count := 1
    for n%2 == 0 {
        n >>= 1
        count++
    }
    for d := 3; d*d <= n; d += 2 {
        q, r := n/d, n%d
        if r == 0 {
            dc := 0
            for r == 0 {
                dc += count
                n = q
                q, r = n/d, n%d
            }
            count += dc
        }
    }
    if n != 1 {
        count *= 2
    }
    return count
}

func main() {
    const max = 33
    primes := generateSmallPrimes(max)
    z := new(big.Int)
    p := new(big.Int)
    fmt.Println("The first", max, "terms in the sequence are:")
    for i := 1; i <= max; i++ {
        if isPrime(i) {
            z.SetUint64(uint64(primes[i-1]))
            p.SetUint64(uint64(i - 1))
            z.Exp(z, p, nil)
            fmt.Printf("%2d : %d\n", i, z)
        } else {
            count := 0
            for j := 1; ; j++ {
                if i%2 == 1 {
                    sq := int(math.Sqrt(float64(j)))
                    if sq*sq != j {
                        continue
                    }
                }
                if countDivisors(j) == i {
                    count++
                    if count == i {
                        fmt.Printf("%2d : %d\n", i, j)
                        break
                    }
                }
            }
        }
    }
}
Task: Readline interface




Go: package main

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

type vf = func()

var history []string

func hello() {
    fmt.Println("Hello World!")
    history = append(history, "hello")
}

func hist() {
    if len(history) == 0 {
        fmt.Println("No history")
    } else {
        for _, cmd := range history {
            fmt.Println("  -", cmd)
        }
    }
    history = append(history, "hist")
}

func help() {
    fmt.Println("Available commands:")
    fmt.Println("  hello")
    fmt.Println("  hist")
    fmt.Println("  exit")
    fmt.Println("  help")
    history = append(history, "help")
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    vfs := map[string]vf{"help": help, "hist": hist, "hello": hello}
    fmt.Println("Enter a command, type help for a listing.")
    for {
        fmt.Print(">")
        scanner.Scan()
        if scerr := scanner.Err(); scerr != nil {
            log.Fatal(scerr)
        }
        line := strings.TrimSpace(scanner.Text())
        if line == "exit" {
            return
        }
        cmd, ok := vfs[line]
        if !ok {
            fmt.Println("Unknown command, try again")
        } else {
            cmd()
        }
    }
}
Task: ASCII control characters




Go: package main

import "fmt"

type Ctrl int

const (
    nul Ctrl = iota
    soh
    stx
    etx
    eot
    enq
    ack
    bel
    bs
    ht
    lf
    vt
    ff
    cr
    so
    si
    dle
    dc1
    dc2
    dc3
    dc4
    nak
    syn
    etb
    can
    em
    sub
    esc
    fs
    gs
    rs
    us
    space
    del = 127
)

func main() {
    
    fmt.Println(cr)
    fmt.Println(del)
}
Task: Rosetta Code_Tasks without examples




Go: package main

import (
    "fmt"
    "html"
    "io/ioutil"
    "net/http"
    "regexp"
    "strings"
    "time"
)

func main() {    
    ex := `<li><a href="/wiki/(.*?)"`
    re := regexp.MustCompile(ex)
    page := "http:
    resp, _ := http.Get(page)
    body, _ := ioutil.ReadAll(resp.Body)
    matches := re.FindAllStringSubmatch(string(body), -1)
    resp.Body.Close()
    tasks := make([]string, len(matches))
    for i, match := range matches {
        tasks[i] = match[1]
    }
    const base = "http:
    const limit = 3 
    ex = `(?s)using any language you may know.</div>(.*?)<div id="toc"`
    ex2 := `</?[^>]*>` 
    re = regexp.MustCompile(ex)
    re2 := regexp.MustCompile(ex2)
    for i, task := range tasks {
        page = base + task
        resp, _ = http.Get(page)
        body, _ = ioutil.ReadAll(resp.Body)
        match := re.FindStringSubmatch(string(body))
        resp.Body.Close()
        text := html.UnescapeString(re2.ReplaceAllLiteralString(match[1], ""))
        fmt.Println(strings.Replace(task, "_", " ", -1), "\n", text)
        if i == limit-1 {
            break
        }
        time.Sleep(5 * time.Second) 
    }
}
Task: Just in time processing on a character stream




Go: package main

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

type userInput struct{ formFeed, lineFeed, tab, space int }

func getUserInput() []userInput {
    h := "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " +
        "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47 0 84 2 28"
    flds := strings.Fields(h)
    var uis []userInput
    var uif [4]int
    for i := 0; i < len(flds); i += 4 {
        for j := 0; j < 4; j++ {
            uif[j], _ = strconv.Atoi(flds[i+j])
        }
        uis = append(uis, userInput{uif[0], uif[1], uif[2], uif[3]})
    }
    return uis
}

func decode(fileName string, uis []userInput) error {
    text, err := ioutil.ReadFile(fileName)
    if err != nil {
        return err
    }

    decode2 := func(ui userInput) bool {
        var f, l, t, s int
        for _, c := range text {
            if f == ui.formFeed && l == ui.lineFeed && t == ui.tab && s == ui.space {
                if c == '!' {
                    return false
                }
                fmt.Printf("%c", c)
                return true
            }
            switch c {
            case '\f':
                f++
                l = 0
                t = 0
                s = 0
            case '\n':
                l++
                t = 0
                s = 0
            case '\t':
                t++
                s = 0
            default:
                s++
            }
        }
        return true
    }

    for _, ui := range uis {
        if !decode2(ui) {
            break
        }
    }
    fmt.Println()
    return nil
}

func main() {
    uis := getUserInput()
    err := decode("theRaven.txt", uis)
    if err != nil {
        log.Fatal(err)
    }
}
Task: Print debugging statement




Go: package main

import (
    "fmt"
    "runtime"
)

type point struct {
    x, y float64
}

func add(x, y int) int {
    result := x + y
    debug("x", x)
    debug("y", y)
    debug("result", result)
    debug("result+1", result+1)
    return result
}

func debug(s string, x interface{}) {
    _, _, lineNo, _ := runtime.Caller(1)
    fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}

func main() {
    add(2, 7)
    b := true
    debug("b", b)
    s := "Hello"
    debug("s", s)
    p := point{2, 3}
    debug("p", p)
    q := &p
    debug("q", q)
}
Task: Montgomery reduction




Go: package main

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


type mont struct {
    n  uint     
    m  *big.Int 
    r2 *big.Int 
}


func newMont(m *big.Int) *mont {
    if m.Bit(0) != 1 {
        return nil
    }
    n := uint(m.BitLen())
    x := big.NewInt(1)
    x.Sub(x.Lsh(x, n), m)
    return &mont{n, new(big.Int).Set(m), x.Mod(x.Mul(x, x), m)}
}


func (m mont) reduce(t *big.Int) *big.Int {
    a := new(big.Int).Set(t)
    for i := uint(0); i < m.n; i++ {
        if a.Bit(0) == 1 {
            a.Add(a, m.m)
        }
        a.Rsh(a, 1)
    }
    if a.Cmp(m.m) >= 0 {
        a.Sub(a, m.m)
    }
    return a
}


func main() {
    const n = 100 

    
    rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
    one := big.NewInt(1)
    r1 := new(big.Int).Lsh(one, n-1)
    r2 := new(big.Int).Lsh(one, n-2)
    m := new(big.Int)
    m.Or(r1, m.Or(m.Lsh(m.Rand(rnd, r2), 1), one))

    
    mr := newMont(m)

    
    
    x1 := new(big.Int).Rand(rnd, m)
    x2 := new(big.Int).Rand(rnd, m)

    
    
    t1 := new(big.Int).Mul(x1, mr.r2)
    t2 := new(big.Int).Mul(x2, mr.r2)

    
    r1 = mr.reduce(t1)
    r2 = mr.reduce(t2)

    
    fmt.Println("b:  2")
    fmt.Println("n: ", mr.n)
    fmt.Println("r: ", new(big.Int).Lsh(one, mr.n))
    fmt.Println("m: ", mr.m)
    fmt.Println("t1:", t1)
    fmt.Println("t2:", t2)
    fmt.Println("r1:", r1)
    fmt.Println("r2:", r2)

    
    fmt.Println()
    fmt.Println("Original x1:       ", x1)
    fmt.Println("Recovererd from r1:", mr.reduce(r1))
    fmt.Println("Original x2:       ", x2)
    fmt.Println("Recovererd from r2:", mr.reduce(r2))

    
    fmt.Println("\nMontgomery computation of x1 ^ x2 mod m:")
    
    
    prod := mr.reduce(mr.r2)             
    base := mr.reduce(t1.Mul(x1, mr.r2)) 
    exp := new(big.Int).Set(x2)          
    for exp.BitLen() > 0 {
        if exp.Bit(0) == 1 {
            prod = mr.reduce(prod.Mul(prod, base))
        }
        exp.Rsh(exp, 1)
        base = mr.reduce(base.Mul(base, base))
    }
    fmt.Println(mr.reduce(prod))

    
    fmt.Println("\nLibrary-based computation of x1 ^ x2 mod m:")
    fmt.Println(new(big.Int).Exp(x1, x2, m))
}
Task: Finite state machine




Go: package main

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

type state int

const (
    ready state = iota
    waiting
    exit
    dispense
    refunding
)

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

func fsm() {
    fmt.Println("Please enter your option when prompted")
    fmt.Println("(any characters after the first will be ignored)")
    state := ready
    var trans string
    scanner := bufio.NewScanner(os.Stdin)
    for {
        switch state {
        case ready:
            for {
                fmt.Print("\n(D)ispense or (Q)uit : ")
                scanner.Scan()
                trans = scanner.Text()
                check(scanner.Err())
                if len(trans) == 0 {
                    continue
                }
                option := strings.ToLower(trans)[0]
                if option == 'd' {
                    state = waiting
                    break
                } else if option == 'q' {
                    state = exit
                    break
                }
            }
        case waiting:
            fmt.Println("OK, put your money in the slot")
            for {
                fmt.Print("(S)elect product or choose a (R)efund : ")
                scanner.Scan()
                trans = scanner.Text()
                check(scanner.Err())
                if len(trans) == 0 {
                    continue
                }
                option := strings.ToLower(trans)[0]
                if option == 's' {
                    state = dispense
                    break
                } else if option == 'r' {
                    state = refunding
                    break
                }
            }
        case dispense:
            for {
                fmt.Print("(R)emove product : ")
                scanner.Scan()
                trans = scanner.Text()
                check(scanner.Err())
                if len(trans) == 0 {
                    continue
                }
                option := strings.ToLower(trans)[0]
                if option == 'r' {
                    state = ready
                    break
                }
            }
        case refunding:
            
            fmt.Println("OK, refunding your money")
            state = ready
        case exit:
            fmt.Println("OK, quitting")
            return
        }
    }
}

func main() {
    fsm()
}
Task: Sokoban




Go: package main

import (
    "fmt"
    "strings"
)

func main() {
    level := `
#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######`
    fmt.Printf("level:%s\n", level)
    fmt.Printf("solution:\n%s\n", solve(level))
}   
    
func solve(board string) string {
    buffer = make([]byte, len(board))
    width := strings.Index(board[1:], "\n") + 1
    dirs := []struct {
        move, push string 
        dPos       int
    }{
        {"u", "U", -width},
        {"r", "R", 1},
        {"d", "D", width},
        {"l", "L", -1},
    }
    visited := map[string]bool{board: true}
    open := []state{state{board, "", strings.Index(board, "@")}}
    for len(open) > 0 {
        s1 := &open[0]
        open = open[1:]
        for _, dir := range dirs {
            var newBoard, newSol string
            newPos := s1.pos + dir.dPos
            switch s1.board[newPos] {
            case '$', '*':
                newBoard = s1.push(dir.dPos)
                if newBoard == "" || visited[newBoard] {
                    continue
                }
                newSol = s1.cSol + dir.push
                if strings.IndexAny(newBoard, ".+") < 0 {
                    return newSol
                }
            case ' ', '.':
                newBoard = s1.move(dir.dPos)
                if visited[newBoard] {
                    continue
                }
                newSol = s1.cSol + dir.move
            default:
                continue
            }
            open = append(open, state{newBoard, newSol, newPos})
            visited[newBoard] = true
        }
    }
    return "No solution"
}

type state struct {
    board string
    cSol  string
    pos   int
}

var buffer []byte

func (s *state) move(dPos int) string {
    copy(buffer, s.board)
    if buffer[s.pos] == '@' {
        buffer[s.pos] = ' '
    } else {
        buffer[s.pos] = '.'
    }
    newPos := s.pos + dPos
    if buffer[newPos] == ' ' {
        buffer[newPos] = '@'
    } else {
        buffer[newPos] = '+'
    }
    return string(buffer)
}

func (s *state) push(dPos int) string {
    newPos := s.pos + dPos
    boxPos := newPos + dPos
    switch s.board[boxPos] {
    case ' ', '.':
    default:
        return ""
    }
    copy(buffer, s.board)
    if buffer[s.pos] == '@' {
        buffer[s.pos] = ' '
    } else {
        buffer[s.pos] = '.'
    }
    if buffer[newPos] == '$' {
        buffer[newPos] = '@'
    } else {
        buffer[newPos] = '+'
    }
    if buffer[boxPos] == ' ' {
        buffer[boxPos] = '$'
    } else {
        buffer[boxPos] = '*'
    }
    return string(buffer)
}
Task: Zumkeller numbers




Go: package main

import "fmt"

func getDivisors(n int) []int {
    divs := []int{1, n}
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            j := n / i
            divs = append(divs, i)
            if i != j {
                divs = append(divs, j)
            }
        }
    }
    return divs
}

func sum(divs []int) int {
    sum := 0
    for _, div := range divs {
        sum += div
    }
    return sum
}

func isPartSum(divs []int, sum int) bool {
    if sum == 0 {
        return true
    }
    le := len(divs)
    if le == 0 {
        return false
    }
    last := divs[le-1]
    divs = divs[0 : le-1]
    if last > sum {
        return isPartSum(divs, sum)
    }
    return isPartSum(divs, sum) || isPartSum(divs, sum-last)
}

func isZumkeller(n int) bool {
    divs := getDivisors(n)
    sum := sum(divs)
    
    if sum%2 == 1 {
        return false
    }
    
    if n%2 == 1 {
        abundance := sum - 2*n
        return abundance > 0 && abundance%2 == 0
    }
    
    return isPartSum(divs, sum/2)
}

func main() {
    fmt.Println("The first 220 Zumkeller numbers are:")
    for i, count := 2, 0; count < 220; i++ {
        if isZumkeller(i) {
            fmt.Printf("%3d ", i)
            count++
            if count%20 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println("\nThe first 40 odd Zumkeller numbers are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if isZumkeller(i) {
            fmt.Printf("%5d ", i)
            count++
            if count%10 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:")
    for i, count := 3, 0; count < 40; i += 2 {
        if (i % 10 != 5) && isZumkeller(i) {
            fmt.Printf("%7d ", i)
            count++
            if count%8 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println()
}