Continued fraction/Arithmetic/G(matrix ng, continued fraction n)

This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:
: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix}
I may perform perform the following operations:
:Input the next term of N1
:Output a term of the continued fraction resulting from the operation.

I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty.

When I input a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1  \\
  b + b_1 * t & b_1
\end{bmatrix}

When I output a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b  \\
  a_1 - b_1 * t & a - b * t
\end{bmatrix}

When I need a term t but there are no more my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\
  b_1 & b_1
\end{bmatrix}

I am done when b1 and b are zero.

Demonstrate your solution by calculating:
:[1;5,2] + 1/2
:[3;7] + 1/2
:[3;7] divided by 4
Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.

The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.

Solution:
package cf

// A 2×2 matix:
//     [ a₁   a ]
//     [ b₁   b ]
//
// which when "applied" to a continued fraction representing x
// gives a new continued fraction z such that:
//
//         a₁ * x + a
//     z = ----------
//         b₁ * x + b
//
// Examples:
//      NG4{0, 1, 0, 4}.ApplyTo(x) gives 0*x + 1/4 -> 1/4 = [0; 4]
//      NG4{0, 1, 1, 0}.ApplyTo(x) gives 1/x
//      NG4{1, 1, 0, 2}.ApplyTo(x) gives (x+1)/2
//
// Note that several operations (e.g. addition and division)
// can be efficiently done with a single matrix application.
// However, each matrix application may require
// several calculations for each outputed term.
type NG4 struct {
	A1, A int64
	B1, B int64
}

func (ng NG4) needsIngest() bool {
	if ng.isDone() {
		panic("b₁==b==0")
	}
	return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}

func (ng NG4) isDone() bool {
	return ng.B1 == 0 && ng.B == 0
}

func (ng *NG4) ingest(t int64) {
	// [ a₁   a ] becomes [ a + a₁×t   a₁ ]
	// [ b₁   b ]         [ b + b₁×t   b₁ ]
	ng.A1, ng.A, ng.B1, ng.B =
		ng.A+ng.A1*t, ng.A1,
		ng.B+ng.B1*t, ng.B1
}

func (ng *NG4) ingestInfinite() {
	// [ a₁   a ] becomes [ a₁   a₁ ]
	// [ b₁   b ]         [ b₁   b₁ ]
	ng.A, ng.B = ng.A1, ng.B1
}

func (ng *NG4) egest(t int64) {
	// [ a₁   a ] becomes [      b₁         b   ]
	// [ b₁   b ]         [ a₁ - b₁×t   a - b×t ]
	ng.A1, ng.A, ng.B1, ng.B =
		ng.B1, ng.B,
		ng.A1-ng.B1*t, ng.A-ng.B*t
}

// ApplyTo "applies" the matrix `ng` to the continued fraction `cf`,
// returning the resulting continued fraction.
func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
	return func() NextFn {
		next := cf()
		done := false
		return func() (int64, bool) {
			if done {
				return 0, false
			}
			for ng.needsIngest() {
				if t, ok := next(); ok {
					ng.ingest(t)
				} else {
					ng.ingestInfinite()
				}
			}
			t := ng.A1 / ng.B1
			ng.egest(t)
			done = ng.isDone()
			return t, true
		}
	}
}


Convert decimal number to rational

The task is to write a program to transform a decimal number into a fraction in lowest terms.

It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...

Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518)  = 0.518518...

Acceptable output:

* 0.9054054 - 4527027 / 5000000
* 0.518518  - 259259 / 500000

Finite decimals are of course no problem:

* 0.75      - 3 / 4

Solution:
package main

import (
    "fmt"
    "math/big"
)

func main() {
    for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
        if r, ok := new(big.Rat).SetString(d); ok {
            fmt.Println(d, "=", r)
        } else {
            fmt.Println(d, "invalid decimal number")
        }
    }
}


Convert seconds to compound duration

Write a function or program which:
*   takes a positive integer representing a duration in seconds as input (e.g., 100), and
*   returns a string which shows the same duration decomposed into:
:::*   weeks,
:::*   days,
:::*   hours,
:::*   minutes,   and
:::*   seconds.

This is detailed below (e.g., "2 hr, 59 sec").

Demonstrate that it passes the following three test-cases:

'''''Test Cases'''''

:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}

'''''Details'''''

The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}

However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").

Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)

Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).

Solution:
package main

import "fmt"

func main(){
	fmt.Println(TimeStr(7259))
	fmt.Println(TimeStr(86400))
	fmt.Println(TimeStr(6000000))
}

func TimeStr(sec int)(res string){
	wks, sec := sec / 604800,sec % 604800
	ds, sec := sec / 86400, sec % 86400
	hrs, sec := sec / 3600, sec % 3600
	mins, sec := sec / 60, sec % 60
	CommaRequired := false
	if wks != 0 {
		res += fmt.Sprintf("%d wk",wks)
		CommaRequired = true
	}
	if ds != 0 {
		if CommaRequired {
			res += ", "
		}
		res += fmt.Sprintf("%d d",ds)
		CommaRequired = true
	}
	if hrs != 0 {
		if CommaRequired {
			res += ", "
		}
		res += fmt.Sprintf("%d hr",hrs)
		CommaRequired = true
	}
	if mins != 0 {
		if CommaRequired {
			res += ", "
		}
		res += fmt.Sprintf("%d min",mins)
		CommaRequired = true
	}
	if sec != 0 {
		if CommaRequired {
			res += ", "
		}
		res += fmt.Sprintf("%d sec",sec)
	}
	return
}


Copy stdin to stdout

Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.

Solution:
package main

import (
    "bufio"
    "io"
    "os"
)

func main() {
    r := bufio.NewReader(os.Stdin)
    w := bufio.NewWriter(os.Stdout)
    for {
        b, err := r.ReadByte()
        if err == io.EOF {
            return
        }
        w.WriteByte(b)
        w.Flush()
    }
}


Count the coins

There are four types of common coins in   US   currency:
:::#   quarters   (25 cents)
:::#   dimes   (10 cents)
:::#   nickels   (5 cents),   and
:::#   pennies   (1 cent)

There are six ways to make change for 15 cents:
:::#   A dime and a nickel
:::#   A dime and 5 pennies
:::#   3 nickels
:::#   2 nickels and 5 pennies
:::#   A nickel and 10 pennies
:::#   15 pennies

;Task:
How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents).

;Optional:
Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000?

(Note:   the answer is larger than   232).

;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.

Solution:
package main

import "fmt"

func main() {
    amount := 100
    fmt.Println("amount, ways to make change:", amount, countChange(amount))
}

func countChange(amount int) int64 {
    return cc(amount, 4)
}

func cc(amount, kindsOfCoins int) int64 {
    switch {
    case amount == 0:
        return 1
    case amount < 0 || kindsOfCoins == 0:
        return 0
    }
    return cc(amount, kindsOfCoins-1) +
        cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)
}

func firstDenomination(kindsOfCoins int) int {
    switch kindsOfCoins {
    case 1:
        return 1
    case 2:
        return 5
    case 3:
        return 10
    case 4:
        return 25
    }
    panic(kindsOfCoins)
}


Create an HTML table

Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.

Solution:
package main

import (
    "fmt"
    "html/template"
    "os"
)

type row struct {
    X, Y, Z int
}

var tmpl = `

	X	Y	Z

{{range $ix, $row := .}}
{{$ix}}
        {{$row.X}}
        {{$row.Y}}
        {{$row.Z}}

{{end}}

`

func main() {
    // create template
    ct := template.Must(template.New("").Parse(tmpl))

    // make up data
    data := make([]row, 4)
    for r := range data {
        data[r] = row{r*3, r*3+1, r*3+2}
    }

    // apply template to data
    if err := ct.Execute(os.Stdout, data); err != nil {
        fmt.Println(err)
    }
}


Currency

Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.

;Note:
The '''IEEE 754''' binary floating point representations of numbers like   '''2.86'''   and   '''.0765'''   are not exact.

For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.

Use the values:
::* 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.

(That number of hamburgers is a 4 with 15 zeros after it.    The number is contrived to exclude naive task solutions using 64 bit floating point types.)

Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax

The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.

The output must show dollars and cents with a decimal point.

The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16

Dollar signs and thousands separators are optional.

Solution:
package main

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

// DC for dollars and cents.  Value is an integer number of cents.
type DC int64

func (dc DC) String() string {
    d := dc / 100
    if dc < 0 {
        dc = -dc
    }
    return fmt.Sprintf("%d.%02d", d, dc%100)
}

// Extend returns extended price of a unit price.
func (dc DC) Extend(n int) DC {
    return dc * DC(n)
}

var one = big.NewInt(1)
var hundred = big.NewRat(100, 1)

// ParseDC parses dollars and cents as a string into a DC.
func ParseDC(s string) (DC, bool) {
    r, ok := new(big.Rat).SetString(s)
    if !ok {
        return 0, false
    }
    r.Mul(r, hundred)
    if r.Denom().Cmp(one) != 0 {
        return 0, false
    }
    return DC(r.Num().Int64()), true
}

// TR for tax rate.  Value is an an exact rational.
type TR struct {
    *big.Rat
}
func NewTR() TR {
    return TR{new(big.Rat)}
}

// SetString overrides Rat.SetString to return the TR type.
func (tr TR) SetString(s string) (TR, bool) {
    if _, ok := tr.Rat.SetString(s); !ok {
        return TR{}, false
    }
    return tr, true
}

var half = big.NewRat(1, 2)

// Tax computes a tax amount, rounding to the nearest cent.
func (tr TR) Tax(dc DC) DC {
    r := big.NewRat(int64(dc), 1)
    r.Add(r.Mul(r, tr.Rat), half)
    return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())
}

func main() {
    hamburgerPrice, ok := ParseDC("5.50")
    if !ok {
        log.Fatal("Invalid hamburger price")
    }
    milkshakePrice, ok := ParseDC("2.86")
    if !ok {
        log.Fatal("Invalid milkshake price")
    }
    taxRate, ok := NewTR().SetString("0.0765")
    if !ok {
        log.Fatal("Invalid tax rate")
    }

    totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +
        milkshakePrice.Extend(2)
    tax := taxRate.Tax(totalBeforeTax)
    total := totalBeforeTax + tax

    fmt.Printf("Total before tax: %22s\n", totalBeforeTax)
    fmt.Printf("             Tax: %22s\n", tax)
    fmt.Printf("           Total: %22s\n", total)
}


Currying

{{Wikipedia|Currying}}

;Task:
Create a simple demonstrative example of Currying in a specific language.

Add any historic details as to how the feature made its way into the language.

Solution:
package main

import (
        "fmt"
        "math"
)

func PowN(b float64) func(float64) float64 {
        return func(e float64) float64 { return math.Pow(b, e) }
}

func PowE(e float64) func(float64) float64 {
        return func(b float64) float64 { return math.Pow(b, e) }
}

type Foo int

func (f Foo) Method(b int) int {
        return int(f) + b
}

func main() {
        pow2 := PowN(2)
        cube := PowE(3)

        fmt.Println("2^8 =", pow2(8))
        fmt.Println("4³ =", cube(4))

        var a Foo = 2
        fn1 := a.Method   // A "method value", like currying 'a'
        fn2 := Foo.Method // A "method expression", like uncurrying

        fmt.Println("2 + 2 =", a.Method(2)) // regular method call
        fmt.Println("2 + 3 =", fn1(3))
        fmt.Println("2 + 4 =", fn2(a, 4))
        fmt.Println("3 + 5 =", fn2(Foo(3), 5))
}


Curzon numbers

A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by  '''2 x n + 1'''.

'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by  '''k x n + 1'''.

''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.''

Generalized Curzon numbers only exist for even base integers.

;Task

* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.

;Stretch

* Find and show the '''one thousandth'''.

;See also

;* Numbers Aplenty - Curzon numbers
;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)

''and even though it is not specifically mentioned that they are Curzon numbers:''

;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)

Solution:
package main

import (
    "fmt"
    "math/big"
)

func main() {
    zero := big.NewInt(0)
    one := big.NewInt(1)
    for k := int64(2); k <= 10; k += 2 {
        bk := big.NewInt(k)
        fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
        count := 0
        n := int64(1)
        pow := big.NewInt(k)
        z := new(big.Int)
        var curzon50 []int64
        for {
            z.Add(pow, one)
            d := k*n + 1
            bd := big.NewInt(d)
            if z.Rem(z, bd).Cmp(zero) == 0 {
                if count < 50 {
                    curzon50 = append(curzon50, n)
                }
                count++
                if count == 50 {
                    for i := 0; i < len(curzon50); i++ {
                        fmt.Printf("%4d ", curzon50[i])
                        if (i+1)%10 == 0 {
                            fmt.Println()
                        }
                    }
                    fmt.Print("\nOne thousandth: ")
                }
                if count == 1000 {
                    fmt.Println(n)
                    break
                }
            }
            n++
            pow.Mul(pow, bk)
        }
        fmt.Println()
    }
}


Cut a rectangle

A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.

[[file:rect-cut.svg]]

Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle.  Optionally, show each of the cuts.

Possibly related task: [[Maze generation]] for depth-first search.

Solution:
package main

import "fmt"

var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}

func walk(y, x int) {
    if y == 0 || y == h || x == 0 || x == w {
        cnt += 2
        return
    }
    t := y*(w+1) + x
    grid[t]++
    grid[last-t]++
    for i, d := range dir {
        if grid[t+next[i]] == 0 {
            walk(y+d[0], x+d[1])
        }
    }
    grid[t]--
    grid[last-t]--
}

func solve(hh, ww, recur int) int {
    h = hh
    w = ww

    if h&1 != 0 {
        h, w = w, h
    }
    switch {
    case h&1 == 1:
        return 0
    case w == 1:
        return 1
    case w == 2:
        return h
    case h == 2:
        return w
    }
    cy := h / 2
    cx := w / 2

    grid = make([]byte, (h+1)*(w+1))
    last = len(grid) - 1
    next[0] = -1
    next[1] = -w - 1
    next[2] = 1
    next[3] = w + 1

    if recur != 0 {
        cnt = 0
    }
    for x := cx + 1; x < w; x++ {
        t := cy*(w+1) + x
        grid[t] = 1
        grid[last-t] = 1
        walk(cy-1, x)
    }
    cnt++

    if h == w {
        cnt *= 2
    } else if w&1 == 0 && recur != 0 {
        solve(w, h, 0)
    }
    return cnt
}

func main() {
    for y := 1; y <= 10; y++ {
        for x := 1; x <= y; x++ {
            if x&1 == 0 || y&1 == 0 {
                fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
            }
        }
    }
}


Cyclotomic polynomial

The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.

;Task:
*   Find and print the first 30 cyclotomic polynomials.
*   Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.

;See also
*   Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
*   The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.

Solution:
package main

import (
    "fmt"
    "log"
    "math"
    "sort"
    "strings"
)

const (
    algo          = 2
    maxAllFactors = 100000
)

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

type term struct{ coef, exp int }

func (t term) mul(t2 term) term {
    return term{t.coef * t2.coef, t.exp + t2.exp}
}

func (t term) add(t2 term) term {
    if t.exp != t2.exp {
        log.Fatal("exponents unequal in term.add method")
    }
    return term{t.coef + t2.coef, t.exp}
}

func (t term) negate() term { return term{-t.coef, t.exp} }

func (t term) String() string {
    switch {
    case t.coef == 0:
        return "0"
    case t.exp == 0:
        return fmt.Sprintf("%d", t.coef)
    case t.coef == 1:
        if t.exp == 1 {
            return "x"
        } else {
            return fmt.Sprintf("x^%d", t.exp)
        }
    case t.exp == 1:
        return fmt.Sprintf("%dx", t.coef)
    }
    return fmt.Sprintf("%dx^%d", t.coef, t.exp)
}

type poly struct{ terms []term }

// pass coef, exp in pairs as parameters
func newPoly(values ...int) poly {
    le := len(values)
    if le == 0 {
        return poly{[]term{term{0, 0}}}
    }
    if le%2 != 0 {
        log.Fatalf("odd number of parameters (%d) passed to newPoly function", le)
    }
    var terms []term
    for i := 0; i < le; i += 2 {
        terms = append(terms, term{values[i], values[i+1]})
    }
    p := poly{terms}.tidy()
    return p
}

func (p poly) hasCoefAbs(coef int) bool {
    for _, t := range p.terms {
        if iabs(t.coef) == coef {
            return true
        }
    }
    return false
}

func (p poly) add(p2 poly) poly {
    p3 := newPoly()
    le, le2 := len(p.terms), len(p2.terms)
    for le > 0 || le2 > 0 {
        if le == 0 {
            p3.terms = append(p3.terms, p2.terms[le2-1])
            le2--
        } else if le2 == 0 {
            p3.terms = append(p3.terms, p.terms[le-1])
            le--
        } else {
            t := p.terms[le-1]
            t2 := p2.terms[le2-1]
            if t.exp == t2.exp {
                t3 := t.add(t2)
                if t3.coef != 0 {
                    p3.terms = append(p3.terms, t3)
                }
                le--
                le2--
            } else if t.exp < t2.exp {
                p3.terms = append(p3.terms, t)
                le--
            } else {
                p3.terms = append(p3.terms, t2)
                le2--
            }
        }
    }
    return p3.tidy()
}

func (p poly) addTerm(t term) poly {
    q := newPoly()
    added := false
    for i := 0; i < len(p.terms); i++ {
        ct := p.terms[i]
        if ct.exp == t.exp {
            added = true
            if ct.coef+t.coef != 0 {
                q.terms = append(q.terms, ct.add(t))
            }
        } else {
            q.terms = append(q.terms, ct)
        }
    }
    if !added {
        q.terms = append(q.terms, t)
    }
    return q.tidy()
}

func (p poly) mulTerm(t term) poly {
    q := newPoly()
    for i := 0; i < len(p.terms); i++ {
        ct := p.terms[i]
        q.terms = append(q.terms, ct.mul(t))
    }
    return q.tidy()
}

func (p poly) div(v poly) poly {
    q := newPoly()
    lcv := v.leadingCoef()
    dv := v.degree()
    for p.degree() >= v.degree() {
        lcp := p.leadingCoef()
        s := lcp / lcv
        t := term{s, p.degree() - dv}
        q = q.addTerm(t)
        p = p.add(v.mulTerm(t.negate()))
    }
    return q.tidy()
}

func (p poly) leadingCoef() int {
    return p.terms[0].coef
}

func (p poly) degree() int {
    return p.terms[0].exp
}

func (p poly) String() string {
    var sb strings.Builder
    first := true
    for _, t := range p.terms {
        if first {
            sb.WriteString(t.String())
            first = false
        } else {
            sb.WriteString(" ")
            if t.coef > 0 {
                sb.WriteString("+ ")
                sb.WriteString(t.String())
            } else {
                sb.WriteString("- ")
                sb.WriteString(t.negate().String())
            }
        }
    }
    return sb.String()
}

// in place descending sort by term.exp
func (p poly) sortTerms() {
    sort.Slice(p.terms, func(i, j int) bool {
        return p.terms[i].exp > p.terms[j].exp
    })
}

// sort terms and remove any unnecesary zero terms
func (p poly) tidy() poly {
    p.sortTerms()
    if p.degree() == 0 {
        return p
    }
    for i := len(p.terms) - 1; i >= 0; i-- {
        if p.terms[i].coef == 0 {
            copy(p.terms[i:], p.terms[i+1:])
            p.terms[len(p.terms)-1] = term{0, 0}
            p.terms = p.terms[:len(p.terms)-1]
        }
    }
    if len(p.terms) == 0 {
        p.terms = append(p.terms, term{0, 0})
    }
    return p
}

func getDivisors(n int) []int {
    var divs []int
    sqrt := int(math.Sqrt(float64(n)))
    for i := 1; i <= sqrt; i++ {
        if n%i == 0 {
            divs = append(divs, i)
            d := n / i
            if d != i && d != n {
                divs = append(divs, d)
            }
        }
    }
    return divs
}

var (
    computed   = make(map[int]poly)
    allFactors = make(map[int]map[int]int)
)

func init() {
    f := map[int]int{2: 1}
    allFactors[2] = f
}

func getFactors(n int) map[int]int {
    if f, ok := allFactors[n]; ok {
        return f
    }
    factors := make(map[int]int)
    if n%2 == 0 {
        factorsDivTwo := getFactors(n / 2)
        for k, v := range factorsDivTwo {
            factors[k] = v
        }
        factors[2]++
        if n < maxAllFactors {
            allFactors[n] = factors
        }
        return factors
    }
    prime := true
    sqrt := int(math.Sqrt(float64(n)))
    for i := 3; i <= sqrt; i += 2 {
        if n%i == 0 {
            prime = false
            for k, v := range getFactors(n / i) {
                factors[k] = v
            }
            factors[i]++
            if n < maxAllFactors {
                allFactors[n] = factors
            }
            return factors
        }
    }
    if prime {
        factors[n] = 1
        if n < maxAllFactors {
            allFactors[n] = factors
        }
    }
    return factors
}

func cycloPoly(n int) poly {
    if p, ok := computed[n]; ok {
        return p
    }
    if n == 1 {
        // polynomial: x - 1
        p := newPoly(1, 1, -1, 0)
        computed[1] = p
        return p
    }
    factors := getFactors(n)
    cyclo := newPoly()
    if _, ok := factors[n]; ok {
        // n is prime
        for i := 0; i < n; i++ {
            cyclo.terms = append(cyclo.terms, term{1, i})
        }
    } else if len(factors) == 2 && factors[2] == 1 && factors[n/2] == 1 {
        // n == 2p
        prime := n / 2
        coef := -1
        for i := 0; i < prime; i++ {
            coef *= -1
            cyclo.terms = append(cyclo.terms, term{coef, i})
        }
    } else if len(factors) == 1 {
        if h, ok := factors[2]; ok {
            // n == 2^h
            cyclo.terms = append(cyclo.terms, term{1, 1 << (h - 1)}, term{1, 0})
        } else if _, ok := factors[n]; !ok {
            // n == p ^ k
            p := 0
            for prime := range factors {
                p = prime
            }
            k := factors[p]
            for i := 0; i < p; i++ {
                pk := int(math.Pow(float64(p), float64(k-1)))
                cyclo.terms = append(cyclo.terms, term{1, i * pk})
            }
        }
    } else if len(factors) == 2 && factors[2] != 0 {
        // n = 2^h * p^k
        p := 0
        for prime := range factors {
            if prime != 2 {
                p = prime
            }
        }
        coef := -1
        twoExp := 1 << (factors[2] - 1)
        k := factors[p]
        for i := 0; i < p; i++ {
            coef *= -1
            pk := int(math.Pow(float64(p), float64(k-1)))
            cyclo.terms = append(cyclo.terms, term{coef, i * twoExp * pk})
        }
    } else if factors[2] != 0 && ((n/2)%2 == 1) && (n/2) > 1 {
        //  CP(2m)[x] == CP(-m)[x], n odd integer > 1
        cycloDiv2 := cycloPoly(n / 2)
        for _, t := range cycloDiv2.terms {
            t2 := t
            if t.exp%2 != 0 {
                t2 = t.negate()
            }
            cyclo.terms = append(cyclo.terms, t2)
        }
    } else if algo == 0 {
        // slow - uses basic definition
        divs := getDivisors(n)
        // polynomial: x^n - 1
        cyclo = newPoly(1, n, -1, 0)
        for _, i := range divs {
            p := cycloPoly(i)
            cyclo = cyclo.div(p)
        }
    } else if algo == 1 {
        //  faster - remove max divisor (and all divisors of max divisor)
        //  only one divide for all divisors of max divisor
        divs := getDivisors(n)
        maxDiv := math.MinInt32
        for _, d := range divs {
            if d > maxDiv {
                maxDiv = d
            }
        }
        var divsExceptMax []int
        for _, d := range divs {
            if maxDiv%d != 0 {
                divsExceptMax = append(divsExceptMax, d)
            }
        }
        // polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
        cyclo = newPoly(1, n, -1, 0)
        cyclo = cyclo.div(newPoly(1, maxDiv, -1, 0))
        for _, i := range divsExceptMax {
            p := cycloPoly(i)
            cyclo = cyclo.div(p)
        }
    } else if algo == 2 {
        //  fastest
        //  let p, q be primes such that p does not divide n, and q divides n
        //  then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
        m := 1
        cyclo = cycloPoly(m)
        var primes []int
        for prime := range factors {
            primes = append(primes, prime)
        }
        sort.Ints(primes)
        for _, prime := range primes {
            //  CP(m)[x]
            cycloM := cyclo
            //  compute CP(m)[x^p]
            var terms []term
            for _, t := range cycloM.terms {
                terms = append(terms, term{t.coef, t.exp * prime})
            }
            cyclo = newPoly()
            cyclo.terms = append(cyclo.terms, terms...)
            cyclo = cyclo.tidy()
            cyclo = cyclo.div(cycloM)
            m *= prime
        }
        //  now, m is the largest square free divisor of n
        s := n / m
        //  Compute CP(n)[x] = CP(m)[x^s]
        var terms []term
        for _, t := range cyclo.terms {
            terms = append(terms, term{t.coef, t.exp * s})
        }
        cyclo = newPoly()
        cyclo.terms = append(cyclo.terms, terms...)
    } else {
        log.Fatal("invalid algorithm")
    }
    cyclo = cyclo.tidy()
    computed[n] = cyclo
    return cyclo
}

func main() {
    fmt.Println("Task 1:  cyclotomic polynomials for n <= 30:")
    for i := 1; i <= 30; i++ {
        p := cycloPoly(i)
        fmt.Printf("CP[%2d] = %s\n", i, p)
    }

    fmt.Println("\nTask 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:")
    n := 0
    for i := 1; i <= 10; i++ {
        for {
            n++
            cyclo := cycloPoly(n)
            if cyclo.hasCoefAbs(i) {
                fmt.Printf("CP[%d] has coefficient with magnitude = %d\n", n, i)
                n--
                break
            }
        }
    }
}


Damm algorithm

The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.

The algorithm is named after H. Michael Damm.

;Task:
Verify the checksum, stored as last digit of an input.

Solution:
package main

import "fmt"

var table = [10][10]byte{
    {0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
    {7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
    {4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
    {1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
    {6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
    {3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
    {5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
    {8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
    {9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
    {2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
}

func damm(input string) bool {
    var interim byte
    for _, c := range []byte(input) {
        interim = table[interim][c-'0']
    }
    return interim == 0
}

func main() {
    for _, s := range []string{"5724", "5727", "112946", "112949"} {
        fmt.Printf("%6s  %t\n", s, damm(s))
    }
}


De Bruijn sequences

{{DISPLAYTITLE:de Bruijn sequences}}
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn.

A note on Dutch capitalization:   Nicolaas' last name is   '''de Bruijn''',   the   '''de'''   isn't normally capitalized
unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.

In combinatorial mathematics,   a   '''de Bruijn sequence'''   of order    ''n''    on
a    size-''k''    alphabet (computer science)    ''A''    is a cyclic sequence in which every
possible    length-''n''    string (computer science, formal theory)   on    ''A''    occurs
exactly once as a contiguous substring.

Such a sequence is denoted by    ''B''(''k'', ''n'')    and has
length   ''k''''n'',   which is also the number of distinct substrings of
length   ''n''   on   ''A'';
de Bruijn sequences are therefore optimally short.

There are:
                          (k!)k(n-1)   /   kn
distinct de Bruijn sequences    ''B''(''k'', ''n'').

;Task:
For this Rosetta Code task,   a   '''de Bruijn'''   sequence is to be generated that can be used to shorten a brute-force attack on
a   PIN-like   code lock that does not have an "enter"
key and accepts the last    ''n''    digits entered.

Note:   automated teller machines (ATMs)   used to work like
this,   but their software has been updated to not allow a brute-force attack.

;Example:
A   digital door lock   with a 4-digit code would
have ''B'' (10, 4) solutions,   with a length of   '''10,000'''   (digits).

Therefore, only at most     '''10,000 + 3'''     (as the solutions are cyclic or ''wrap-around'')   presses are needed to
open the lock.

Trying all 4-digit codes separately would require   '''4 x 10,000'''   or   '''40,000'''   presses.

;Task requirements:
:*   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
:::*   Show the length of the generated de Bruijn sequence.
:::*   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the ''discussion'' page).
:::*   Show the first and last   '''130'''   digits of the de Bruijn sequence.
:*   Verify that all four-digit (decimal)   '''1,000'''   PIN codes are contained within the de Bruijn sequence.
:::*   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).
:*   Reverse the de Bruijn sequence.
:*   Again, perform the (above) verification test.
:*   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
:::*   Perform the verification test (again).   There should be four PIN codes missing.

(The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list
any and all missing PIN codes.)

Show all output here, on this page.

;References:
:*   Wikipedia           entry:   de Bruijn sequence.
:*   MathWorld           entry:   de Bruijn sequence.
:*   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.

Solution:
package main

import (
    "bytes"
    "fmt"
    "strconv"
    "strings"
)

const digits = "0123456789"

func deBruijn(k, n int) string {
    alphabet := digits[0:k]
    a := make([]byte, k*n)
    var seq []byte
    var db func(int, int) // recursive closure
    db = func(t, p int) {
        if t > n {
            if n%p == 0 {
                seq = append(seq, a[1:p+1]...)
            }
        } else {
            a[t] = a[t-p]
            db(t+1, p)
            for j := int(a[t-p] + 1); j < k; j++ {
                a[t] = byte(j)
                db(t+1, t)
            }
        }
    }
    db(1, 1)
    var buf bytes.Buffer
    for _, i := range seq {
        buf.WriteByte(alphabet[i])
    }
    b := buf.String()
    return b + b[0:n-1] // as cyclic append first (n-1) digits
}

func allDigits(s string) bool {
    for _, b := range s {
        if b < '0' || b > '9' {
            return false
        }
    }
    return true
}

func validate(db string) {
    le := len(db)
    found := make([]int, 10000)
    var errs []string
    // Check all strings of 4 consecutive digits within 'db'
    // to see if all 10,000 combinations occur without duplication.
    for i := 0; i < le-3; i++ {
        s := db[i : i+4]
        if allDigits(s) {
            n, _ := strconv.Atoi(s)
            found[n]++
        }
    }
    for i := 0; i < 10000; i++ {
        if found[i] == 0 {
            errs = append(errs, fmt.Sprintf("    PIN number %04d missing", i))
        } else if found[i] > 1 {
            errs = append(errs, fmt.Sprintf("    PIN number %04d occurs %d times", i, found[i]))
        }
    }
    lerr := len(errs)
    if lerr == 0 {
        fmt.Println("  No errors found")
    } else {
        pl := "s"
        if lerr == 1 {
            pl = ""
        }
        fmt.Printf("  %d error%s found:\n", lerr, pl)
        fmt.Println(strings.Join(errs, "\n"))
    }
}

func reverse(s string) string {
    bytes := []byte(s)
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        bytes[i], bytes[j] = bytes[j], bytes[i]
    }
    return string(bytes)
}

func main() {
    db := deBruijn(10, 4)
    le := len(db)
    fmt.Println("The length of the de Bruijn sequence is", le)
    fmt.Println("\nThe first 130 digits of the de Bruijn sequence are:")
    fmt.Println(db[0:130])
    fmt.Println("\nThe last 130 digits of the de Bruijn sequence are:")
    fmt.Println(db[le-130:])
    fmt.Println("\nValidating the de Bruijn sequence:")
    validate(db)

    fmt.Println("\nValidating the reversed de Bruijn sequence:")
    dbr := reverse(db)
    validate(dbr)

    bytes := []byte(db)
    bytes[4443] = '.'
    db = string(bytes)
    fmt.Println("\nValidating the overlaid de Bruijn sequence:")
    validate(db)
}


Deepcopy

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.

The task should show:

* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.

* Any limitations of the method.

* That the structure and its copy are different.

* Suitable links to external documentation for common libraries.

Solution:
package main

import "fmt"

// a type that allows cyclic structures
type node []*node

// recursively print the contents of a node
func (n *node) list() {
    if n == nil {
        fmt.Println(n)
        return
    }
    listed := map[*node]bool{nil: true}
    var r func(*node)
    r = func(n *node) {
        listed[n] = true
        fmt.Printf("%p -> %v\n", n, *n)
        for _, m := range *n {
            if !listed[m] {
                r(m)
            }
        }
    }
    r(n)
}

// construct a deep copy of a node
func (n *node) ccopy() *node {
    if n == nil {
        return n
    }
    cc := map[*node]*node{nil: nil}
    var r func(*node) *node
    r = func(n *node) *node {
        c := make(node, len(*n))
        cc[n] = &c
        for i, m := range *n {
            d, ok := cc[m]
            if !ok {
                d = r(m)
            }
            c[i] = d
        }
        return &c
    }
    return r(n)
}

func main() {
    a := node{nil}
    c := &node{&node{&a}}
    a[0] = c
    c.list()
    cc := c.ccopy()
    fmt.Println("copy:")
    cc.list()
    fmt.Println("original:")
    c.list()
}


Deming's funnel

W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings.  In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern.  He applied a sequence of "rules" to try to improve performance.  In each case the experiment begins with the funnel positioned directly over the target.

* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop.  E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment.  E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.

Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys.  '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.

Note that rules 2, 3, and 4 give successively worse results.  Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.

'''Stretch goal 1''': Generate fresh pseudorandom data.  The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.

'''Stretch goal 2''': Show scatter plots of all four results.

;Further information:
* Further explanation and interpretation
* Video demonstration of the funnel experiment at the Mayo Clinic.

Solution:
package main

import (
    "fmt"
    "math"
)

type rule func(float64, float64) float64

var dxs = []float64{
    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,
     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,
    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,
     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,
    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,
    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,
     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,
    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,
     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,
    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,
     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,
     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,
     0.443, -0.521, -0.799,  0.087,
}

var dys = []float64{
     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,
     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,
     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,
     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,
    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,
     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,
     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,
     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,
    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,
     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,
    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,
     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,
    -0.947, -1.424, -0.542, -1.032,
}

func funnel(fa []float64, r rule) []float64 {
    x := 0.0
    result := make([]float64, len(fa))
    for i, f := range fa {
        result[i] = x + f
        x = r(x, f)
    }
    return result
}

func mean(fa []float64) float64 {
    sum := 0.0
    for _, f := range fa {
        sum += f
    }
    return sum / float64(len(fa))
}

func stdDev(fa []float64) float64 {
    m := mean(fa)
    sum := 0.0
    for _, f := range fa {
        sum += (f - m) * (f - m)
    }
    return math.Sqrt(sum / float64(len(fa)))
}

func experiment(label string, r rule) {
    rxs := funnel(dxs, r)
    rys := funnel(dys, r)
    fmt.Println(label, " :      x        y")
    fmt.Printf("Mean    :  %7.4f, %7.4f\n", mean(rxs), mean(rys))
    fmt.Printf("Std Dev :  %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
    fmt.Println()
}

func main() {
    experiment("Rule 1", func(_, _ float64) float64 {
        return 0.0
    })
    experiment("Rule 2", func(_, dz float64) float64 {
        return -dz
    })
    experiment("Rule 3", func(z, dz float64) float64 {
        return -(z + dz)
    })
    experiment("Rule 4", func(z, dz float64) float64 {
        return z + dz
    })
}


Department numbers

There is a highly organized city that has decided to assign a number to each of their departments:
::*   police department
::*   sanitation department
::*   fire department

Each department can have a number between   '''1'''   and   '''7'''   (inclusive).

The three department numbers are to be unique (different from each other) and must add up to   '''12'''.

The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.

;Task:
Write a computer program which outputs all valid combinations.

Possible output   (for the 1st and 14th solutions):

  --police--  --sanitation--  --fire--
      2             3            7
      6             5            1

Solution:
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)
}


Detect division by zero

Write a function to detect a   ''divide by zero error''   without checking if the denominator is zero.

Solution:
package main

import "fmt"

func divCheck(x, y int) (q int, ok bool) {
    defer func() {
        recover()
    }()
    q = x / y
    return q, true
}

func main() {
    fmt.Println(divCheck(3, 2))
    fmt.Println(divCheck(3, 0))
}


Determinant and permanent

permanent of the matrix.

The determinant is given by
:: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i}
while the permanent is given by
::  \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i}
In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)

More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.

;Related task:
* [[Permutations by swapping]]

Solution:
package main

import (
    "fmt"
    "permute"
)

func determinant(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += float64(s) * pr
    }
    return
}

func permanent(m [][]float64) (d float64) {
    p := make([]int, len(m))
    for i := range p {
        p[i] = i
    }
    it := permute.Iter(p)
    for s := it(); s != 0; s = it() {
        pr := 1.
        for i, σ := range p {
            pr *= m[i][σ]
        }
        d += pr
    }
    return
}

var m2 = [][]float64{
    {1, 2},
    {3, 4}}

var m3 = [][]float64{
    {2, 9, 4},
    {7, 5, 3},
    {6, 1, 8}}

func main() {
    fmt.Println(determinant(m2), permanent(m2))
    fmt.Println(determinant(m3), permanent(m3))
}


Determine if a string has all the same characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are the same
::::*    indicate if or which character is different from the previous character
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as all the same character(s)
::*   process the strings from left-to-right
::*   if       all the same character,   display a message saying such
::*   if                  not all the same character,   then:
::::*    display a message saying such
::::*    display what character is different
::::*    only the 1st different character need be displayed
::::*    display where the different character is in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the different character

Use (at least) these seven test values   (strings):
:::*   a string of length   0   (an empty string)
:::*   a string of length   3   which contains three blanks
:::*   a string of length   1   which contains:   '''2'''
:::*   a string of length   3   which contains:   '''333'''
:::*   a string of length   3   which contains:   '''.55'''
:::*   a string of length   6   which contains:   '''tttTTT'''
:::*   a string of length   9   with a blank in the middle:   '''4444   444k'''

Show all output here on this page.

Solution:
package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 1; i < le; i++ {
            if chars[i] != chars[i-1] {
                fmt.Println("  Not all characters in the string are the same.")
                fmt.Printf("  %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1)
                return
            }
        }
    }
    fmt.Println("  All characters in the string are the same.\n")
}

func main() {
    strings := []string{
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄",
    }
    for _, s := range strings {
        analyze(s)
    }
}


Determine if a string has all unique characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are unique
::::*    indicate if or which character is duplicated and where
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as unique
::*   process the strings from left-to-right
::*   if       unique,   display a message saying such
::*   if                  not unique,   then:
::::*    display a message saying such
::::*    display what character is duplicated
::::*    only the 1st non-unique character need be displayed
::::*    display where "both" duplicated characters are in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the duplicated character

Use (at least) these five test values   (strings):
:::*   a string of length     0   (an empty string)
:::*   a string of length     1   which is a single period   ('''.''')
:::*   a string of length     6   which contains:   '''abcABC'''
:::*   a string of length     7   which contains a blank in the middle:   '''XYZ  ZYX'''
:::*   a string of length         36   which   ''doesn't''   contain the letter "oh":
::::::::  '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''

Show all output here on this page.

Solution:
package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 0; i < le-1; i++ {
            for j := i + 1; j < le; j++ {
                if chars[j] == chars[i] {
                    fmt.Println("  Not all characters in the string are unique.")
                    fmt.Printf("  %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)
                    return
                }
            }
        }
    }
    fmt.Println("  All characters in the string are unique.\n")
}

func main() {
    strings := []string{
        "",
        ".",
        "abcABC",
        "XYZ ZYX",
        "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
        "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
        "hétérogénéité",
        "🎆🎃🎇🎈",
        "😍😀🙌💃😍🙌",
        "🐠🐟🐡🦈🐬🐳🐋🐡",
    }
    for _, s := range strings {
        analyze(s)
    }
}


Determine if a string is collapsible

Determine if a character string is   ''collapsible''.

And if so,   collapse the string   (by removing   ''immediately repeated''   characters).

If a character string has   ''immediately repeated''   character(s),   the repeated characters are to be
deleted (removed),   but not the primary (1st) character(s).

An   ''immediately repeated''   character is any character that is   immediately   followed by an
identical character (or characters).   Another word choice could've been   ''duplicated character'',   but that
might have ruled out   (to some readers)   triplicated characters   ***   or more.

{This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   '''PL/I'''   BIF:   '''collapse'''.}

;Examples:
In the following character string:

  The better the 4-wheel drive, the further you'll be from help when ya get stuck!

Only the 2nd   '''t''',   '''e''', and   '''l'''   are repeated characters,   indicated
by underscores (above),   even though they (those characters) appear elsewhere in the character string.

So, after ''collapsing'' the string, the result would be:

  The beter the 4-whel drive, the further you'l be from help when ya get stuck!

Another example:
In the following character string:

  headmistressship

The "collapsed" string would be:

  headmistreship

;Task:
Write a subroutine/function/procedure/routine***   to
locate   ''repeated''   characters and   ''collapse''   (delete)   them from the character
string.   The character string can be processed from either direction.

Show all output here, on this page:
:*   the   original string and its length
:*   the       resultant string and its length
:*   the above strings should be "bracketed" with   '''<<<'''   and   '''>>>'''   (to delineate blanks)
;*   <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here>>>>>>

Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except
the 1st string:

  string
  number
         ++
    1    |+-----------------------------------------------------------------------+   <######  a null string  (length zero)
    2    |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |
    3    |..1111111111111111111111111111111111111111111111111111111111111117777888|
    4    |I never give 'em hell, I just tell the truth, and they think it's hell. |
    5    |                                                    --- Harry S Truman  |   <######  has many repeated blanks
         +------------------------------------------------------------------------+

Solution:
package main

import "fmt"

// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
func collapse(s string) (string, int, int) {
    r := []rune(s)
    le, del := len(r), 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == r[i+1] {
            copy(r[i:], r[i+1:])
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[:le-del]
    return string(r), le, len(r)
}

func main() {
    strings:= []string {
        "",
        `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
    }
    for _, s := range strings {
        cs, olen, clen := collapse(s)
        fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
        fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
    }
}


Determine if a string is squeezable

Determine if a character string is   ''squeezable''.

And if so,   squeeze the string   (by removing any number of
a   ''specified''   ''immediately repeated''   character).

This task is very similar to the task     '''Determine if a character string is collapsible'''     except
that only a specified character is   ''squeezed''   instead of any character that is ''immediately repeated''.

If a character string has a specified   ''immediately repeated''   character(s),   the repeated characters are to be
deleted (removed),   but not the primary (1st) character(s).

A specified   ''immediately repeated''   character is any specified character that is   immediately
followed by an identical character (or characters).   Another word choice could've been   ''duplicated
character'',   but that might have ruled out   (to some readers)   triplicated characters   ***   or more.

{This Rosetta Code task was inspired by a newly introduced   (as of around
November 2019)   '''PL/I'''   BIF:   '''squeeze'''.}

;Examples:
In the following character string with a specified   ''immediately repeated''   character of   '''e''':

  The better the 4-wheel drive, the further you'll be from help when ya get stuck!

Only the 2nd   '''e'''   is an specified repeated character,   indicated by an underscore
(above),   even though they (the characters) appear elsewhere in the character string.

So, after ''squeezing'' the string, the result would be:

  The better the 4-whel drive, the further you'll be from help when ya get stuck!

Another example:
In the following character string,   using a specified immediately repeated character   '''s''':

  headmistressship

The "squeezed" string would be:

  headmistreship

;Task:
Write a subroutine/function/procedure/routine***   to locate a   ''specified immediately repeated''   character
and   ''squeeze''   (delete)   them from the character string.   The
character string can be processed from either direction.

Show all output here, on this page:
:*   the   specified repeated character   (to be searched for and possibly ''squeezed''):
:*   the   original string and its length
:*   the       resultant string and its length
:*   the above strings should be "bracketed" with   '''<<<'''   and   '''>>>'''   (to delineate blanks)
;*   <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here>>>>>>

Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except
the 1st string:

                                                                                immediately
  string                                                                            repeated
  number                                                                            character
                                                                                ( |   a blank,  a minus,  a seven,  a period)
         ++
    1    |+-----------------------------------------------------------------------+    ' '    <######  a null string  (length zero)
    2    |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |    '-'
    3    |..1111111111111111111111111111111111111111111111111111111111111117777888|    '7'
    4    |I never give 'em hell, I just tell the truth, and they think it's hell. |    '.'
    5    |                                                    --- Harry S Truman  |  (below)  <######  has many repeated blanks
         +------------------------------------------------------------------------+     |
                                                                                |
                                                                                |
         For the 5th string  (Truman's signature line),  use each of these  specified immediately  repeated characters:
                                   *  a blank
                                   *  a minus
                                   *  a lowercase  '''r'''

Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for
the 5th string.

Solution:
package main

import "fmt"

// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
func squeeze(s string, c rune) (string, int, int) {
    r := []rune(s)
    le, del := len(r), 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == c && r[i] == r[i+1] {
            copy(r[i:], r[i+1:])
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[:le-del]
    return string(r), le, len(r)
}

func main() {
    strings := []string{
        "",
        `"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
    }
    chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}

    for i, s := range strings {
        for _, c := range chars[i] {
            ss, olen, slen := squeeze(s, c)
            fmt.Printf("specified character = %q\n", c)
            fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
            fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
        }
    }
}


Determine if two triangles overlap

Solution:
package main

import "fmt"

type point struct {
    x, y float64
}

func (p point) String() string {
    return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y)
}

type triangle struct {
    p1, p2, p3 point
}

func (t *triangle) String() string {
    return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3)
}

func (t *triangle) det2D() float64 {
    return t.p1.x * (t.p2.y - t.p3.y) +
           t.p2.x * (t.p3.y - t.p1.y) +
           t.p3.x * (t.p1.y - t.p2.y)
}

func (t *triangle) checkTriWinding(allowReversed bool) {
    detTri := t.det2D()
    if detTri < 0.0 {
        if allowReversed {
            a := t.p3
            t.p3 = t.p2
            t.p2 = a
        } else {
            panic("Triangle has wrong winding direction.")
        }
    }
}

func boundaryCollideChk(t *triangle, eps float64) bool {
    return t.det2D() < eps
}

func boundaryDoesntCollideChk(t *triangle, eps float64) bool {
    return t.det2D() <= eps
}

func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool {
    // Triangles must be expressed anti-clockwise.
    t1.checkTriWinding(allowReversed)
    t2.checkTriWinding(allowReversed)

    // 'onBoundary' determines whether points on boundary are considered as colliding or not.
    var chkEdge func (*triangle, float64) bool
    if onBoundary {
        chkEdge = boundaryCollideChk
    } else {
        chkEdge = boundaryDoesntCollideChk
    }
    lp1 := [3]point{t1.p1, t1.p2, t1.p3}
    lp2 := [3]point{t2.p1, t2.p2, t2.p3}

    // for each edge E of t1
    for i := 0; i < 3; i++ {
        j := (i + 1) % 3
        // Check all points of t2 lay on the external side of edge E.
        // If they do, the triangles do not overlap.
        tri1 := &triangle{lp1[i], lp1[j], lp2[0]}
        tri2 := &triangle{lp1[i], lp1[j], lp2[1]}
        tri3 := &triangle{lp1[i], lp1[j], lp2[2]}
        if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {
            return false
        }
    }

    // for each edge E of t2
    for i := 0; i < 3; i++ {
        j := (i + 1) % 3
        // Check all points of t1 lay on the external side of edge E.
        // If they do, the triangles do not overlap.
        tri1 := &triangle{lp2[i], lp2[j], lp1[0]}
        tri2 := &triangle{lp2[i], lp2[j], lp1[1]}
        tri3 := &triangle{lp2[i], lp2[j], lp1[2]}
        if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {
            return false
        }
    }

    // The triangles overlap.
    return true
}

func iff(cond bool, s1, s2 string) string {
    if cond {
        return s1
    }
    return s2
}

func main() {
    t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}
    t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}}
    fmt.Printf("%s and\n%s\n", t1, t2)
    overlapping := triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    // Need to allow reversed for this pair to avoid panic.
    t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}}
    t2 = t1
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    overlapping = triTri2D(t1, t2, 0.0, true, true)
    fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap"))

    t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}
    t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}}
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    overlapping = triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    t1.p3 = point{2.5, 5.0}
    t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}}
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    overlapping = triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}}
    t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}}
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    overlapping = triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}}
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    overlapping = triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}}
    t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}}
    fmt.Printf("\n%s and\n%s\n", t1, t2)
    println("which have only a single corner in contact, if boundary points collide")
    overlapping = triTri2D(t1, t2, 0.0, false, true)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))

    fmt.Printf("\n%s and\n%s\n", t1, t2)
    fmt.Println("which have only a single corner in contact, if boundary points do not collide")
    overlapping = triTri2D(t1, t2, 0.0, false, false)
    fmt.Println(iff(overlapping, "overlap", "do not overlap"))
}


Dice game probabilities

Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.

They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?

Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?

This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205

Solution:
package main

import(
    "math"
    "fmt"
)

func minOf(x, y uint) uint {
    if x < y {
        return x
    }
    return y
}

func throwDie(nSides, nDice, s uint, counts []uint) {
    if nDice == 0 {
        counts[s]++
        return
    }
    for i := uint(1); i <= nSides; i++ {
        throwDie(nSides, nDice - 1, s + i, counts)
    }
}

func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
    len1 := (nSides1 + 1) * nDice1
    c1 := make([]uint, len1)  // all elements zero by default
    throwDie(nSides1, nDice1, 0, c1)

    len2 := (nSides2 + 1) * nDice2
    c2 := make([]uint, len2)
    throwDie(nSides2, nDice2, 0, c2)
    p12 := math.Pow(float64(nSides1), float64(nDice1)) *
           math.Pow(float64(nSides2), float64(nDice2))

    tot := 0.0
    for i := uint(0); i < len1; i++ {
        for j := uint(0); j < minOf(i, len2); j++ {
            tot += float64(c1[i] * c2[j]) / p12
        }
    }
    return tot
}

func main() {
    fmt.Println(beatingProbability(4, 9, 6, 6))
    fmt.Println(beatingProbability(10, 5, 7, 6))
}


Digital root

The digital root, X, of a number, n, is calculated:
: find X as the sum of the digits of n
: find a new X by summing the digits of X, repeating until X has only one digit.

The additive persistence is the number of summations required to obtain the single digit.

The task is to calculate the additive persistence and the digital root of a number, e.g.:
:627615 has additive persistence 2 and digital root of 9;
:39390 has additive persistence 2 and digital root of 6;
:588225 has additive persistence 2 and digital root of 3;
:393900588225 has additive persistence 2 and digital root of 9;

The digital root may be calculated in bases other than 10.

;See:
* [[Casting out nines]] for this wiki's use of this procedure.
* [[Digital root/Multiplicative digital root]]
* [[Sum digits of an integer]]
* Digital root sequence on OEIS
* Additive persistence sequence on OEIS
* [[Iterated digits squaring]]

Solution:
package main

import (
	"fmt"
	"log"
	"strconv"
)

func Sum(i uint64, base int) (sum int) {
	b64 := uint64(base)
	for ; i > 0; i /= b64 {
		sum += int(i % b64)
	}
	return
}

func DigitalRoot(n uint64, base int) (persistence, root int) {
	root = int(n)
	for x := n; x >= uint64(base); x = uint64(root) {
		root = Sum(x, base)
		persistence++
	}
	return
}

// Normally the below would be moved to a *_test.go file and
// use the testing package to be runnable as a regular test.

var testCases = []struct {
	n           string
	base        int
	persistence int
	root        int
}{
	{"627615", 10, 2, 9},
	{"39390", 10, 2, 6},
	{"588225", 10, 2, 3},
	{"393900588225", 10, 2, 9},
	{"1", 10, 0, 1},
	{"11", 10, 1, 2},
	{"e", 16, 0, 0xe},
	{"87", 16, 1, 0xf},
	// From Applesoft BASIC example:
	{"DigitalRoot", 30, 2, 26}, // 26 is Q base 30
	// From C++ example:
	{"448944221089", 10, 3, 1},
	{"7e0", 16, 2, 0x6},
	{"14e344", 16, 2, 0xf},
	{"d60141", 16, 2, 0xa},
	{"12343210", 16, 2, 0x1},
	// From the D example:
	{"1101122201121110011000000", 3, 3, 1},
}

func main() {
	for _, tc := range testCases {
		n, err := strconv.ParseUint(tc.n, tc.base, 64)
		if err != nil {
			log.Fatal(err)
		}
		p, r := DigitalRoot(n, tc.base)
		fmt.Printf("%12v (base %2d) has additive persistence %d and digital root %s\n",
			tc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))
		if p != tc.persistence || r != tc.root {
			log.Fatalln("bad result:", tc, p, r)
		}
	}
}


Disarium numbers

A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.

;E.G.

'''135''' is a '''Disarium number''':

 11 + 32 + 53 == 1 + 9 + 125 == 135

There are a finite number of '''Disarium numbers'''.

;Task

* Find and display the first 18 '''Disarium numbers'''.

;Stretch

* Find and display all 20 '''Disarium numbers'''.

;See also

;* Geeks for Geeks - Disarium numbers
;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
;* Related task: Narcissistic decimal number
;* Related task: Own digits power sum  ''Which seems to be the same task as Narcissistic decimal number...''

Solution:
package main

import (
    "fmt"
    "strconv"
)

const DMAX = 20  // maximum digits
const LIMIT = 20 // maximum number of disariums to find

func main() {
    // Pre-calculated exponential and power serials
    EXP := make([][]uint64, 1+DMAX)
    POW := make([][]uint64, 1+DMAX)

    EXP[0] = make([]uint64, 11)
    EXP[1] = make([]uint64, 11)
    POW[0] = make([]uint64, 11)
    POW[1] = make([]uint64, 11)
    for i := uint64(1); i <= 10; i++ {
        EXP[1][i] = i
    }
    for i := uint64(1); i <= 9; i++ {
        POW[1][i] = i
    }
    POW[1][10] = 9

    for i := 2; i <= DMAX; i++ {
        EXP[i] = make([]uint64, 11)
        POW[i] = make([]uint64, 11)
    }
    for i := 1; i < DMAX; i++ {
        for j := 0; j <= 9; j++ {
            EXP[i+1][j] = EXP[i][j] * 10
            POW[i+1][j] = POW[i][j] * uint64(j)
        }
        EXP[i+1][10] = EXP[i][10] * 10
        POW[i+1][10] = POW[i][10] + POW[i+1][9]
    }

    // Digits of candidate and values of known low bits
    DIGITS := make([]int, 1+DMAX) // Digits form
    Exp := make([]uint64, 1+DMAX) // Number form
    Pow := make([]uint64, 1+DMAX) // Powers form

    var exp, pow, min, max uint64
    start := 1
    final := DMAX
    count := 0
    for digit := start; digit <= final; digit++ {
        fmt.Println("# of digits:", digit)
        level := 1
        DIGITS[0] = 0
        for {
            // Check limits derived from already known low bit values
            // to find the most possible candidates
            for 0 < level && level < digit {
                // Reset path to try next if checking in level is done
                if DIGITS[level] > 9 {
                    DIGITS[level] = 0
                    level--
                    DIGITS[level]++
                    continue
                }

                // Update known low bit values
                Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
                Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]

                // Max possible value
                pow = Pow[level] + POW[digit-level][10]

                if pow < EXP[digit][1] { // Try next since upper limit is invalidly low
                    DIGITS[level]++
                    continue
                }

                max = pow % EXP[level][10]
                pow -= max
                if max < Exp[level] {
                    pow -= EXP[level][10]
                }
                max = pow + Exp[level]

                if max < EXP[digit][1] { // Try next since upper limit is invalidly low
                    DIGITS[level]++
                    continue
                }

                // Min possible value
                exp = Exp[level] + EXP[digit][1]
                pow = Pow[level] + 1

                if exp > max || max < pow { // Try next since upper limit is invalidly low
                    DIGITS[level]++
                    continue
                }

                if pow > exp {
                    min = pow % EXP[level][10]
                    pow -= min
                    if min > Exp[level] {
                        pow += EXP[level][10]
                    }
                    min = pow + Exp[level]
                } else {
                    min = exp
                }

                // Check limits existence
                if max < min {
                    DIGITS[level]++ // Try next number since current limits invalid
                } else {
                    level++ // Go for further level checking since limits available
                }
            }

            // All checking is done, escape from the main check loop
            if level < 1 {
                break
            }

            // Finally check last bit of the most possible candidates
            // Update known low bit values
            Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
            Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]

            // Loop to check all last bits of candidates
            for DIGITS[level] < 10 {
                // Print out new Disarium number
                if Exp[level] == Pow[level] {
                    s := ""
                    for i := DMAX; i > 0; i-- {
                        s += fmt.Sprintf("%d", DIGITS[i])
                    }
                    n, _ := strconv.ParseUint(s, 10, 64)
                    fmt.Println(n)
                    count++
                    if count == LIMIT {
                        fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
                        return
                    }
                }

                // Go to followed last bit candidate
                DIGITS[level]++
                Exp[level] += EXP[level][1]
                Pow[level]++
            }

            // Reset to try next path
            DIGITS[level] = 0
            level--
            DIGITS[level]++
        }
        fmt.Println()
    }
}


Display a linear combination

Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots).

Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is:

:\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots

where \alpha^{i_k}\neq 0

The output must comply to the following rules:
*   don't show null terms, unless the whole combination is null.
:::::::  '''e(1)'''     is fine,     '''e(1) + 0*e(3)'''     or     '''e(1) + 0'''     is wrong.
*   don't show scalars when they are equal to one or minus one.
:::::::  '''e(3)'''     is fine,     '''1*e(3)'''     is wrong.
*   don't prefix by a minus sign if it follows a preceding term.   Instead you use subtraction.
:::::::  '''e(4) - e(5)'''     is fine,     '''e(4) + -e(5)'''     is wrong.

Show here output for the following lists of scalars:

 1)    1,  2,  3
 2)    0,  1,  2,  3
 3)    1,  0,  3,  4
 4)    1,  2,  0
 5)    0,  0,  0
 6)    0
 7)    1,  1,  1
 8)   -1, -1, -1
 9)   -1, -2,  0, -3
10)   -1

Solution:
package main

import (
    "fmt"
    "strings"
)

func linearCombo(c []int) string {
    var sb strings.Builder
    for i, n := range c {
        if n == 0 {
            continue
        }
        var op string
        switch {
        case n < 0 && sb.Len() == 0:
            op = "-"
        case n < 0:
            op = " - "
        case n > 0 && sb.Len() == 0:
            op = ""
        default:
            op = " + "
        }
        av := n
        if av < 0 {
            av = -av
        }
        coeff := fmt.Sprintf("%d*", av)
        if av == 1 {
            coeff = ""
        }
        sb.WriteString(fmt.Sprintf("%s%se(%d)", op, coeff, i+1))
    }
    if sb.Len() == 0 {
        return "0"
    } else {
        return sb.String()
    }
}

func main() {
    combos := [][]int{
        {1, 2, 3},
        {0, 1, 2, 3},
        {1, 0, 3, 4},
        {1, 2, 0},
        {0, 0, 0},
        {0},
        {1, 1, 1},
        {-1, -1, -1},
        {-1, -2, 0, -3},
        {-1},
    }
    for _, c := range combos {
        t := strings.Replace(fmt.Sprint(c), " ", ", ", -1)
        fmt.Printf("%-15s  ->  %s\n", t, linearCombo(c))
    }
}


Display an outline as a nested table

{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
|  |
|  |
|  |
|  |
| style="background: #f0fff0; " | (The sum of the widths of its children)
|  |
|  |
|}

The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.

;Task:
Given a outline with at least 3 levels of indentation, for example:

Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.

write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.

The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:

{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
|  |
|  |
|  |
|  |
| style="background: #f0fff0; " | (The sum of the widths of its children)
|  |
|  |
|}

;Extra credit:
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.

;Output:
Display your nested table on this page.

Solution:
package main

import (
    "fmt"
    "strings"
)

type nNode struct {
    name     string
    children []nNode
}

type iNode struct {
    level int
    name  string
}

func toNest(iNodes []iNode, start, level int, n *nNode) {
    if level == 0 {
        n.name = iNodes[0].name
    }
    for i := start + 1; i < len(iNodes); i++ {
        if iNodes[i].level == level+1 {
            c := nNode{iNodes[i].name, nil}
            toNest(iNodes, i, level+1, &c)
            n.children = append(n.children, c)
        } else if iNodes[i].level <= level {
            return
        }
    }
}

func makeIndent(outline string, tab int) []iNode {
    lines := strings.Split(outline, "\n")
    iNodes := make([]iNode, len(lines))
    for i, line := range lines {
        line2 := strings.TrimLeft(line, " ")
        le, le2 := len(line), len(line2)
        level := (le - le2) / tab
        iNodes[i] = iNode{level, line2}
    }
    return iNodes
}

func toMarkup(n nNode, cols []string, depth int) string {
    var span int

    var colSpan func(nn nNode)
    colSpan = func(nn nNode) {
        for i, c := range nn.children {
            if i > 0 {
                span++
            }
            colSpan(c)
        }
    }

    for _, c := range n.children {
        span = 1
        colSpan(c)
    }
    var lines []string
    lines = append(lines, `{| class="wikitable" style="text-align: center;"`)
    const l1, l2 = "|-", "|  |"
    lines = append(lines, l1)
    span = 1
    colSpan(n)
    s := fmt.Sprintf(`| style="background: %s " colSpan=%d | %s`, cols[0], span, n.name)
    lines = append(lines, s, l1)

    var nestedFor func(nn nNode, level, maxLevel, col int)
    nestedFor = func(nn nNode, level, maxLevel, col int) {
        if level == 1 && maxLevel > level {
            for i, c := range nn.children {
                nestedFor(c, 2, maxLevel, i)
            }
        } else if level < maxLevel {
            for _, c := range nn.children {
                nestedFor(c, level+1, maxLevel, col)
            }
        } else {
            if len(nn.children) > 0 {
                for i, c := range nn.children {
                    span = 1
                    colSpan(c)
                    cn := col + 1
                    if maxLevel == 1 {
                        cn = i + 1
                    }
                    s := fmt.Sprintf(`| style="background: %s " colspan=%d | %s`, cols[cn], span, c.name)
                    lines = append(lines, s)
                }
            } else {
                lines = append(lines, l2)
            }
        }
    }
    for maxLevel := 1; maxLevel < depth; maxLevel++ {
        nestedFor(n, 1, maxLevel, 0)
        if maxLevel < depth-1 {
            lines = append(lines, l1)
        }
    }
    lines = append(lines, "|}")
    return strings.Join(lines, "\n")
}

func main() {
    const outline = `Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.`
    const (
        yellow = "#ffffe6;"
        orange = "#ffebd2;"
        green  = "#f0fff0;"
        blue   = "#e6ffff;"
        pink   = "#ffeeff;"
    )
    cols := []string{yellow, orange, green, blue, pink}
    iNodes := makeIndent(outline, 4)
    var n nNode
    toNest(iNodes, 0, 0, &n)
    fmt.Println(toMarkup(n, cols, 4))

    fmt.Println("\n")
    const outline2 = `Display an outline as a nested table.
    Parse the outline to a tree,
        measuring the indent of each line,
        translating the indentation to a nested structure,
        and padding the tree to even depth.
    count the leaves descending from each node,
        defining the width of a leaf as 1,
        and the width of a parent node as a sum.
            (The sum of the widths of its children)
            Propagating the sums upward as necessary.
    and write out a table with 'colspan' values
        either as a wiki table,
        or as HTML.
    Optionally add color to the nodes.`
    cols2 := []string{blue, yellow, orange, green, pink}
    var n2 nNode
    iNodes2 := makeIndent(outline2, 4)
    toNest(iNodes2, 0, 0, &n2)
    fmt.Println(toMarkup(n2, cols2, 4))
}


Diversity prediction theorem

The   ''wisdom of the crowd''   is the collective opinion of a group of individuals rather than that of a single expert.

Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the individual judgments from each other.

Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.

Scott E. Page introduced the diversity prediction theorem:
: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''.

Therefore,   when the diversity in a group is large,   the error of the crowd is small.

;Definitions:
::*   Average Individual Error:   Average of the individual squared errors
::*   Collective Error:           Squared error of the collective prediction
::*   Prediction Diversity:       Average squared distance from the individual predictions to the collective prediction
::*   Diversity Prediction Theorem:   ''Given a crowd of predictive models'',     then
::::::   Collective Error   =   Average Individual Error   -   Prediction Diversity

;Task:
For a given   true   value and a number of number of estimates (from a crowd),   show   (here on this page):
:::*   the true value   and   the crowd estimates
:::*   the average error
:::*   the crowd error
:::*   the prediction diversity

Use   (at least)   these two examples:
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51'''
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51   42'''

;Also see:
:*   Wikipedia entry:   Wisdom of the crowd
:*   University of Michigan: PDF paper         (exists on a web archive,   the ''Wayback Machine'').

Solution:
package main

import "fmt"

func averageSquareDiff(f float64, preds []float64) (av float64) {
    for _, pred := range preds {
        av += (pred - f) * (pred - f)
    }
    av /= float64(len(preds))
    return
}

func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
    av := 0.0
    for _, pred := range preds {
        av += pred
    }
    av /= float64(len(preds))
    avErr := averageSquareDiff(truth, preds)
    crowdErr := (truth - av) * (truth - av)
    div := averageSquareDiff(av, preds)
    return avErr, crowdErr, div
}

func main() {
    predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}
    truth := 49.0
    for _, preds := range predsArray {
        avErr, crowdErr, div := diversityTheorem(truth, preds)
        fmt.Printf("Average-error : %6.3f\n", avErr)
        fmt.Printf("Crowd-error   : %6.3f\n", crowdErr)
        fmt.Printf("Diversity     : %6.3f\n\n", div)
    }
}


Doomsday rule

 About the task
John Conway (1937-2020), was a mathematician who also invented several mathematically
oriented computer pastimes, such as the famous Game of Life cellular automaton program.
Dr. Conway invented a simple algorithm for finding the day of the week, given any date.
The algorithm was based on calculating the distance of a given date from certain
"anchor days" which follow a pattern for the day of the week upon which they fall.

; Algorithm
The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and

    doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7

which, for 2021, is 0 (Sunday).

To calculate the day of the week, we then count days from a close doomsday,
with these as charted here by month, then add the doomsday for the year,
then get the remainder after dividing by 7. This should give us the number
corresponding to the day of the week for that date.

    Month	        Doomsday Dates for Month
    --------------------------------------------
    January (common years)   3, 10, 17, 24, 31
    January (leap years)     4, 11, 18, 25
    February (common years)  7, 14, 21, 28
    February (leap years)    1, 8, 15, 22, 29
    March                    7, 14, 21, 28
    April                    4, 11, 18, 25
    May                      2, 9, 16, 23, 30
    June                     6, 13, 20, 27
    July                     4, 11, 18, 25
    August                   1, 8, 15, 22, 29
    September                5, 12, 19, 26
    October                  3, 10, 17, 24, 31
    November                 7, 14, 21, 28
    December                 5, 12, 19, 26

; Task

Given the following dates:

*   1800-01-06 (January 6, 1800)
*   1875-03-29 (March 29, 1875)
*   1915-12-07 (December 7, 1915)
*   1970-12-23 (December 23, 1970)
*   2043-05-14 (May 14, 2043)
*   2077-02-12 (February 12, 2077)
*   2101-04-02 (April 2, 2101)

Use Conway's Doomsday rule to calculate the day of the week for each date.

; see also
*   Doomsday rule
*   Tomorrow is the Day After Doomsday (p.28)

Solution:
package main

import (
    "fmt"
    "strconv"
)

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

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

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

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

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

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


Dot product

Create a function/use an in-built function, to compute the   '''dot product''',   also known as the   '''scalar product'''   of two vectors.

If possible, make the vectors of arbitrary length.

As an example, compute the dot product of the vectors:
::::     [1,  3, -5]       and
::::     [4,      -2, -1]

If implementing the dot product of two vectors directly:
:::*   each vector must be the same length
:::*   multiply corresponding terms from each vector
:::*   sum the products   (to produce the answer)

;Related task:
*   [[Vector products]]

Solution:
package main

import (
    "errors"
    "fmt"
    "log"
)

var (
    v1 = []int{1, 3, -5}
    v2 = []int{4, -2, -1}
)

func dot(x, y []int) (r int, err error) {
    if len(x) != len(y) {
        return 0, errors.New("incompatible lengths")
    }
    for i, xi := range x {
        r += xi * y[i]
    }
    return
}

func main() {
    d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(d)
}


Draw a clock

Draw a clock.

More specific:
# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.

;Key points
* animate simple object
* timed event
* polling system resources
* code clarity

Solution:
<!DOCTYPE html>
<meta charset="utf-8" />
<title>Clock</title>

Clock

  <canvas id="rim" width="512" height="512" style="position: absolute; left: 0; top: 0; z-index: 0;">
        Sorry, your browser does not support Canvas
  </canvas>
	<canvas id="hourhand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 1;">
        Sorry, your browser does not support Canvas
  </canvas>
	<canvas id="minutehand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 2;">
        Sorry, your browser does not support Canvas
  </canvas>
	<canvas id="secondhand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 3;">
        Sorry, your browser does not support Canvas
  </canvas>


Draw a rotating cube

Task
Draw a rotating cube.

It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.

;Related tasks
* Draw a cuboid
* write language name in 3D ASCII

Solution:
package main

import (
	"image"
	"image/color"
	"image/gif"
	"log"
	"math"
	"os"
)

const (
	width, height = 640, 640
	offset        = height / 2
	fileName      = "rotatingCube.gif"
)

var nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100},
	{100, -100, -100}, {100, -100, 100}, {100, 100, -100}, {100, 100, 100}}
var edges = [][]int{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
	{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}

func main() {
	var images []*image.Paletted
	fgCol := color.RGBA{0xff, 0x00, 0xff, 0xff}
	var palette = []color.Color{color.RGBA{0x00, 0x00, 0x00, 0xff}, fgCol}
	var delays []int

	imgFile, err := os.Create(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer imgFile.Close()

	rotateCube(math.Pi/4, math.Atan(math.Sqrt(2)))
	var frame float64
	for frame = 0; frame < 360; frame++ {
		img := image.NewPaletted(image.Rect(0, 0, width, height), palette)
		images = append(images, img)
		delays = append(delays, 5)
		for _, edge := range edges {
			xy1 := nodes[edge[0]]
			xy2 := nodes[edge[1]]
			drawLine(int(xy1[0])+offset, int(xy1[1])+offset, int(xy2[0])+offset, int(xy2[1])+offset, img, fgCol)
		}
		rotateCube(math.Pi/180, 0)
	}
	if err := gif.EncodeAll(imgFile, &gif.GIF{Image: images, Delay: delays}); err != nil {
		imgFile.Close()
		log.Fatal(err)
	}

}

func rotateCube(angleX, angleY float64) {
	sinX := math.Sin(angleX)
	cosX := math.Cos(angleX)
	sinY := math.Sin(angleY)
	cosY := math.Cos(angleY)
	for _, node := range nodes {
		x := node[0]
		y := node[1]
		z := node[2]
		node[0] = x*cosX - z*sinX
		node[2] = z*cosX + x*sinX
		z = node[2]
		node[1] = y*cosY - z*sinY
		node[2] = z*cosY + y*sinY
	}
}

func drawLine(x0, y0, x1, y1 int, img *image.Paletted, col color.RGBA) {
	dx := abs(x1 - x0)
	dy := abs(y1 - y0)
	var sx, sy int = -1, -1
	if x0 < x1 {
		sx = 1
	}
	if y0 < y1 {
		sy = 1
	}
	err := dx - dy
	for {
		img.Set(x0, y0, col)
		if x0 == x1 && y0 == y1 {
			break
		}
		e2 := 2 * err
		if e2 > -dy {
			err -= dy
			x0 += sx
		}
		if e2 < dx {
			err += dx
			y0 += sy
		}
	}
}

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