WeixiangYan/CodeTransOcean huggingface dataset:
Task: Extreme floating point values




Go: package main

import (
    "fmt"
    "math"
)

func main() {
    
    var zero float64                         
    var negZero, posInf, negInf, nan float64 
    negZero = zero * -1
    posInf = 1 / zero
    negInf = -1 / zero
    nan = zero / zero

    
    fmt.Println(negZero, posInf, negInf, nan)

    
    fmt.Println(math.Float64frombits(1<<63),
        math.Inf(1), math.Inf(-1), math.NaN())

    
    fmt.Println()
    validateNaN(negInf+posInf, "-Inf + Inf")
    validateNaN(0*posInf, "0 * Inf")
    validateNaN(posInf/posInf, "Inf / Inf")
    
    
    validateNaN(math.Mod(posInf, 1), "Inf % 1")
    validateNaN(1+nan, "1 + NaN")
    validateZero(1/posInf, "1 / Inf")
    validateGT(posInf, math.MaxFloat64, "Inf > max value")
    validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
    validateNE(nan, nan, "NaN != NaN")
    validateEQ(negZero, 0, "-0 == 0")
}

func validateNaN(n float64, op string) {
    if math.IsNaN(n) {
        fmt.Println(op, "-> NaN")
    } else {
        fmt.Println("!!! Expected NaN from", op, "  Found", n)
    }
}

func validateZero(n float64, op string) {
    if n == 0 {
        fmt.Println(op, "-> 0")
    } else {
        fmt.Println("!!! Expected 0 from", op, "  Found", n)
    }
}

func validateGT(a, b float64, op string) {
    if a > b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}

func validateNE(a, b float64, op string) {
    if a == b {
        fmt.Println("!!! Expected", op, "  Found not true.")
    } else {
        fmt.Println(op)
    }
}

func validateEQ(a, b float64, op string) {
    if a == b {
        fmt.Println(op)
    } else {
        fmt.Println("!!! Expected", op, "  Found not true.")
    }
}
Task: Soundex




Go: package main

import (
    "errors"
    "fmt"
    "unicode"
)

var code = []byte("01230127022455012623017202")

func soundex(s string) (string, error) {
    var sx [4]byte
    var sxi int
    var cx, lastCode byte
    for i, c := range s {
        switch {
        case !unicode.IsLetter(c):
            if c < ' ' || c == 127 {
                return "", errors.New("ASCII control characters disallowed")
            }
            if i == 0 {
                return "", errors.New("initial character must be a letter")
            }
            lastCode = '0'
            continue
        case c >= 'A' && c <= 'Z':
            cx = byte(c - 'A')
        case c >= 'a' && c <= 'z':
            cx = byte(c - 'a')
        default:
            return "", errors.New("non-ASCII letters unsupported")
        }
        
        if i == 0 {
            sx[0] = cx + 'A'
            sxi = 1
            continue
        }
        switch x := code[cx]; x {
        case '7', lastCode:
        case '0':
            lastCode = '0'
        default:
            sx[sxi] = x
            if sxi == 3 {
                return string(sx[:]), nil
            }
            sxi++
            lastCode = x
        }
    }
    if sxi == 0 {
        return "", errors.New("no letters present")
    }
    for ; sxi < 4; sxi++ {
        sx[sxi] = '0'
    }
    return string(sx[:]), nil
}

func main() {
    for _, s := range []string{
        "Robert",   
        "Rupert",   
        "Rubin",    
        "ashcroft", 
        "ashcraft", 
        "moses",    
        "O'Mally",  
        "d jay",    
        "R2-D2",    
        "12p2",     
        "naïve",    
        "",         
        "bump\t",   
    } {
        if x, err := soundex(s); err == nil {
            fmt.Println("soundex", s, "=", x)
        } else {
            fmt.Printf("\"%s\" fail. %s\n", s, err)
        }
    }
}
Task: Knuth's algorithm S




Go: package main

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

func sOfNCreator(n int) func(byte) []byte {
    s := make([]byte, 0, n)
    m := n
    return func(item byte) []byte {
        if len(s) < n {
            s = append(s, item)
        } else {
            m++
            if rand.Intn(m) < n {
                s[rand.Intn(n)] = item
            }
        }
        return s
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    var freq [10]int
    for r := 0; r < 1e5; r++ {
        sOfN := sOfNCreator(3)
        for d := byte('0'); d < '9'; d++ {
            sOfN(d)
        }
        for _, d := range sOfN('9') {
            freq[d-'0']++
        }
    }
    fmt.Println(freq)
}
Task: Conjugate transpose




Go: package main

import (
    "fmt"
    "math"
    "math/cmplx"
)


type matrix struct {
    ele  []complex128
    cols int
}


func (m *matrix) conjTranspose() *matrix {
    r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
    rx := 0
    for _, e := range m.ele {
        r.ele[rx] = cmplx.Conj(e)
        rx += r.cols
        if rx >= len(r.ele) {
            rx -= len(r.ele) - 1
        }
    }
    return r
}


func main() {
    show("h", matrixFromRows([][]complex128{
        {3, 2 + 1i},
        {2 - 1i, 1}}))

    show("n", matrixFromRows([][]complex128{
        {1, 1, 0},
        {0, 1, 1},
        {1, 0, 1}}))

    show("u", matrixFromRows([][]complex128{
        {math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
        {math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
        {0, 0, 1i}}))
}

func show(name string, m *matrix) {
    m.print(name)
    ct := m.conjTranspose()
    ct.print(name + "_ct")

    fmt.Println("Hermitian:", m.equal(ct, 1e-14))

    mct := m.mult(ct)
    ctm := ct.mult(m)
    fmt.Println("Normal:", mct.equal(ctm, 1e-14))

    i := eye(m.cols)
    fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}


func matrixFromRows(rows [][]complex128) *matrix {
    m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
    for rx, row := range rows {
        copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
    }
    return m
}

func eye(n int) *matrix {
    r := &matrix{make([]complex128, n*n), n}
    n++
    for x := 0; x < len(r.ele); x += n {
        r.ele[x] = 1
    }
    return r
}


func (m *matrix) print(heading string) {
    fmt.Print("\n", heading, "\n")
    for e := 0; e < len(m.ele); e += m.cols {
        fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
        fmt.Println()
    }
}


func (a *matrix) equal(b *matrix, ε float64) bool {
    for x, aEle := range a.ele {
        if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
            math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
            return false
        }
    }
    return true
}


func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
    m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
    for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
        for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
            for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
                m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
                m1x++
            }
            m3x++
        }
    }
    return m3
}
Task: Cousin primes




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        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() {
    count := 0
    fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
    for i := 3; i <= 995; i += 2 {
        if isPrime(i) && isPrime(i+4) {
            fmt.Printf("%3d:%3d  ", i, i+4)
            count++
            if count%7 == 0 {
                fmt.Println()
            }
            if i != 3 {
                i += 4
            } else {
                i += 2
            }
        }
    }
    fmt.Printf("\n\n%d pairs found\n", count)
}
Task: Return multiple values




Go: func addsub(x, y int) (int, int) {
  return x + y, x - y
}
Task: Change e letters to i in words




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) > 5 {
            words = append(words, s)
        }
    }
    count := 0
    le := len(words)
    for _, word := range words {
        if strings.ContainsRune(word, 'e') {
            repl := strings.ReplaceAll(word, "e", "i")
            ix := sort.SearchStrings(words, repl) 
            if ix < le && words[ix] == repl {
                count++
                fmt.Printf("%2d: %-9s -> %s\n", count, word, repl)
            }
        }
    }
}
Task: Fractran




Go: package main

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

func compile(src string) ([]big.Rat, bool) {
    s := strings.Fields(src)
    r := make([]big.Rat, len(s))
    for i, s1 := range s {
        if _, ok := r[i].SetString(s1); !ok {
            return nil, false
        }
    }
    return r, true
}

func exec(p []big.Rat, n *big.Int, limit int) {
    var q, r big.Int
rule:
    for i := 0; i < limit; i++ {
        fmt.Printf("%d ", n)
        for j := range p {
            q.QuoRem(n, p[j].Denom(), &r)
            if r.BitLen() == 0 {
                n.Mul(&q, p[j].Num())
                continue rule
            }
        }
        break
    }
    fmt.Println()
}

func usage() {
    log.Fatal("usage: ft <limit> <n> <prog>")
}

func main() {
    if len(os.Args) != 4 {
        usage()
    }
    limit, err := strconv.Atoi(os.Args[1])
    if err != nil {
        usage()
    }
    var n big.Int
    _, ok := n.SetString(os.Args[2], 10)
    if !ok {
        usage()
    }
    p, ok := compile(os.Args[3])
    if !ok {
        usage()
    }
    exec(p, &n, limit)
}
Task: Substring_Top and tail




Go: package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    
    s := "ASCII"
    fmt.Println("String:                ", s)
    fmt.Println("First byte removed:    ", s[1:])
    fmt.Println("Last byte removed:     ", s[:len(s)-1])
    fmt.Println("First and last removed:", s[1:len(s)-1])
    
    u := "Δημοτική"
    fmt.Println("String:                ", u)
    _, sizeFirst := utf8.DecodeRuneInString(u)
    fmt.Println("First rune removed:    ", u[sizeFirst:])
    _, sizeLast := utf8.DecodeLastRuneInString(u)
    fmt.Println("Last rune removed:     ", u[:len(u)-sizeLast])
    fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast])
}
Task: Boolean values




Go:  
package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	var n bool = true
	fmt.Println(n)        
	fmt.Printf("%T\n", n) 
	n = !n
	fmt.Println(n) 

	x := 5
	y := 8
	fmt.Println("x == y:", x == y) 
	fmt.Println("x < y:", x < y)   

	fmt.Println("\nConvert String into Boolean Data type\n")
	str1 := "japan"
	fmt.Println("Before :", reflect.TypeOf(str1)) 
	bolStr, _ := strconv.ParseBool(str1)
	fmt.Println("After :", reflect.TypeOf(bolStr)) 
}
Task: Bitmap_Histogram




Go: package raster

import "math"

func (g *Grmap) Histogram(bins int) []int {
    if bins <= 0 {
        bins = g.cols
    }
    h := make([]int, bins)
    for _, p := range g.px {
        h[int(p)*(bins-1)/math.MaxUint16]++
    }
    return h
}

func (g *Grmap) Threshold(t uint16) {
    for i, p := range g.px {
        if p < t {
            g.px[i] = 0
        } else {
            g.px[i] = math.MaxUint16
        }
    }
}
Task: Plot coordinate pairs




Go: package main

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

var (
  x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)

func main() {
  g := exec.Command("gnuplot", "-persist")
  w, err := g.StdinPipe()
  if err != nil {
    log.Fatal(err)
  }
  if err = g.Start(); err != nil {
    log.Fatal(err)
  }
  fmt.Fprintln(w, "unset key; plot '-'")
  for i, xi := range x {
    fmt.Fprintf(w, "%d %f\n", xi, y[i])
  }
  fmt.Fprintln(w, "e")
  w.Close()
  g.Wait()
}
Task: LZW compression




Go: package main

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


func compress(uncompressed string) []int {
	
	dictSize := 256
	
	
	dictionary := make(map[string]int, dictSize)
	for i := 0; i < dictSize; i++ {
		
		
		dictionary[string([]byte{byte(i)})] = i
	}

	var result []int
	var w []byte
	for i := 0; i < len(uncompressed); i++ {
		c := uncompressed[i]
		wc := append(w, c)
		if _, ok := dictionary[string(wc)]; ok {
			w = wc
		} else {
			result = append(result, dictionary[string(w)])
			
			dictionary[string(wc)] = dictSize
			dictSize++
			
			wc[0] = c
			w = wc[:1]
		}
	}

	if len(w) > 0 {
		
		result = append(result, dictionary[string(w)])
	}
	return result
}

type BadSymbolError int

func (e BadSymbolError) Error() string {
	return fmt.Sprint("Bad compressed symbol ", int(e))
}


func decompress(compressed []int) (string, error) {
	
	dictSize := 256
	dictionary := make(map[int][]byte, dictSize)
	for i := 0; i < dictSize; i++ {
		dictionary[i] = []byte{byte(i)}
	}

	var result strings.Builder
	var w []byte
	for _, k := range compressed {
		var entry []byte
		if x, ok := dictionary[k]; ok {
			
			entry = x[:len(x):len(x)]
		} else if k == dictSize && len(w) > 0 {
			entry = append(w, w[0])
		} else {
			return result.String(), BadSymbolError(k)
		}
		result.Write(entry)

		if len(w) > 0 {
			
			w = append(w, entry[0])
			dictionary[dictSize] = w
			dictSize++
		}
		w = entry
	}
	return result.String(), nil
}

func main() {
	compressed := compress("TOBEORNOTTOBEORTOBEORNOT")
	fmt.Println(compressed)
	decompressed, err := decompress(compressed)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(decompressed)
}
Task: Peano curve




Go: package main

import "github.com/fogleman/gg"

var points []gg.Point

const width = 81

func peano(x, y, lg, i1, i2 int) {
    if lg == 1 {
        px := float64(width-x) * 10
        py := float64(width-y) * 10
        points = append(points, gg.Point{px, py})
        return
    }
    lg /= 3
    peano(x+2*i1*lg, y+2*i1*lg, lg, i1, i2)
    peano(x+(i1-i2+1)*lg, y+(i1+i2)*lg, lg, i1, 1-i2)
    peano(x+lg, y+lg, lg, i1, 1-i2)
    peano(x+(i1+i2)*lg, y+(i1-i2+1)*lg, lg, 1-i1, 1-i2)
    peano(x+2*i2*lg, y+2*(1-i2)*lg, lg, i1, i2)
    peano(x+(1+i2-i1)*lg, y+(2-i1-i2)*lg, lg, i1, i2)
    peano(x+2*(1-i1)*lg, y+2*(1-i1)*lg, lg, i1, i2)
    peano(x+(2-i1-i2)*lg, y+(1+i2-i1)*lg, lg, 1-i1, i2)
    peano(x+2*(1-i2)*lg, y+2*i2*lg, lg, 1-i1, i2)
}

func main() {
    peano(0, 0, width, 0, 0)
    dc := gg.NewContext(820, 820)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    for _, p := range points {
        dc.LineTo(p.X, p.Y)
    }
    dc.SetRGB(1, 0, 1) 
    dc.SetLineWidth(1)
    dc.Stroke()
    dc.SavePNG("peano.png")
}
Task: Check input device is a terminal




Go: package main

import (
    "golang.org/x/crypto/ssh/terminal"
    "fmt"
    "os"
)

func main() {
    if terminal.IsTerminal(int(os.Stdin.Fd())) {
        fmt.Println("Hello terminal")
    } else {
        fmt.Println("Who are you?  You're not a terminal.")
    }
}
Task: First 9 prime Fibonacci number




Go: package main

import "fmt"

func isPrime(n uint64) bool {
    if n < 2 {
        return false
    }
    if n%2 == 0 {
        return n == 2
    }
    if n%3 == 0 {
        return n == 3
    }
    d := uint64(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() {
    f1 := uint64(1)
    f2 := f1
    count := 0
    limit := 12 
    fmt.Printf("The first %d prime Fibonacci numbers are:\n", limit)
    for count < limit {
        f3 := f1 + f2
        if isPrime(f3) {
            fmt.Printf("%d ", f3)
            count++
        }
        f1 = f2
        f2 = f3
    }
    fmt.Println()
}
Task: Bioinformatics_base count




Go: package main

import (
    "fmt"
    "sort"
)

func main() {
    dna := "" +
        "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" +
        "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" +
        "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" +
        "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" +
        "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" +
        "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" +
        "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" +
        "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" +
        "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" +
        "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"

    fmt.Println("SEQUENCE:")
    le := len(dna)
    for i := 0; i < le; i += 50 {
        k := i + 50
        if k > le {
            k = le
        }
        fmt.Printf("%5d: %s\n", i, dna[i:k])
    }
    baseMap := make(map[byte]int) 
    for i := 0; i < le; i++ {
        baseMap[dna[i]]++
    }
    var bases []byte
    for k := range baseMap {
        bases = append(bases, k)
    }
    sort.Slice(bases, func(i, j int) bool { 
        return bases[i] < bases[j]
    })

    fmt.Println("\nBASE COUNT:")
    for _, base := range bases {
        fmt.Printf("    %c: %3d\n", base, baseMap[base])
    }
    fmt.Println("    ------")
    fmt.Println("    Σ:", le)
    fmt.Println("    ======")
}
Task: Wireworld




Go: package main

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

var rows, cols int 
var rx, cx int     
var mn []int       

func main() {
    
    src, err := ioutil.ReadFile("ww.config")
    if err != nil {
        fmt.Println(err)
        return
    }
    srcRows := bytes.Split(src, []byte{'\n'})

    
    rows = len(srcRows)
    for _, r := range srcRows {
        if len(r) > cols {
            cols = len(r)
        }
    }
    rx, cx = rows+2, cols+2
    mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1}

    
    odd := make([]byte, rx*cx)
    even := make([]byte, rx*cx)
    for ri, r := range srcRows {
        copy(odd[(ri+1)*cx+1:], r)
    }

    
    for {
        print(odd)
        step(even, odd)
        fmt.Scanln()

        print(even)
        step(odd, even)
        fmt.Scanln()
    }
}

func print(grid []byte) {
    fmt.Println(strings.Repeat("__", cols))
    fmt.Println()
    for r := 1; r <= rows; r++ {
        for c := 1; c <= cols; c++ {
            if grid[r*cx+c] == 0 {
                fmt.Print("  ")
            } else {
                fmt.Printf(" %c", grid[r*cx+c])
            }
        }
        fmt.Println()
    }
}

func step(dst, src []byte) {
    for r := 1; r <= rows; r++ {
        for c := 1; c <= cols; c++ {
            x := r*cx + c
            dst[x] = src[x]
            switch dst[x] {
            case 'H':
                dst[x] = 't'
            case 't':
                dst[x] = '.'
            case '.':
                var nn int
                for _, n := range mn {
                    if src[x+n] == 'H' {
                        nn++
                    }
                }
                if nn == 1 || nn == 2 {
                    dst[x] = 'H'
                }
            }
        }
    }
}
Task: Terminal control_Inverse video




Go: package main

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

func main() {
    tput("rev")
    fmt.Print("Rosetta")
    tput("sgr0")
    fmt.Println(" Code")
}

func tput(arg string) error {
    cmd := exec.Command("tput", arg)
    cmd.Stdout = os.Stdout
    return cmd.Run()
}
Task: Ulam spiral (for primes)




Go: package main

import (
	"math"
	"fmt"
)

type Direction byte

const (
	RIGHT Direction = iota
	UP
	LEFT
	DOWN
)

func generate(n,i int, c byte) {
	s := make([][]string, n)
	for i := 0; i < n; i++ { s[i] = make([]string, n) }
	dir := RIGHT
	y := n / 2
	var x int
	if (n % 2 == 0) { x = y - 1 } else { x = y } 

	for j := i; j <= n * n - 1 + i; j++ {
		if (isPrime(j)) {
			if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) }
		} else { s[y][x] = "---" }

		switch dir {
		case RIGHT : if (x <= n - 1 && s[y - 1][x] == "" && j > i) { dir = UP }
		case UP : if (s[y][x - 1] == "") { dir = LEFT }
		case LEFT : if (x == 0 || s[y + 1][x] == "") { dir = DOWN }
		case DOWN : if (s[y][x + 1] == "") { dir = RIGHT }
		}

		switch dir {
		case RIGHT : x += 1
		case UP : y -= 1
		case LEFT : x -= 1
		case DOWN : y += 1
		}
	}

	for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) }
	fmt.Println()
}

func isPrime(a int) bool {
	if (a == 2) { return true }
	if (a <= 1 || a % 2 == 0) { return false }
	max := int(math.Sqrt(float64(a)))
	for n := 3; n <= max; n += 2 { if (a % n == 0) { return false } }
	return true
}

func main() {
	generate(9, 1, 0) 
	generate(9, 1, '*') 
}
Task: Fibonacci word




Go: package main

import (
	"fmt"
	"math"
)


func entropy(s string) float64 {
	m := map[rune]float64{}
	for _, r := range s {
		m[r]++
	}
	hm := 0.
	for _, c := range m {
		hm += c * math.Log2(c)
	}
	l := float64(len(s))
	return math.Log2(l) - hm/l
}

const F_Word1 = "1"
const F_Word2 = "0"

func FibonacciWord(n int) string {
	a, b := F_Word1, F_Word2
	for ; n > 1; n-- {
		a, b = b, b+a
	}
	return a
}

func FibonacciWordGen() <-chan string {
	ch := make(chan string)
	go func() {
		a, b := F_Word1, F_Word2
		for {
			ch <- a
			a, b = b, b+a
		}
	}()
	return ch
}

func main() {
	fibWords := FibonacciWordGen()
	fmt.Printf("%3s %9s  %-18s  %s\n", "N", "Length", "Entropy", "Word")
	n := 1
	for ; n < 10; n++ {
		s := <-fibWords
		
		if s2 := FibonacciWord(n); s != s2 {
			fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
		}
		fmt.Printf("%3d %9d  %.16f  %s\n", n, len(s), entropy(s), s)
	}
	for ; n <= 37; n++ {
		s := <-fibWords
		fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s))
	}
}
Task: Text processing_1




Go: package main

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

const (
	filename = "readings.txt"
	readings = 24             
	fields   = readings*2 + 1 
)

func main() {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	var (
		badRun, maxRun   int
		badDate, maxDate string
		fileSum          float64
		fileAccept       int
	)
	endBadRun := func() {
		if badRun > maxRun {
			maxRun = badRun
			maxDate = badDate
		}
		badRun = 0
	}
	s := bufio.NewScanner(file)
	for s.Scan() {
		f := strings.Fields(s.Text())
		if len(f) != fields {
			log.Fatal("unexpected format,", len(f), "fields.")
		}
		var accept int
		var sum float64
		for i := 1; i < fields; i += 2 {
			flag, err := strconv.Atoi(f[i+1])
			if err != nil {
				log.Fatal(err)
			}
			if flag <= 0 { 
				if badRun++; badRun == 1 {
					badDate = f[0]
				}
			} else { 
				endBadRun()
				value, err := strconv.ParseFloat(f[i], 64)
				if err != nil {
					log.Fatal(err)
				}
				sum += value
				accept++
			}
		}
		fmt.Printf("Line: %s  Reject %2d  Accept: %2d  Line_tot:%9.3f",
			f[0], readings-accept, accept, sum)
		if accept > 0 {
			fmt.Printf("  Line_avg:%8.3f\n", sum/float64(accept))
		} else {
			fmt.Println()
		}
		fileSum += sum
		fileAccept += accept
	}
	if err := s.Err(); err != nil {
		log.Fatal(err)
	}
	endBadRun()

	fmt.Println("\nFile     =", filename)
	fmt.Printf("Total    = %.3f\n", fileSum)
	fmt.Println("Readings = ", fileAccept)
	if fileAccept > 0 {
		fmt.Printf("Average  =  %.3f\n", fileSum/float64(fileAccept))
	}
	if maxRun == 0 {
		fmt.Println("\nAll data valid.")
	} else {
		fmt.Printf("\nMax data gap = %d, beginning on line %s.\n",
			maxRun, maxDate)
	}
}