Approximate equality

Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.

For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.

;Task:
Create a function which returns true if two floating point numbers are approximately equal.

The function should allow for differences in the magnitude of numbers, so that, for example,
'''100000000000000.01'''   may be approximately equal to   '''100000000000000.011''',
even though   '''100.01'''   is not approximately equal to   '''100.011'''.

If the language has such a feature in its standard library, this may be used instead of a custom function.

Show the function results with comparisons on the following pairs of values:
:#     100000000000000.01,                        100000000000000.011       (note: should return ''true'')
:#     100.01,                                    100.011                                                     (note: should return ''false'')
:#     10000000000000.001 / 10000.0,   1000000000.0000001000
:#     0.001,                                     0.0010000001
:#     0.000000000000000000000101,                0.0
:#      sqrt(2) * sqrt(2),                    2.0
:#     -sqrt(2) * sqrt(2),                        -2.0
:#     3.14159265358979323846,                    3.14159265358979324

Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.

__TOC__

Solution:
package main

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

func max(a, b *big.Float) *big.Float {
    if a.Cmp(b) > 0 {
        return a
    }
    return b
}

func isClose(a, b *big.Float) bool {
    relTol := big.NewFloat(1e-9) // same as default for Python's math.isclose() function
    t := new(big.Float)
    t.Sub(a, b)
    t.Abs(t)
    u, v, w := new(big.Float), new(big.Float), new(big.Float)
    u.Mul(relTol, max(v.Abs(a), w.Abs(b)))
    return t.Cmp(u) <= 0
}

func nbf(s string) *big.Float {
    n, ok := new(big.Float).SetString(s)
    if !ok {
        log.Fatal("invalid floating point number")
    }
    return n
}

func main() {
    root2 := big.NewFloat(2.0)
    root2.Sqrt(root2)
    pairs := [][2]*big.Float{
        {nbf("100000000000000.01"), nbf("100000000000000.011")},
        {nbf("100.01"), nbf("100.011")},
        {nbf("0").Quo(nbf("10000000000000.001"), nbf("10000.0")), nbf("1000000000.0000001000")},
        {nbf("0.001"), nbf("0.0010000001")},
        {nbf("0.000000000000000000000101"), nbf("0.0")},
        {nbf("0").Mul(root2, root2), nbf("2.0")},
        {nbf("0").Mul(nbf("0").Neg(root2), root2), nbf("-2.0")},
        {nbf("100000000000000003.0"), nbf("100000000000000004.0")},
        {nbf("3.14159265358979323846"), nbf("3.14159265358979324")},
    }
    for _, pair := range pairs {
        s := "≉"
        if isClose(pair[0], pair[1]) {
            s = "≈"
        }
        fmt.Printf("% 21.19g %s %- 21.19g\n", pair[0], s, pair[1])
    }
}


Arena storage pool

Dynamically allocated objects take their memory from a [[heap]].

The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].

Often a call to allocator is denoted as
P := new T
where   '''T'''   is the type of an allocated object,   and   '''P'''   is a [[reference]] to the object.

The storage pool chosen by the allocator can be determined by either:
* the object type   '''T'''
* the type of pointer   '''P'''

In the former case objects can be allocated only in one storage pool.

In the latter case objects of the type can be allocated in any storage pool or on the [[stack]].

;Task:
The task is to show how allocators and user-defined storage pools are supported by the language.

In particular:
# define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups.
# allocate some objects (e.g., integers) in the pool.

Explain what controls the storage pool choice in the language.

Solution:
package main

import (
    "fmt"
    "runtime"
    "sync"
)

// New to Go 1.3 are sync.Pools, basically goroutine-safe free lists.
// There is overhead in the goroutine-safety and if you do not need this
// you might do better by implementing your own free list.

func main() {
    // Task 1:  Define a pool (of ints).  Just as the task says, a sync.Pool
    // allocates individually and can free as a group.
    p := sync.Pool{New: func() interface{} {
        fmt.Println("pool empty")
        return new(int)
    }}
    // Task 2: Allocate some ints.
    i := new(int)
    j := new(int)
    // Show that they're usable.
    *i = 1
    *j = 2
    fmt.Println(*i + *j) // prints 3
    // Task 2 continued:  Put allocated ints in pool p.
    // Task explanation:  Variable p has a pool as its value.  Another pool
    // could be be created and assigned to a different variable.  You choose
    // a pool simply by using the appropriate variable, p here.
    p.Put(i)
    p.Put(j)
    // Drop references to i and j.  This allows them to be garbage collected;
    // that is, freed as a group.
    i = nil
    j = nil
    // Get ints for i and j again, this time from the pool.  P.Get may reuse
    // an object allocated above as long as objects haven't been garbage
    // collected yet; otherwise p.Get will allocate a new object.
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 4
    *j = 5
    fmt.Println(*i + *j) // prints 9
    // One more test, this time forcing a garbage collection.
    p.Put(i)
    p.Put(j)
    i = nil
    j = nil
    runtime.GC()
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 7
    *j = 8
    fmt.Println(*i + *j) // prints 15
}


Arithmetic-geometric mean

{{wikipedia|Arithmetic-geometric mean}}

;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.

The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})

;Also see:
*   mathworld.wolfram.com/Arithmetic-Geometric Mean

Solution:
package main

import (
    "fmt"
    "math"
)

const ε = 1e-14

func agm(a, g float64) float64 {
    for math.Abs(a-g) > math.Abs(a)*ε {
        a, g = (a+g)*.5, math.Sqrt(a*g)
    }
    return a
}

func main() {
    fmt.Println(agm(1, 1/math.Sqrt2))
}


Arithmetic-geometric mean/Calculate Pi

Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi.

With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:

\pi =
\frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2}
{1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)}

This allows you to make the approximation, for any large   '''N''':

\pi \approx
\frac{4\; a_N^2}
{1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}

The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.

Solution:
package main

import (
    "fmt"
    "math/big"
)

func main() {
    one := big.NewFloat(1)
    two := big.NewFloat(2)
    four := big.NewFloat(4)
    prec := uint(768) // say

    a := big.NewFloat(1).SetPrec(prec)
    g := new(big.Float).SetPrec(prec)

    // temporary variables
    t := new(big.Float).SetPrec(prec)
    u := new(big.Float).SetPrec(prec)

    g.Quo(a, t.Sqrt(two))
    sum := new(big.Float)
    pow := big.NewFloat(2)

    for a.Cmp(g) != 0 {
        t.Add(a, g)
        t.Quo(t, two)
        g.Sqrt(u.Mul(a, g))
        a.Set(t)
        pow.Mul(pow, two)
        t.Sub(t.Mul(a, a), u.Mul(g, g))
        sum.Add(sum, t.Mul(t, pow))
    }

    t.Mul(a, a)
    t.Mul(t, four)
    pi := t.Quo(t, u.Sub(one, sum))
    fmt.Println(pi)
}


Arithmetic numbers

Definition
A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.

Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.

;Example
30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer.

;Task
Calculate and show here:

1. The first 100 arithmetic numbers.

2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.

3. How many of the first '''x''' arithmetic numbers are composite.

Note that, technically, the arithmetic number '''1''' is neither prime nor composite.

;Stretch
Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.

;References

* Wikipedia: Arithmetic number
* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer

Solution:
package main

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

func main() {
    arithmetic := []int{1}
    primes := []int{}
    limit := int(1e6)
    for n := 3; len(arithmetic) < limit; n++ {
        divs := rcu.Divisors(n)
        if len(divs) == 2 {
            primes = append(primes, n)
            arithmetic = append(arithmetic, n)
        } else {
            mean := float64(rcu.SumInts(divs)) / float64(len(divs))
            if mean == math.Trunc(mean) {
                arithmetic = append(arithmetic, n)
            }
        }
    }
    fmt.Println("The first 100 arithmetic numbers are:")
    rcu.PrintTable(arithmetic[0:100], 10, 3, false)

    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
        last := arithmetic[x-1]
        lastc := rcu.Commatize(last)
        fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
        pcount := sort.SearchInts(primes, last) + 1
        if !rcu.IsPrime(last) {
            pcount--
        }
        comp := x - pcount - 1 // 1 is not composite
        compc := rcu.Commatize(comp)
        fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
    }
}


Array length

Determine the amount of elements in an array.

As an example use an array holding the strings 'apple' and 'orange'.

Solution:
package main

import "fmt"

func main() {
	arr := [...]string{"apple", "orange", "pear"}

	fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}


Associative array/Merging

Define two associative arrays, where one represents the following "base" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}

And the other represents "update" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

Merge these into a new associative array that contains every key found in either of the source ones.  Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table.  If possible, do this in a way that does not mutate the original two associative arrays.  Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

Solution:
package main

import "fmt"

type assoc map[string]interface{}

func merge(base, update assoc) assoc {
    result := make(assoc)
    for k, v := range base {
        result[k] = v
    }
    for k, v := range update {
        result[k] = v
    }
    return result
}

func main() {
    base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
    update := assoc{"price": 15.25, "color": "red", "year": 1974}
    result := merge(base, update)
    fmt.Println(result)
}


Attractive numbers

A number is an   ''attractive number''   if the number of its prime factors (whether distinct or not) is also prime.

;Example:
The number   '''20''',   whose prime decomposition is   '''2 x 2 x 5''',   is an   ''attractive number''   because the number of its prime factors   ('''3''')   is also prime.

;Task:
Show sequence items up to   '''120'''.

;Reference:
:*   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.

Solution:
package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func countPrimeFactors(n int) int {
    switch {
    case n == 1:
        return 0
    case isPrime(n):
        return 1
    default:
        count, f := 0, 2
        for {
            if n%f == 0 {
                count++
                n /= f
                if n == 1 {
                    return count
                }
                if isPrime(n) {
                    f = n
                }
            } else if f >= 3 {
                f += 2
            } else {
                f = 3
            }
        }
        return count
    }
}

func main() {
    const max = 120
    fmt.Println("The attractive numbers up to and including", max, "are:")
    count := 0
    for i := 1; i <= max; i++ {
        n := countPrimeFactors(i)
        if isPrime(n) {
            fmt.Printf("%4d", i)
            count++
            if count % 20 == 0 {
                fmt.Println()
            }
        }
    }
    fmt.Println()
}


Average loop length

Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.

;Task:
Write a program or a script that estimates, for each N, the average length until the first such repetition.

Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.

This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.

Example of expected output:

 N    average    analytical    (error)
===  =========  ============  =========
  1     1.0000        1.0000  (  0.00%)
  2     1.4992        1.5000  (  0.05%)
  3     1.8784        1.8889  (  0.56%)
  4     2.2316        2.2188  (  0.58%)
  5     2.4982        2.5104  (  0.49%)
  6     2.7897        2.7747  (  0.54%)
  7     3.0153        3.0181  (  0.09%)
  8     3.2429        3.2450  (  0.07%)
  9     3.4536        3.4583  (  0.14%)
 10     3.6649        3.6602  (  0.13%)
 11     3.8091        3.8524  (  1.12%)
 12     3.9986        4.0361  (  0.93%)
 13     4.2074        4.2123  (  0.12%)
 14     4.3711        4.3820  (  0.25%)
 15     4.5275        4.5458  (  0.40%)
 16     4.6755        4.7043  (  0.61%)
 17     4.8877        4.8579  (  0.61%)
 18     4.9951        5.0071  (  0.24%)
 19     5.1312        5.1522  (  0.41%)
 20     5.2699        5.2936  (  0.45%)

Solution:
package main

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

const nmax = 20

func main() {
    fmt.Println(" N    average    analytical    (error)")
    fmt.Println("===  =========  ============  =========")
    for n := 1; n <= nmax; n++ {
        a := avg(n)
        b := ana(n)
        fmt.Printf("%3d  %9.4f  %12.4f  (%6.2f%%)\n",
            n, a, b, math.Abs(a-b)/b*100)
    }
}

func avg(n int) float64 {
    const tests = 1e4
    sum := 0
    for t := 0; t < tests; t++ {
        var v [nmax]bool
        for x := 0; !v[x]; x = rand.Intn(n) {
            v[x] = true
            sum++
        }
    }
    return float64(sum) / tests
}

func ana(n int) float64 {
    nn := float64(n)
    term := 1.
    sum := 1.
    for i := nn - 1; i >= 1; i-- {
        term *= i / nn
        sum += term
    }
    return sum
}


Averages/Mean angle

Solution:
package main

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

func deg2rad(d float64) float64 { return d * math.Pi / 180 }
func rad2deg(r float64) float64 { return r * 180 / math.Pi }

func mean_angle(deg []float64) float64 {
	sum := 0i
	for _, x := range deg {
		sum += cmplx.Rect(1, deg2rad(x))
	}
	return rad2deg(cmplx.Phase(sum))
}

func main() {
	for _, angles := range [][]float64{
		{350, 10},
		{90, 180, 270, 360},
		{10, 20, 30},
	} {
		fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles))
	}
}


Averages/Pythagorean means

Solution:
package main

import (
    "fmt"
    "math"
)

func main() {
    sum, sumr, prod := 0., 0., 1.
    for n := 1.; n <= 10; n++ {
        sum += n
        sumr += 1 / n
        prod *= n
    }
    a, g, h := sum/10, math.Pow(prod, .1), 10/sumr
    fmt.Println("A:", a, "G:", g, "H:", h)
    fmt.Println("A >= G >= H:", a >= g && g >= h)
}


Averages/Root mean square

Task

Compute the   Root mean square   of the numbers 1..10.

The   ''root mean square''   is also known by its initials RMS (or rms), and as the '''quadratic mean'''.

The RMS is calculated as the mean of the squares of the numbers, square-rooted:

::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}.

;See also

{{Related tasks/Statistical measures}}

Solution:
package main

import (
    "fmt"
    "math"
)

func main() {
    const n = 10
    sum := 0.
    for x := 1.; x <= n; x++ {
        sum += x * x
    }
    fmt.Println(math.Sqrt(sum / n))
}


Babbage problem

Charles Babbage
Charles Babbage's analytical engine.

Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
{{quote
 | What is the smallest positive integer whose square ends in the digits 269,696?
 | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
}}
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.

;Task

The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.

For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].

;Motivation

The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.

Solution:
package main

import "fmt"

func main() {
	const (
		target  = 269696
		modulus = 1000000
	)
	for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ...
		square := n * n
		ending := square % modulus
		if ending == target {
			fmt.Println("The smallest number whose square ends with",
				target, "is", n,
			)
			return
		}
	}
}


Balanced brackets

'''Task''':
* Generate a string with   '''N'''   opening brackets   '''['''   and with   '''N'''   closing brackets   ''']''',   in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.

;Examples:
    (empty)      OK
    []           OK
    [][]         OK
    [[][]]       OK
    ][         NOT OK
    ][][       NOT OK
    []][[]     NOT OK

Solution:
package main

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

func init() {
    rand.Seed(time.Now().UnixNano())
}

func generate(n uint) string {
    a := bytes.Repeat([]byte("[]"), int(n))
    for i := len(a) - 1; i >= 1; i-- {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
    return string(a)
}

func testBalanced(s string) {
    fmt.Print(s + ": ")
    open := 0
    for _,c := range s {
        switch c {
        case '[':
            open++
        case ']':
            if open == 0 {
                fmt.Println("not ok")
                return
            }
            open--
        default:
            fmt.Println("not ok")
            return
        }
    }
    if open == 0 {
        fmt.Println("ok")
    } else {
        fmt.Println("not ok")
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    for i := uint(0); i < 10; i++ {
        testBalanced(generate(i))
    }
    testBalanced("()")
}


Balanced ternary

Balanced ternary is a way of representing numbers.  Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1.

;Examples:
Decimal 11 = 32 + 31 - 30, thus it can be written as "++-"

Decimal  6 = 32 - 31 + 0 x 30, thus it can be written as "+-0"

;Task:
Implement balanced ternary representation of integers with the following:
# Support arbitrarily large integers, both positive and negative;
# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary).  If your native integers can't support arbitrary length, overflows during conversion must be indicated.
# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.
# Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").

'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-":
* write out ''a'', ''b'' and ''c'' in decimal notation;
* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.

'''Note:''' The pages floating point balanced ternary.

Solution:
package main

import (
    "fmt"
    "strings"
)

// R1: representation is a slice of int8 digits of -1, 0, or 1.
// digit at index 0 is least significant.  zero value of type is
// representation of the number 0.
type bt []int8

// R2: string conversion:

// btString is a constructor.  valid input is a string of any length
// consisting of only '+', '-', and '0' characters.
// leading zeros are allowed but are trimmed and not represented.
// false return means input was invalid.
func btString(s string) (*bt, bool) {
    s = strings.TrimLeft(s, "0")
    b := make(bt, len(s))
    for i, last := 0, len(s)-1; i < len(s); i++ {
        switch s[i] {
        case '-':
            b[last-i] = -1
        case '0':
            b[last-i] = 0
        case '+':
            b[last-i] = 1
        default:
            return nil, false
        }
    }
    return &b, true
}

// String method converts the other direction, returning a string of
// '+', '-', and '0' characters representing the number.
func (b bt) String() string {
    if len(b) == 0 {
        return "0"
    }
    last := len(b) - 1
    r := make([]byte, len(b))
    for i, d := range b {
        r[last-i] = "-0+"[d+1]
    }
    return string(r)
}

// R3: integer conversion
// int chosen as "native integer"

// btInt is a constructor like btString.
func btInt(i int) *bt {
    if i == 0 {
        return new(bt)
    }
    var b bt
    var btDigit func(int)
    btDigit = func(digit int) {
        m := int8(i % 3)
        i /= 3
        switch m {
        case 2:
            m = -1
            i++
        case -2:
            m = 1
            i--
        }
        if i == 0 {
            b = make(bt, digit+1)
        } else {
            btDigit(digit + 1)
        }
        b[digit] = m
    }
    btDigit(0)
    return &b
}

// Int method converts the other way, returning the value as an int type.
// !ok means overflow occurred during conversion, not necessarily that the
// value is not representable as an int.  (Of course there are other ways
// of doing it but this was chosen as "reasonable.")
func (b bt) Int() (r int, ok bool) {
    pt := 1
    for _, d := range b {
        dp := int(d) * pt
        neg := r < 0
        r += dp
        if neg {
            if r > dp {
                return 0, false
            }
        } else {
            if r < dp {
                return 0, false
            }
        }
        pt *= 3
    }
    return r, true
}

// R4: negation, addition, and multiplication

func (z *bt) Neg(b *bt) *bt {
    if z != b {
        if cap(*z) < len(*b) {
            *z = make(bt, len(*b))
        } else {
            *z = (*z)[:len(*b)]
        }
    }
    for i, d := range *b {
        (*z)[i] = -d
    }
    return z
}

func (z *bt) Add(a, b *bt) *bt {
    if len(*a) < len(*b) {
        a, b = b, a
    }
    r := *z
    r = r[:cap(r)]
    var carry int8
    for i, da := range *a {
        if i == len(r) {
            n := make(bt, len(*a)+4)
            copy(n, r)
            r = n
        }
        sum := da + carry
        if i < len(*b) {
            sum += (*b)[i]
        }
        carry = sum / 3
        sum %= 3
        switch {
        case sum > 1:
            sum -= 3
            carry++
        case sum < -1:
            sum += 3
            carry--
        }
        r[i] = sum
    }
    last := len(*a)
    if carry != 0 {
        if len(r) == last {
            n := make(bt, last+4)
            copy(n, r)
            r = n
        }
        r[last] = carry
        *z = r[:last+1]
        return z
    }
    for {
        if last == 0 {
            *z = nil
            break
        }
        last--
        if r[last] != 0 {
            *z = r[:last+1]
            break
        }
    }
    return z
}

func (z *bt) Mul(a, b *bt) *bt {
    if len(*a) < len(*b) {
        a, b = b, a
    }
    var na bt
    for _, d := range *b {
        if d == -1 {
            na.Neg(a)
            break
        }
    }
    r := make(bt, len(*a)+len(*b))
    for i := len(*b) - 1; i >= 0; i-- {
        switch (*b)[i] {
        case 1:
            p := r[i:]
            p.Add(&p, a)
        case -1:
            p := r[i:]
            p.Add(&p, &na)
        }
    }
    i := len(r)
    for i > 0 && r[i-1] == 0 {
        i--
    }
    *z = r[:i]
    return z
}

func main() {
    a, _ := btString("+-0++0+")
    b := btInt(-436)
    c, _ := btString("+-++-")
    show("a:", a)
    show("b:", b)
    show("c:", c)
    show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c))))
}

func show(label string, b *bt) {
    fmt.Printf("%7s %12v ", label, b)
    if i, ok := b.Int(); ok {
        fmt.Printf("%7d\n", i)
    } else {
        fmt.Println("int overflow")
    }
}


Barnsley fern

A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).

;Task:
Create this fractal fern, using the following transformations:
* f1   (chosen 1% of the time)
         xn + 1 = 0
         yn + 1 = 0.16 yn

* f2   (chosen 85% of the time)
         xn + 1 = 0.85 xn + 0.04 yn
         yn + 1 = -0.04 xn + 0.85 yn + 1.6

* f3   (chosen 7% of the time)
         xn + 1 = 0.2 xn - 0.26 yn
         yn + 1 = 0.23 xn + 0.22 yn + 1.6

* f4   (chosen 7% of the time)
         xn + 1 = -0.15 xn + 0.28 yn
         yn + 1 = 0.26 xn + 0.24 yn + 0.44.

Starting position: x = 0, y = 0

Solution:
package main

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

// values from WP
const (
    xMin = -2.1820
    xMax = 2.6558
    yMin = 0.
    yMax = 9.9983
)

// parameters
var (
    width = 200
    n     = int(1e6)
    c     = color.RGBA{34, 139, 34, 255} // forest green
)

func main() {
    dx := xMax - xMin
    dy := yMax - yMin
    fw := float64(width)
    fh := fw * dy / dx
    height := int(fh)
    r := image.Rect(0, 0, width, height)
    img := image.NewRGBA(r)
    draw.Draw(img, r, &image.Uniform{color.White}, image.ZP, draw.Src)
    var x, y float64
    plot := func() {
        // transform computed float x, y to integer image coordinates
        ix := int(fw * (x - xMin) / dx)
        iy := int(fh * (yMax - y) / dy)
        img.SetRGBA(ix, iy, c)
    }
    plot()
    for i := 0; i < n; i++ {
        switch s := rand.Intn(100); {
        case s < 85:
            x, y =
                .85*x+.04*y,
                -.04*x+.85*y+1.6
        case s < 85+7:
            x, y =
                .2*x-.26*y,
                .23*x+.22*y+1.6
        case s < 85+7+7:
            x, y =
                -.15*x+.28*y,
                .26*x+.24*y+.44
        default:
            x, y = 0, .16*y
        }
        plot()
    }
    // write img to png file
    f, err := os.Create("bf.png")
    if err != nil {
        log.Fatal(err)
    }
    if err := png.Encode(f, img); err != nil {
        log.Fatal(err)
    }
}


Base64 decode data

See [[Base64 encode data]].

Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.

When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

Solution:
package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    msg := "Rosetta Code Base64 decode data task"
    fmt.Println("Original :", msg)
    encoded := base64.StdEncoding.EncodeToString([]byte(msg))
    fmt.Println("\nEncoded  :", encoded)
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("\nDecoded  :", string(decoded))
}


Bell numbers

Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.

;So:

:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''

:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''

:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''

:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''

: and so on.

A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.

;Task:

Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence.

If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.

;See also:

:* '''OEIS:A000110 Bell or exponential numbers'''
:* '''OEIS:A011971 Aitken's array'''

Solution:
package main

import (
    "fmt"
    "math/big"
)

func bellTriangle(n int) [][]*big.Int {
    tri := make([][]*big.Int, n)
    for i := 0; i < n; i++ {
        tri[i] = make([]*big.Int, i)
        for j := 0; j < i; j++ {
            tri[i][j] = new(big.Int)
        }
    }
    tri[1][0].SetUint64(1)
    for i := 2; i < n; i++ {
        tri[i][0].Set(tri[i-1][i-2])
        for j := 1; j < i; j++ {
            tri[i][j].Add(tri[i][j-1], tri[i-1][j-1])
        }
    }
    return tri
}

func main() {
    bt := bellTriangle(51)
    fmt.Println("First fifteen and fiftieth Bell numbers:")
    for i := 1; i <= 15; i++ {
        fmt.Printf("%2d: %d\n", i, bt[i][0])
    }
    fmt.Println("50:", bt[50][0])
    fmt.Println("\nThe first ten rows of Bell's triangle:")
    for i := 1; i <= 10; i++ {
        fmt.Println(bt[i])
    }
}


Benford's law

{{Wikipedia|Benford's_law}}

'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.

In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.

Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.

This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.

A set of numbers is said to satisfy Benford's law if the leading digit d  (d \in \{1, \ldots, 9\}) occurs with probability

:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)

For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).

Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.

You can generate them or load them from a file; whichever is easiest.

Display your actual vs expected distribution.

''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.

Solution:
package main

import (
    "fmt"
    "math"
)

func Fib1000() []float64 {
    a, b, r := 0., 1., [1000]float64{}
    for i := range r {
        r[i], a, b = b, b, b+a
    }
    return r[:]
}

func main() {
    show(Fib1000(), "First 1000 Fibonacci numbers")
}

func show(c []float64, title string) {
    var f [9]int
    for _, v := range c {
        f[fmt.Sprintf("%g", v)[0]-'1']++
    }
    fmt.Println(title)
    fmt.Println("Digit  Observed  Predicted")
    for i, n := range f {
        fmt.Printf("  %d  %9.3f  %8.3f\n", i+1, float64(n)/float64(len(c)),
            math.Log10(1+1/float64(i+1)))
    }
}


Best shuffle

Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.

A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.

Display the result as follows:

 original string, shuffled string, (score)

The score gives the number of positions whose character value did ''not'' change.

;Example:
 tree, eetr, (0)

;Test cases:
 abracadabra
 seesaw
 elk
 grrrrrr
 up
 a

;Related tasks
*   [[Anagrams/Deranged anagrams]]
*   [[Permutations/Derangements]]

Solution:
package main

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

var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"}

func main() {
    rand.Seed(time.Now().UnixNano())
    for _, s := range ts {
        // create shuffled byte array of original string
        t := make([]byte, len(s))
        for i, r := range rand.Perm(len(s)) {
            t[i] = s[r]
        }
        // algorithm of Icon solution
        for i := range t {
            for j := range t {
                if i != j && t[i] != s[j] && t[j] != s[i] {
                    t[i], t[j] = t[j], t[i]
                    break
                }
            }
        }
        // count unchanged and output
        var count int
        for i, ic := range t {
            if ic == s[i] {
                count++
            }
        }
        fmt.Printf("%s -> %s (%d)\n", s, string(t), count)
    }
}


Bin given limits

Solution:
package main

import (
    "fmt"
    "sort"
)

func getBins(limits, data []int) []int {
    n := len(limits)
    bins := make([]int, n+1)
    for _, d := range data {
        index := sort.SearchInts(limits, d) // uses binary search
        if index < len(limits) && d == limits[index] {
            index++
        }
        bins[index]++
    }
    return bins
}

func printBins(limits, bins []int) {
    n := len(limits)
    fmt.Printf("           < %3d = %2d\n", limits[0], bins[0])
    for i := 1; i < n; i++ {
        fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i])
    }
    fmt.Printf(">= %3d           = %2d\n", limits[n-1], bins[n])
    fmt.Println()
}

func main() {
    limitsList := [][]int{
        {23, 37, 43, 53, 67, 83},
        {14, 18, 249, 312, 389, 392, 513, 591, 634, 720},
    }

    dataList := [][]int{
        {
            95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47,
            16,  8,  9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55,
        },
        {
            445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932,  77, 323, 525, 570, 219, 367, 523, 442, 933,
            416, 589, 930, 373, 202, 253, 775,  47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306,
            655, 267, 248, 477, 549, 238,  62, 678,  98, 534, 622, 907, 406, 714, 184, 391, 913,  42, 560, 247,
            346, 860,  56, 138, 546,  38, 985, 948,  58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123,
            345, 110, 720, 917, 313, 845, 426,   9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397,  97,
            854, 740,  83, 216, 421,  94, 517, 479, 292, 963, 376, 981, 480,  39, 257, 272, 157,   5, 316, 395,
            787, 942, 456, 242, 759, 898, 576,  67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
            698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585,  40,  54, 901, 408, 359, 577, 237,
            605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791,
            466,  23, 707, 467,  33, 670, 921, 180, 991, 396, 160, 436, 717, 918,   8, 374, 101, 684, 727, 749,
        },
    }

    for i := 0; i < len(limitsList); i++ {
        fmt.Println("Example", i+1, "\b\n")
        bins := getBins(limitsList[i], dataList[i])
        printBins(limitsList[i], bins)
    }
}


Bioinformatics/Global alignment

Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the
sequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle.

Current DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, "AAGATGGA", GGAGCGCATC", and "ATCGCAATAAGGA" can be assembled into the sequence "AAGATGGAGCGCATCGCAATAAGGA" by noting that "GGA" is at the tail of the first string and head of the second string and "ATC" likewise is at the tail
of the second and head of the third string.

When looking for the best global alignment in the output strings produced by DNA sequences, there are
typically a large number of such overlaps among a large number of sequences. In such a case, the ordering
that results in the shortest common superstring is generrally preferred.

Finding such a supersequence is an NP-hard problem, and many algorithms have been proposed to
shorten calculations, especially when many very long sequences are matched.

The shortest common superstring as used in bioinfomatics here differs from the string task
[[Shortest_common_supersequence]]. In that task, a supersequence
may have other characters interposed as long as the characters of each subsequence appear in order,
so that (abcbdab, abdcaba) -> abdcabdab.  In this task, (abcbdab, abdcaba) -> abcbdabdcaba.

;Task:
:*   Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences.

:*    Handle cases where two sequences are identical or one sequence is entirely contained in another.

:*   Print the resulting sequence along with its size (its base count) and a count of each base in the sequence.

:*   Find the shortest common superstring for the following four examples:
:
 ("TA", "AAG", "TA", "GAA", "TA")

 ("CATTAGGG", "ATTAG", "GGG", "TA")

 ("AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA")

 ("ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT",
 "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT",
 "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
 "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
 "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT",
 "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC",
 "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT",
 "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
 "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC",
 "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT",
 "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
 "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
 "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA")

;Related tasks:
:* Bioinformatics base count.
:* Bioinformatics sequence mutation.

Solution:
package main

import (
    "fmt"
    "strings"
)

/* Gets n! for small n. */
func factorial(n int) int {
    fact := 1
    for i := 2; i <= n; i++ {
        fact *= i
    }
    return fact
}

/* Gets all permutations of a list of strings. */
func getPerms(input []string) [][]string {
    perms := [][]string{input}
    le := len(input)
    a := make([]string, le)
    copy(a, input)
    n := le - 1
    fact := factorial(n + 1)

    for c := 1; c < fact; c++ {
        i := n - 1
        j := n
        for i >= 0 && a[i] > a[i+1] {
            i--
        }
        if i == -1 {
            i = n
        }
        for a[j] < a[i] {
            j--
        }
        a[i], a[j] = a[j], a[i]
        j = n
        i++
        if i == n+1 {
            i = 0
        }
        for i < j {
            a[i], a[j] = a[j], a[i]
            i++
            j--
        }
        b := make([]string, le)
        copy(b, a)
        perms = append(perms, b)
    }
    return perms
}

/* Returns all distinct elements from a list of strings. */
func distinct(slist []string) []string {
    distinctSet := make(map[string]int, len(slist))
    i := 0
    for _, s := range slist {
        if _, ok := distinctSet[s]; !ok {
            distinctSet[s] = i
            i++
        }
    }
    result := make([]string, len(distinctSet))
    for s, i := range distinctSet {
        result[i] = s
    }
    return result
}

/* Given a DNA sequence, report the sequence, length and base counts. */
func printCounts(seq string) {
    bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}}
    for _, c := range seq {
        for _, base := range bases {
            if c == base[0] {
                base[1]++
            }
        }
    }
    sum := 0
    fmt.Println("\nNucleotide counts for", seq, "\b:\n")
    for _, base := range bases {
        fmt.Printf("%10c%12d\n", base[0], base[1])
        sum += int(base[1])
    }
    le := len(seq)
    fmt.Printf("%10s%12d\n", "Other", le-sum)
    fmt.Printf("  ____________________\n%14s%8d\n", "Total length", le)
}

/* Return the position in s1 of the start of overlap of tail of string s1 with head of string s2. */
func headTailOverlap(s1, s2 string) int {
    for start := 0; ; start++ {
        ix := strings.IndexByte(s1[start:], s2[0])
        if ix == -1 {
            return 0
        } else {
            start += ix
        }
        if strings.HasPrefix(s2, s1[start:]) {
            return len(s1) - start
        }
    }
}

/* Remove duplicates and strings contained within a larger string from a list of strings. */
func deduplicate(slist []string) []string {
    var filtered []string
    arr := distinct(slist)
    for i, s1 := range arr {
        withinLarger := false
        for j, s2 := range arr {
            if j != i && strings.Contains(s2, s1) {
                withinLarger = true
                break
            }
        }
        if !withinLarger {
            filtered = append(filtered, s1)
        }
    }
    return filtered
}

/* Returns shortest common superstring of a list of strings. */
func shortestCommonSuperstring(slist []string) string {
    ss := deduplicate(slist)
    shortestSuper := strings.Join(ss, "")
    for _, perm := range getPerms(ss) {
        sup := perm[0]
        for i := 0; i < len(ss)-1; i++ {
            overlapPos := headTailOverlap(perm[i], perm[i+1])
            sup += perm[i+1][overlapPos:]
        }
        if len(sup) < len(shortestSuper) {
            shortestSuper = sup
        }
    }
    return shortestSuper
}

func main() {
    testSequences := [][]string{
        {"TA", "AAG", "TA", "GAA", "TA"},
        {"CATTAGGG", "ATTAG", "GGG", "TA"},
        {"AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"},
        {
            "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT",
            "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT",
            "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
            "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
            "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT",
            "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC",
            "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT",
            "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
            "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC",
            "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT",
            "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC",
            "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA",
            "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA",
        },
    }

    for _, test := range testSequences {
        scs := shortestCommonSuperstring(test)
        printCounts(scs)
    }
}


Bioinformatics/Sequence mutation

Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
# Choosing a random base position in the sequence.
# Mutate the sequence by  doing one of either:
## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
## '''D'''elete the chosen base at the position.
## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.
# Randomly generate a test DNA sequence of at least 200 bases
# "Pretty print" the sequence and a count of its size, and the count of each base in the sequence
# Mutate the sequence ten times.
# "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.

;Extra credit:
* Give more information on the individual mutations applied.
* Allow mutations to be weighted and/or chosen.

Solution:
package main

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

const bases = "ACGT"

// 'w' contains the weights out of 300 for each
// of swap, delete or insert in that order.
func mutate(dna string, w [3]int) string {
    le := len(dna)
    // get a random position in the dna to mutate
    p := rand.Intn(le)
    // get a random number between 0 and 299 inclusive
    r := rand.Intn(300)
    bytes := []byte(dna)
    switch {
    case r < w[0]: // swap
        base := bases[rand.Intn(4)]
        fmt.Printf("  Change @%3d %q to %q\n", p, bytes[p], base)
        bytes[p] = base
    case r < w[0]+w[1]: // delete
        fmt.Printf("  Delete @%3d %q\n", p, bytes[p])
        copy(bytes[p:], bytes[p+1:])
        bytes = bytes[0 : le-1]
    default: // insert
        base := bases[rand.Intn(4)]
        bytes = append(bytes, 0)
        copy(bytes[p+1:], bytes[p:])
        fmt.Printf("  Insert @%3d %q\n", p, base)
        bytes[p] = base
    }
    return string(bytes)
}

// Generate a random dna sequence of given length.
func generate(le int) string {
    bytes := make([]byte, le)
    for i := 0; i < le; i++ {
        bytes[i] = bases[rand.Intn(4)]
    }
    return string(bytes)
}

// Pretty print dna and stats.
func prettyPrint(dna string, rowLen int) {
    fmt.Println("SEQUENCE:")
    le := len(dna)
    for i := 0; i < le; i += rowLen {
        k := i + rowLen
        if k > le {
            k = le
        }
        fmt.Printf("%5d: %s\n", i, dna[i:k])
    }
    baseMap := make(map[byte]int) // allows for 'any' base
    for i := 0; i < le; i++ {
        baseMap[dna[i]]++
    }
    var bases []byte
    for k := range baseMap {
        bases = append(bases, k)
    }
    sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order
        return bases[i] < bases[j]
    })

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

// Express weights as a string.
func wstring(w [3]int) string {
    return fmt.Sprintf("  Change: %d\n  Delete: %d\n  Insert: %d\n", w[0], w[1], w[2])
}

func main() {
    rand.Seed(time.Now().UnixNano())
    dna := generate(250)
    prettyPrint(dna, 50)
    muts := 10
    w := [3]int{100, 100, 100} // use e.g. {0, 300, 0} to choose only deletions
    fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w))
    fmt.Printf("MUTATIONS (%d):\n", muts)
    for i := 0; i < muts; i++ {
        dna = mutate(dna, w)
    }
    fmt.Println()
    prettyPrint(dna, 50)
}


Bioinformatics/base count

Given this string representing ordered DNA bases:

CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT

;Task:
:*   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   ('''A''', '''C''', '''G''', and '''T''')   in the sequence
:*   print the total count of each base in the string.

Solution:
package main

import (
    "fmt"
    "sort"
)

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

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

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


Biorhythms

For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.

It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!

To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.

The three cycles and their lengths are as follows:
:::{| class="wikitable"
! Cycle
! Length
|-
|Physical
| 23 days
|-
|Emotional
| 28 days
|-
|Mental
| 33 days
|}

The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.

The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.

Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11

Solution:
package main

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

const layout = "2006-01-02" // template for time.Parse

var cycles = [3]string{"Physical day ", "Emotional day", "Mental day   "}
var lengths = [3]int{23, 28, 33}
var quadrants = [4][2]string{
    {"up and rising", "peak"},
    {"up but falling", "transition"},
    {"down and falling", "valley"},
    {"down but rising", "transition"},
}

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

// Parameters assumed to be in YYYY-MM-DD format.
func biorhythms(birthDate, targetDate string) {
    bd, err := time.Parse(layout, birthDate)
    check(err)
    td, err := time.Parse(layout, targetDate)
    check(err)
    days := int(td.Sub(bd).Hours() / 24)
    fmt.Printf("Born %s, Target %s\n", birthDate, targetDate)
    fmt.Println("Day", days)
    for i := 0; i < 3; i++ {
        length := lengths[i]
        cycle := cycles[i]
        position := days % length
        quadrant := position * 4 / length
        percent := math.Sin(2 * math.Pi * float64(position) / float64(length))
        percent = math.Floor(percent*1000) / 10
        descript := ""
        if percent > 95 {
            descript = " peak"
        } else if percent < -95 {
            descript = " valley"
        } else if math.Abs(percent) < 5 {
            descript = " critical transition"
        } else {
            daysToAdd := (quadrant+1)*length/4 - position
            transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd))
            trend := quadrants[quadrant][0]
            next := quadrants[quadrant][1]
            transStr := transition.Format(layout)
            descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr)
        }
        fmt.Printf("%s %2d : %s\n", cycle, position, descript)
    }
    fmt.Println()
}

func main() {
    datePairs := [][2]string{
        {"1943-03-09", "1972-07-11"},
        {"1809-01-12", "1863-11-19"},
        {"1809-02-12", "1863-11-19"}, // correct DOB for Abraham Lincoln
    }
    for _, datePair := range datePairs {
        biorhythms(datePair[0], datePair[1])
    }
}


Bitcoin/address validation

Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.

A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
:::*   0   zero
:::*   O   uppercase oh
:::*   I   uppercase eye
:::*   l   lowercase ell

With this encoding, a bitcoin address encodes 25 bytes:
* the first byte is the version number, which will be zero for this task ;
* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task:  you can consider them a pure arbitrary data ;
* the last four bytes are a checksum check.  They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.

To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.

The program can either return a boolean value or throw an exception when not valid.

You can use a digest library for [[SHA-256]].

;Example of a bitcoin address:

 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i

It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.

Solution:
<syntaxhighlight lang="go">package main

import (
    "bytes"
    "crypto/sha256"
    "errors"
    "os"
)

// With at least one other bitcoin RC task, this source is styled more like
// a package to show how functions of the two tasks might be combined into
// a single package.  It turns out there's not really that much shared code,
// just the A25 type and doubleSHA256 method, but it's enough to suggest how
// the code might be organized.  Types, methods, and functions are capitalized
// where they might be exported from a package.

// A25 is a type for a 25 byte (not base58 encoded) bitcoin address.
type A25 [25]byte

func (a *A25) Version() byte {
    return a[0]
}

func (a *A25) EmbeddedChecksum() (c [4]byte) {
    copy(c[:], a[21:])
    return
}

// DoubleSHA256 computes a double sha256 hash of the first 21 bytes of the
// address.  This is the one function shared with the other bitcoin RC task.
// Returned is the full 32 byte sha256 hash.  (The bitcoin checksum will be
// the first four bytes of the slice.)
func (a *A25) doubleSHA256() []byte {
    h := sha256.New()
    h.Write(a[:21])
    d := h.Sum([]byte{})
    h = sha256.New()
    h.Write(d)
    return h.Sum(d[:0])
}

// ComputeChecksum returns a four byte checksum computed from the first 21
// bytes of the address.  The embedded checksum is not updated.
func (a *A25) ComputeChecksum() (c [4]byte) {
    copy(c[:], a.doubleSHA256())
    return


Bitwise IO

The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
''quantized'' by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.

As test, you can implement a '''rough''' (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).

These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''
nine (or more) bits long.

* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
* Errors handling is not mandatory

Solution:
// Package bit provides bit-wise IO to an io.Writer and from an io.Reader.
package bit

import (
    "bufio"
    "errors"
    "io"
)

// Order specifies the bit ordering within a byte stream.
type Order int

const (
    // LSB is for Least Significant Bits first
    LSB Order = iota
    // MSB is for Most  Significant Bits first
    MSB
)

// ==== Writing / Encoding ====

type writer interface {
    io.ByteWriter
    Flush() error
}

// Writer implements bit-wise writing to an io.Writer.
type Writer struct {
    w     writer
    order Order
    write func(uint32, uint) error // writeLSB or writeMSB
    bits  uint32
    nBits uint
    err   error
}

// writeLSB writes `width` bits of `c` in LSB order.
func (w *Writer) writeLSB(c uint32, width uint) error {
    w.bits |= c << w.nBits
    w.nBits += width
    for w.nBits >= 8 {
        if err := w.w.WriteByte(uint8(w.bits)); err != nil {
            return err
        }
        w.bits >>= 8
        w.nBits -= 8
    }
    return nil
}

// writeMSB writes `width` bits of `c` in MSB order.
func (w *Writer) writeMSB(c uint32, width uint) error {
    w.bits |= c << (32 - width - w.nBits)
    w.nBits += width
    for w.nBits >= 8 {
        if err := w.w.WriteByte(uint8(w.bits >> 24)); err != nil {
            return err
        }
        w.bits <<= 8
        w.nBits -= 8
    }
    return nil
}

// WriteBits writes up to 16 bits of `c` to the underlying writer.
// Even for MSB ordering the bits are taken from the lower bits of `c`.
// (e.g. WriteBits(0x0f,4) writes four 1 bits).
func (w *Writer) WriteBits(c uint16, width uint) error {
    if w.err == nil {
        w.err = w.write(uint32(c), width)
    }
    return w.err
}

var errClosed = errors.New("bit reader/writer is closed")

// Close closes the writer, flushing any pending output.
// It does not close the underlying writer.
func (w *Writer) Close() error {
    if w.err != nil {
        if w.err == errClosed {
            return nil
        }
        return w.err
    }
    // Write the final bits (zero padded).
    if w.nBits > 0 {
        if w.order == MSB {
            w.bits >>= 24
        }
        if w.err = w.w.WriteByte(uint8(w.bits)); w.err != nil {
            return w.err
        }
    }
    w.err = w.w.Flush()
    if w.err != nil {
        return w.err
    }

    // Make any future calls to Write return errClosed.
    w.err = errClosed
    return nil
}

// NewWriter returns a new bit Writer that writes completed bytes to `w`.
func NewWriter(w io.Writer, order Order) *Writer {
    bw := &Writer{order: order}
    switch order {
    case LSB:
        bw.write = bw.writeLSB
    case MSB:
        bw.write = bw.writeMSB
    default:
        bw.err = errors.New("bit writer: unknown order")
        return bw
    }
    if byteWriter, ok := w.(writer); ok {
        bw.w = byteWriter
    } else {
        bw.w = bufio.NewWriter(w)
    }
    return bw
}

// ==== Reading / Decoding ====

// Reader implements bit-wise reading from an io.Reader.
type Reader struct {
    r     io.ByteReader
    bits  uint32
    nBits uint
    read  func(width uint) (uint16, error) // readLSB or readMSB
    err   error
}

func (r *Reader) readLSB(width uint) (uint16, error) {
    for r.nBits < width {
        x, err := r.r.ReadByte()
        if err != nil {
            return 0, err
        }
        r.bits |= uint32(x) << r.nBits
        r.nBits += 8
    }
    bits := uint16(r.bits & (1<<width - 1))
    r.bits >>= width
    r.nBits -= width
    return bits, nil
}

func (r *Reader) readMSB(width uint) (uint16, error) {
    for r.nBits < width {
        x, err := r.r.ReadByte()
        if err != nil {
            return 0, err
        }
        r.bits |= uint32(x) << (24 - r.nBits)
        r.nBits += 8
    }
    bits := uint16(r.bits >> (32 - width))
    r.bits <<= width
    r.nBits -= width
    return bits, nil
}

// ReadBits reads up to 16 bits from the underlying reader.
func (r *Reader) ReadBits(width uint) (uint16, error) {
    var bits uint16
    if r.err == nil {
        bits, r.err = r.read(width)
    }
    return bits, r.err
}

// Close closes the reader.
// It does not close the underlying reader.
func (r *Reader) Close() error {
    if r.err != nil && r.err != errClosed {
        return r.err
    }
    r.err = errClosed
    return nil
}

// NewReader returns a new bit Reader that reads bytes from `r`.
func NewReader(r io.Reader, order Order) *Reader {
    br := new(Reader)
    switch order {
    case LSB:
        br.read = br.readLSB
    case MSB:
        br.read = br.readMSB
    default:
        br.err = errors.New("bit writer: unknown order")
        return br
    }
    if byteReader, ok := r.(io.ByteReader); ok {
        br.r = byteReader
    } else {
        br.r = bufio.NewReader(r)
    }
    return br
}


Box the compass

Avast me hearties!
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!

;Task description:
# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).

;Notes;
* The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
    heading = i * 11.25
    case i %3:
      if 1: heading += 5.62; break
      if 2: heading -= 5.62; break
    end
    index = ( i mod 32) + 1
* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..

Solution:
package main

import "fmt"

// function required by task
func degrees2compasspoint(h float32) string {
    return compassPoint[cpx(h)]
}

// cpx returns integer index from 0 to 31 corresponding to compass point.
// input heading h is in degrees.  Note this index is a zero-based index
// suitable for indexing into the table of printable compass points,
// and is not the same as the index specified to be printed in the output.
func cpx(h float32) int {
    x := int(h/11.25+.5) % 32
    if x < 0 {
        x += 32
    }
    return x
}

// printable compass points
var compassPoint = []string{
    "North",
    "North by east",
    "North-northeast",
    "Northeast by north",
    "Northeast",
    "Northeast by east",
    "East-northeast",
    "East by north",
    "East",
    "East by south",
    "East-southeast",
    "Southeast by east",
    "Southeast",
    "Southeast by south",
    "South-southeast",
    "South by east",
    "South",
    "South by west",
    "South-southwest",
    "Southwest by south",
    "Southwest",
    "Southwest by west",
    "West-southwest",
    "West by south",
    "West",
    "West by north",
    "West-northwest",
    "Northwest by west",
    "Northwest",
    "Northwest by north",
    "North-northwest",
    "North by west",
}

func main() {
    fmt.Println("Index  Compass point         Degree")
    for i, h := range []float32{0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5,
        84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75,
        185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0,
        286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38} {
        index := i%32 + 1 // printable index computed per pseudocode
        fmt.Printf("%4d   %-19s %7.2f°\n", index, degrees2compasspoint(h), h)
    }
}


Brazilian numbers

Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.

Brazilian numbers are defined as:

The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.

;E.G.:

:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.
:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.
:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.
:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.
:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.
:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.
:* ''and so on...''

All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.
More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes >  2

;Task:

Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;

:* the first '''20''' Brazilian numbers;
:* the first '''20 odd''' Brazilian numbers;
:* the first '''20 prime''' Brazilian numbers;

;See also:

:* '''OEIS:A125134 - Brazilian numbers'''
:* '''OEIS:A257521 - Odd Brazilian numbers'''
:* '''OEIS:A085104 - Prime Brazilian numbers'''

Solution:
package main

import "fmt"

func sameDigits(n, b int) bool {
    f := n % b
    n /= b
    for n > 0 {
        if n%b != f {
            return false
        }
        n /= b
    }
    return true
}

func isBrazilian(n int) bool {
    if n < 7 {
        return false
    }
    if n%2 == 0 && n >= 8 {
        return true
    }
    for b := 2; b < n-1; b++ {
        if sameDigits(n, b) {
            return true
        }
    }
    return false
}

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func main() {
    kinds := []string{" ", " odd ", " prime "}
    for _, kind := range kinds {
        fmt.Printf("First 20%sBrazilian numbers:\n", kind)
        c := 0
        n := 7
        for {
            if isBrazilian(n) {
                fmt.Printf("%d ", n)
                c++
                if c == 20 {
                    fmt.Println("\n")
                    break
                }
            }
            switch kind {
            case " ":
                n++
            case " odd ":
                n += 2
            case " prime ":
                for {
                    n += 2
                    if isPrime(n) {
                        break
                    }
                }
            }
        }
    }

    n := 7
    for c := 0; c < 100000; n++ {
        if isBrazilian(n) {
            c++
        }
    }
    fmt.Println("The 100,000th Brazilian number:", n-1)
}


Brazilian numbers

Solution:
package main

import (
    "fmt"
    "math"
    "time"
)

// flags
const (
    prMk int8 = 0   // prime
    sqMk      = 1   // prime square
    upMk      = 2   // non-prime
    brMk      = -2  // Brazilian prime
    excp      = 121 // the only Brazilian square prime
)

var (
    pow = 9
    max = 0
    ps  []int8
)

// typical sieve of Eratosthenes
func primeSieve(top int) {
    ps = make([]int8, top)
    i, j := 2, 4
    ps[j] = sqMk
    for j < top-2 {
        j += 2
        ps[j] = upMk
    }
    i, j = 3, 9
    ps[j] = sqMk
    for j < top-6 {
        j += 6
        ps[j] = upMk
    }
    i = 5
    for i*i < top {
        if ps[i] == prMk {
            j = (top - i) / i
            if (j & 1) == 0 {
                j--
            }
            for {
                if ps[j] == prMk {
                    ps[i*j] = upMk
                }
                j -= 2
                if j <= i {
                    break
                }
            }
            ps[i*i] = sqMk
        }
        for {
            i += 2
            if ps[i] == prMk {
                break
            }
        }
    }
}

// returns whether a number is Brazilian
func isBr(number int) bool {
    temp := ps[number]
    if temp < 0 {
        temp = -temp
    }
    return temp > sqMk
}

// shows the first few Brazilian numbers of several kinds
func firstFew(kind string, amt int) {
    fmt.Printf("\nThe first %d %sBrazilian numbers are:\n", amt, kind)
    i := 7
    for amt > 0 {
        if isBr(i) {
            amt--
            fmt.Printf("%d ", i)
        }
        switch kind {
        case "odd ":
            i += 2
        case "prime ":
            for {
                i += 2
                if ps[i] == brMk && i != excp {
                    break
                }
            }
        default:
            i++
        }
    }
    fmt.Println()
}

// expands a 111_X number into an integer
func expand(numberOfOnes, base int) int {
    res := 1
    for numberOfOnes > 1 {
        numberOfOnes--
        res = res*base + 1
    }
    if res > max || res < 0 {
        res = 0
    }
    return res
}

func toMs(d time.Duration) float64 {
    return float64(d) / 1e6
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    start := time.Now()
    st0 := start
    p2 := pow << 1
    p10 := int(math.Pow10(pow))
    p, cnt := 10, 0
    max = p10 * p2 / (p2 - 1)
    primeSieve(max)
    fmt.Printf("Sieving took %.4f ms\n", toMs(time.Since(start)))
    start = time.Now()
    primes := make([]int, 7)
    n := 3
    for i := 0; i < len(primes); i++ {
        primes[i] = n
        for {
            n += 2
            if ps[n] == 0 {
                break
            }
        }
    }
    fmt.Println("\nChecking first few prime numbers of sequential ones:")
    fmt.Println("ones checked found")
    for _, i := range primes {
        fmt.Printf("%4d", i)
        cnt, n = 0, 2
        for {
            if (n-1)%i != 0 {
                br := expand(i, n)
                if br > 0 {
                    if ps[br] < upMk {
                        ps[br] = brMk
                        cnt++
                    }
                } else {
                    fmt.Printf("%8d%6d\n", n, cnt)
                    break
                }
            }
            n++
        }
    }
    ms := toMs(time.Since(start))
    fmt.Printf("Adding Brazilian primes to the sieve took %.4f ms\n", ms)
    start = time.Now()
    for _, s := range []string{"", "odd ", "prime "} {
        firstFew(s, 20)
    }
    fmt.Printf("\nRequired output took %.4f ms\n", toMs(time.Since(start)))
    fmt.Println("\nDecade count of Brazilian numbers:")
    n, cnt = 6, 0
    for {
        for cnt < p {
            n++
            if isBr(n) {
                cnt++
            }
        }
        ms = toMs(time.Since(start))
        fmt.Printf("%15sth is %-15s  time: %8.4f ms\n", commatize(cnt), commatize(n), ms)
        p *= 10
        if p > p10 {
            break
        }
    }
    fmt.Printf("\nTotal elapsed was %.4f ms\n", toMs(time.Since(st0)))
}


Break OO privacy

Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object  but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.

Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.

Solution:
package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"reflect"
	"unsafe"
)

type foobar struct {
	Exported   int // In Go identifiers that are capitalized are exported,
	unexported int // while lowercase identifiers are not.
}

func main() {
	obj := foobar{12, 42}
	fmt.Println("obj:", obj)

	examineAndModify(&obj)
	fmt.Println("obj:", obj)

	anotherExample()
}

// For simplicity this skips several checks. It assumes the thing in the
// interface is a pointer without checking (v.Kind()==reflect.Ptr),
// it then assumes it is a structure type with two int fields
// (v.Kind()==reflect.Struct, f.Type()==reflect.TypeOf(int(0))).
func examineAndModify(any interface{}) {
	v := reflect.ValueOf(any) // get a reflect.Value
	v = v.Elem()              // dereference the pointer
	fmt.Println(" v:", v, "=", v.Interface())
	t := v.Type()
	// Loop through the struct fields
	fmt.Printf("    %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i) // reflect.Value of the field
		fmt.Printf("    %2d: %-10s %-4s %t\n", i,
			t.Field(i).Name, f.Type(), f.CanSet())
	}

	// "Exported", field 0, has CanSet==true so we can do:
	v.Field(0).SetInt(16)
	// "unexported", field 1, has CanSet==false so the following
	// would fail at run-time with:
	//   panic: reflect: reflect.Value.SetInt using value obtained using unexported field
	//v.Field(1).SetInt(43)

	// However, we can bypass this restriction with the unsafe
	// package once we know what type it is (so we can use the
	// correct pointer type, here *int):
	vp := v.Field(1).Addr()            // Take the fields's address
	up := unsafe.Pointer(vp.Pointer()) // … get an int value of the address and convert it "unsafely"
	p := (*int)(up)                    // … and end up with what we want/need
	fmt.Printf("  vp has type %-14T = %v\n", vp, vp)
	fmt.Printf("  up has type %-14T = %#0x\n", up, up)
	fmt.Printf("   p has type %-14T = %v pointing at %v\n", p, p, *p)
	*p = 43 // effectively obj.unexported = 43
	// or an incr all on one ulgy line:
	*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++

	// Note that as-per the package "unsafe" documentation,
	// the return value from vp.Pointer *must* be converted to
	// unsafe.Pointer in the same expression; the result is fragile.
	//
	// I.e. it is invalid to do:
	//	thisIsFragile := vp.Pointer()
	//	up := unsafe.Pointer(thisIsFragile)
}

// This time we'll use an external package to demonstrate that it's not
// restricted to things defined locally. We'll mess with bufio.Reader's
// interal workings by happening to know they have a non-exported
// "err error" field. Of course future versions of Go may not have this
// field or use it in the same way :).
func anotherExample() {
	r := bufio.NewReader(os.Stdin)

	// Do the dirty stuff in one ugly and unsafe statement:
	errp := (*error)(unsafe.Pointer(
		reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
	*errp = errors.New("unsafely injected error value into bufio inner workings")

	_, err := r.ReadByte()
	fmt.Println("bufio.ReadByte returned error:", err)
}


Burrows–Wheeler transform

{{Wikipedia|Burrows-Wheeler_transform}}

The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.

This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.

More importantly, the transformation is reversible, without needing to store any additional data.

The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.

Source: Burrows-Wheeler transform

Solution:
package main

import (
    "fmt"
    "sort"
    "strings"
)

const stx = "\002"
const etx = "\003"

func bwt(s string) (string, error) {
    if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 {
        return "", fmt.Errorf("String can't contain STX or ETX")
    }
    s = stx + s + etx
    le := len(s)
    table := make([]string, le)
    table[0] = s
    for i := 1; i < le; i++ {
        table[i] = s[i:] + s[:i]
    }
    sort.Strings(table)
    lastBytes := make([]byte, le)
    for i := 0; i < le; i++ {
        lastBytes[i] = table[i][le-1]
    }
    return string(lastBytes), nil
}

func ibwt(r string) string {
    le := len(r)
    table := make([]string, le)
    for range table {
        for i := 0; i < le; i++ {
            table[i] = r[i:i+1] + table[i]
        }
        sort.Strings(table)
    }
    for _, row := range table {
        if strings.HasSuffix(row, etx) {
            return row[1 : le-1]
        }
    }
    return ""
}

func makePrintable(s string) string {
    // substitute ^ for STX and | for ETX to print results
    t := strings.Replace(s, stx, "^", 1)
    return strings.Replace(t, etx, "|", 1)
}

func main() {
    tests := []string{
        "banana",
        "appellee",
        "dogwood",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "\002ABC\003",
    }
    for _, test := range tests {
        fmt.Println(makePrintable(test))
        fmt.Print(" --> ")
        t, err := bwt(test)
        if err != nil {
            fmt.Println("ERROR:", err)
        } else {
            fmt.Println(makePrintable(t))
        }
        r := ibwt(t)
        fmt.Println(" -->", r, "\n")
    }
}


CSV data manipulation

CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.

The CSV format is flexible but somewhat ill-defined.

For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.

;Task:
Read a CSV file, change some values and save the changes back to a file.

For this task we will use the following CSV file:

 C1,C2,C3,C4,C5
 1,5,9,13,17
 2,6,10,14,18
 3,7,11,15,19
 4,8,12,16,20

Suggestions

 Show how to add a column, headed 'SUM', of the sums of the rows.
 If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.

Solution:
package main

import (
	"encoding/csv"
	"log"
	"os"
	"strconv"
)

func main() {
	rows := readSample()
	appendSum(rows)
	writeChanges(rows)
}

func readSample() [][]string {
	f, err := os.Open("sample.csv")
	if err != nil {
		log.Fatal(err)
	}
	rows, err := csv.NewReader(f).ReadAll()
	f.Close()
	if err != nil {
		log.Fatal(err)
	}
	return rows
}

func appendSum(rows [][]string) {
	rows[0] = append(rows[0], "SUM")
	for i := 1; i < len(rows); i++ {
		rows[i] = append(rows[i], sum(rows[i]))
	}
}

func sum(row []string) string {
	sum := 0
	for _, s := range row {
		x, err := strconv.Atoi(s)
		if err != nil {
			return "NA"
		}
		sum += x
	}
	return strconv.Itoa(sum)
}

func writeChanges(rows [][]string) {
	f, err := os.Create("output.csv")
	if err != nil {
		log.Fatal(err)
	}
	err = csv.NewWriter(f).WriteAll(rows)
	f.Close()
	if err != nil {
		log.Fatal(err)
	}
}


CSV to HTML translation

Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.

No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be   ''escaped''   when converted to HTML

;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.

Use the following  data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!

;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via  preferably; CSS if you must).

Solution:
package main

import (
    "bytes"
    "encoding/csv"
    "flag"
    "fmt"
    "html/template"
    "strings"
)

var csvStr = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`

func main() {
    headings := flag.Bool("h", false, "format first row as column headings")
    flag.Parse()
    if html, err := csvToHtml(csvStr, *headings); err != nil {
        fmt.Println(err)
    } else {
        fmt.Print(html)
    }
}

func csvToHtml(csvStr string, headings bool) (string, error) {
    data, err := csv.NewReader(bytes.NewBufferString(csvStr)).ReadAll()
    if err != nil {
        return "", err
    }
    tStr := tPlain
    if headings {
        tStr = tHeadings
    }
    var b strings.Builder
    err = template.Must(template.New("").Parse(tStr)).Execute(&b, data)
    return b.String(), err
}

const (
    tPlain = `

{{range .}}
{{range .}}{{.}}	{{end}}

{{end}}

`
    tHeadings = `
{{if .}}
{{range $x, $e := .}}{{if $x}}

{{range .}}{{.}}	{{end}}
{{else}}

{{range .}}{{.}}	{{end}}

{{end}}{{end}}

{{end}}

`
)


Calculating the value of e

Calculate the value of   ''e''.

(''e''   is also known as   ''Euler's number''   and   ''Napier's constant''.)

See details: Calculating the value of e

Solution:
package main

import (
    "fmt"
    "math"
)

const epsilon = 1.0e-15

func main() {
    fact := uint64(1)
    e := 2.0
    n := uint64(2)
    for {
        e0 := e
        fact *= n
        n++
        e += 1.0 / float64(fact)
        if math.Abs(e - e0) < epsilon {
            break
        }
    }
    fmt.Printf("e = %.15f\n", e)
}


Calkin-Wilf sequence

The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once.

It can be calculated recursively as follows:

        {{math|a1}}   =  {{math|1}}
 {{math|an+1}}  =  {{math|1/(2an+1-an)}} for n > 1

;Task part 1:
* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.

To avoid floating point error, you may want to use a rational number data type.

It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:

        {{math|[a0; a1, a2, ..., an]}}  =  {{math|[a0; a1, a2 ,..., an-1, 1]}}

;Example:
The fraction   '''9/4'''   has odd continued fraction representation      {{math|2; 3, 1}},     giving a binary representation of   '''100011''',
which means   '''9/4'''   appears as the   '''35th'''   term of the sequence.

;Task part 2:
* Find the position of the number   '''83116''''''/''''''51639'''   in the Calkin-Wilf sequence.

;See also:
* Wikipedia entry:  Calkin-Wilf tree
* [[Continued fraction]]
* [[Continued fraction/Arithmetic/Construct from rational number]]

Solution:
package main

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

func calkinWilf(n int) []*big.Rat {
    cw := make([]*big.Rat, n+1)
    cw[0] = big.NewRat(1, 1)
    one := big.NewRat(1, 1)
    two := big.NewRat(2, 1)
    for i := 1; i < n; i++ {
        t := new(big.Rat).Set(cw[i-1])
        f, _ := t.Float64()
        f = math.Floor(f)
        t.SetFloat64(f)
        t.Mul(t, two)
        t.Sub(t, cw[i-1])
        t.Add(t, one)
        t.Inv(t)
        cw[i] = new(big.Rat).Set(t)
    }
    return cw
}

func toContinued(r *big.Rat) []int {
    a := r.Num().Int64()
    b := r.Denom().Int64()
    var res []int
    for {
        res = append(res, int(a/b))
        t := a % b
        a, b = b, t
        if a == 1 {
            break
        }
    }
    le := len(res)
    if le%2 == 0 { // ensure always odd
        res[le-1]--
        res = append(res, 1)
    }
    return res
}

func getTermNumber(cf []int) int {
    b := ""
    d := "1"
    for _, n := range cf {
        b = strings.Repeat(d, n) + b
        if d == "1" {
            d = "0"
        } else {
            d = "1"
        }
    }
    i, _ := strconv.ParseInt(b, 2, 64)
    return int(i)
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    cw := calkinWilf(20)
    fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:")
    for i := 1; i <= 20; i++ {
        fmt.Printf("%2d: %s\n", i, cw[i-1].RatString())
    }
    fmt.Println()
    r := big.NewRat(83116, 51639)
    cf := toContinued(r)
    tn := getTermNumber(cf)
    fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn))
}


Call a function

Demonstrate the different syntax and semantics provided for calling a function.

This may include:
:*   Calling a function that requires no arguments
:*   Calling a function with a fixed number of arguments
:*   Calling a function with optional arguments
:*   Calling a function with a variable number of arguments
:*   Calling a function with named arguments
:*   Using a function in statement context
:*   Using a function in first-class context within an expression
:*   Obtaining the return value of a function
:*   Distinguishing built-in functions and user-defined functions
:*   Distinguishing subroutines and functions
;*   Stating whether arguments are passed by value or by reference
;*   Is partial application possible and how

This task is ''not'' about defining functions.

Solution:
package main

import "fmt"

// int parameter, so arguments will be passed to it by value.
func zeroval(ival int) {
	ival = 0
}
// has an *int parameter, meaning that it takes an int pointer.
func zeroptr(iptr *int) {
	*iptr = 0
}
func main() {
	i := 1
	fmt.Println("initial:", i) // prt initial: 1
	zeroval(i)
	fmt.Println("zeroval:", i) // prt zeroval: 1
	zeroptr(&i)
	fmt.Println("zeroptr:", i)  // prt zeroptr: 0
	fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8
}


Canonicalize CIDR

Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.

That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.

;Example:
Given   '''87.70.141.1/22''',    your code should output    '''87.70.140.0/22'''

;Explanation:
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.

In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.

The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.

;More examples for testing

        36.18.154.103/12    -  36.16.0.0/12
        62.62.197.11/29     -  62.62.197.8/29
        67.137.119.181/4    -  64.0.0.0/4
        161.214.74.21/24    -  161.214.74.0/24
        184.232.176.184/18  -  184.232.128.0/18

Solution:
package main

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

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

// canonicalize a CIDR block: make sure none of the host bits are set
func canonicalize(cidr string) string {
    // dotted-decimal / bits in network part
    split := strings.Split(cidr, "/")
    dotted := split[0]
    size, err := strconv.Atoi(split[1])
    check(err)

    // get IP as binary string
    var bin []string
    for _, n := range strings.Split(dotted, ".") {
        i, err := strconv.Atoi(n)
        check(err)
        bin = append(bin, fmt.Sprintf("%08b", i))
    }
    binary := strings.Join(bin, "")

    // replace the host part with all zeros
    binary = binary[0:size] + strings.Repeat("0", 32-size)

    // convert back to dotted-decimal
    var canon []string
    for i := 0; i < len(binary); i += 8 {
        num, err := strconv.ParseInt(binary[i:i+8], 2, 64)
        check(err)
        canon = append(canon, fmt.Sprintf("%d", num))
    }

    // and return
    return strings.Join(canon, ".") + "/" + split[1]
}

func main() {
    tests := []string{
        "87.70.141.1/22",
        "36.18.154.103/12",
        "62.62.197.11/29",
        "67.137.119.181/4",
        "161.214.74.21/24",
        "184.232.176.184/18",
    }

    for _, test := range tests {
        fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
    }
}


Cantor set

Draw a Cantor set.

See details at this Wikipedia webpage:   Cantor set

Solution:
package main

import "fmt"

const (
    width = 81
    height = 5
)

var lines [height][width]byte

func init() {
    for i := 0; i < height; i++ {
        for j := 0; j < width; j++ {
            lines[i][j] = '*'
        }
    }
}

func cantor(start, len, index int) {
    seg := len / 3
    if seg == 0 {
        return
    }
    for i := index; i < height; i++ {
        for j := start + seg; j < start + 2 * seg; j++ {
            lines[i][j] = ' '
        }
    }
    cantor(start, seg, index + 1)
    cantor(start + seg * 2, seg, index + 1)
}

func main() {
    cantor(0, width, 1)
    for _, line := range lines {
        fmt.Println(string(line[:]))
    }
}