Pseudo-random numbers/Combined recursive generator MRG32k3a

MRG32k3a Combined recursive generator (pseudo-code):

    /* Constants */
    /* First generator */
    a1 = [0, 1403580, -810728]
    m1 = 2**32 - 209
    /* Second Generator */
    a2 = [527612, 0, -1370589]
    m2 = 2**32 - 22853

    d = m1 + 1

    class MRG32k3a
        x1 = [0, 0, 0]  /* list of three last values of gen #1 */
        x2 = [0, 0, 0]  /* list of three last values of gen #2 */

        method seed(u64 seed_state)
            assert seed_state in range >0 and < d
            x1 = [seed_state, 0, 0]
            x2 = [seed_state, 0, 0]
        end method

        method next_int()
            x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1
            x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2
            x1 = [x1i, x1[0], x1[1]]    /* Keep last three */
            x2 = [x2i, x2[0], x2[1]]    /* Keep last three */
            z = (x1i - x2i) % m1
            answer = (z + 1)

            return answer
        end method

        method next_float():
            return float next_int() / d
        end method

    end class

:MRG32k3a Use:
    random_gen = instance MRG32k3a
    random_gen.seed(1234567)
    print(random_gen.next_int())   /* 1459213977 */
    print(random_gen.next_int())   /* 2827710106 */
    print(random_gen.next_int())   /* 4245671317 */
    print(random_gen.next_int())   /* 3877608661 */
    print(random_gen.next_int())   /* 2595287583 */

;Task

* Generate a class/set of functions that generates pseudo-random
numbers as shown above.

* Show that the first five integers generated with the seed `1234567`
are as shown above

* Show that for an initial seed of '987654321' the counts of 100_000
repetitions of

    floor(random_gen.next_float() * 5)

Is as follows:

    0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931

* Show your output here, on this page.

Solution:
package main

import (
    "fmt"
    "log"
    "math"
)

var a1 = []int64{0, 1403580, -810728}
var a2 = []int64{527612, 0, -1370589}

const m1 = int64((1 << 32) - 209)
const m2 = int64((1 << 32) - 22853)
const d = m1 + 1

// Python style modulus
func mod(x, y int64) int64 {
    m := x % y
    if m < 0 {
        if y < 0 {
            return m - y
        } else {
            return m + y
        }
    }
    return m
}

type MRG32k3a struct{ x1, x2 [3]int64 }

func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} }

func (mrg *MRG32k3a) seed(seedState int64) {
    if seedState <= 0 || seedState >= d {
        log.Fatalf("Argument must be in the range [0, %d].\n", d)
    }
    mrg.x1 = [3]int64{seedState, 0, 0}
    mrg.x2 = [3]int64{seedState, 0, 0}
}

func (mrg *MRG32k3a) nextInt() int64 {
    x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1)
    x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2)
    mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} /* keep last three */
    mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} /* keep last three */
    return mod(x1i-x2i, m1) + 1
}

func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) }

func main() {
    randomGen := MRG32k3aNew()
    randomGen.seed(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}


Pseudo-random numbers/Middle-square method

{{Wikipedia|Middle-square method|en}}
; The Method:
To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers.
; Pseudo code:

var seed = 675248
function random()
    var s = str(seed * seed) 'str: turn a number into string
    do while not len(s) = 12
        s = "0" + s          'add zeroes before the string
    end do
    seed = val(mid(s, 4, 6)) 'mid: string variable, start, length
                             'val: turn a string into number
    return seed
end function

; Middle-square method use:

for i = 1 to 5
    print random()
end for

;Task:

* Generate a class/set of functions that generates pseudo-random
numbers (6 digits) as shown above.

* Show the first five integers generated with the seed 675248 as shown above.

* Show your output here, on this page.

Solution:
package main

import "fmt"

func random(seed int) int {
    return seed * seed / 1e3 % 1e6
}

func main() {
    seed := 675248
    for i := 1; i <= 5; i++ {
        seed = random(seed)
        fmt.Println(seed)
    }
}


Pseudo-random numbers/PCG32

Some definitions to help in the explanation:

:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.

:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.

:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100

:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101

:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110

:'''|''' Bitwise or operator
::https://en.wikipedia.org/wiki/Bitwise_operation#OR
::Bitwise comparison gives 1 if any of corresponding bits are 1
:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111

;PCG32 Generator (pseudo-code):

PCG32 has two unsigned 64-bit integers of internal state:
# '''state''': All 2**64 values may be attained.
# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).

Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state.

The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-

const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
  xs<-U32 (((state>>18)^state)>>27)
  rot<-INT (state>>59)
  OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
  state<-state*N+inc
end do

Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.

;Task:

* Generate a class/set of functions that generates pseudo-random
numbers using the above.

* Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955

* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of

    floor(random_gen.next_float() * 5)

:Is as follows:

    0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005

* Show your output here, on this page.

Solution:
package main

import (
    "fmt"
    "math"
)

const CONST = 6364136223846793005

type Pcg32 struct{ state, inc uint64 }

func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} }

func (pcg *Pcg32) seed(seedState, seedSequence uint64) {
    pcg.state = 0
    pcg.inc = (seedSequence << 1) | 1
    pcg.nextInt()
    pcg.state = pcg.state + seedState
    pcg.nextInt()
}

func (pcg *Pcg32) nextInt() uint32 {
    old := pcg.state
    pcg.state = old*CONST + pcg.inc
    pcgshifted := uint32(((old >> 18) ^ old) >> 27)
    rot := uint32(old >> 59)
    return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31))
}

func (pcg *Pcg32) nextFloat() float64 {
    return float64(pcg.nextInt()) / (1 << 32)
}

func main() {
    randomGen := Pcg32New()
    randomGen.seed(42, 54)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321, 1)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}


Pseudo-random numbers/Xorshift star

Some definitions to help in the explanation:

:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.

:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.

:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100

:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101

:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110

;Xorshift_star Generator (pseudo-code):

    /* Let u64 denote an unsigned 64 bit integer type. */
    /* Let u32 denote an unsigned 32 bit integer type. */

    class Xorshift_star
        u64 state       /* Must be seeded to non-zero initial value */
        u64 const = HEX '2545F4914F6CDD1D'

        method seed(u64 num):
            state =  num
        end method

        method next_int():
            u64 x = state
            x = x ^ (x >> 12)
            x = x ^ (x << 25)
            x = x ^ (x >> 27)
            state = x
            u32 answer = ((x * const) >> 32)

            return answer
        end method

        method next_float():
            return float next_int() / (1 << 32)
        end method

    end class

:;Xorshift use:

    random_gen = instance Xorshift_star
    random_gen.seed(1234567)
    print(random_gen.next_int())   /* 3540625527 */
    print(random_gen.next_int())   /* 2750739987 */
    print(random_gen.next_int())   /* 4037983143 */
    print(random_gen.next_int())   /* 1993361440 */
    print(random_gen.next_int())   /* 3809424708 */

;Task:

* Generate a class/set of functions that generates pseudo-random
numbers as shown above.

* Show that the first five integers genrated with the seed 1234567
are as shown above

* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of

    floor(random_gen.next_float() * 5)

:Is as follows:

    0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007

* Show your output here, on this page.

Solution:
package main

import (
    "fmt"
    "math"
)

const CONST = 0x2545F4914F6CDD1D

type XorshiftStar struct{ state uint64 }

func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} }

func (xor *XorshiftStar) seed(state uint64) { xor.state = state }

func (xor *XorshiftStar) nextInt() uint32 {
    x := xor.state
    x = x ^ (x >> 12)
    x = x ^ (x << 25)
    x = x ^ (x >> 27)
    xor.state = x
    return uint32((x * CONST) >> 32)
}

func (xor *XorshiftStar) nextFloat() float64 {
    return float64(xor.nextInt()) / (1 << 32)
}

func main() {
    randomGen := XorshiftStarNew(1234567)
    for i := 0; i < 5; i++ {
        fmt.Println(randomGen.nextInt())
    }

    var counts [5]int
    randomGen.seed(987654321)
    for i := 0; i < 1e5; i++ {
        j := int(math.Floor(randomGen.nextFloat() * 5))
        counts[j]++
    }
    fmt.Println("\nThe counts for 100,000 repetitions are:")
    for i := 0; i < 5; i++ {
        fmt.Printf("  %d : %d\n", i, counts[i])
    }
}


Pythagoras tree

The Pythagoras tree is a fractal tree constructed from squares.  It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.

;Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).

;Related tasks
* Fractal tree

Solution:
package main

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"log"
	"os"
)

const (
	width, height = 800, 600
	maxDepth      = 11                    // how far to recurse, between 1 and 20 is reasonable
	colFactor     = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out
	fileName      = "pythagorasTree.png"
)

func main() {
	img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image
	bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background
	draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src)   // fill the background

	drawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image

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

func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) {
	if depth > maxDepth {
		return
	}
	dx, dy := bx-ax, ay-by
	x3, y3 := bx-dy, by-dx
	x4, y4 := ax-dy, ay-dx
	x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2
	col := color.RGBA{0, uint8(depth) * colFactor, 0, 255}
	drawLine(ax, ay, bx, by, img, col)
	drawLine(bx, by, x3, y3, img, col)
	drawLine(x3, y3, x4, y4, img, col)
	drawLine(x4, y4, ax, ay, img, col)
	drawSquares(x4, y4, x5, y5, img, depth+1)
	drawSquares(x5, y5, x3, y3, img, depth+1)
}

func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, 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
}


Pythagorean quadruples

One form of   '''Pythagorean quadruples'''   is   (for positive integers   '''a''',   '''b''',   '''c''',   and   '''d'''):

::::::::    a2   +   b2   +   c2     =     d2

An example:

::::::::    22   +   32   +   62     =     72

::::: which is:

::::::::    4    +   9    +   36     =     49

;Task:

For positive integers up   '''2,200'''   (inclusive),   for all values of   '''a''',
'''b''',   '''c''',   and   '''d''',
find   (and show here)   those values of   '''d'''   that   ''can't''   be represented.

Show the values of   '''d'''   on one line of output   (optionally with a title).

;Related tasks:
*   [[Euler's sum of powers conjecture]].
*   [[Pythagorean triples]].

;Reference:
:*   the Wikipedia article:   Pythagorean quadruple.

Solution:
package main

import "fmt"

const (
    N = 2200
    N2 = N * N * 2
)

func main() {
    s  := 3
    var s1, s2 int
    var r  [N + 1]bool
    var ab [N2 + 1]bool

    for a := 1; a <= N; a++ {
        a2 := a * a
        for b := a; b <= N; b++ {
            ab[a2 + b * b] = true
        }
    }

    for c := 1; c <= N; c++ {
        s1 = s
        s += 2
        s2 = s
        for d := c + 1; d <= N; d++ {
            if ab[s1] {
                r[d] = true
            }
            s1 += s2
            s2 += 2
        }
    }

    for d := 1; d <= N; d++ {
        if !r[d] {
            fmt.Printf("%d ", d)
        }
    }
    fmt.Println()
}


Pythagorean triples

A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.

They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1.

Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1).

Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.

;Task:
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.

;Extra credit:
Deal with large values.   Can your program handle a maximum perimeter of 1,000,000?   What about 10,000,000?   100,000,000?

Note: the extra credit is not for you to demonstrate how fast your language is compared to others;   you need a proper algorithm to solve them in a timely manner.

;Related tasks:
*   [[Euler's sum of powers conjecture]]
*   [[List comprehensions]]
*   [[Pythagorean quadruples]]

Solution:
package main

import "fmt"

var total, prim, maxPeri int64

func newTri(s0, s1, s2 int64) {
    if p := s0 + s1 + s2; p <= maxPeri {
        prim++
        total += maxPeri / p
        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)
        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)
        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
    }
}

func main() {
    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {
        prim = 0
        total = 0
        newTri(3, 4, 5)
        fmt.Printf("Up to %d:  %d triples, %d primitives\n",
            maxPeri, total, prim)
    }
}


Quaternion type

complex numbers.

A complex number has a real and complex part,   sometimes written as     a + bi,
where     a     and     b     stand for real numbers, and     i     stands for the square root of minus 1.

An example of a complex number might be     -3 + 2i,
where the real part,     a     is     '''-3.0'''     and the complex part,     b     is     '''+2.0'''.

A quaternion has one real part and ''three'' imaginary parts,     i,       j,     and     k.

A quaternion might be written as     a + bi + cj + dk.

In the quaternion numbering system:
:::*     ii = jj = kk = ijk = -1,         or more simply,
:::*     ii  = jj  = kk  = ijk   = -1.

The order of multiplication is important, as, in general, for two quaternions:
::::     q1     and     q2:         q1q2  q2q1.

An example of a quaternion might be     1 +2i +3j +4k

There is a list form of notation where just the numbers are shown and the imaginary multipliers    i,       j,     and     k     are assumed by position.

So the example above would be written as     (1, 2, 3, 4)

;Task:
Given the three quaternions and their components:
    q  = (1, 2, 3, 4) = (a,  b,  c,  d)
    q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
    q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number     r = 7.

Create functions   (or classes)   to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion:    = (-a, -b, -c, -d)
# The conjugate of a quaternion:    = ( a, -b, -c, -d)
# Addition of a real number     r     and a quaternion     q:      r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions:    q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion:    qr = rq = (ar, br, cr, dr)
# Multiplication of two quaternions     q1     and   q2     is given by:    ( a1a2 - b1b2 - c1c2 - d1d2,      a1b2 + b1a2 + c1d2 - d1c2,      a1c2 - b1d2 + c1a2 + d1b2,      a1d2 + b1c2 - c1b2 + d1a2 )
# Show that, for the two quaternions     q1     and     q2:  q1q2  q2q1

If a language has built-in support for quaternions, then use it.

;C.f.:
*   [[Vector products]]
*   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.

Solution:
package main

import (
    "fmt"
    "math"
)

type qtn struct {
    r, i, j, k float64
}

var (
    q  = &qtn{1, 2, 3, 4}
    q1 = &qtn{2, 3, 4, 5}
    q2 = &qtn{3, 4, 5, 6}

    r  float64 = 7
)

func main() {
    fmt.Println("Inputs")
    fmt.Println("q:", q)
    fmt.Println("q1:", q1)
    fmt.Println("q2:", q2)
    fmt.Println("r:", r)

    var qr qtn
    fmt.Println("\nFunctions")
    fmt.Println("q.norm():", q.norm())
    fmt.Println("neg(q):", qr.neg(q))
    fmt.Println("conj(q):", qr.conj(q))
    fmt.Println("addF(q, r):", qr.addF(q, r))
    fmt.Println("addQ(q1, q2):", qr.addQ(q1, q2))
    fmt.Println("mulF(q, r):", qr.mulF(q, r))
    fmt.Println("mulQ(q1, q2):", qr.mulQ(q1, q2))
    fmt.Println("mulQ(q2, q1):", qr.mulQ(q2, q1))
}

func (q *qtn) String() string {
    return fmt.Sprintf("(%g, %g, %g, %g)", q.r, q.i, q.j, q.k)
}

func (q *qtn) norm() float64 {
    return math.Sqrt(q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k)
}

func (z *qtn) neg(q *qtn) *qtn {
    z.r, z.i, z.j, z.k = -q.r, -q.i, -q.j, -q.k
    return z
}

func (z *qtn) conj(q *qtn) *qtn {
    z.r, z.i, z.j, z.k = q.r, -q.i, -q.j, -q.k
    return z
}

func (z *qtn) addF(q *qtn, r float64) *qtn {
    z.r, z.i, z.j, z.k = q.r+r, q.i, q.j, q.k
    return z
}

func (z *qtn) addQ(q1, q2 *qtn) *qtn {
    z.r, z.i, z.j, z.k = q1.r+q2.r, q1.i+q2.i, q1.j+q2.j, q1.k+q2.k
    return z
}

func (z *qtn) mulF(q *qtn, r float64) *qtn {
    z.r, z.i, z.j, z.k = q.r*r, q.i*r, q.j*r, q.k*r
    return z
}

func (z *qtn) mulQ(q1, q2 *qtn) *qtn {
    z.r, z.i, z.j, z.k =
        q1.r*q2.r-q1.i*q2.i-q1.j*q2.j-q1.k*q2.k,
        q1.r*q2.i+q1.i*q2.r+q1.j*q2.k-q1.k*q2.j,
        q1.r*q2.j-q1.i*q2.k+q1.j*q2.r+q1.k*q2.i,
        q1.r*q2.k+q1.i*q2.j-q1.j*q2.i+q1.k*q2.r
    return z
}


Quine

A quine is a self-referential program that can,
without any external access, output its own source.

A   '''quine'''   (named after Willard Van Orman Quine)   is also known as:
::*   ''self-reproducing automata''        (1972)
::*   ''self-replicating program''                             or   ''self-replicating computer program''
::*   ''self-reproducing program''                                  or   ''self-reproducing computer program''
::*   ''self-copying program''                       or   ''self-copying computer program''

It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."

"Source" has one of two meanings. It can refer to the text-based program source.
For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.

The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.

;Task:
Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out.  Empty programs producing no output are not allowed.

There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.
** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.
** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.
* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.
** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.

'''Next to the Quines presented here, many other versions can be found on the Quine page.'''

;Related task:
:*   print itself.

Solution:
package main

import "fmt"

func main() {
	a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n"
	fmt.Printf(a, a)
}


Quoting constructs

Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.

Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format?

This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, '''NOT''' just a link to [See the language docs].

Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.

Solution:
package main

import (
    "fmt"
    "os"
    "regexp"
    "strconv"
)

/* Quoting constructs in Go. */

// In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune'
// but the more familiar term 'character' will be used instead here.

// Character literal (single quotes).
// Can contain any single character including an escaped character.
var (
    rl1 = 'a'
    rl2 = '\'' // single quote can only be included in escaped form
)

// Interpreted string literal (double quotes).
// A sequence of characters including escaped characters.
var (
    is1 = "abc"
    is2 = "\"ab\tc\"" // double quote can only be included in escaped form
)

// Raw string literal(single back quotes).
// Can contain any character including a 'physical' new line but excluding back quote.
// Escaped characters are interpreted literally i.e. `\n` is backslash followed by n.
// Raw strings are typically used for hard-coding pieces of text perhaps
// including single and/or double quotes without the need to escape them.
// They are particularly useful for regular expressions.
var (
    rs1 = `
first"
second'
third"
`
    rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.`
    rs3 = `\d+` // a sequence of one or more digits in a regular expression
)

func main() {
    fmt.Println(rl1, rl2) // prints the code point value not the character itself
    fmt.Println(is1, is2)
    fmt.Println(rs1)
    fmt.Println(rs2)
    re := regexp.MustCompile(rs3)
    fmt.Println(re.FindString("abcd1234efgh"))

    /* None of the above quoting constructs can deal directly with interpolation.
       This is done instead using library functions.
    */

    // C-style using %d, %f, %s etc. within a 'printf' type function.
    n := 3
    fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)

    // Using a function such as fmt.Println which can take a variable
    // number of arguments, of any type, and print then out separated by spaces.
    s := "constructs"
    fmt.Println("There are", n, "quoting", s, "in Go.")

    // Using the function os.Expand which requires a mapper function to fill placeholders
    // denoted by ${...} within a string.
    mapper := func(placeholder string) string {
        switch placeholder {
        case "NUMBER":
            return strconv.Itoa(n)
        case "TYPES":
            return s
        }
        return ""
    }
    fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper))
}


RPG attributes generator

'''RPG'''   =   Role Playing Game.

You're running a tabletop RPG, and your players are creating characters.

Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.

One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.

Some players like to assign values to their attributes in the order they're rolled.

To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:

* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.

However, this can require a lot of manual dice rolling. A programatic solution would be much faster.

;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
# Saves the sum of the 3 largest values.
# Generates a total of 6 values this way.
# Displays the total, and all 6 values once finished.

* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.

Solution:
package main

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

func main() {
    s := rand.NewSource(time.Now().UnixNano())
    r := rand.New(s)
    for {
        var values [6]int
        vsum := 0
        for i := range values {
            var numbers [4]int
            for j := range numbers {
                numbers[j] = 1 + r.Intn(6)
            }
            sort.Ints(numbers[:])
            nsum := 0
            for _, n := range numbers[1:] {
                nsum += n
            }
            values[i] = nsum
            vsum += values[i]
        }
        if vsum < 75 {
            continue
        }
        vcount := 0
        for _, v := range values {
            if v >= 15 {
                vcount++
            }
        }
        if vcount < 2 {
            continue
        }
        fmt.Println("The 6 random numbers generated are:")
        fmt.Println(values)
        fmt.Println("\nTheir sum is", vsum, "and", vcount, "of them are >= 15")
        break
    }
}


Ramer-Douglas-Peucker line simplification

The   '''Ramer-Douglas-Peucker'''   algorithm is a line simplification algorithm for reducing the number of points used to define its shape.

;Task:
Using the   '''Ramer-Douglas-Peucker'''   algorithm, simplify the   2D   line defined by the points:
    (0,0)  (1,0.1)  (2,-0.1)  (3,5)  (4,6)  (5,7)  (6,8.1)  (7,9)  (8,9)  (9,9)

The error threshold to be used is:   '''1.0'''.

Display the remaining points here.

;Reference:
:*   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.

Solution:
package main

import (
    "fmt"
    "math"
)

type point struct{ x, y float64 }

func RDP(l []point, ε float64) []point {
    x := 0
    dMax := -1.
    last := len(l) - 1
    p1 := l[0]
    p2 := l[last]
    x21 := p2.x - p1.x
    y21 := p2.y - p1.y
    for i, p := range l[1:last] {
        if d := math.Abs(y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax {
            x = i + 1
            dMax = d
        }
    }
    if dMax > ε {
        return append(RDP(l[:x+1], ε), RDP(l[x:], ε)[1:]...)
    }
    return []point{l[0], l[len(l)-1]}
}

func main() {
    fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1},
        {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1))
}


Random Latin squares

A Latin square of size n is an arrangement of n symbols  in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.
For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.

;Example n=4 randomised Latin square:
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0

;Task:
# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
# Use the function to generate ''and show here'', two randomly generated squares of size 5.

;Note:
Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.

;Related tasks:
* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]
* [[Latin Squares in reduced form]]

;Reference:
* Wikipedia: Latin square
* OEIS: A002860

Solution:
package main

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

type matrix [][]int

func shuffle(row []int, n int) {
    rand.Shuffle(n, func(i, j int) {
        row[i], row[j] = row[j], row[i]
    })
}

func latinSquare(n int) {
    if n <= 0 {
        fmt.Println("[]\n")
        return
    }
    latin := make(matrix, n)
    for i := 0; i < n; i++ {
        latin[i] = make([]int, n)
        if i == n-1 {
            break
        }
        for j := 0; j < n; j++ {
            latin[i][j] = j
        }
    }
    // first row
    shuffle(latin[0], n)

    // middle row(s)
    for i := 1; i < n-1; i++ {
        shuffled := false
    shuffling:
        for !shuffled {
            shuffle(latin[i], n)
            for k := 0; k < i; k++ {
                for j := 0; j < n; j++ {
                    if latin[k][j] == latin[i][j] {
                        continue shuffling
                    }
                }
            }
            shuffled = true
        }
    }

    // last row
    for j := 0; j < n; j++ {
        used := make([]bool, n)
        for i := 0; i < n-1; i++ {
            used[latin[i][j]] = true
        }
        for k := 0; k < n; k++ {
            if !used[k] {
                latin[n-1][j] = k
                break
            }
        }
    }
    printSquare(latin, n)
}

func printSquare(latin matrix, n int) {
    for i := 0; i < n; i++ {
        fmt.Println(latin[i])
    }
    fmt.Println()
}

func main() {
    rand.Seed(time.Now().UnixNano())
    latinSquare(5)
    latinSquare(5)
    latinSquare(10) // for good measure
}


Random number generator (device)

If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then:

show how to obtain a random 32-bit number from that mechanism.

;Related task
* [[Random_number_generator_(included)]]

Solution:
package main

import (
    "crypto/rand"
    "encoding/binary"
    "fmt"
    "io"
    "os"
)

func main() {
    testRandom("crypto/rand", rand.Reader)
    testRandom("dev/random", newDevRandom())
}

func newDevRandom() (f *os.File) {
    var err error
    if f, err = os.Open("/dev/random"); err != nil {
        panic(err)
    }
    return
}

func testRandom(label string, src io.Reader) {
    fmt.Printf("%s:\n", label)
    var r int32
    for i := 0; i < 10; i++ {
        if err := binary.Read(src, binary.LittleEndian, &r); err != nil {
            panic(err)
        }
        fmt.Print(r, " ")
    }
    fmt.Println()
}


Random number generator (included)

The task is to:
: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
: If possible, give a link to a wider explanation of the algorithm used.

Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.

The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits.

Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.

Solution:
Go has two random number packages in the standard library and another package in the "subrepository."

# [https://golang.org/pkg/math/rand/ math/rand] in the standard library provides general purpose random number support, implementing some sort of feedback shift register.  (It uses a large array commented "feeback register" and has variables named "tap" and "feed.")  Comments in the code attribute the algorithm to DP Mitchell and JA Reeds.  A little more insight is in [https://github.com/golang/go/issues/21835 this issue] in the Go issue tracker.
# [https://golang.org/pkg/crypto/rand/ crypto/rand], also in the standard library, says it "implements a cryptographically secure pseudorandom number generator."  I think though it should say that it ''accesses'' a cryptographically secure pseudorandom number generator.  It uses <tt>/dev/urandom</tt> on Unix-like systems and the CryptGenRandom API on Windows.
# [https://godoc.org/golang.org/x/exp/rand x/exp/rand] implements the Permuted Congruential Generator which is also described in the issue linked above.


Range consolidation

Define a range of numbers   '''R''',   with bounds   '''b0'''   and   '''b1'''   covering all numbers ''between and including both bounds''.

That range can be shown as:
::::::::: '''[b0, b1]'''
::::::::    or equally as:
::::::::: '''[b1, b0]'''

Given two ranges, the act of consolidation between them compares the two ranges:
*   If one range covers all of the other then the result is that encompassing range.
*   If the ranges touch or intersect then the result is   ''one''   new single range covering the overlapping ranges.
*   Otherwise the act of consolidation is to return the two non-touching ranges.

Given   '''N'''   ranges where   '''N > 2'''   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible.

If   '''N < 2'''   then range consolidation has no strict meaning and the input can be returned.

;Example 1:
:   Given the two ranges   '''[1, 2.5]'''   and   '''[3, 4.2]'''   then
:   there is no common region between the ranges and the result is the same as the input.

;Example 2:
:   Given the two ranges   '''[1, 2.5]'''   and   '''[1.8, 4.7]'''   then
:   there is :   an overlap   '''[2.5, 1.8]'''   between the ranges and
:   the result is the single range   '''[1, 4.7]'''.
:   Note that order of bounds in a range is not (yet) stated.

;Example 3:
:   Given the two ranges   '''[6.1, 7.2]'''   and   '''[7.2, 8.3]'''   then
:   they touch at   '''7.2'''   and
:   the result is the single range   '''[6.1, 8.3]'''.

;Example 4:
:   Given the three ranges   '''[1, 2]'''   and   '''[4, 8]'''   and   '''[2, 5]'''
:   then there is no intersection of the ranges   '''[1, 2]'''   and   '''[4, 8]'''
:   but the ranges   '''[1, 2]'''   and   '''[2, 5]'''   overlap and
:   consolidate to produce the range   '''[1, 5]'''.
:   This range, in turn, overlaps the other range   '''[4, 8]''',   and
:   so consolidates to the final output of the single range   '''[1, 8]'''.

;Task:
Let a normalized range display show the smaller bound to the left;   and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.

Output the ''normalized'' result of applying consolidation to these five sets of ranges:
            [1.1, 2.2]
            [6.1, 7.2], [7.2, 8.3]
            [4, 3], [2, 1]
            [4, 3], [2, 1], [-1, -2], [3.9, 10]
            [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.

;See also:
* [[Set consolidation]]
* [[Set of real numbers]]

Solution:
package main

import (
    "fmt"
    "math"
    "sort"
)

type Range struct{ Lower, Upper float64 }

func (r Range) Norm() Range {
    if r.Lower > r.Upper {
        return Range{r.Upper, r.Lower}
    }
    return r
}

func (r Range) String() string {
    return fmt.Sprintf("[%g, %g]", r.Lower, r.Upper)
}

func (r1 Range) Union(r2 Range) []Range {
    if r1.Upper < r2.Lower {
        return []Range{r1, r2}
    }
    r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)}
    return []Range{r}
}

func consolidate(rs []Range) []Range {
    for i := range rs {
        rs[i] = rs[i].Norm()
    }
    le := len(rs)
    if le < 2 {
        return rs
    }
    sort.Slice(rs, func(i, j int) bool {
        return rs[i].Lower < rs[j].Lower
    })
    if le == 2 {
        return rs[0].Union(rs[1])
    }
    for i := 0; i < le-1; i++ {
        for j := i + 1; j < le; j++ {
            ru := rs[i].Union(rs[j])
            if len(ru) == 1 {
                rs[i] = ru[0]
                copy(rs[j:], rs[j+1:])
                rs = rs[:le-1]
                le--
                i--
                break
            }
        }
    }
    return rs
}

func main() {
    rss := [][]Range{
        {{1.1, 2.2}},
        {{6.1, 7.2}, {7.2, 8.3}},
        {{4, 3}, {2, 1}},
        {{4, 3}, {2, 1}, {-1, -2}, {3.9, 10}},
        {{1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6}},
    }
    for _, rs := range rss {
        s := fmt.Sprintf("%v", rs)
        fmt.Printf("%40s => ", s[1:len(s)-1])
        rs2 := consolidate(rs)
        s = fmt.Sprintf("%v", rs2)
        fmt.Println(s[1 : len(s)-1])
    }
}


Range expansion

{{:Range extraction/Format}}

;Task:
Expand the range description:
   -6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.

;Related task:
*   [[Range extraction]]

Solution:
package main

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

const input = "-6,-3--1,3-5,7-11,14,15,17-20"

func main() {
    fmt.Println("range:", input)
    var r []int
    var last int
    for _, part := range strings.Split(input, ",") {
        if i := strings.Index(part[1:], "-"); i == -1 {
            n, err := strconv.Atoi(part)
            if err != nil {
                fmt.Println(err)
                return
            }
            if len(r) > 0 {
                if last == n {
                    fmt.Println("duplicate value:", n)
                    return
                } else if last > n {
                    fmt.Println("values not ordered:", last, ">", n)
                    return
                }
            }
            r = append(r, n)
            last = n
        } else {
            n1, err := strconv.Atoi(part[:i+1])
            if err != nil {
                fmt.Println(err)
                return
            }
            n2, err := strconv.Atoi(part[i+2:])
            if err != nil {
                fmt.Println(err)
                return
            }
            if n2 < n1+2 {
                fmt.Println("invalid range:", part)
                return
            }
            if len(r) > 0 {
                if last == n1 {
                    fmt.Println("duplicate value:", n1)
                    return
                } else if last > n1 {
                    fmt.Println("values not ordered:", last, ">", n1)
                    return
                }
            }
            for i = n1; i <= n2; i++ {
                r = append(r, i)
            }
            last = n2
        }
    }
    fmt.Println("expanded:", r)
}


Range extraction

{{:Range extraction/Format}}

;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).

     0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
    25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
    37, 38, 39
* Show the output of your program.

;Related task:
*   [[Range expansion]]

Solution:
package main

import (
    "errors"
    "fmt"
    "strconv"
    "strings"
)

func main() {
    rf, err := rangeFormat([]int{
        0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
        25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
        37, 38, 39,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("range format:", rf)
}

func rangeFormat(a []int) (string, error) {
    if len(a) == 0 {
        return "", nil
    }
    var parts []string
    for n1 := 0; ; {
        n2 := n1 + 1
        for n2 < len(a) && a[n2] == a[n2-1]+1 {
            n2++
        }
        s := strconv.Itoa(a[n1])
        if n2 == n1+2 {
            s += "," + strconv.Itoa(a[n2-1])
        } else if n2 > n1+2 {
            s += "-" + strconv.Itoa(a[n2-1])
        }
        parts = append(parts, s)
        if n2 == len(a) {
            break
        }
        if a[n2] == a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence repeats value %d", a[n2]))
        }
        if a[n2] < a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence not ordered: %d < %d", a[n2], a[n2-1]))
        }
        n1 = n2
    }
    return strings.Join(parts, ","), nil
}


Rate counter

Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.

Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:

* Run N seconds worth of jobs and/or Y jobs.
* Report at least three distinct times.

Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.

'''See also:''' [[System time]], [[Time a function]]

Solution:
package main

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

// representation of time.Time is nanosecond, actual resolution system specific
type rateStateS struct {
    lastFlush time.Time
    period    time.Duration
    tickCount int
}

func ticRate(pRate *rateStateS) {
    pRate.tickCount++
    now := time.Now()
    if now.Sub(pRate.lastFlush) >= pRate.period {
        // TPS Report
        tps := 0.
        if pRate.tickCount > 0 {
            tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds()
        }
        fmt.Println(tps, "tics per second.")

        // Reset
        pRate.tickCount = 0
        pRate.lastFlush = now
    }
}

func somethingWeDo() {
    time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) // sleep about .1 second.
}

func main() {
    start := time.Now()

    rateWatch := rateStateS{
        lastFlush: start,
        period:    5 * time.Second,
    }

    // Loop for twenty seconds
    latest := start
    for latest.Sub(start) < 20*time.Second {
        somethingWeDo()
        ticRate(&rateWatch)
        latest = time.Now()
    }
}


Read a specific line from a file

Some languages have special semantics for obtaining a known line number from a file.

;Task:
Demonstrate how to obtain the contents of a specific line within a file.

For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (for potential future use within the program if the code were to become embedded).

If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message.

If no special semantics are available for obtaining the required line,   it is permissible to read line by line.

Note that empty lines are considered and should still be counted.

Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.

Solution:
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
)

func main() {
	if line, err := rsl("input.txt", 7); err == nil {
		fmt.Println("7th line:")
		fmt.Println(line)
	} else {
		fmt.Println("rsl:", err)
	}
}

func rsl(fn string, n int) (string, error) {
	if n < 1 {
		return "", fmt.Errorf("invalid request: line %d", n)
	}
	f, err := os.Open(fn)
	if err != nil {
		return "", err
	}
	defer f.Close()
	bf := bufio.NewReader(f)
	var line string
	for lnum := 0; lnum < n; lnum++ {
		line, err = bf.ReadString('\n')
		if err == io.EOF {
			switch lnum {
			case 0:
				return "", errors.New("no lines in file")
			case 1:
				return "", errors.New("only 1 line")
			default:
				return "", fmt.Errorf("only %d lines", lnum)
			}
		}
		if err != nil {
			return "", err
		}
	}
	if line == "" {
		return "", fmt.Errorf("line %d empty", n)
	}
	return line, nil
}


Recaman's sequence

The '''Recaman's sequence''' generates Natural numbers.

Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.

If the conditions ''don't'' hold then a(n) = a(n-1) + n.

;Task:
# Generate and show here the first 15 members of the sequence.
# Find and show here, the first duplicated number in the sequence.
# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.

;References:
* A005132,  The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recaman Sequence, Numberphile video.
* Recaman's sequence, on Wikipedia.

Solution:
package main

import "fmt"

func main() {
    a := []int{0}
    used := make(map[int]bool, 1001)
    used[0] = true
    used1000 := make(map[int]bool, 1001)
    used1000[0] = true
    for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ {
        next := a[n-1] - n
        if next < 1 || used[next] {
            next += 2 * n
        }
        alreadyUsed := used[next]
        a = append(a, next)

        if !alreadyUsed {
            used[next] = true
            if next >= 0 && next <= 1000 {
                used1000[next] = true
            }
        }

        if n == 14 {
            fmt.Println("The first 15 terms of the Recaman's sequence are:", a)
        }

        if !foundDup && alreadyUsed {
            fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next)
            foundDup = true
        }

        if len(used1000) == 1001 {
            fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n)
        }
    }
}


Remove lines from a file

Remove a specific line or a number of lines from a file.

This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).

For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2

Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.

An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.

Solution:
package main

import (
    "bytes"
    "errors"
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    if err := removeLines("foobar.txt", 1, 2); err != nil {
        fmt.Println(err)
    }
}

func removeLines(fn string, start, n int) (err error) {
    if start < 1 {
        return errors.New("invalid request.  line numbers start at 1.")
    }
    if n < 0 {
        return errors.New("invalid request.  negative number to remove.")
    }
    var f *os.File
    if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
        return
    }
    defer func() {
        if cErr := f.Close(); err == nil {
            err = cErr
        }
    }()
    var b []byte
    if b, err = ioutil.ReadAll(f); err != nil {
        return
    }
    cut, ok := skip(b, start-1)
    if !ok {
        return fmt.Errorf("less than %d lines", start)
    }
    if n == 0 {
        return nil
    }
    tail, ok := skip(cut, n)
    if !ok {
        return fmt.Errorf("less than %d lines after line %d", n, start)
    }
    t := int64(len(b) - len(cut))
    if err = f.Truncate(t); err != nil {
        return
    }
    if len(tail) > 0 {
        _, err = f.WriteAt(tail, t)
    }
    return
}

func skip(b []byte, n int) ([]byte, bool) {
    for ; n > 0; n-- {
        if len(b) == 0 {
            return nil, false
        }
        x := bytes.IndexByte(b, '\n')
        if x < 0 {
            x = len(b)
        } else {
            x++
        }
        b = b[x:]
    }
    return b, true
}


Rep-string

Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.

For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.

Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.

;Task:
* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string.   (Either the string that is repeated, or the number of repeated characters would suffice).
* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.
* Use the function to indicate the repeating substring if any, in the following:

1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1

* Show your output on this page.

Solution:
package main

import (
    "fmt"
    "strings"
)

func rep(s string) int {
    for x := len(s) / 2; x > 0; x-- {
        if strings.HasPrefix(s, s[x:]) {
            return x
        }
    }
    return 0
}

const m = `
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1`

func main() {
    for _, s := range strings.Fields(m) {
        if n := rep(s); n > 0 {
            fmt.Printf("%q  %d rep-string %q\n", s, n, s[:n])
        } else {
            fmt.Printf("%q  not a rep-string\n", s)
        }
    }
}


Repeat

Write a procedure which accepts as arguments another procedure and a positive integer.

The latter procedure is executed a number of times equal to the accepted integer.

Solution:
package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}


Resistor mesh

Given    10x10    grid nodes   (as shown in the image)   interconnected by    1O    resistors as shown,
find the resistance between points   '''A'''   and   '''B'''.

;See also:
*   (humor, nerd sniping)   xkcd.com cartoon (you can solve that for extra credits)
*   An article on how to calculate this and an implementation in Mathematica

Solution:
package main

import "fmt"

const (
	S = 10
)

type node struct {
	v     float64
	fixed int
}

func alloc2(w, h int) [][]node {
	a := make([][]node, h)

	for i := range a {
		a[i] = make([]node, w)
	}
	return a
}

func set_boundary(m [][]node) {
	m[1][1].fixed = 1
	m[1][1].v = 1
	m[6][7].fixed = -1
	m[6][7].v = -1
}

func calc_diff(m [][]node, d [][]node, w, h int) float64 {
	total := 0.0
	for i := 0; i < h; i++ {
		for j := 0; j < w; j++ {
			v := 0.0
			n := 0
			if i != 0 {
				v += m[i-1][j].v
				n++
			}
			if j != 0 {
				v += m[i][j-1].v
				n++
			}
			if i+1 < h {
				v += m[i+1][j].v
				n++
			}
			if j+1 < w {
				v += m[i][j+1].v
				n++
			}

			v = m[i][j].v - v/float64(n)
			d[i][j].v = v
			if m[i][j].fixed == 0 {
				total += v * v
			}
		}
	}
	return total
}

func iter(m [][]node, w, h int) float64 {
	d := alloc2(w, h)
	diff := 1.0e10
	cur := []float64{0, 0, 0}

	for diff > 1e-24 {
		set_boundary(m)
		diff = calc_diff(m, d, w, h)
		for i := 0; i < h; i++ {
			for j := 0; j < w; j++ {
				m[i][j].v -= d[i][j].v
			}
		}
	}

	for i := 0; i < h; i++ {
		for j := 0; j < w; j++ {
			t := 0
			if i != 0 {
				t += 1
			}
			if j != 0 {
				t += 1
			}
			if i < h-1 {
				t += 1
			}
			if j < w-1 {
				t += 1
			}
			cur[m[i][j].fixed+1] += d[i][j].v * float64(t)
		}
	}
	return (cur[2] - cur[0]) / 2
}

func main() {
	mesh := alloc2(S, S)
	fmt.Printf("R = %g\n", 2/iter(mesh, S, S))
}


Reverse words in a string

Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified.

;Example:
Hey you, Bub!    would be shown reversed as:    Bub! you, Hey

Tokens are any non-space characters separated by spaces (formally, white-space);   the visible punctuation form part of the word within which it is located and should not be modified.

You may assume that there are no significant non-visible characters in the input.   Multiple or superfluous spaces may be compressed into a single space.

Some strings have no tokens, so an empty string   (or one just containing spaces)   would be the result.

'''Display''' the strings in order   (1st, 2nd, 3rd, ***),   and one string per line.

(You can consider the ten strings as ten lines, and the tokens as words.)

;Input data

             (ten lines within the box)
 line
     +----------------------------------------+
   1 |  ---------- Ice and Fire ------------  |
   2 |                                        |  <--- a blank line here.
   3 |  fire, in end will world the say Some  |
   4 |  ice. in say Some                      |
   5 |  desire of tasted I've what From       |
   6 |  fire. favor who those with hold I     |
   7 |                                        |  <--- a blank line here.
   8 |  ... elided paragraph last ...         |
   9 |                                        |  <--- a blank line here.
  10 |  Frost Robert -----------------------  |
     +----------------------------------------+

;Cf.
* [[Phrase reversals]]

Solution:
package main

import (
    "fmt"
    "strings"
)

// a number of strings
var n = []string{
    "---------- Ice and Fire ------------",
    "                                    ",
    "fire, in end will world the say Some",
    "ice. in say Some                    ",
    "desire of tasted I've what From     ",
    "fire. favor who those with hold I   ",
    "                                    ",
    "... elided paragraph last ...       ",
    "                                    ",
    "Frost Robert -----------------------",
}

func main() {
    for i, s := range n {
        t := strings.Fields(s) // tokenize
        // reverse
        last := len(t) - 1
        for j, k := range t[:len(t)/2] {
            t[j], t[last-j] = t[last-j], k
        }
        n[i] = strings.Join(t, " ")
    }
    // display result
    for _, t := range n {
        fmt.Println(t)
    }
}


Roman numerals/Decode

Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.

You don't need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s   (zeroes).

'''1990''' is rendered as   '''MCMXC'''     (1000 = M,   900 = CM,   90 = XC)     and
'''2008''' is rendered as   '''MMVIII'''       (2000 = MM,   8 = VIII).

The Roman numeral for '''1666''',   '''MDCLXVI''',   uses each letter in descending order.

Solution:
package main

import (
    "errors"
    "fmt"
)

var m = map[rune]int{
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
}

func parseRoman(s string) (r int, err error) {
    if s == "" {
        return 0, errors.New("Empty string")
    }
    is := []rune(s) // easier to convert string up front
    var c0 rune     // c0: roman character last read
    var cv0 int     // cv0: value of cv

    // the key to the algorithm is to process digits from right to left
    for i := len(is) - 1; i >= 0; i-- {
        // read roman digit
        c := is[i]
        k := c == '\u0305' // unicode overbar combining character
        if k {
            if i == 0 {
                return 0, errors.New(
                    "Overbar combining character invalid at position 0")
            }
            i--
            c = is[i]
        }
        cv := m[c]
        if cv == 0 {
            if c == 0x0305 {
                return 0, fmt.Errorf(
                    "Overbar combining character invalid at position %d", i)
            } else {
                return 0, fmt.Errorf(
                    "Character unrecognized as Roman digit: %c", c)
            }
        }
        if k {
            c = -c // convention indicating overbar
            cv *= 1000
        }

        // handle cases of new, same, subtractive, changed, in that order.
        switch {
        default: // case 4: digit change
            fallthrough
        case c0 == 0: // case 1: no previous digit
            c0 = c
            cv0 = cv
        case c == c0: // case 2: same digit
        case cv*5 == cv0 || cv*10 == cv0: // case 3: subtractive
            // handle next digit as new.
            // a subtractive digit doesn't count as a previous digit.
            c0 = 0
            r -= cv  // subtract...
            continue // ...instead of adding
        }
        r += cv // add, in all cases except subtractive
    }
    return r, nil
}

func main() {
    // parse three numbers mentioned in task description
    for _, r := range []string{"MCMXC", "MMVIII", "MDCLXVI"} {
        v, err := parseRoman(r)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println(r, "==", v)
        }
    }
}


Roman numerals/Encode

Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.

In Roman numerals:
* 1990  is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008  is written as 2000=MM, 8=VIII; or MMVIII
* 1666  uses each Roman symbol in descending order: MDCLXVI

Solution:
package main

import "fmt"

var (
    m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
    m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
    m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
    m3 = []string{"", "M", "MM", "MMM", "I̅V̅",
        "V̅", "V̅I̅", "V̅I̅I̅", "V̅I̅I̅I̅", "I̅X̅"}
    m4 = []string{"", "X̅", "X̅X̅", "X̅X̅X̅", "X̅L̅",
        "L̅", "L̅X̅", "L̅X̅X̅", "L̅X̅X̅X̅", "X̅C̅"}
    m5 = []string{"", "C̅", "C̅C̅", "C̅C̅C̅", "C̅D̅",
        "D̅", "D̅C̅", "D̅C̅C̅", "D̅C̅C̅C̅", "C̅M̅"}
    m6 = []string{"", "M̅", "M̅M̅", "M̅M̅M̅"}
)

func formatRoman(n int) (string, bool) {
    if n < 1 || n >= 4e6 {
        return "", false
    }
    // this is efficient in Go.  the seven operands are evaluated,
    // then a single allocation is made of the exact size needed for the result.
    return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +
        m2[n%1e3/1e2] + m1[n%100/10] + m0[n%10],
        true
}

func main() {
    // show three numbers mentioned in task descriptions
    for _, n := range []int{1990, 2008, 1666} {
        r, ok := formatRoman(n)
        if ok {
            fmt.Println(n, "==", r)
        } else {
            fmt.Println(n, "not representable")
        }
    }
}


Rosetta Code/Rank languages by number of users

Sort most popular programming languages based on the number of users on Rosetta Code.

Show the languages with at least 100 users.

;A method to solve the task:
Users of a computer programming language   '''X'''   are those referenced in the page:
  https://rosettacode.org/wiki/Category:X_User,     or preferably:
  https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions.

In order to find the list of such categories,   it's possible to first parse the entries of:
  http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000.

Then download and parse each computer language   ''users''   category to find the number of users of that computer language.

Sample output on 18 February 2019:
Language             Users
--------------------------
C                      391
Java                   276
C++                    275
Python                 262
JavaScript             238
Perl                   171
PHP                    167
SQL                    138
UNIX Shell             131
BASIC                  120
C sharp                118
Pascal                 116
Haskell                102

A Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page.

Solution:
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "regexp"
    "sort"
    "strconv"
)

type Result struct {
    lang  string
    users int
}

func main() {
    const minimum = 25
    ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
    re := regexp.MustCompile(ex)
    page := "http://rosettacode.org/mw/api.php?"
    action := "action=query"
    format := "format=json"
    fversion := "formatversion=2"
    generator := "generator=categorymembers"
    gcmTitle := "gcmtitle=Category:Language%20users"
    gcmLimit := "gcmlimit=500"
    prop := "prop=categoryinfo"
    rawContinue := "rawcontinue="
    page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
        generator, gcmTitle, gcmLimit, prop, rawContinue)
    resp, _ := http.Get(page)
    body, _ := ioutil.ReadAll(resp.Body)
    matches := re.FindAllStringSubmatch(string(body), -1)
    resp.Body.Close()
    var results []Result
    for _, match := range matches {
        if len(match) == 5 {
            users, _ := strconv.Atoi(match[4])
            if users >= minimum {
                result := Result{match[1], users}
                results = append(results, result)
            }
        }
    }
    sort.Slice(results, func(i, j int) bool {
        return results[j].users < results[i].users
    })

    fmt.Println("Rank  Users  Language")
    fmt.Println("----  -----  --------")
    rank := 0
    lastUsers := 0
    lastRank := 0
    for i, result := range results {
        eq := " "
        rank = i + 1
        if lastUsers == result.users {
            eq = "="
            rank = lastRank
        } else {
            lastUsers = result.users
            lastRank = rank
        }
        fmt.Printf(" %-2d%s   %3d    %s\n", rank, eq, result.users, result.lang)
    }
}


Runtime evaluation

Demonstrate a language's ability for programs to execute code written in the language provided at runtime.

Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.

You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.

For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].

Solution:
package main
import (
	"fmt"
	"bitbucket.org/binet/go-eval/pkg/eval"
	"go/token"
)

func main() {
	w := eval.NewWorld();
	fset := token.NewFileSet();

	code, err := w.Compile(fset, "1 + 2")
	if err != nil {
		fmt.Println("Compile error");
		return
	}

	val, err := code.Run();
	if err != nil {
		fmt.Println("Run time error");
		return;
	}
	fmt.Println("Return value:", val) //prints, well, 3

}


Runtime evaluation/In an environment

Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.

Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable

or note that these are impossible.

;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.

Solution:
package main

import (
    "bitbucket.org/binet/go-eval/pkg/eval"
    "fmt"
    "go/parser"
    "go/token"
)

func main() {
    // an expression on x
    squareExpr := "x*x"

    // parse to abstract syntax tree
    fset := token.NewFileSet()
    squareAst, err := parser.ParseExpr(squareExpr)
    if err != nil {
        fmt.Println(err)
        return
    }
    // create an environment or "world"
    w := eval.NewWorld()

    // allocate a variable
    wVar := new(intV)

    // bind the variable to the name x
    err = w.DefineVar("x", eval.IntType, wVar)
    if err != nil {
        fmt.Println(err)
        return
    }
    // bind the expression AST to the world
    squareCode, err := w.CompileExpr(fset, squareAst)
    if err != nil {
        fmt.Println(err)
        return
    }
    // directly manipulate value of variable within world
    *wVar = 5
    // evaluate
    r0, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    // change value
    *wVar--
    // revaluate
    r1, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    // print difference
    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}

// int value implementation.
type intV int64

func (v *intV) String() string              { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64      { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
    *v = intV(o.(eval.IntValue).Get(t))
}


SHA-1

'''SHA-1''' or '''SHA1''' is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.

A US government standard, FIPS 180-1, defines SHA-1.

Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.

{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}

Solution:
package main

import (
    "crypto/sha1"
    "fmt"
)

func main() {
    h := sha1.New()
    h.Write([]byte("Rosetta Code"))
    fmt.Printf("%x\n", h.Sum(nil))
}


Sailors, coconuts and a monkey problem

Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.

That night the first sailor wakes up and decides to take his first share early  so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.

To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.

In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)

;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)
# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
# Show your answers here.

;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.

;Note:
* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!

;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).

Solution:
package main

import "fmt"

func main() {
    coconuts := 11
outer:
    for ns := 2; ns < 10; ns++ {
        hidden := make([]int, ns)
        coconuts = (coconuts/ns)*ns + 1
        for {
            nc := coconuts
            for s := 1; s <= ns; s++ {
                if nc%ns == 1 {
                    hidden[s-1] = nc / ns
                    nc -= hidden[s-1] + 1
                    if s == ns && nc%ns == 0 {
                        fmt.Println(ns, "sailors require a minimum of", coconuts, "coconuts")
                        for t := 1; t <= ns; t++ {
                            fmt.Println("\tSailor", t, "hides", hidden[t-1])
                        }
                        fmt.Println("\tThe monkey gets", ns)
                        fmt.Println("\tFinally, each sailor takes", nc/ns, "\b\n")
                        continue outer
                    }
                } else {
                    break
                }
            }
            coconuts += ns
        }
    }
}


Same fringe

Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right.  The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.

Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one.  In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first).  Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.

Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).

Solution:
package main

import "fmt"

type node struct {
    int
    left, right *node
}

// function returns a channel that yields the leaves of the tree.
// the channel is closed after all leaves are received.
func leaves(t *node) chan int {
    ch := make(chan int)
    // recursive function to walk tree.
    var f func(*node)
    f = func(n *node) {
        if n == nil {
            return
        }
        // leaves are identified by having no children.
        if n.left == nil && n.right == nil {
            ch <- n.int
        } else {
            f(n.left)
            f(n.right)
        }
    }
    // goroutine runs concurrently with others.
    // it walks the tree then closes the channel.
    go func() {
        f(t)
        close(ch)
    }()
    return ch
}

func sameFringe(t1, t2 *node) bool {
    f1 := leaves(t1)
    f2 := leaves(t2)
    for l1 := range f1 {
        // both trees must yield a leaf, and the leaves must be equal.
        if l2, ok := <-f2; !ok || l1 != l2 {
            return false
        }
    }
    // there must be nothing left in f2 after consuming all of f1.
    _, ok := <-f2
    return !ok
}

func main() {
    // the different shapes of the trees is shown with indention.
    // the leaves are easy to spot by the int: key.
    t1 := &node{3,
        &node{1,
            &node{int: 1},
            &node{int: 2}},
        &node{8,
            &node{int: 5},
            &node{int: 13}}}
    // t2 with negative values for internal nodes that can't possibly match
    // positive values in t1, just to show that only leaves are being compared.
    t2 := &node{-8,
        &node{-3,
            &node{-1,
                &node{int: 1},
                &node{int: 2}},
            &node{int: 5}},
        &node{int: 13}}
    fmt.Println(sameFringe(t1, t2)) // prints true.
}


Selectively replace multiple instances of a character within a string

Task
This is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.

Given the string: "abracadabra", replace programatically:

* the first 'a' with 'A'
* the second 'a' with 'B'
* the fourth 'a' with 'C'
* the fifth 'a' with 'D'
* the first 'b' with 'E'
* the second 'r' with 'F'

Note that there is no replacement for the third 'a', second 'b' or first 'r'.

The answer should, of course, be : "AErBcadCbFD".

Solution:
package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "abracadabra"
    ss := []byte(s)
    var ixs []int
    for ix, c := range s {
        if c == 'a' {
            ixs = append(ixs, ix)
        }
    }
    repl := "ABaCD"
    for i := 0; i < 5; i++ {
        ss[ixs[i]] = repl[i]
    }
    s = string(ss)
    s = strings.Replace(s, "b", "E", 1)
    s = strings.Replace(s, "r", "F", 2)
    s = strings.Replace(s, "F", "r", 1)
    fmt.Println(s)
}


Self-describing numbers

{{task}}There are several so-called "self-describing" or "self-descriptive" integers.

An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.

For example,   '''2020'''   is a four-digit self describing number:

*   position   0   has value   2   and there are two 0s in the number;
*   position   1   has value   0   and there are no 1s in the number;
*   position   2   has value   2   and there are two 2s;
*   position   3   has value   0   and there are zero 3s.

Self-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000.

;Task Description
# Write a function/routine/method/... that will check whether a given positive integer is self-describing.
# As an optional stretch goal - generate and display the set of self-describing numbers.

;Related tasks:
*   [[Fours is the number of letters in the ...]]
*   [[Look-and-say sequence]]
*   [[Number names]]
*   [[Self-referential sequence]]
*   [[Spelling of ordinal numbers]]

Solution:
package main

import (
    "fmt"
    "strconv"
    "strings"
    "time"
)

func selfDesc(n uint64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatUint(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}

func main() {
    start := time.Now()
    fmt.Println("The self-describing numbers are:")
    i := uint64(10)   // self-describing number must end in 0
    pw := uint64(10)  // power of 10
    fd := uint64(1)   // first digit
    sd := uint64(1)   // second digit
    dg := uint64(2)   // number of digits
    mx := uint64(11)  // maximum for current batch
    lim := uint64(9_100_000_001) // sum of digits can't be more than 10
    for i < lim {
        if selfDesc(i) {
            secs := time.Since(start).Seconds()
            fmt.Printf("%d (in %.1f secs)\n", i, secs)
        }
        i += 10
        if i > mx {
            fd++
            sd--
            if sd >= 0 {
                i = fd * pw
            } else {
                pw *= 10
                dg++
                i = pw
                fd = 1
                sd = dg - 1
            }
            mx = i + sd*pw/10
        }
    }
    osecs := time.Since(start).Seconds()
    fmt.Printf("\nTook %.1f secs overall\n", osecs)
}


Self numbers

A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.

The task is:
  Display the first 50 self numbers;
  I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.

224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.

;See also:

;*OEIS: A003052 - Self numbers or Colombian numbers
;*Wikipedia: Self numbers

Solution:
package main

import (
    "fmt"
    "time"
)

func sumDigits(n int) int {
    sum := 0
    for n > 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

func main() {
    st := time.Now()
    count := 0
    var selfs []int
    i := 1
    pow := 10
    digits := 1
    offset := 9
    lastSelf := 0
    for count < 1e8 {
        isSelf := true
        start := max(i-offset, 0)
        sum := sumDigits(start)
        for j := start; j < i; j++ {
            if j+sum == i {
                isSelf = false
                break
            }
            if (j+1)%10 != 0 {
                sum++
            } else {
                sum = sumDigits(j + 1)
            }
        }
        if isSelf {
            count++
            lastSelf = i
            if count <= 50 {
                selfs = append(selfs, i)
                if count == 50 {
                    fmt.Println("The first 50 self numbers are:")
                    fmt.Println(selfs)
                }
            }
        }
        i++
        if i%pow == 0 {
            pow *= 10
            digits++
            offset = digits * 9
        }
    }
    fmt.Println("\nThe 100 millionth self number is", lastSelf)
    fmt.Println("Took", time.Since(st))
}


Self numbers

Solution:
package main

import (
    "fmt"
    "time"
)

const MAX_COUNT = 103*1e4*1e4 + 11*9 + 1

var sv = make([]bool, MAX_COUNT+1)
var digitSum = make([]int, 1e4)

func init() {
    i := 9999
    var s, t int
    for a := 9; a >= 0; a-- {
        for b := 9; b >= 0; b-- {
            s = a + b
            for c := 9; c >= 0; c-- {
                t = s + c
                for d := 9; d >= 0; d-- {
                    digitSum[i] = t + d
                    i--
                }
            }
        }
    }
}

func sieve() {
    n := 0
    for a := 0; a < 103; a++ {
        for b := 0; b < 1e4; b++ {
            s := digitSum[a] + digitSum[b] + n
            for c := 0; c < 1e4; c++ {
                sv[digitSum[c]+s] = true
                s++
            }
            n += 1e4
        }
    }
}

func main() {
    st := time.Now()
    sieve()
    fmt.Println("Sieving took", time.Since(st))
    count := 0
    fmt.Println("\nThe first 50 self numbers are:")
    for i := 0; i < len(sv); i++ {
        if !sv[i] {
            count++
            if count <= 50 {
                fmt.Printf("%d ", i)
            } else {
                fmt.Println("\n\n     Index  Self number")
                break
            }
        }
    }
    count = 0
    limit := 1
    for i := 0; i < len(sv); i++ {
        if !sv[i] {
            count++
            if count == limit {
                fmt.Printf("%10d  %11d\n", count, i)
                limit *= 10
                if limit == 1e10 {
                    break
                }
            }
        }
    }
    fmt.Println("\nOverall took", time.Since(st))
}


Semordnilap

A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.

Example: ''lager'' and ''regal''

;Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)

Solution:
package main

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

func main() {
    // read file into memory as one big block
    data, err := ioutil.ReadFile("unixdict.txt")
    if err != nil {
        log.Fatal(err)
    }
    // copy the block, split it up into words
    words := strings.Split(string(data), "\n")
    // optional, free the first block for garbage collection
    data = nil
    // put words in a map, also determine length of longest word
    m := make(map[string]bool)
    longest := 0
    for _, w := range words {
        m[string(w)] = true
        if len(w) > longest {
            longest = len(w)
        }
    }
    // allocate a buffer for reversing words
    r := make([]byte, longest)
    // iterate over word list
    sem := 0
    var five []string
    for _, w := range words {
        // first, delete from map.  this prevents a palindrome from matching
        // itself, and also prevents it's reversal from matching later.
        delete(m, w)
        // use buffer to reverse word
        last := len(w) - 1
        for i := 0; i < len(w); i++ {
            r[i] = w[last-i]
        }
        rs := string(r[:len(w)])
        // see if reversed word is in map, accumulate results
        if m[rs] {
            sem++
            if len(five) < 5 {
                five = append(five, w+"/"+rs)
            }
        }
    }
    // print results
    fmt.Println(sem, "pairs")
    fmt.Println("examples:")
    for _, e := range five {
        fmt.Println("  ", e)
    }
}


Sequence: nth number with exactly n divisors

Calculate the sequence where each term an is the nth that has '''n''' divisors.

;Task

Show here, on this page, at least the first '''15''' terms of the sequence.

;See also

:*OEIS:A073916

;Related tasks

:*[[Sequence: smallest number greater than previous term with exactly n divisors]]
:*[[Sequence: smallest number with exactly n divisors]]

Solution:
package main

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

var bi = new(big.Int)

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

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

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

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


Sequence: smallest number greater than previous term with exactly n divisors

Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.

;Task
Show here, on this page, at least the first '''15''' terms of the sequence.

;See also
:* OEIS:A069654

;Related tasks
:* [[Sequence: smallest number with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]

Solution:
package main

import "fmt"

func countDivisors(n int) int {
    count := 0
    for i := 1; i*i <= n; i++ {
        if n%i == 0 {
            if i == n/i {
                count++
            } else {
                count += 2
            }
        }
    }
    return count
}

func main() {
    const max = 15
    fmt.Println("The first", max, "terms of the sequence are:")
    for i, next := 1, 1; next <= max; i++ {
        if next == countDivisors(i) {
            fmt.Printf("%d ", i)
            next++
        }
    }
    fmt.Println()
}


Sequence: smallest number with exactly n divisors

Calculate the sequence where each term   an   is the '''smallest natural number''' that has exactly   '''n'''   divisors.

;Task
Show here, on this page, at least the first  '''15'''  terms of the sequence.

;Related tasks:
:* [[Sequence: smallest number greater than previous term with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]

;See also:
:* OEIS:A005179

Solution:
package main

import "fmt"

func countDivisors(n int) int {
    count := 0
    for i := 1; i*i <= n; i++ {
        if n%i == 0 {
            if i == n/i {
                count++
            } else {
                count += 2
            }
        }
    }
    return count
}

func main() {
    const max = 15
    seq := make([]int, max)
    fmt.Println("The first", max, "terms of the sequence are:")
    for i, n := 1, 0; n < max; i++ {
        if k := countDivisors(i); k <= max && seq[k-1] == 0 {
            seq[k-1] = i
            n++
        }
    }
    fmt.Println(seq)
}


Set consolidation

Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:
*  The two input sets if no common item exists between the two input sets of items.
*  The single set that is the union of the two input sets if they share a common item.

Given N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.
If N<2 then consolidation has no strict meaning and the input can be returned.

;'''Example 1:'''
:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.
;'''Example 2:'''
:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}.  (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).
;'''Example 3:'''
:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}

'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]

Solution:
package main

import "fmt"

type set map[string]bool

var testCase = []set{
    set{"H": true, "I": true, "K": true},
    set{"A": true, "B": true},
    set{"C": true, "D": true},
    set{"D": true, "B": true},
    set{"F": true, "G": true, "H": true},
}

func main() {
    fmt.Println(consolidate(testCase))
}

func consolidate(sets []set) []set {
    setlist := []set{}
    for _, s := range sets {
        if s != nil && len(s) > 0 {
            setlist = append(setlist, s)
        }
    }
    for i, s1 := range setlist {
        if len(s1) > 0 {
            for _, s2 := range setlist[i+1:] {
                if s1.disjoint(s2) {
                    continue
                }
                for e := range s1 {
                    s2[e] = true
                    delete(s1, e)
                }
                s1 = s2
            }
        }
    }
    r := []set{}
    for _, s := range setlist {
        if len(s) > 0 {
            r = append(r, s)
        }
    }
    return r
}

func (s1 set) disjoint(s2 set) bool {
    for e := range s2 {
        if s1[e] {
            return false
        }
    }
    return true
}


Set of real numbers

All real numbers form the uncountable set R.  Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''.  There are actually four cases for the meaning of "between", depending on open or closed boundary:
* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.

'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x''  ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A''  ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x''  ''A'' or ''x''  ''B''}
:: example: [0, 2)  (1, 3) = [0, 3); [0, 1)  (2, 3] = well, [0, 1)  (2, 3]
:* ''A''  ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x''  ''A'' and ''x''  ''B''}
:: example: [0, 2)  (1, 3) = (1, 2); [0, 1)  (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x''  ''A'' and ''x''  ''B''}
:: example: [0, 2) - (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1]  [0, 2)
:* [0, 2)  (1, 2]
:* [0, 3) - (0, 1)
:* [0, 3) - [0, 1]

'''Implementation notes'''
* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'.  Cantor's set needs not apply.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).

'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''.  Note that
|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.

Solution:
package main

import "fmt"

type Set func(float64) bool

func Union(a, b Set) Set      { return func(x float64) bool { return a(x) || b(x) } }
func Inter(a, b Set) Set      { return func(x float64) bool { return a(x) && b(x) } }
func Diff(a, b Set) Set       { return func(x float64) bool { return a(x) && !b(x) } }
func open(a, b float64) Set   { return func(x float64) bool { return a < x && x < b } }
func closed(a, b float64) Set { return func(x float64) bool { return a <= x && x <= b } }
func opCl(a, b float64) Set   { return func(x float64) bool { return a < x && x <= b } }
func clOp(a, b float64) Set   { return func(x float64) bool { return a <= x && x < b } }

func main() {
	s := make([]Set, 4)
	s[0] = Union(opCl(0, 1), clOp(0, 2))  // (0,1] ∪ [0,2)
	s[1] = Inter(clOp(0, 2), opCl(1, 2))  // [0,2) ∩ (1,2]
	s[2] = Diff(clOp(0, 3), open(0, 1))   // [0,3) − (0,1)
	s[3] = Diff(clOp(0, 3), closed(0, 1)) // [0,3) − [0,1]

	for i := range s {
		for x := float64(0); x < 3; x++ {
			fmt.Printf("%v ∈ s%d: %t\n", x, i, s[i](x))
		}
		fmt.Println()
	}
}