package main

import "fmt"

// sudoku puzzle representation is an 81 character string
var puzzle = "" +
    "394  267 " +
    "   3  4  " +
    "5  69  2 " +
    " 45   9  " +
    "6       7" +
    "  7   58 " +
    " 1  67  8" +
    "  9  8   " +
    " 264  735"

func main() {
    printGrid("puzzle:", puzzle)
    if s := solve(puzzle); s == "" {
        fmt.Println("no solution")
    } else {
        printGrid("solved:", s)
    }
}

// print grid (with title) from 81 character string
func printGrid(title, s string) {
    fmt.Println(title)
    for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
        fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
            s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
        if r == 2 || r == 5 {
            fmt.Println("------+-------+------")
        }
    }
}

// solve puzzle in 81 character string format.
// if solved, result is 81 character string.
// if not solved, result is the empty string.
func solve(u string) string {
    // construct an dlx object with 324 constraint columns.
    // other than the number 324, this is not specific to sudoku.
    d := newDlxObject(324)
    // now add constraints that define sudoku rules.
    for r, i := 0, 0; r < 9; r++ {
        for c := 0; c < 9; c, i = c+1, i+1 {
            b := r/3*3 + c/3
            n := int(u[i] - '1')
            if n >= 0 && n < 9 {
                d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
                    243 + b*9 + n})
            } else {
                for n = 0; n < 9; n++ {
                    d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
                        243 + b*9 + n})
                }
            }
        }
    }
    // run dlx.  not sudoku specific.
    d.search()
    // extract the sudoku-specific 81 character result from the dlx solution.
    return d.text()
}

// Knuth's data object
type x struct {
    c          *y
    u, d, l, r *x
    // except x0 is not Knuth's.  it's pointer to first constraint in row,
    // so that the sudoku string can be constructed from the dlx solution.
    x0 *x
}

// Knuth's column object
type y struct {
    x
    s int // size
    n int // name
}

// an object to hold the matrix and solution
type dlx struct {
    ch []y  // all column headers
    h  *y   // ch[0], the root node
    o  []*x // solution
}

// constructor creates the column headers but no rows.
func newDlxObject(nCols int) *dlx {
    ch := make([]y, nCols+1)
    h := &ch[0]
    d := &dlx{ch, h, nil}
    h.c = h
    h.l = &ch[nCols].x
    ch[nCols].r = &h.x
    nh := ch[1:]
    for i := range ch[1:] {
        hi := &nh[i]
        ix := &hi.x
        hi.n = i
        hi.c = hi
        hi.u = ix
        hi.d = ix
        hi.l = &h.x
        h.r = ix
        h = hi
    }
    return d
}

// rows define constraints
func (d *dlx) addRow(nr []int) {
    if len(nr) == 0 {
        return
    }
    r := make([]x, len(nr))
    x0 := &r[0]
    for x, j := range nr {
        ch := &d.ch[j+1]
        ch.s++
        np := &r[x]
        np.c = ch
        np.u = ch.u
        np.d = &ch.x
        np.l = &r[(x+len(r)-1)%len(r)]
        np.r = &r[(x+1)%len(r)]
        np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
        np.x0 = x0
    }
}

// extracts 81 character sudoku string
func (d *dlx) text() string {
    b := make([]byte, len(d.o))
    for _, r := range d.o {
        x0 := r.x0
        b[x0.c.n] = byte(x0.r.c.n%9) + '1'
    }
    return string(b)
}

// the dlx algorithm
func (d *dlx) search() bool {
    h := d.h
    j := h.r.c
    if j == h {
        return true
    }
    c := j
    for minS := j.s; ; {
        j = j.r.c
        if j == h {
            break
        }
        if j.s < minS {
            c, minS = j, j.s
        }
    }

    cover(c)
    k := len(d.o)
    d.o = append(d.o, nil)
    for r := c.d; r != &c.x; r = r.d {
        d.o[k] = r
        for j := r.r; j != r; j = j.r {
            cover(j.c)
        }
        if d.search() {
            return true
        }
        r = d.o[k]
        c = r.c
        for j := r.l; j != r; j = j.l {
            uncover(j.c)
        }
    }
    d.o = d.o[:len(d.o)-1]
    uncover(c)
    return false
}

func cover(c *y) {
    c.r.l, c.l.r = c.l, c.r
    for i := c.d; i != &c.x; i = i.d {
        for j := i.r; j != i; j = j.r {
            j.d.u, j.u.d = j.u, j.d
            j.c.s--
        }
    }
}

func uncover(c *y) {
    for i := c.u; i != &c.x; i = i.u {
        for j := i.l; j != i; j = j.l {
            j.c.s++
            j.d.u, j.u.d = j, j
        }
    }
    c.r.l, c.l.r = &c.x, &c.x
}

implement a Sudoku solver that takes an 81 character string representing a partially filled 9x9 Sudoku grid as input, solves it using Knuth's DLX algorithm, and displays the solved Sudoku grid in a human-readable format.


package main

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

func main() {
    var a [20]int
    for i := range a {
        a[i] = i
    }
    fmt.Println(a)

    rand.Seed(time.Now().UnixNano())
    for i := len(a) - 1; i >= 1; i-- {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
    fmt.Println(a)
}

package main

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

// Generic Knuth Shuffle algorithm.  In Go, this is done with interface
// types.  The parameter s of function shuffle is an interface type.
// Any type satisfying the interface "shuffler" can be shuffled with
// this function.  Since the shuffle function uses the random number
// generator, it's nice to seed the generator at program load time.
func init() {
    rand.Seed(time.Now().UnixNano())
}
func shuffle(s shuffler) {
    for i := s.Len() - 1; i >= 1; i-- {
        j := rand.Intn(i + 1)
        s.Swap(i, j)
    }
}

// Conceptually, a shuffler is an indexed collection of things.
// It requires just two simple methods.
type shuffler interface {
    Len() int      // number of things in the collection
    Swap(i, j int) // swap the two things indexed by i and j
}

// ints is an example of a concrete type implementing the shuffler
// interface.
type ints []int

func (s ints) Len() int      { return len(s) }
func (s ints) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// Example program.  Make an ints collection, fill with sequential numbers,
// print, shuffle, print.
func main() {
    a := make(ints, 20)
    for i := range a {
        a[i] = i
    }
    fmt.Println(a)
    shuffle(a)
    fmt.Println(a)
}

Example output: (of either program)
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[11 10 12 19 4 13 15 17 14 2 5 18 8 0 6 9 7 3 1 16]

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an integer array or an array of any type. The shuffle is performed in-place on the input array, but can be modified to return a new array if necessary. It can also be adjusted to iterate from left to right. The function also includes test cases for validation.


package main

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

func main() {
	y := time.Now().Year()
	if len(os.Args) == 2 {
		if i, err := strconv.Atoi(os.Args[1]); err == nil {
			y = i
		}
	}
	for m := time.January; m <= time.December; m++ {
		d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour)
		d = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour)
		fmt.Println(d.Format("2006-01-02"))
	}
}

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


package main

import "fmt"

func main() { fmt.Print("Goodbye, World!") }

"Display the string 'Goodbye, World!' without appending a newline at the end."


Library: gotk3
package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str1, str2 string) bool {
    n, err := strconv.ParseFloat(str2, 64)
    if len(str1) == 0 || err != nil || n != 75000 {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid input",
        )
        dialog.Run()
        dialog.Destroy()
        return false
    }
    return true
}

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

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)
    check(err, "Unable to create vertical box:")
    vbox.SetBorderWidth(1)

    hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create first horizontal box:")

    hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create second horizontal box:")

    label, err := gtk.LabelNew("Enter a string and the number 75000   \n")
    check(err, "Unable to create label:")

    sel, err := gtk.LabelNew("String:      ")
    check(err, "Unable to create string entry label:")

    nel, err := gtk.LabelNew("Number: ")
    check(err, "Unable to create number entry label:")

    se, err := gtk.EntryNew()
    check(err, "Unable to create string entry:")

    ne, err := gtk.EntryNew()
    check(err, "Unable to create number entry:")

    hbox1.PackStart(sel, false, false, 2)
    hbox1.PackStart(se, false, false, 2)

    hbox2.PackStart(nel, false, false, 2)
    hbox2.PackStart(ne, false, false, 2)

    // button to accept
    ab, err := gtk.ButtonNewWithLabel("Accept")
    check(err, "Unable to create accept button:")
    ab.Connect("clicked", func() {
        // read and validate the entered values
        str1, _ := se.GetText()
        str2, _ := ne.GetText()
        if validateInput(window, str1, str2) {
            window.Destroy() // close window if input is OK
        }
    })

    vbox.Add(label)
    vbox.Add(hbox1)
    vbox.Add(hbox2)
    vbox.Add(ab)
    window.Add(vbox)

    window.ShowAll()
    gtk.Main()
}

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


package main

import (
    "fmt"
    "strings"
)

type ckey struct {
    enc, dec func(rune) rune
}

func newCaesar(k int) (*ckey, bool) {
    if k < 1 || k > 25 {
        return nil, false
    }
    rk := rune(k)
    return &ckey{
        enc: func(c rune) rune {
            if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk {
                return c + rk
            } else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' {
                return c + rk - 26
            }
            return c
        },
        dec: func(c rune) rune {
            if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' {
                return c - rk
            } else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk {
                return c - rk + 26
            }
            return c
        },
    }, true
}

func (ck ckey) encipher(pt string) string {
    return strings.Map(ck.enc, pt)
}

func (ck ckey) decipher(ct string) string {
    return strings.Map(ck.dec, ct)
}

func main() {
    pt := "The five boxing wizards jump quickly"
    fmt.Println("Plaintext:", pt)
    for _, key := range []int{0, 1, 7, 25, 26} {
        ck, ok := newCaesar(key)
        if !ok {
            fmt.Println("Key", key, "invalid")
            continue
        }
        ct := ck.encipher(pt)
        fmt.Println("Key", key)
        fmt.Println("  Enciphered:", ct)
        fmt.Println("  Deciphered:", ck.decipher(ct))
    }
}

package main

import (
    "fmt"
    "strings"
    "unicode"
)

type ckey struct {
    enc, dec unicode.SpecialCase
}

func newCaesar(k int) (*ckey, bool) {
    if k < 1 || k > 25 {
        return nil, false
    }
    i := uint32(k)
    r := rune(k)
    return &ckey{
        unicode.SpecialCase{
            {'A', 'Z' - i, [3]rune{r}},
            {'Z' - i + 1, 'Z', [3]rune{r - 26}},
            {'a', 'z' - i, [3]rune{r}},
            {'z' - i + 1, 'z', [3]rune{r - 26}},
        },
        unicode.SpecialCase{
            {'A', 'A' + i - 1, [3]rune{26 - r}},
            {'A' + i, 'Z', [3]rune{-r}},
            {'a', 'a' + i - 1, [3]rune{26 - r}},
            {'a' + i, 'z', [3]rune{-r}},
        },
    }, true
}

func (ck ckey) encipher(pt string) string {
    return strings.ToUpperSpecial(ck.enc, pt)
}

func (ck ckey) decipher(ct string) string {
    return strings.ToUpperSpecial(ck.dec, ct)
}

func main() {
    pt := "The five boxing wizards jump quickly"
    fmt.Println("Plaintext:", pt)
    for _, key := range []int{0, 1, 7, 25, 26} {
        ck, ok := newCaesar(key)
        if !ok {
            fmt.Println("Key", key, "invalid")
            continue
        }
        ct := ck.encipher(pt)
        fmt.Println("Key", key)
        fmt.Println("  Enciphered:", ct)
        fmt.Println("  Deciphered:", ck.decipher(ct))
    }
}

implement both encoding and decoding functionalities of a Caesar cipher. The cipher uses a key ranging from 1 to 25 to rotate the letters of the alphabet. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z to A. The codes also consider the vulnerabilities of the cipher, such as frequency analysis and key guessing. It also highlights the similarities between Caesar cipher and Vigenère cipher with a key of length 1, and Rot-13 with key 13.


calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


package main

import "fmt"

func isCusip(s string) bool {
    if len(s) != 9 { return false }
    sum := 0
    for i := 0; i < 8; i++ {
        c := s[i]
        var v int
        switch {
            case c >= '0' && c <= '9':
                v = int(c) - 48
            case c >= 'A' && c <= 'Z':
                v = int(c) - 55
            case c == '*':
                v = 36
            case c == '@':
                v = 37
            case c == '#':
                v = 38
            default:
                return false
        }
        if i % 2 == 1 { v *= 2 }  // check if odd as using 0-based indexing
        sum += v/10 + v%10
    }
    return int(s[8]) - 48 == (10 - (sum%10)) % 10
}

func main() {
    candidates := []string {
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105",
    }

    for _, candidate := range candidates {
        var b string
        if isCusip(candidate) {
            b = "correct"
        } else {
            b = "incorrect"
        }
        fmt.Printf("%s -> %s\n", candidate, b)
    }
}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


package main

import (
	"fmt"
	"io/ioutil"
	"runtime"
	"strconv"
	"strings"
	"unsafe"
)

func main() {
	fmt.Println(runtime.Version(), runtime.GOOS, runtime.GOARCH)

	// Inspect a uint32 variable to determine endianness.
	x := uint32(0x01020304)
	switch *(*byte)(unsafe.Pointer(&x)) {
	case 0x01:
		fmt.Println("big endian")
	case 0x04:
		fmt.Println("little endian")
	default:
		fmt.Println("mixed endian?")
	}

	// Usually one cares about the size the executible was compiled for
	// rather than the actual underlying host's size.

	// There are several ways of determining the size of an int/uint.
	fmt.Println("         strconv.IntSize =", strconv.IntSize)
	// That uses the following definition we can also be done by hand
	intSize := 32 << uint(^uint(0)>>63)
	fmt.Println("32 << uint(^uint(0)>>63) =", intSize)

	// With Go 1.0, 64-bit architectures had 32-bit int and 64-bit
	// uintptr. This was changed in Go 1.1. In general it would
	// still be possible that int and uintptr (the type large enough
	// to hold the bit pattern of any pointer) are of different sizes.
	const bitsPerByte = 8
	fmt.Println("  sizeof(int)     in bits:", unsafe.Sizeof(int(0))*bitsPerByte)
	fmt.Println("  sizeof(uintptr) in bits:", unsafe.Sizeof(uintptr(0))*bitsPerByte)
	// If we really want to know the architecture size the executable was
	// compiled for and not the size of int it safest to take the max of those.
	archSize := unsafe.Sizeof(int(0))
	if psize := unsafe.Sizeof(uintptr(0)); psize > archSize {
		archSize = psize
	}
	fmt.Println("  compiled with word size:", archSize*bitsPerByte)

	// There are some *very* unportable ways to attempt to get the actual
	// underlying hosts' word size.
	// Inspect cpuinfo to determine word size (some unix-like OS' only).
	c, err := ioutil.ReadFile("/proc/cpuinfo")
	if err != nil {
		fmt.Println(err)
		return
	}
	ls := strings.Split(string(c), "\n")
	for _, l := range ls {
		if strings.HasPrefix(l, "flags") {
			for _, f := range strings.Fields(l) {
				if f == "lm" { // "long mode"
					fmt.Println("64 bit word size")
					return
				}
			}
			fmt.Println("32 bit word size")
			return
		}
	}
}

"Code prints the word size and endianness of the host machine using an alternative technique."


package main

import (
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"sort"
	"strconv"
	"strings"
)

var baseQuery = "http://rosettacode.org/mw/api.php?action=query" +
	"&format=xml&list=categorymembers&cmlimit=500"

func req(u string, foundCm func(string)) string {
	resp, err := http.Get(u)
	if err != nil {
		log.Fatal(err) // connection or request fail
	}
	defer resp.Body.Close()
	for p := xml.NewDecoder(resp.Body); ; {
		t, err := p.RawToken()
		switch s, ok := t.(xml.StartElement); {
		case err == io.EOF:
			return ""
		case err != nil:
			log.Fatal(err)
		case !ok:
			continue
		case s.Name.Local == "cm":
			for _, a := range s.Attr {
				if a.Name.Local == "title" {
					foundCm(a.Value)
				}
			}
		case s.Name.Local == "categorymembers" && len(s.Attr) > 0 &&
			s.Attr[0].Name.Local == "cmcontinue":
			return url.QueryEscape(s.Attr[0].Value)
		}
	}
	return ""
}

// satisfy sort interface (reverse sorting)
type pop struct {
	string
	int
}
type popList []pop

func (pl popList) Len() int      { return len(pl) }
func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }
func (pl popList) Less(i, j int) bool {
	switch d := pl[i].int - pl[j].int; {
	case d > 0:
		return true
	case d < 0:
		return false
	}
	return pl[i].string < pl[j].string
}

func main() {
	// get languages, store in a map
	langMap := make(map[string]bool)
	storeLang := func(cm string) {
		if strings.HasPrefix(cm, "Category:") {
			cm = cm[9:]
		}
		langMap[cm] = true
	}
	languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages"
	continueAt := req(languageQuery, storeLang)
	for continueAt != "" {
		continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang)
	}
	// allocate slice for sorting
	s := make(popList, 0, len(langMap))

	// get big list of categories
	resp, err := http.Get("http://rosettacode.org/mw/index.php" +
		"?title=Special:Categories&limit=5000")
	if err != nil {
		log.Fatal(err)
	}
	page, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	// split out fields of interest and populate sortable slice
	rx := regexp.MustCompile("
(.*).*[(]([0-9]+) member")
	for _, sm := range rx.FindAllSubmatch(page, -1) {
		ls := string(sm[1])
		if langMap[ls] {
			if n, err := strconv.Atoi(string(sm[2])); err == nil {
				s = append(s, pop{ls, n})
			}
		}
	}

	// output
	sort.Sort(s)
	lastCnt, lastIdx := -1, 1
	for i, lang := range s {
		if lang.int != lastCnt {
			lastCnt = lang.int
			lastIdx = i + 1
		}
		fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string)
	}
}

Output on 11 Aug 2014:
  1. 832 - Tcl
  2. 783 - Racket
  3. 774 - Python
  4. 733 - Perl 6
  5. 729 - J
…
506.   1 - Supernova
506.   1 - TestML
506.   1 - Vox
506.   1 - XPath 2.0
506.   1 - Xanadu

sort and rank the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data, optionally filters incorrect results, and compares the results with a complete, periodically updated list of all programming languages. The final output is a ranked list of all languages.


func printAll(values []int) {
   for i, x := range values {
      fmt.Printf("Item %d = %d\n", i, x)
   }
}

Iterates through each element in a collection in sequence using a "for each" loop or an alternative loop if "for each" is not available. The range function is utilized with either one or two variables to retrieve the index and/or value of each item in the collection. For channels, only the single-variable variant is used.


package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "Hello,How,Are,You,Today"
    fmt.Println(strings.Join(strings.Split(s, ","), "."))
}

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


Binary Euclidian[edit]
package main

import "fmt"

func gcd(a, b int) int {
    var bgcd func(a, b, res int) int

    bgcd = func(a, b, res int) int {
	switch {
	case a == b:
	    return res * a
	case a % 2 == 0 && b % 2 == 0:
	    return bgcd(a/2, b/2, 2*res)
	case a % 2 == 0:
	    return bgcd(a/2, b, res)
	case b % 2 == 0:
	    return bgcd(a, b/2, res)
	case a > b:
	    return bgcd(a-b, b, res)
	default:
	    return bgcd(a, b-a, res)
	}
    }

    return bgcd(a, b, 1)
}

func main() {
    type pair struct {
	a int
	b int
    }

    var testdata []pair = []pair{
	pair{33, 77},
	pair{49865, 69811},
    }

    for _, v := range testdata {
	fmt.Printf("gcd(%d, %d) = %d\n", v.a, v.b, gcd(v.a, v.b))
    }
}

Output for Binary Euclidian algorithm:
gcd(33, 77) = 11
gcd(49865, 69811) = 9973

Iterative[edit]
package main

import "fmt"

func gcd(x, y int) int {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

func main() {
    fmt.Println(gcd(33, 77))
    fmt.Println(gcd(49865, 69811))
}

Builtin[edit]

package main

import (
    "fmt"
    "math/big"
)

func gcd(x, y int64) int64 {
    return new(big.Int).GCD(nil, nil, big.NewInt(x), big.NewInt(y)).Int64()
}

func main() {
    fmt.Println(gcd(33, 77))
    fmt.Println(gcd(49865, 69811))
}

Output in either case:
11
9973

find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. This function is a wrapper for big.GCD.


package main

import (
	"fmt"
	"net"
	"bufio"
)

func echo(s net.Conn, i int) {
	defer s.Close();

	fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
	b := bufio.NewReader(s)
	for {
		line, e := b.ReadBytes('\n')
		if e != nil {
			break
		}
		s.Write(line)
	}
	fmt.Printf("%d: closed\n", i)
}

func main() {
	l, e := net.Listen("tcp", ":12321")
	for i := 0; e == nil; i++ {
		var s net.Conn
		s, e = l.Accept()
		go echo(s, i)
	}
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


package main

import (
    "fmt"
    "strconv"
)

func isNumeric(s string) bool {
    _, err := strconv.ParseFloat(s, 64)
    return err == nil
}

func main() {
    fmt.Println("Are these strings numeric?")
    strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"}
    for _, s := range strings {
        fmt.Printf("  %4s -> %t\n", s, isNumeric(s))
    }
}

check if a given string is a numeric value, including floating point and negative numbers, using a boolean function. The function utilizes both a library function and a custom one, but only verifies if the string can be converted into an integer.


package main

import (
    "io"
    "log"
    "net/http"
    "os"
)

func main() {
    r, err := http.Get("https://sourceforge.net/")
    if err != nil {
        log.Fatalln(err)
    }
    io.Copy(os.Stdout, r.Body)
}

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


package main

import "fmt"

type point struct {
    x, y float32
}

var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}

var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}

func main() {
    var cp1, cp2, s, e point
    inside := func(p point) bool {
        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
    }
    intersection := func() (p point) {
        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y
        dpx, dpy := s.x-e.x, s.y-e.y
        n1 := cp1.x*cp2.y - cp1.y*cp2.x
        n2 := s.x*e.y - s.y*e.x
        n3 := 1 / (dcx*dpy - dcy*dpx)
        p.x = (n1*dpx - n2*dcx) * n3
        p.y = (n1*dpy - n2*dcy) * n3
        return
    }
    outputList := subjectPolygon
    cp1 = clipPolygon[len(clipPolygon)-1]
    for _, cp2 = range clipPolygon { // WP clipEdge is cp1,cp2 here
        inputList := outputList
        outputList = nil
        s = inputList[len(inputList)-1]
        for _, e = range inputList {
            if inside(e) {
                if !inside(s) {
                    outputList = append(outputList, intersection())
                }
                outputList = append(outputList, e)
            } else if inside(s) {
                outputList = append(outputList, intersection())
            }
            s = e
        }
        cp1 = cp2
    }
    fmt.Println(outputList)
}

Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The code takes a polygon defined by a sequence of points and clips it by a rectangle, also defined by a sequence of points. The resulting clipped polygon is then printed. For extra credit, the code also displays all three polygons on a graphical surface, each in a different color, with the resulting polygon filled in.


package main

import (
	"fmt"
	"sort"
)

type rankable interface {
	Len() int
	RankEqual(int, int) bool
}

func StandardRank(d rankable) []float64 {
	r := make([]float64, d.Len())
	var k int
	for i := range r {
		if i == 0 || !d.RankEqual(i, i-1) {
			k = i + 1
		}
		r[i] = float64(k)
	}
	return r
}

func ModifiedRank(d rankable) []float64 {
	r := make([]float64, d.Len())
	for i := range r {
		k := i + 1
		for j := i + 1; j < len(r) && d.RankEqual(i, j); j++ {
			k = j + 1
		}
		r[i] = float64(k)
	}
	return r
}

func DenseRank(d rankable) []float64 {
	r := make([]float64, d.Len())
	var k int
	for i := range r {
		if i == 0 || !d.RankEqual(i, i-1) {
			k++
		}
		r[i] = float64(k)
	}
	return r
}

func OrdinalRank(d rankable) []float64 {
	r := make([]float64, d.Len())
	for i := range r {
		r[i] = float64(i + 1)
	}
	return r
}

func FractionalRank(d rankable) []float64 {
	r := make([]float64, d.Len())
	for i := 0; i < len(r); {
		var j int
		f := float64(i + 1)
		for j = i + 1; j < len(r) && d.RankEqual(i, j); j++ {
			f += float64(j + 1)
		}
		f /= float64(j - i)
		for ; i < j; i++ {
			r[i] = f
		}
	}
	return r
}

type scores []struct {
	score int
	name  string
}

func (s scores) Len() int                { return len(s) }
func (s scores) RankEqual(i, j int) bool { return s[i].score == s[j].score }
func (s scores) Swap(i, j int)           { s[i], s[j] = s[j], s[i] }
func (s scores) Less(i, j int) bool {
	if s[i].score != s[j].score {
		return s[i].score > s[j].score
	}
	return s[i].name < s[j].name
}

var data = scores{
	{44, "Solomon"},
	{42, "Jason"},
	{42, "Errol"},
	{41, "Garry"},
	{41, "Bernard"},
	{41, "Barry"},
	{39, "Stephen"},
}

func main() {
	show := func(name string, fn func(rankable) []float64) {
		fmt.Println(name, "Ranking:")
		r := fn(data)
		for i, d := range data {
			fmt.Printf("%4v - %2d %s\n", r[i], d.score, d.name)
		}
	}

	sort.Sort(data)
	show("Standard", StandardRank)
	show("\nModified", ModifiedRank)
	show("\nDense", DenseRank)
	show("\nOrdinal", OrdinalRank)
	show("\nFractional", FractionalRank)
}

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


package main

import (
    "fmt"
    "math"
)

const d = 30.
const r = d * math.Pi / 180

var s = .5
var c = math.Sqrt(3) / 2
var t = 1 / math.Sqrt(3)

func main() {
    fmt.Printf("sin(%9.6f deg) = %f\n", d, math.Sin(d*math.Pi/180))
    fmt.Printf("sin(%9.6f rad) = %f\n", r, math.Sin(r))
    fmt.Printf("cos(%9.6f deg) = %f\n", d, math.Cos(d*math.Pi/180))
    fmt.Printf("cos(%9.6f rad) = %f\n", r, math.Cos(r))
    fmt.Printf("tan(%9.6f deg) = %f\n", d, math.Tan(d*math.Pi/180))
    fmt.Printf("tan(%9.6f rad) = %f\n", r, math.Tan(r))
    fmt.Printf("asin(%f) = %9.6f deg\n", s, math.Asin(s)*180/math.Pi)
    fmt.Printf("asin(%f) = %9.6f rad\n", s, math.Asin(s))
    fmt.Printf("acos(%f) = %9.6f deg\n", c, math.Acos(c)*180/math.Pi)
    fmt.Printf("acos(%f) = %9.6f rad\n", c, math.Acos(c))
    fmt.Printf("atan(%f) = %9.6f deg\n", t, math.Atan(t)*180/math.Pi)
    fmt.Printf("atan(%f) = %9.6f rad\n", t, math.Atan(t))
}

demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in a given programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. The Go math package's constant pi and six trigonometric functions are also utilized.


package main

import "fmt"

type Item struct {
	name               string
	weight, value, qty int
}

var items = []Item{
	{"map",			9,	150,	1},
	{"compass",		13,	35,	1},
	{"water",		153,	200,	2},
	{"sandwich",		50,	60,	2},
	{"glucose",		15,	60,	2},
	{"tin",			68,	45,	3},
	{"banana",		27,	60,	3},
	{"apple",		39,	40,	3},
	{"cheese",		23,	30,	1},
	{"beer",		52,	10,	3},
	{"suntancream",		11,	70,	1},
	{"camera",		32,	30,	1},
	{"T-shirt",		24,	15,	2},
	{"trousers",		48,	10,	2},
	{"umbrella",		73,	40,	1},
	{"w-trousers",		42,	70,	1},
	{"w-overclothes",	43,	75,	1},
	{"note-case",		22,	80,	1},
	{"sunglasses",		7,      20,	1},
	{"towel",		18,	12,	2},
	{"socks",		4,      50,	1},
	{"book",		30,	10,	2},
}

type Chooser struct {
	Items []Item
	cache map[key]solution
}

type key struct {
	w, p int
}

type solution struct {
	v, w int
	qty  []int
}

func (c Chooser) Choose(limit int) (w, v int, qty []int) {
	c.cache = make(map[key]solution)
	s := c.rchoose(limit, len(c.Items)-1)
	c.cache = nil // allow cache to be garbage collected
	return s.v, s.w, s.qty
}

func (c Chooser) rchoose(limit, pos int) solution {
	if pos < 0 || limit <= 0 {
		return solution{0, 0, nil}
	}

	key := key{limit, pos}
	if s, ok := c.cache[key]; ok {
		return s
	}

	best_i, best := 0, solution{0, 0, nil}
	for i := 0; i*items[pos].weight <= limit && i <= items[pos].qty; i++ {
		sol := c.rchoose(limit-i*items[pos].weight, pos-1)
		sol.v += i * items[pos].value
		if sol.v > best.v {
			best_i, best = i, sol
		}
	}

	if best_i > 0 {
		// best.qty is used in another cache entry,
		// we need to duplicate it before modifying it to
		// store as our cache entry.
		old := best.qty
		best.qty = make([]int, len(items))
		copy(best.qty, old)
		best.qty[pos] = best_i
		best.w += best_i * items[pos].weight
	}
	c.cache[key] = best
	return best
}

func main() {
	v, w, s := Chooser{Items: items}.Choose(400)

	fmt.Println("Taking:")
	for i, t := range s {
		if t > 0 {
			fmt.Printf("  %d of %d %s\n", t, items[i].qty, items[i].name)
		}
	}
	fmt.Printf("Value: %d; weight: %d\n", v, w)
}

The code implements a solution to the Bounded Knapsack Problem. It helps a tourist to determine the optimal combination of items to carry in his knapsack, ensuring the total weight does not exceed 4 kg and the total value is maximized. The code uses caching to improve performance. It considers the weight, value, and quantity of each item, and assumes that only whole units of any item can be taken.


package main

import (
    "fmt"
    "os"
    "os/signal"
    "time"
)

func main() {
    start := time.Now()
    k := time.Tick(time.Second / 2)
    sc := make(chan os.Signal, 1)
    signal.Notify(sc, os.Interrupt)
    for n := 1; ; {
        // not busy waiting, this blocks until one of the two
        // channel operations is possible
        select {
        case <-k:
            fmt.Println(n)
            n++
        case <-sc:
            fmt.Printf("Ran for %f seconds.\n",
                time.Now().Sub(start).Seconds())
            return
        }
    }
}

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


package main
import "fmt"
import "strconv"
func main() {
  i, _ := strconv.Atoi("1234")
  fmt.Println(strconv.Itoa(i + 1))
}

package main

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

func main() {
    // integer
    is := "1234"
    fmt.Println("original:   ", is)
    i, err := strconv.Atoi(is)
    if err != nil {
        fmt.Println(err)
        return
    }
    // assignment back to original variable shows result is the same type.
    is = strconv.Itoa(i + 1)
    fmt.Println("incremented:", is)

    // error checking worthwhile
    fmt.Println()
    _, err = strconv.Atoi(" 1234") // whitespace not allowed
    fmt.Println(err)
    _, err = strconv.Atoi("12345678901")
    fmt.Println(err)
    _, err = strconv.Atoi("_1234")
    fmt.Println(err)
    _, err = strconv.ParseFloat("12.D34", 64)
    fmt.Println(err)

    // float
    fmt.Println()
    fs := "12.34"
    fmt.Println("original:   ", fs)
    f, err := strconv.ParseFloat(fs, 64)
    if err != nil {
        fmt.Println(err)
        return
    }
    // various options on FormatFloat produce different formats.  All are valid
    // input to ParseFloat, so result format does not have to match original
    // format.  (Matching original format would take more code.)
    fs = strconv.FormatFloat(f+1, 'g', -1, 64)
    fmt.Println("incremented:", fs)
    fs = strconv.FormatFloat(f+1, 'e', 4, 64)
    fmt.Println("what format?", fs)

    // complex
    // strconv package doesn't handle complex types, but fmt does.
    // (fmt can be used on ints and floats too, but strconv is more efficient.)
    fmt.Println()
    cs := "(12+34i)"
    fmt.Println("original:   ", cs)
    var c complex128
    _, err = fmt.Sscan(cs, &c)
    if err != nil {
        fmt.Println(err)
        return
    }
    cs = fmt.Sprint(c + 1)
    fmt.Println("incremented:", cs)

    // big integers have their own functions
    fmt.Println()
    bs := "170141183460469231731687303715884105728"
    fmt.Println("original:   ", bs)
    var b, one big.Int
    _, ok := b.SetString(bs, 10)
    if !ok {
        fmt.Println("big.SetString fail")
        return
    }
    one.SetInt64(1)
    bs = b.Add(&b, &one).String()
    fmt.Println("incremented:", bs)
}


package main

import (
	"fmt"
	"os"
	"path"
)

func CommonPrefix(sep byte, paths ...string) string {
	// Handle special cases.
	switch len(paths) {
	case 0:
		return ""
	case 1:
		return path.Clean(paths[0])
	}

	// Note, we treat string as []byte, not []rune as is often
	// done in Go. (And sep as byte, not rune). This is because
	// most/all supported OS' treat paths as string of non-zero
	// bytes. A filename may be displayed as a sequence of Unicode
	// runes (typically encoded as UTF-8) but paths are
	// not required to be valid UTF-8 or in any normalized form
	// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
	// file names.
	c := []byte(path.Clean(paths[0]))

	// We add a trailing sep to handle the case where the
	// common prefix directory is included in the path list
	// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
	// path.Clean will have cleaned off trailing / separators with
	// the exception of the root directory, "/" (in which case we
	// make it "//", but this will get fixed up to "/" bellow).
	c = append(c, sep)

	// Ignore the first path since it's already in c
	for _, v := range paths[1:] {
		// Clean up each path before testing it
		v = path.Clean(v) + string(sep)

		// Find the first non-common byte and truncate c
		if len(v) < len(c) {
			c = c[:len(v)]
		}
		for i := 0; i < len(c); i++ {
			if v[i] != c[i] {
				c = c[:i]
				break
			}
		}
	}

	// Remove trailing non-separator characters and the final separator
	for i := len(c) - 1; i >= 0; i-- {
		if c[i] == sep {
			c = c[:i]
			break
		}
	}

	return string(c)
}

func main() {
	c := CommonPrefix(os.PathSeparator,
		//"/home/user1/tmp",
		"/home/user1/tmp/coverage/test",
		"/home/user1/tmp/covert/operator",
		"/home/user1/tmp/coven/members",
		"/home//user1/tmp/coventry",
		"/home/user1/././tmp/covertly/foo",
		"/home/bob/../user1/tmp/coved/bar",
	)
	if c == "" {
		fmt.Println("No common path")
	} else {
		fmt.Println("Common path:", c)
	}
}

The code identifies the common directory path from a set of given directory paths. It uses a specified directory separator to determine commonality. The code ensures that if the common path is also a directory in the list, it is not truncated. It has been tested with the forward slash '/' as the directory separator and three specific strings as input paths. The function returns the valid directory and not the longest common string.


package main

import (
	"math/rand"
	"fmt"
)

func main() {
	list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	for i := 1; i <= 10; i++ {
		sattoloCycle(list)
		fmt.Println(list)
	}
}

func sattoloCycle(list []int) {
	for x := len(list) -1; x > 0; x-- {
		j := rand.Intn(x)
		list[x], list[j] = list[j], list[x]
	}
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


Library: Go Soap

package main

import (
    "fmt"
    "github.com/tiaguinho/gosoap"
    "log"
)

type CheckVatResponse struct {
    CountryCode string `xml:"countryCode"`
    VatNumber   string `xml:"vatNumber"`
    RequestDate string `xml:"requestDate"`
    Valid       string `xml:"valid"`
    Name        string `xml:"name"`
    Address     string `xml:"address"`
}

var (
    rv CheckVatResponse
)

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

func main() {
    // create SOAP client
    soap, err := gosoap.SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl")

    // map parameter names to values
    params := gosoap.Params{
        "vatNumber":   "6388047V",
        "countryCode": "IE",
    }

    // call 'checkVat' function
    err = soap.Call("checkVat", params)
    check(err)

    // unmarshal response to 'rv'
    err = soap.Unmarshal(&rv)
    check(err)

    // print response
    fmt.Println("Country Code  : ", rv.CountryCode)
    fmt.Println("Vat Number    : ", rv.VatNumber)
    fmt.Println("Request Date  : ", rv.RequestDate)
    fmt.Println("Valid         : ", rv.Valid)
    fmt.Println("Name          : ", rv.Name)
    fmt.Println("Address       : ", rv.Address)
}

create a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() from the SOAP server at http://example.com/soap/wsdl. The functionality is tested against a publicly available SOAP server.


Sort[edit]

package main

import (
    "fmt"
    "sort"
)

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(a []float64) float64 {
    sort.Float64s(a)
    half := len(a) / 2
    m := a[half]
    if len(a)%2 == 0 {
        m = (m + a[half-1]) / 2
    }
    return m
}

Partial selection sort[edit]

package main

import "fmt"

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(a []float64) float64 {
    half := len(a) / 2
    med := sel(a, half)
    if len(a)%2 == 0 {
        return (med + a[half-1]) / 2
    }
    return med
}

func sel(list []float64, k int) float64 {
    for i, minValue := range list[:k+1] {
        minIndex := i
        for j := i + 1; j < len(list); j++ {
            if list[j] < minValue {
                minIndex = j
                minValue = list[j]
                list[i], list[minIndex] = minValue, list[i]
            }
        }
    }
    return list[k]
}

Quickselect[edit]

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(median([]float64{3, 1, 4, 1}))    // prints 2
    fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3
}

func median(list []float64) float64 {
    half := len(list) / 2
    med := qsel(list, half)
    if len(list)%2 == 0 {
        return (med + qsel(list, half-1)) / 2
    }
    return med
}

func qsel(a []float64, k int) float64 {
    for len(a) > 1 {
        px := rand.Intn(len(a))
        pv := a[px]
        last := len(a) - 1
        a[px], a[last] = a[last], pv
        px = 0
        for i, v := range a[:last] {
            if v < pv {
                a[px], a[i] = v, a[px]
                px++
            }
        }
        if px == k {
            return pv
        }
        if k < px {
            a = a[:px]
        } else {
            // swap elements.  simply assigning a[last] would be enough to
            // allow qsel to return the correct result but it would leave slice
            // "a" unusable for subsequent use.  we want this full swap so that
            // we can make two successive qsel calls in the case of median
            // of an even number of elements.
            a[px], a[last] = pv, a[px]
            a = a[px+1:]
            k -= px + 1
        }
    }
    return a[0]
}

The code calculates the median value of a vector of floating-point numbers. It handles cases with an even number of elements by returning the average of the two middle values. The code implements the selection algorithm for finding the median in O(n) time. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The code references a selection algorithm and implements a quickselect with random pivoting for efficient computation.


switch/case approach[edit]
package main

import "fmt"

func main() {
    for i := 1; i <= 100; i++ {
        switch {
        case i%15==0:
            fmt.Println("FizzBuzz")
        case i%3==0:
            fmt.Println("Fizz")
        case i%5==0:
            fmt.Println("Buzz")
        default:
            fmt.Println(i)
        }
    }
}
map approach[edit]
package main

import "fmt"

func main() {
    for i := 1; i <= 100; i++ {
        fmt.Println(map[bool]map[bool]interface{}{
            false: {false: i, true: "Fizz"}, true: {false: "Buzz", true: "FizzBuzz"},
        }[i%5 == 0][i%3 == 0])
    }
}

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


Text

package main

import "fmt"
import "math/cmplx"

func mandelbrot(a complex128) (z complex128) {
    for i := 0; i < 50; i++ {
        z = z*z + a
    }
    return
}

func main() {
    for y := 1.0; y >= -1.0; y -= 0.05 {
        for x := -2.0; x <= 0.5; x += 0.0315 {
            if cmplx.Abs(mandelbrot(complex(x, y))) < 2 {
                fmt.Print("*")
            } else {
                fmt.Print(" ")
            }
        }
        fmt.Println("")
    }
}

Graphical
.png image
package main

import (
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "math/cmplx"
    "os"
)

const (
    maxEsc = 100
    rMin   = -2.
    rMax   = .5
    iMin   = -1.
    iMax   = 1.
    width  = 750
    red    = 230
    green  = 235
    blue   = 255
)

func mandelbrot(a complex128) float64 {
    i := 0
    for z := a; cmplx.Abs(z) < 2 && i < maxEsc; i++ {
        z = z*z + a
    }
    return float64(maxEsc-i) / maxEsc
}

func main() {
    scale := width / (rMax - rMin)
    height := int(scale * (iMax - iMin))
    bounds := image.Rect(0, 0, width, height)
    b := image.NewNRGBA(bounds)
    draw.Draw(b, bounds, image.NewUniform(color.Black), image.ZP, draw.Src)
    for x := 0; x < width; x++ {
        for y := 0; y < height; y++ {
            fEsc := mandelbrot(complex(
                float64(x)/scale+rMin,
                float64(y)/scale+iMin))
            b.Set(x, y, color.NRGBA{uint8(red * fEsc),
                uint8(green * fEsc), uint8(blue * fEsc), 255})

        }
    }
    f, err := os.Create("mandelbrot.png")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = png.Encode(f, b); err != nil {
        fmt.Println(err)
    }
    if err = f.Close(); err != nil {
        fmt.Println(err)
    }
}

generate and draw the Mandelbrot set using various algorithms and functions, and print an 80-character by 41-line depiction of it.


Implementation
package main

import "fmt"

func main() {
    sum, prod := 0, 1
    for _, x := range []int{1,2,5} {
        sum += x
        prod *= x
    }
    fmt.Println(sum, prod)
}

Calculate the sum and product of all integers in an array.


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

"Determines if a specified year is a leap year in the Gregorian calendar."


Translation of: Kotlin
package main

import (
    "bufio"
    "crypto/rand"
    "fmt"
    "io/ioutil"
    "log"
    "math/big"
    "os"
    "strconv"
    "strings"
    "unicode"
)

const (
    charsPerLine = 48
    chunkSize    = 6
    cols         = 8
    demo         = true // would normally be set to false
)

type fileType int

const (
    otp fileType = iota
    enc
    dec
)

var scnr = bufio.NewScanner(os.Stdin)

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

func toAlpha(s string) string {
    var filtered []rune
    for _, r := range s {
        if unicode.IsUpper(r) {
            filtered = append(filtered, r)
        }
    }
    return string(filtered)
}

func isOtpRelated(s string) bool {
    return strings.HasSuffix(s, ".1tp") || strings.HasSuffix(s, "1tp_cpy") ||
        strings.HasSuffix(s, ".1tp_enc") || strings.HasSuffix(s, "1tp_dec")
}

func makePad(nLines int) string {
    nChars := nLines * charsPerLine
    bytes := make([]byte, nChars)
    /* generate random upper case letters */
    max := big.NewInt(26)
    for i := 0; i < nChars; i++ {
        n, err := rand.Int(rand.Reader, max)
        check(err)
        bytes[i] = byte(65 + n.Uint64())
    }
    return inChunks(string(bytes), nLines, otp)
}

func vigenere(text, key string, encrypt bool) string {
    bytes := make([]byte, len(text))
    var ci byte
    for i, c := range text {
        if encrypt {
            ci = (byte(c) + key[i] - 130) % 26
        } else {
            ci = (byte(c) + 26 - key[i]) % 26
        }
        bytes[i] = ci + 65
    }
    temp := len(bytes) % charsPerLine
    if temp > 0 { // pad with random characters so each line is a full one
        max := big.NewInt(26)
        for i := temp; i < charsPerLine; i++ {
            n, err := rand.Int(rand.Reader, max)
            check(err)
            bytes = append(bytes, byte(65+n.Uint64()))
        }
    }
    ft := enc
    if !encrypt {
        ft = dec
    }
    return inChunks(string(bytes), len(bytes)/charsPerLine, ft)
}

func inChunks(s string, nLines int, ft fileType) string {
    nChunks := len(s) / chunkSize
    remainder := len(s) % chunkSize
    chunks := make([]string, nChunks)
    for i := 0; i < nChunks; i++ {
        chunks[i] = s[i*chunkSize : (i+1)*chunkSize]
    }
    if remainder > 0 {
        chunks = append(chunks, s[nChunks*chunkSize:])
    }
    var sb strings.Builder
    for i := 0; i < nLines; i++ {
        j := i * cols
        sb.WriteString(" " + strings.Join(chunks[j:j+cols], " ") + "\n")
    }
    ss := " file\n" + sb.String()
    switch ft {
    case otp:
        return "# OTP" + ss
    case enc:
        return "# Encrypted" + ss
    default: // case dec:
        return "# Decrypted" + ss
    }
}

func menu() int {
    fmt.Println(`
1. Create one time pad file.

2. Delete one time pad file.

3. List one time pad files.

4. Encrypt plain text.

5. Decrypt cipher text.

6. Quit program.
`)
    choice := 0
    for choice < 1 || choice > 6 {
        fmt.Print("Your choice (1 to 6) : ")
        scnr.Scan()
        choice, _ = strconv.Atoi(scnr.Text())
        check(scnr.Err())
    }
    return choice
}

func main() {
    for {
        choice := menu()
        fmt.Println()
        switch choice {
        case 1: // Create OTP
            fmt.Println("Note that encrypted lines always contain 48 characters.\n")
            fmt.Print("OTP file name to create (without extension) : ")
            scnr.Scan()
            fileName := scnr.Text() + ".1tp"
            nLines := 0
            for nLines < 1 || nLines > 1000 {
                fmt.Print("Number of lines in OTP (max 1000) : ")
                scnr.Scan()
                nLines, _ = strconv.Atoi(scnr.Text())
            }
            check(scnr.Err())
            key := makePad(nLines)
            file, err := os.Create(fileName)
            check(err)
            _, err = file.WriteString(key)
            check(err)
            file.Close()
            fmt.Printf("\n'%s' has been created in the current directory.\n", fileName)
            if demo {
                // a copy of the OTP file would normally be on a different machine
                fileName2 := fileName + "_cpy" // copy for decryption
                file, err := os.Create(fileName2)
                check(err)
                _, err = file.WriteString(key)
                check(err)
                file.Close()
                fmt.Printf("'%s' has been created in the current directory.\n", fileName2)
                fmt.Println("\nThe contents of these files are :\n")
                fmt.Println(key)
            }
        case 2: // Delete OTP
            fmt.Println("Note that this will also delete ALL associated files.\n")
            fmt.Print("OTP file name to delete (without extension) : ")
            scnr.Scan()
            toDelete1 := scnr.Text() + ".1tp"
            check(scnr.Err())
            toDelete2 := toDelete1 + "_cpy"
            toDelete3 := toDelete1 + "_enc"
            toDelete4 := toDelete1 + "_dec"
            allToDelete := []string{toDelete1, toDelete2, toDelete3, toDelete4}
            deleted := 0
            fmt.Println()
            for _, name := range allToDelete {
                if _, err := os.Stat(name); !os.IsNotExist(err) {
                    err = os.Remove(name)
                    check(err)
                    deleted++
                    fmt.Printf("'%s' has been deleted from the current directory.\n", name)
                }
            }
            if deleted == 0 {
                fmt.Println("There are no files to delete.")
            }
        case 3: // List OTPs
            fmt.Println("The OTP (and related) files in the current directory are:\n")
            files, err := ioutil.ReadDir(".") // already sorted by file name
            check(err)
            for _, fi := range files {
                name := fi.Name()
                if !fi.IsDir() && isOtpRelated(name) {
                    fmt.Println(name)
                }
            }
        case 4: // Encrypt
            fmt.Print("OTP file name to use (without extension) : ")
            scnr.Scan()
            keyFile := scnr.Text() + ".1tp"
            if _, err := os.Stat(keyFile); !os.IsNotExist(err) {
                file, err := os.Open(keyFile)
                check(err)
                bytes, err := ioutil.ReadAll(file)
                check(err)
                file.Close()
                lines := strings.Split(string(bytes), "\n")
                le := len(lines)
                first := le
                for i := 0; i < le; i++ {
                    if strings.HasPrefix(lines[i], " ") {
                        first = i
                        break
                    }
                }
                if first == le {
                    fmt.Println("\nThat file has no unused lines.")
                    continue
                }
                lines2 := lines[first:] // get rid of comments and used lines

                fmt.Println("Text to encrypt :-\n")
                scnr.Scan()
                text := toAlpha(strings.ToUpper(scnr.Text()))
                check(scnr.Err())
                tl := len(text)
                nLines := tl / charsPerLine
                if tl%charsPerLine > 0 {
                    nLines++
                }
                if len(lines2) >= nLines {
                    key := toAlpha(strings.Join(lines2[0:nLines], ""))
                    encrypted := vigenere(text, key, true)
                    encFile := keyFile + "_enc"
                    file2, err := os.Create(encFile)
                    check(err)
                    _, err = file2.WriteString(encrypted)
                    check(err)
                    file2.Close()
                    fmt.Printf("\n'%s' has been created in the current directory.\n", encFile)
                    for i := first; i < first+nLines; i++ {
                        lines[i] = "-" + lines[i][1:]
                    }
                    file3, err := os.Create(keyFile)
                    check(err)
                    _, err = file3.WriteString(strings.Join(lines, "\n"))
                    check(err)
                    file3.Close()
                    if demo {
                        fmt.Println("\nThe contents of the encrypted file are :\n")
                        fmt.Println(encrypted)
                    }
                } else {
                    fmt.Println("Not enough lines left in that file to do encryption.")
                }
            } else {
                fmt.Println("\nThat file does not exist.")
            }
        case 5: // Decrypt
            fmt.Print("OTP file name to use (without extension) : ")
            scnr.Scan()
            keyFile := scnr.Text() + ".1tp_cpy"
            check(scnr.Err())
            if _, err := os.Stat(keyFile); !os.IsNotExist(err) {
                file, err := os.Open(keyFile)
                check(err)
                bytes, err := ioutil.ReadAll(file)
                check(err)
                file.Close()
                keyLines := strings.Split(string(bytes), "\n")
                le := len(keyLines)
                first := le
                for i := 0; i < le; i++ {
                    if strings.HasPrefix(keyLines[i], " ") {
                        first = i
                        break
                    }
                }
                if first == le {
                    fmt.Println("\nThat file has no unused lines.")
                    continue
                }
                keyLines2 := keyLines[first:] // get rid of comments and used lines

                encFile := keyFile[0:len(keyFile)-3] + "enc"
                if _, err := os.Stat(encFile); !os.IsNotExist(err) {
                    file2, err := os.Open(encFile)
                    check(err)
                    bytes, err := ioutil.ReadAll(file2)
                    check(err)
                    file2.Close()
                    encLines := strings.Split(string(bytes), "\n")[1:] // exclude comment line
                    nLines := len(encLines)
                    if len(keyLines2) >= nLines {
                        encrypted := toAlpha(strings.Join(encLines, ""))
                        key := toAlpha(strings.Join(keyLines2[0:nLines], ""))
                        decrypted := vigenere(encrypted, key, false)
                        decFile := keyFile[0:len(keyFile)-3] + "dec"
                        file3, err := os.Create(decFile)
                        check(err)
                        _, err = file3.WriteString(decrypted)
                        check(err)
                        file3.Close()
                        fmt.Printf("\n'%s' has been created in the current directory.\n", decFile)
                        for i := first; i < first+nLines; i++ {
                            keyLines[i] = "-" + keyLines[i][1:]
                        }
                        file4, err := os.Create(keyFile)
                        check(err)
                        _, err = file4.WriteString(strings.Join(keyLines, "\n"))
                        check(err)
                        file4.Close()
                        if demo {
                            fmt.Println("\nThe contents of the decrypted file are :\n")
                            fmt.Println(decrypted)
                        }
                    }
                } else {
                    fmt.Println("Not enough lines left in that file to do decryption.")
                }
            } else {
                fmt.Println("\nThat file does not exist.")
            }
        case 6: // Quit program
            return
        }
    }
}

The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for a One-time pad based on user-specified filename and length, ensuring the use of "true random" numbers. The encryption and decryption process is similar to Rot-13, and much of Vigenère cipher is reused with the key read from the One-time pad file. The code also optionally manages One-time pads, allowing users to list, mark as used, delete, and track which pad to use for which partner. It supports the management of pad-files with a ".1tp" extension, and handles lines starting with "#" as comments, lines starting with "-" as "used", and ignores whitespace within the otp-data.


package main

import (
    "fmt"
    "math"
    "bytes"
    "encoding/binary"
)

type testCase struct {
    hashCode string
    string
}

var testCases = []testCase{
    {"d41d8cd98f00b204e9800998ecf8427e", ""},
    {"0cc175b9c0f1b6a831c399e269772661", "a"},
    {"900150983cd24fb0d6963f7d28e17f72", "abc"},
    {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"},
    {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"},
    {"d174ab98d277d9f5a5611c2c9f419d9f",
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"},
    {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" +
        "123456789012345678901234567890123456789012345678901234567890"},
}

func main() {
    for _, tc := range testCases {
        fmt.Printf("%s\n%x\n\n", tc.hashCode, md5(tc.string))
    }
}

var shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}
var table [64]uint32

func init() {
    for i := range table {
        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))
    }
}

func md5(s string) (r [16]byte) {
    padded := bytes.NewBuffer([]byte(s))
    padded.WriteByte(0x80)
    for padded.Len() % 64 != 56 {
        padded.WriteByte(0)
    }
    messageLenBits := uint64(len(s)) * 8
    binary.Write(padded, binary.LittleEndian, messageLenBits)

    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476
    var buffer [16]uint32
    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { // read every 64 bytes
        a1, b1, c1, d1 := a, b, c, d
        for j := 0; j < 64; j++ {
            var f uint32
            bufferIndex := j
            round := j >> 4
            switch round {
            case 0:
                f = (b1 & c1) | (^b1 & d1)
            case 1:
                f = (b1 & d1) | (c1 & ^d1)
                bufferIndex = (bufferIndex*5 + 1) & 0x0F
            case 2:
                f = b1 ^ c1 ^ d1
                bufferIndex = (bufferIndex*3 + 5) & 0x0F
            case 3:
                f = c1 ^ (b1 | ^d1)
                bufferIndex = (bufferIndex * 7) & 0x0F
            }
            sa := shift[(round<<2)|(j&3)]
            a1 += f + buffer[bufferIndex] + table[j]
            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1
        }
        a, b, c, d = a+a1, b+b1, c+c1, d+d1
    }

    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})
    return
}

d41d8cd98f00b204e9800998ecf8427e
d41d8cd98f00b204e9800998ecf8427e

0cc175b9c0f1b6a831c399e269772661
0cc175b9c0f1b6a831c399e269772661

900150983cd24fb0d6963f7d28e17f72
900150983cd24fb0d6963f7d28e17f72

f96b697d7cb7938d525a2f31aaf161d0
f96b697d7cb7938d525a2f31aaf161d0

c3fcd3d76192e4007dfb496cca67e13b
c3fcd3d76192e4007dfb496cca67e13b

d174ab98d277d9f5a5611c2c9f419d9f
d174ab98d277d9f5a5611c2c9f419d9f

57edf4a22be3c955ac49da2e2107b67a
57edf4a22be3c955ac49da2e2107b67a

The code is an implementation of the MD5 Message Digest Algorithm, developed without using built-in or external hashing libraries. It generates a correct message digest for an input string, demonstrating bit manipulation, working with unsigned integers, and handling little-endian data. The code also handles boundary conditions and ensures accuracy in padding, endianness, and data layout. However, it does not support messages of arbitrary bit length, only those that are a number of whole bytes. It's important to note that the MD5 algorithm is not secure and should not be used in applications requiring high security.


Translation of: Kotlin
package main

import "fmt"

func main() {
    fmt.Println("Police  Sanitation  Fire")
    fmt.Println("------  ----------  ----")
    count := 0
    for i := 2; i < 7; i += 2 {
        for j := 1; j < 8; j++ {
            if j == i { continue }
            for k := 1; k < 8; k++ {
                if k == i || k == j { continue }
                if i + j + k != 12 { continue }
                fmt.Printf("  %d         %d         %d\n", i, j, k)
                count++
            }
        }
    }
    fmt.Printf("\n%d valid combinations\n", count)
}

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


src := "Hello"
dst := src

package main

import "fmt"

func main() {
	// creature string
	var creature string = "shark"
	// point to creature
	var pointer *string = &creature
	// creature string
	fmt.Println("creature =", creature) // creature = shark
	// creature location in memory
	fmt.Println("pointer =", pointer) // pointer = 0xc000010210
	// creature through the pointer
	fmt.Println("*pointer =", *pointer) // *pointer = shark
	// set creature through the pointer
	*pointer = "jellyfish"
	// creature through the pointer
	fmt.Println("*pointer =", *pointer) // *pointer = jellyfish
	// creature string
	fmt.Println("creature =", creature) // creature = jellyfish
}

The code copies a string in Go language, where there's no need to differentiate between copying the contents and making an additional reference due to the immutability of strings. A new slice object is created during the assignment, possibly pointing to the same underlying array as the source string. However, this behavior is not guaranteed by the language.


package main
import "fmt"

func F(n int) int {
  if n == 0 { return 1 }
  return n - M(F(n-1))
}

func M(n int) int {
  if n == 0 { return 0 }
  return n - F(M(n-1))
}

func main() {
  for i := 0; i < 20; i++ {
    fmt.Printf("%2d ", F(i))
  }
  fmt.Println()
  for i := 0; i < 20; i++ {
    fmt.Printf("%2d ", M(i))
  }
  fmt.Println()
}

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions call each other in their definitions. If mutual recursion is not supported, the code will indicate this instead of providing an alternative solution. No special pre-declaration is required for these functions.


package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}

demonstrate how to select a random element from a list.


package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	for _, escaped := range []string{
		"http%3A%2F%2Ffoo%20bar%2F",
		"google.com/search?q=%60Abdu%27l-Bah%C3%A1",
	} {
		u, err := url.QueryUnescape(escaped)
		if err != nil {
			log.Println(err)
			continue
		}
		fmt.Println(u)
	}
}

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


func binarySearch(a []float64, value float64, low int, high int) int {
    if high < low {
        return -1
    }
    mid := (low + high) / 2
    if a[mid] > value {
        return binarySearch(a, value, low, mid-1)
    } else if a[mid] < value {
        return binarySearch(a, value, mid+1, high)
    }
    return mid
}

func binarySearch(a []float64, value float64) int {
    low := 0
    high := len(a) - 1
    for low <= high {
        mid := (low + high) / 2
        if a[mid] > value {
            high = mid - 1
        } else if a[mid] < value {
            low = mid + 1
        } else {
            return mid
        }
    }
    return -1
}

import "sort"

//...

sort.SearchInts([]int{0,1,4,5,6,7,8,9}, 6) // evaluates to 4

The code implements a binary search algorithm that divides a range of values into halves to find a specific "secret value". It can handle both recursive and iterative methods. The code also includes different versions of binary search algorithms: traditional, leftmost insertion point, and rightmost insertion point. It ensures no overflow bugs occur by using specific techniques to calculate the midpoint. The code also provides the functionality to search within a sorted integer array and returns the index of the secret value if found.


package main
import (
	"fmt"
	"os"
)

func main() {
	for i, x := range os.Args[1:] {
		fmt.Printf("the argument #%d is %s\n", i, x)
	}
}

The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c "alpha beta" -h "gamma"'. It also includes functionalities for intelligent parsing of these arguments.


Using Library: GXUI from Github
package main

import (
	"github.com/google/gxui"
	"github.com/google/gxui/drivers/gl"
	"github.com/google/gxui/math"
	"github.com/google/gxui/themes/dark"
	omath "math"
	"time"
)

//Two pendulums animated
//Top: Mathematical pendulum with small-angle approxmiation (not appropiate with PHI_ZERO=pi/2)
//Bottom: Simulated with differential equation phi'' = g/l * sin(phi)

const (
	ANIMATION_WIDTH  int     = 480
	ANIMATION_HEIGHT int     = 320
	BALL_RADIUS      float32 = 25.0
	METER_PER_PIXEL  float64 = 1.0 / 20.0
	PHI_ZERO         float64 = omath.Pi * 0.5
)

var (
	l    float64 = float64(ANIMATION_HEIGHT) * 0.5
	freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)

type Pendulum interface {
	GetPhi() float64
}

type mathematicalPendulum struct {
	start time.Time
}

func (p *mathematicalPendulum) GetPhi() float64 {
	if (p.start == time.Time{}) {
		p.start = time.Now()
	}
	t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
	return PHI_ZERO * omath.Cos(t*freq)
}

type numericalPendulum struct {
	currentPhi float64
	angAcc     float64
	angVel     float64
	lastTime   time.Time
}

func (p *numericalPendulum) GetPhi() float64 {
	dt := 0.0
	if (p.lastTime != time.Time{}) {
		dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
	}
	p.lastTime = time.Now()

	p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
	p.angVel += p.angAcc * dt
	p.currentPhi += p.angVel * dt

	return p.currentPhi
}

func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
	attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}

	phi := p.GetPhi()
	ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}

	line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}

	canvas.DrawLines(line, gxui.DefaultPen)

	m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
	rect := math.Rect{ball.Sub(m), ball.Add(m)}
	canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}

func appMain(driver gxui.Driver) {
	theme := dark.CreateTheme(driver)

	window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
	window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))

	image := theme.CreateImage()

	ticker := time.NewTicker(time.Millisecond * 15)
	pendulum := &mathematicalPendulum{}
	pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}

	go func() {
		for _ = range ticker.C {
			canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
			canvas.Clear(gxui.White)

			draw(pendulum, canvas, 0, 0)
			draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)

			canvas.Complete()
			driver.Call(func() {
				image.SetCanvas(canvas)
			})
		}
	}()

	window.AddChild(image)

	window.OnClose(ticker.Stop)
	window.OnClose(driver.Terminate)
}

func main() {
	gl.StartDriver(appMain)
}

create and animate a simple physical model of a gravity pendulum.


package main

import "encoding/json"
import "fmt"

func main() {
    var data interface{}
    err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
    if err == nil {
        fmt.Println(data)
    } else {
        fmt.Println(err)
    }

    sample := map[string]interface{}{
        "blue":  []interface{}{1, 2},
        "ocean": "water",
    }
    json_string, err := json.Marshal(sample)
    if err == nil {
        fmt.Println(string(json_string))
    } else {
        fmt.Println(err)
    }
}

load a JSON string into a data structure, create a new data structure and serialize it into JSON, ensuring the JSON is valid. The codes also demonstrate the correspondence between JSON objects and Go maps, and how to handle expected correspondence between JSON data and composite data types in the program.


func root(a float64, n int) float64 {
    n1 := n - 1
    n1f, rn := float64(n1), 1/float64(n)
    x, x0 := 1., 0.
    for {
        potx, t2 := 1/x, a
        for b := n1; b > 0; b >>= 1 {
            if b&1 == 1 {
                t2 *= potx
            }
            potx *= potx
        }
        x0, x = x, rn*(n1f*x+t2)
        if math.Abs(x-x0)*1e15 < x {
            break
        }
    }
    return x
}

import "math/big"

func Root(a *big.Float, n uint64) *big.Float {
	limit := Exp(New(2), 256)
	n1 := n-1
	n1f, rn := New(float64(n1)), Div(New(1.0), New(float64(n)))
	x, x0 := New(1.0), Zero()
	_ = x0
	for {
		potx, t2 := Div(New(1.0), x), a
		for b:=n1; b>0; b>>=1 {
			if b&1 == 1 {
				t2 = Mul(t2, potx)
			}
			potx = Mul(potx, potx)
		}
		x0, x = x, Mul(rn, Add(Mul(n1f, x), t2) )
		if Lesser(Mul(Abs(Sub(x, x0)), limit), x) { break }
	}
	return x
}

func Abs(a *big.Float) *big.Float {
	return Zero().Abs(a)
}

func Exp(a *big.Float, e uint64) *big.Float {
	result := Zero().Copy(a)
	for i:=uint64(0); i<e-1; i++ {
		result = Mul(result, a)
	}
	return result
}

func New(f float64) *big.Float {
	r := big.NewFloat(f)
	r.SetPrec(256)
	return r
}

func Div(a, b *big.Float) *big.Float {
	return Zero().Quo(a, b)
}

func Zero() *big.Float {
	r := big.NewFloat(0.0)
	r.SetPrec(256)
	return r
}

func Mul(a, b *big.Float) *big.Float {
	return Zero().Mul(a, b)
}

func Add(a, b *big.Float) *big.Float {
	return Zero().Add(a, b)
}

func Sub(a, b *big.Float) *big.Float {
	return Zero().Sub(a, b)
}

func Lesser(x, y *big.Float) bool {
	return x.Cmp(y) == -1
}

implement an algorithm to compute the principal nth root of a positive real number using the method explained on Wikipedia. The implementation is for 64-bit wide floating point numbers and uses the `math/big` Float for 256 bits of precision. Wrapper functions are used for readability and a power function (Exp) is created due to its absence in the library. The function avoids an infinite loop by ensuring the exponent in the limit is at least one less than the precision of the input value.


package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println(os.Hostname())
}

Retrieves the hostname of the system where the program is running using os.Hostname.


package main

import "fmt"

func leonardo(n, l0, l1, add int) []int {
    leo := make([]int, n)
    leo[0] = l0
    leo[1] = l1
    for i := 2; i < n; i++ {
        leo[i] = leo[i - 1] + leo[i - 2] + add
    }
    return leo
}

func main() {
    fmt.Println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:")
    fmt.Println(leonardo(25, 1, 1, 1))
    fmt.Println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:")
    fmt.Println(leonardo(25, 0, 1, 0))
}

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


package main

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

func main() {
    rand.Seed(time.Now().Unix())
    n := make([]rune, 4)
    for i := range n {
        n[i] = rune(rand.Intn(9) + '1')
    }
    fmt.Printf("Your numbers: %c\n", n)
    fmt.Print("Enter RPN: ")
    var expr string
    fmt.Scan(&expr)
    if len(expr) != 7 {
        fmt.Println("invalid. expression length must be 7." +
            " (4 numbers, 3 operators, no spaces)")
        return
    }
    stack := make([]float64, 0, 4)
    for _, r := range expr {
        if r >= '0' && r <= '9' {
            if len(n) == 0 {
                fmt.Println("too many numbers.")
                return
            }
            i := 0
            for n[i] != r {
                i++
                if i == len(n) {
                    fmt.Println("wrong numbers.")
                    return
                }
            }
            n = append(n[:i], n[i+1:]...)
            stack = append(stack, float64(r-'0'))
            continue
        }
        if len(stack) < 2 {
            fmt.Println("invalid expression syntax.")
            return
        }
        switch r {
        case '+':
            stack[len(stack)-2] += stack[len(stack)-1]
        case '-':
            stack[len(stack)-2] -= stack[len(stack)-1]
        case '*':
            stack[len(stack)-2] *= stack[len(stack)-1]
        case '/':
            stack[len(stack)-2] /= stack[len(stack)-1]
        default:
            fmt.Printf("%c invalid.\n", r)
            return
        }
        stack = stack[:len(stack)-1]
    }
    if math.Abs(stack[0]-24) > 1e-6 {
        fmt.Println("incorrect.", stack[0], "!= 24")
    } else {
        fmt.Println("correct.")
    }
}

Your numbers: [5 8 1 3]
Enter RPN: 83-5*1-
correct.

The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once each. The expression should evaluate to 24 using the allowed operators (addition, subtraction, multiplication, division). The code also checks and evaluates the player's input expression. The division operator preserves remainders, and the order of the digits in the expression does not need to match the original order.


package main

import "fmt"

// encoding scheme:
// encode to byte array
// byte value < 26 means single character: byte value + 'A'
// byte value 26..255 means (byte value - 24) copies of next byte
func rllEncode(s string) (r []byte) {
    if s == "" {
        return
    }
    c := s[0]
    if c < 'A' || c > 'Z' {
        panic("invalid")
    }
    nc := byte(1)
    for i := 1; i < len(s); i++ {
        d := s[i]
        switch {
        case d != c:
        case nc < (255 - 24):
            nc++
            continue
        }
        if nc > 1 {
            r = append(r, nc+24)
        }
        r = append(r, c-'A')
        if d < 'A' || d > 'Z' {
            panic("invalid")
        }
        c = d
        nc = 1
    }
    if nc > 1 {
        r = append(r, nc+24)
    }
    r = append(r, c-'A')
    return
}

func main() {
    s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
    fmt.Println("source: ", len(s), "bytes:", s)
    e := rllEncode(s)
    fmt.Println("encoded:", len(e), "bytes:", e)
    d := rllDecode(e)
    fmt.Println("decoded:", len(d), "bytes:", d)
    fmt.Println("decoded = source:", d == s)
}

func rllDecode(e []byte) string {
    var c byte
    var d []byte
    for i := 0; i < len(e); i++ {
        b := e[i]
        if b < 26 {
            c = 1
        } else {
            c = b - 24
            i++
            b = e[i]
        }
        for c > 0 {
            d = append(d, b+'A')
            c--
        }
    }
    return string(d)
}

source:  67 bytes: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
encoded: 12 bytes: [36 22 1 36 22 27 1 48 22 1 38 22]
decoded: 67 bytes: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
decoded = source: true

implement a run-length encoding and decoding system. The code compresses consecutive repeated characters in a given string by storing the length of the run. It also provides a function to reverse the compression, effectively decoding the encoded string. The input string consists of uppercase characters (A-Z) only. The output can be any format that can be used to recreate the original input string.


package main

import "fmt"

func main() {
    // text assigned to a string variable
    s := "hello"

    // output string variable
    fmt.Println(s)

    // this output requested by original task descrption, although
    // not really required by current wording of task description.
    fmt.Println(s + " literal")

    // concatenate variable and literal, assign result to another string variable
    s2 := s + " literal"

    // output second string variable
    fmt.Println(s2)
}

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


package main

import (
    "fmt"
    "net/url"
)

func main() {
    fmt.Println(url.QueryEscape("http://foo bar/"))
}

The code provides a function to convert a given string into its URL encoding representation. It converts all characters, except 0-9, A-Z, and a-z, into their corresponding percent-encoded hexadecimal code. The code also allows for variations such as lowercase escapes and different encodings for special characters based on different standards like RFC 3986, HTML 5, and the encodeURI function in Javascript. An optional feature is the use of an exception string that contains symbols that don't need to be converted.


Translation of: Wren
package main

import (
    "fmt"
    "sort"
)

func distinctSortedUnion(ll [][]int) []int {
    var res []int
    for _, l := range ll {
        res = append(res, l...)
    }
    set := make(map[int]bool)
    for _, e := range res {
        set[e] = true
    }
    res = res[:0]
    for key := range set {
        res = append(res, key)
    }
    sort.Ints(res)
    return res
}

func main() {
    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}
    fmt.Println("Distinct sorted union of", ll, "is:")
    fmt.Println(distinctSortedUnion(ll))
}

generates a common sorted list with unique elements from multiple integer arrays.


package main

import (
    "fmt"
    "sort"
)

type item struct {
    item   string
    weight float64
    price  float64
}

type items []item

var all = items{
    {"beef", 3.8, 36},
    {"pork", 5.4, 43},
    {"ham", 3.6, 90},
    {"greaves", 2.4, 45},
    {"flitch", 4.0, 30},
    {"brawn", 2.5, 56},
    {"welt", 3.7, 67},
    {"salami", 3.0, 95},
    {"sausage", 5.9, 98},
}

// satisfy sort interface
func (z items) Len() int      { return len(z) }
func (z items) Swap(i, j int) { z[i], z[j] = z[j], z[i] }
func (z items) Less(i, j int) bool {
    return z[i].price/z[i].weight > z[j].price/z[j].weight
}

func main() {
    left := 15.
    sort.Sort(all)
    for _, i := range all {
        if i.weight <= left {
            fmt.Println("take all the", i.item)
            if i.weight == left {
                return
            }
            left -= i.weight
        } else {
            fmt.Printf("take %.1fkg %s\n", left, i.item)
            return
        }
    }
}

take all the salami
take all the ham
take all the brawn
take all the greaves
take 3.5kg welt

"Implement a solution for the continuous knapsack problem where a thief maximizes his profit by selecting and possibly cutting items from a butcher's shop, given their weights and prices, without exceeding the knapsack's maximum capacity of 15 kg."


package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
    "sort"
)

func main() {
    r, err := http.Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    b, err := ioutil.ReadAll(r.Body)
    r.Body.Close()
    if err != nil {
        fmt.Println(err)
        return
    }
    var ma int
    var bs byteSlice
    m := make(map[string][][]byte)
    for _, word := range bytes.Fields(b) {
        bs = append(bs[:0], byteSlice(word)...)
        sort.Sort(bs)
        k := string(bs)
        a := append(m[k], word)
        if len(a) > ma {
            ma = len(a)
        }
        m[k] = a
    }
    for _, a := range m {
        if len(a) == ma {
            fmt.Printf("%s\n", a)
        }
    }
}

type byteSlice []byte

func (b byteSlice) Len() int           { return len(b) }
func (b byteSlice) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }
func (b byteSlice) Less(i, j int) bool { return b[i] < b[j] }

"Code identifies sets of anagrams with the most words from the provided word list."


package main

import (
    "fmt"
    "strings"
    "unicode/utf8"
)

var order = 3
var grain = "#"

func main() {
    carpet := []string{grain}
    for ; order > 0; order-- {
        // repeat expression allows for multiple character
        // grain and for multi-byte UTF-8 characters.
        hole := strings.Repeat(" ", utf8.RuneCountInString(carpet[0]))
        middle := make([]string, len(carpet))
        for i, s := range carpet {
            middle[i] = s + hole + s
            carpet[i] = strings.Repeat(s, 3)
        }
        carpet = append(append(carpet, middle...), carpet...)
    }
    for _, r := range carpet {
        fmt.Println(r)
    }
}

generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, where the placement of whitespace and non-whitespace characters is crucial. The non-whitespace character can be customized.


Translation of: Java
package main

import (
    "container/heap"
    "fmt"
)

type HuffmanTree interface {
    Freq() int
}

type HuffmanLeaf struct {
    freq  int
    value rune
}

type HuffmanNode struct {
    freq        int
    left, right HuffmanTree
}

func (self HuffmanLeaf) Freq() int {
    return self.freq
}

func (self HuffmanNode) Freq() int {
    return self.freq
}

type treeHeap []HuffmanTree

func (th treeHeap) Len() int { return len(th) }
func (th treeHeap) Less(i, j int) bool {
    return th[i].Freq() < th[j].Freq()
}
func (th *treeHeap) Push(ele interface{}) {
    *th = append(*th, ele.(HuffmanTree))
}
func (th *treeHeap) Pop() (popped interface{}) {
    popped = (*th)[len(*th)-1]
    *th = (*th)[:len(*th)-1]
    return
}
func (th treeHeap) Swap(i, j int) { th[i], th[j] = th[j], th[i] }

func buildTree(symFreqs map[rune]int) HuffmanTree {
    var trees treeHeap
    for c, f := range symFreqs {
        trees = append(trees, HuffmanLeaf{f, c})
    }
    heap.Init(&trees)
    for trees.Len() > 1 {
        // two trees with least frequency
        a := heap.Pop(&trees).(HuffmanTree)
        b := heap.Pop(&trees).(HuffmanTree)

        // put into new node and re-insert into queue
        heap.Push(&trees, HuffmanNode{a.Freq() + b.Freq(), a, b})
    }
    return heap.Pop(&trees).(HuffmanTree)
}

func printCodes(tree HuffmanTree, prefix []byte) {
    switch i := tree.(type) {
    case HuffmanLeaf:
        // print out symbol, frequency, and code for this
        // leaf (which is just the prefix)
        fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix))
    case HuffmanNode:
        // traverse left
        prefix = append(prefix, '0')
        printCodes(i.left, prefix)
        prefix = prefix[:len(prefix)-1]

        // traverse right
        prefix = append(prefix, '1')
        printCodes(i.right, prefix)
        prefix = prefix[:len(prefix)-1]
    }
}

func main() {
    test := "this is an example for huffman encoding"

    symFreqs := make(map[rune]int)
    // read each symbol and record the frequencies
    for _, c := range test {
        symFreqs[c]++
    }

    // build tree
    tree := buildTree(symFreqs)

    // print out results
    fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE")
    printCodes(tree, []byte{})
}

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.


Library: go-gtk
package main

import (
    "fmt"
    "github.com/mattn/go-gtk/gtk"
)

func main() {
    gtk.Init(nil)
    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
    window.SetTitle("Click me")
    label := gtk.NewLabel("There have been no clicks yet")
    var clicks int
    button := gtk.NewButtonWithLabel("click me")
    button.Clicked(func() {
        clicks++
        if clicks == 1 {
            label.SetLabel("Button clicked 1 time")
        } else {
            label.SetLabel(fmt.Sprintf("Button clicked %d times",
                clicks))
        }
    })
    vbox := gtk.NewVBox(false, 1)
    vbox.Add(label)
    vbox.Add(button)
    window.Add(vbox)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })
    window.ShowAll()
    gtk.Main()
}

Implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button, labelled "click me", updates the label to show the number of times it has been clicked when interacted with.


package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    // task req: show database connection
    db, err := sql.Open("sqlite3", "rc.db")
    if err != nil {
        log.Print(err)
        return
    }
    defer db.Close()
    // task req: create table with typed fields, including a unique id
    _, err = db.Exec(`create table addr (
        id     int unique,
        street text,
        city   text,
        state  text,
        zip    text
    )`)
    if err != nil {
        log.Print(err)
        return
    }
    // show output:  query the created field names and types
    rows, err := db.Query(`pragma table_info(addr)`)
    if err != nil {
        log.Print(err)
        return
    }
    var field, storage string
    var ignore sql.RawBytes
    for rows.Next() {
        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
        if err != nil {
            log.Print(err)
            return
        }
        fmt.Println(field, storage)
    }
}

create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.


for i := 10; i >= 0; i-- {
  fmt.Println(i)
}

package main

import "fmt"
import "time"

func main() {
	i := 10
	for i > 0 {
		fmt.Println(i)
		time.Sleep(time.Second)
		i = i - 1
	}
	fmt.Println("blast off")
}

The code performs a countdown from 10 to 0 using a downward for loop.


package main

import "fmt"

type vkey string

func newVigenère(key string) (vkey, bool) {
    v := vkey(upperOnly(key))
    return v, len(v) > 0 // key length 0 invalid
}

func (k vkey) encipher(pt string) string {
    ct := upperOnly(pt)
    for i, c := range ct {
        ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26
    }
    return string(ct)
}

func (k vkey) decipher(ct string) (string, bool) {
    pt := make([]byte, len(ct))
    for i := range pt {
        c := ct[i]
        if c < 'A' || c > 'Z' {
            return "", false // invalid ciphertext
        }
        pt[i] = 'A' + (c-k[i%len(k)]+26)%26
    }
    return string(pt), true
}

// upperOnly extracts letters A-Z, a-z from a string and
// returns them all upper case in a byte slice.
// Useful for vkey constructor and encipher function.
func upperOnly(s string) []byte {
    u := make([]byte, 0, len(s))
    for i := 0; i < len(s); i++ {
        c := s[i]
        if c >= 'A' && c <= 'Z' {
            u = append(u, c)
        } else if c >= 'a' && c <= 'z' {
            u = append(u, c-32)
        }
    }
    return u
}

const testKey = "Vigenère Cipher"
const testPT = `Beware the Jabberwock, my son!
    The jaws that bite, the claws that catch!`

func main() {
    fmt.Println("Supplied key: ", testKey)
    v, ok := newVigenère(testKey)
    if !ok {
        fmt.Println("Invalid key")
        return
    }
    fmt.Println("Effective key:", v)
    fmt.Println("Plain text:", testPT)
    ct := v.encipher(testPT)
    fmt.Println("Enciphered:", ct)
    dt, ok := v.decipher(ct)
    if !ok {
        fmt.Println("Invalid ciphertext")
        return
    }
    fmt.Println("Deciphered:", dt)
}

Implement both encryption and decryption of a Vigenère cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.


demonstrate a for-loop with a step-value greater than one to print all odd digits.


package main

import "fmt"

var i int

func sum(i *int, lo, hi int, term func() float64) float64 {
    temp := 0.0
    for *i = lo; *i <= hi; (*i)++ {
        temp += term()
    }
    return temp
}

func main() {
    fmt.Printf("%f\n", sum(&i, 1, 100, func() float64 { return 1.0 / float64(i) }))
}

implement Jensen's Device, a programming technique devised by Jørn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.


package main

import (
    "image"
    "image/png"
    "os"
)

func main() {
    g := image.NewGray(image.Rect(0, 0, 256, 256))
    for i := range g.Pix {
        g.Pix[i] = uint8(i>>8 ^ i)
    }
    f, _ := os.Create("xor.png")
    png.Encode(f, g)
    f.Close()
}

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


package main

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

type maze struct {
    c  []byte   // cell contents
    h  []byte   // horizontal walls above cells
    v  []byte   // vertical walls to the left of cells
    c2 [][]byte // cells by row
    h2 [][]byte // horizontal walls by row (ignore first row)
    v2 [][]byte // vertical walls by row (ignore first of each column)
}

func newMaze(rows, cols int) *maze {
    c := make([]byte, rows*cols)              // all cells
    h := bytes.Repeat([]byte{'-'}, rows*cols) // all horizontal walls
    v := bytes.Repeat([]byte{'|'}, rows*cols) // all vertical walls
    c2 := make([][]byte, rows)                // cells by row
    h2 := make([][]byte, rows)                // horizontal walls by row
    v2 := make([][]byte, rows)                // vertical walls by row
    for i := range h2 {
        c2[i] = c[i*cols : (i+1)*cols]
        h2[i] = h[i*cols : (i+1)*cols]
        v2[i] = v[i*cols : (i+1)*cols]
    }
    return &maze{c, h, v, c2, h2, v2}
}

func (m *maze) String() string {
    hWall := []byte("+---")
    hOpen := []byte("+   ")
    vWall := []byte("|   ")
    vOpen := []byte("    ")
    rightCorner := []byte("+\n")
    rightWall := []byte("|\n")
    var b []byte
    // for all rows
    for r, hw := range m.h2 {
        // draw h walls
        for _, h := range hw {
            if h == '-' || r == 0 {
                b = append(b, hWall...)
            } else {
                b = append(b, hOpen...)
            }
        }
        b = append(b, rightCorner...)
        // draw v walls
        for c, vw := range m.v2[r] {
            if vw == '|' || c == 0 {
                b = append(b, vWall...)
            } else {
                b = append(b, vOpen...)
            }
            // draw cell contents
            if m.c2[r][c] != 0 {
                b[len(b)-2] = m.c2[r][c]
            }
        }
        b = append(b, rightWall...)
    }
    // draw bottom edge of maze
    for _ = range m.h2[0] {
        b = append(b, hWall...)
    }
    b = append(b, rightCorner...)
    return string(b)
}

func (m *maze) gen() {
    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))
}

const (
    up = iota
    dn
    rt
    lf
)

func (m *maze) g2(r, c int) {
    m.c2[r][c] = ' '
    for _, dir := range rand.Perm(4) {
        switch dir {
        case up:
            if r > 0 && m.c2[r-1][c] == 0 {
                m.h2[r][c] = 0
                m.g2(r-1, c)
            }
        case lf:
            if c > 0 && m.c2[r][c-1] == 0 {
                m.v2[r][c] = 0
                m.g2(r, c-1)
            }
        case dn:
            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {
                m.h2[r+1][c] = 0
                m.g2(r+1, c)
            }
        case rt:
            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {
                m.v2[r][c+1] = 0
                m.g2(r, c+1)
            }
        }
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    m := newMaze(4, 6)
    m.gen()
    fmt.Print(m)
}

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


package main

import (
    "fmt"
    "math/big"
)

type lft struct {
    q,r,s,t big.Int
}

func (t *lft) extr(x *big.Int) *big.Rat {
    var n, d big.Int
    var r big.Rat
    return r.SetFrac(
        n.Add(n.Mul(&t.q, x), &t.r),
        d.Add(d.Mul(&t.s, x), &t.t))
}

var three = big.NewInt(3)
var four = big.NewInt(4)

func (t *lft) next() *big.Int {
    r := t.extr(three)
    var f big.Int
    return f.Div(r.Num(), r.Denom())
}

func (t *lft) safe(n *big.Int) bool {
    r := t.extr(four)
    var f big.Int
    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
        return true
    }
    return false
}

func (t *lft) comp(u *lft) *lft {
    var r lft
    var a, b big.Int
    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
    return &r
}

func (t *lft) prod(n *big.Int) *lft {
    var r lft
    r.q.SetInt64(10)
    r.r.Mul(r.r.SetInt64(-10), n)
    r.t.SetInt64(1)
    return r.comp(t)
}

func main() {
    // init z to unit
    z := new(lft)
    z.q.SetInt64(1)
    z.t.SetInt64(1)

    // lfts generator
    var k int64
    lfts := func() *lft {
        k++
        r := new(lft)
        r.q.SetInt64(k)
        r.r.SetInt64(4*k+2)
        r.t.SetInt64(2*k+1)
        return r
    }

    // stream
    for {
        y := z.next()
        if z.safe(y) {
            fmt.Print(y)
            z = z.prod(y)
        } else {
            z = z.comp(lfts())
        }
    }
}

The code continually calculates and outputs the next decimal digit of Pi. The program runs indefinitely, producing each decimal digit in succession starting from 3.14159265, until it is manually stopped by the user. It is based on the algorithm from the Unbounded Spigot Algorithms for the Digits of Pi and is used for the pidigits benchmark of the Computer Language Benchmarks Game. The code is a simple translation from Haskell and runs slower than the standard Go distribution.