title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Conjugate transpose | Go | Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.
::: (M^H)_{ji} = \overline{M_{ij}}
This means that row j, column i of the conjugate transpose equals the
complex conjugate of row i, column j of the original matrix.
In the next list, M must also be a square matrix.
* A Hermitian matrix equals its own conjugate transpose: M^H = M.
* A multiplication with its conjugate transpose: M^HM = MM^H.
* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.
;Task:
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
::* Hermitian matrix,
::* normal matrix, or
::* unitary matrix.
;See also:
* MathWorld entry: conjugate transpose
* MathWorld entry: Hermitian matrix
* MathWorld entry: normal matrix
* MathWorld entry: unitary matrix
| package main
import (
"fmt"
"math"
"math/cmplx"
)
// a type to represent matrices
type matrix struct {
ele []complex128
cols int
}
// conjugate transpose, implemented here as a method on the matrix type.
func (m *matrix) conjTranspose() *matrix {
r := &matrix{make([]complex128, len(m.ele)), len(m.ele) / m.cols}
rx := 0
for _, e := range m.ele {
r.ele[rx] = cmplx.Conj(e)
rx += r.cols
if rx >= len(r.ele) {
rx -= len(r.ele) - 1
}
}
return r
}
// program to demonstrate capabilites on example matricies
func main() {
show("h", matrixFromRows([][]complex128{
{3, 2 + 1i},
{2 - 1i, 1}}))
show("n", matrixFromRows([][]complex128{
{1, 1, 0},
{0, 1, 1},
{1, 0, 1}}))
show("u", matrixFromRows([][]complex128{
{math.Sqrt2 / 2, math.Sqrt2 / 2, 0},
{math.Sqrt2 / -2i, math.Sqrt2 / 2i, 0},
{0, 0, 1i}}))
}
func show(name string, m *matrix) {
m.print(name)
ct := m.conjTranspose()
ct.print(name + "_ct")
fmt.Println("Hermitian:", m.equal(ct, 1e-14))
mct := m.mult(ct)
ctm := ct.mult(m)
fmt.Println("Normal:", mct.equal(ctm, 1e-14))
i := eye(m.cols)
fmt.Println("Unitary:", mct.equal(i, 1e-14) && ctm.equal(i, 1e-14))
}
// two constructors
func matrixFromRows(rows [][]complex128) *matrix {
m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])}
for rx, row := range rows {
copy(m.ele[rx*m.cols:(rx+1)*m.cols], row)
}
return m
}
func eye(n int) *matrix {
r := &matrix{make([]complex128, n*n), n}
n++
for x := 0; x < len(r.ele); x += n {
r.ele[x] = 1
}
return r
}
// print method outputs matrix to stdout
func (m *matrix) print(heading string) {
fmt.Print("\n", heading, "\n")
for e := 0; e < len(m.ele); e += m.cols {
fmt.Printf("%6.3f ", m.ele[e:e+m.cols])
fmt.Println()
}
}
// equal method uses ε to allow for floating point error.
func (a *matrix) equal(b *matrix, ε float64) bool {
for x, aEle := range a.ele {
if math.Abs(real(aEle)-real(b.ele[x])) > math.Abs(real(aEle))*ε ||
math.Abs(imag(aEle)-imag(b.ele[x])) > math.Abs(imag(aEle))*ε {
return false
}
}
return true
}
// mult method taken from matrix multiply task
func (m1 *matrix) mult(m2 *matrix) (m3 *matrix) {
m3 = &matrix{make([]complex128, (len(m1.ele)/m1.cols)*m2.cols), m2.cols}
for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.cols {
for m2r0 := 0; m2r0 < m2.cols; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.cols {
m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x]
m1x++
}
m3x++
}
}
return m3
} |
Continued fraction | Go | A number may be represented as a continued fraction (see Mathworld for more information) as follows:
:a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.
:\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}}
For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.
:e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}}
For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.
:\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}
;See also:
:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
| package main
import "fmt"
type cfTerm struct {
a, b int
}
// follows subscript convention of mathworld and WP where there is no b(0).
// cf[0].b is unused in this representation.
type cf []cfTerm
func cfSqrt2(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{2, 1}
}
f[0].a = 1
return f
}
func cfNap(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
f[n] = cfTerm{n, n - 1}
}
f[0].a = 2
f[1].b = 1
return f
}
func cfPi(nTerms int) cf {
f := make(cf, nTerms)
for n := range f {
g := 2*n - 1
f[n] = cfTerm{6, g * g}
}
f[0].a = 3
return f
}
func (f cf) real() (r float64) {
for n := len(f) - 1; n > 0; n-- {
r = float64(f[n].b) / (float64(f[n].a) + r)
}
return r + float64(f[0].a)
}
func main() {
fmt.Println("sqrt2:", cfSqrt2(20).real())
fmt.Println("nap: ", cfNap(20).real())
fmt.Println("pi: ", cfPi(20).real())
} |
Continued fraction/Arithmetic/Construct from rational number | Go | To understand this task in context please see [[Continued fraction arithmetic]]
The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming:
:N_1 is the numerator
:N_2 is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero.
Demonstrate the function by outputing the continued fraction for:
: 1/2
: 3
: 23/8
: 13/11
: 22/7
: -151/77
\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you:
: 14142,10000
: 141421,100000
: 1414214,1000000
: 14142136,10000000
Try :
: 31,10
: 314,100
: 3142,1000
: 31428,10000
: 314285,100000
: 3142857,1000000
: 31428571,10000000
: 314285714,100000000
Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
| package cf
import (
"fmt"
"strings"
)
// ContinuedFraction is a regular continued fraction.
type ContinuedFraction func() NextFn
// NextFn is a function/closure that can return
// a posibly infinite sequence of values.
type NextFn func() (term int64, ok bool)
// String implements fmt.Stringer.
// It formats a maximum of 20 values, ending the
// sequence with ", ..." if the sequence is longer.
func (cf ContinuedFraction) String() string {
var buf strings.Builder
buf.WriteByte('[')
sep := "; "
const maxTerms = 20
next := cf()
for n := 0; ; n++ {
t, ok := next()
if !ok {
break
}
if n > 0 {
buf.WriteString(sep)
sep = ", "
}
if n >= maxTerms {
buf.WriteString("...")
break
}
fmt.Fprint(&buf, t)
}
buf.WriteByte(']')
return buf.String()
}
// Sqrt2 is the continued fraction for √2, [1; 2, 2, 2, ...].
func Sqrt2() NextFn {
first := true
return func() (int64, bool) {
if first {
first = false
return 1, true
}
return 2, true
}
}
// Phi is the continued fraction for ϕ, [1; 1, 1, 1, ...].
func Phi() NextFn {
return func() (int64, bool) { return 1, true }
}
// E is the continued fraction for e,
// [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, 1, 1, 10, 1, 1, 12, ...].
func E() NextFn {
var i int
return func() (int64, bool) {
i++
switch {
case i == 1:
return 2, true
case i%3 == 0:
return int64(i/3) * 2, true
default:
return 1, true
}
}
} |
Continued fraction/Arithmetic/G(matrix ng, continued fraction n) | Go | This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:
: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix}
I may perform perform the following operations:
:Input the next term of N1
:Output a term of the continued fraction resulting from the operation.
I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty.
When I input a term t my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1 \\
b + b_1 * t & b_1
\end{bmatrix}
When I output a term t my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b \\
a_1 - b_1 * t & a - b * t
\end{bmatrix}
When I need a term t but there are no more my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\
b_1 & b_1
\end{bmatrix}
I am done when b1 and b are zero.
Demonstrate your solution by calculating:
:[1;5,2] + 1/2
:[3;7] + 1/2
:[3;7] divided by 4
Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.
The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.
| package cf
// A 2×2 matix:
// [ a₁ a ]
// [ b₁ b ]
//
// which when "applied" to a continued fraction representing x
// gives a new continued fraction z such that:
//
// a₁ * x + a
// z = ----------
// b₁ * x + b
//
// Examples:
// NG4{0, 1, 0, 4}.ApplyTo(x) gives 0*x + 1/4 -> 1/4 = [0; 4]
// NG4{0, 1, 1, 0}.ApplyTo(x) gives 1/x
// NG4{1, 1, 0, 2}.ApplyTo(x) gives (x+1)/2
//
// Note that several operations (e.g. addition and division)
// can be efficiently done with a single matrix application.
// However, each matrix application may require
// several calculations for each outputed term.
type NG4 struct {
A1, A int64
B1, B int64
}
func (ng NG4) needsIngest() bool {
if ng.isDone() {
panic("b₁==b==0")
}
return ng.B1 == 0 || ng.B == 0 || ng.A1/ng.B1 != ng.A/ng.B
}
func (ng NG4) isDone() bool {
return ng.B1 == 0 && ng.B == 0
}
func (ng *NG4) ingest(t int64) {
// [ a₁ a ] becomes [ a + a₁×t a₁ ]
// [ b₁ b ] [ b + b₁×t b₁ ]
ng.A1, ng.A, ng.B1, ng.B =
ng.A+ng.A1*t, ng.A1,
ng.B+ng.B1*t, ng.B1
}
func (ng *NG4) ingestInfinite() {
// [ a₁ a ] becomes [ a₁ a₁ ]
// [ b₁ b ] [ b₁ b₁ ]
ng.A, ng.B = ng.A1, ng.B1
}
func (ng *NG4) egest(t int64) {
// [ a₁ a ] becomes [ b₁ b ]
// [ b₁ b ] [ a₁ - b₁×t a - b×t ]
ng.A1, ng.A, ng.B1, ng.B =
ng.B1, ng.B,
ng.A1-ng.B1*t, ng.A-ng.B*t
}
// ApplyTo "applies" the matrix `ng` to the continued fraction `cf`,
// returning the resulting continued fraction.
func (ng NG4) ApplyTo(cf ContinuedFraction) ContinuedFraction {
return func() NextFn {
next := cf()
done := false
return func() (int64, bool) {
if done {
return 0, false
}
for ng.needsIngest() {
if t, ok := next(); ok {
ng.ingest(t)
} else {
ng.ingestInfinite()
}
}
t := ng.A1 / ng.B1
ng.egest(t)
done = ng.isDone()
return t, true
}
}
} |
Convert decimal number to rational | Go | The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...
Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518) = 0.518518...
Acceptable output:
* 0.9054054 - 4527027 / 5000000
* 0.518518 - 259259 / 500000
Finite decimals are of course no problem:
* 0.75 - 3 / 4
| package main
import (
"fmt"
"math/big"
)
func main() {
for _, d := range []string{"0.9054054", "0.518518", "0.75"} {
if r, ok := new(big.Rat).SetString(d); ok {
fmt.Println(d, "=", r)
} else {
fmt.Println(d, "invalid decimal number")
}
}
} |
Convert seconds to compound duration | Go | Write a function or program which:
* takes a positive integer representing a duration in seconds as input (e.g., 100), and
* returns a string which shows the same duration decomposed into:
:::* weeks,
:::* days,
:::* hours,
:::* minutes, and
:::* seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrate that it passes the following three test-cases:
'''''Test Cases'''''
:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}
'''''Details'''''
The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}
However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").
Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)
Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).
| package main
import "fmt"
func main(){
fmt.Println(TimeStr(7259))
fmt.Println(TimeStr(86400))
fmt.Println(TimeStr(6000000))
}
func TimeStr(sec int)(res string){
wks, sec := sec / 604800,sec % 604800
ds, sec := sec / 86400, sec % 86400
hrs, sec := sec / 3600, sec % 3600
mins, sec := sec / 60, sec % 60
CommaRequired := false
if wks != 0 {
res += fmt.Sprintf("%d wk",wks)
CommaRequired = true
}
if ds != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d d",ds)
CommaRequired = true
}
if hrs != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d hr",hrs)
CommaRequired = true
}
if mins != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d min",mins)
CommaRequired = true
}
if sec != 0 {
if CommaRequired {
res += ", "
}
res += fmt.Sprintf("%d sec",sec)
}
return
}
|
Copy stdin to stdout | Go | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| package main
import (
"bufio"
"io"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
for {
b, err := r.ReadByte()
if err == io.EOF {
return
}
w.WriteByte(b)
w.Flush()
}
} |
Count the coins | Go from lisp | There are four types of common coins in US currency:
:::# quarters (25 cents)
:::# dimes (10 cents)
:::# nickels (5 cents), and
:::# pennies (1 cent)
There are six ways to make change for 15 cents:
:::# A dime and a nickel
:::# A dime and 5 pennies
:::# 3 nickels
:::# 2 nickels and 5 pennies
:::# A nickel and 10 pennies
:::# 15 pennies
;Task:
How many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).
;Optional:
Less common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000?
(Note: the answer is larger than 232).
;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.
| package main
import "fmt"
func main() {
amount := 100
fmt.Println("amount, ways to make change:", amount, countChange(amount))
}
func countChange(amount int) int64 {
return cc(amount, 4)
}
func cc(amount, kindsOfCoins int) int64 {
switch {
case amount == 0:
return 1
case amount < 0 || kindsOfCoins == 0:
return 0
}
return cc(amount, kindsOfCoins-1) +
cc(amount - firstDenomination(kindsOfCoins), kindsOfCoins)
}
func firstDenomination(kindsOfCoins int) int {
switch kindsOfCoins {
case 1:
return 1
case 2:
return 5
case 3:
return 10
case 4:
return 25
}
panic(kindsOfCoins)
} |
Create an HTML table | Go | Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.
| package main
import (
"fmt"
"html/template"
"os"
)
type row struct {
X, Y, Z int
}
var tmpl = `<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
{{range $ix, $row := .}} <tr><td>{{$ix}}</td>
<td>{{$row.X}}</td>
<td>{{$row.Y}}</td>
<td>{{$row.Z}}</td></tr>
{{end}}</table>
`
func main() {
// create template
ct := template.Must(template.New("").Parse(tmpl))
// make up data
data := make([]row, 4)
for r := range data {
data[r] = row{r*3, r*3+1, r*3+2}
}
// apply template to data
if err := ct.Execute(os.Stdout, data); err != nil {
fmt.Println(err)
}
} |
Currency | Go | Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
;Note:
The '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16
Dollar signs and thousands separators are optional.
| package main
import (
"fmt"
"log"
"math/big"
)
// DC for dollars and cents. Value is an integer number of cents.
type DC int64
func (dc DC) String() string {
d := dc / 100
if dc < 0 {
dc = -dc
}
return fmt.Sprintf("%d.%02d", d, dc%100)
}
// Extend returns extended price of a unit price.
func (dc DC) Extend(n int) DC {
return dc * DC(n)
}
var one = big.NewInt(1)
var hundred = big.NewRat(100, 1)
// ParseDC parses dollars and cents as a string into a DC.
func ParseDC(s string) (DC, bool) {
r, ok := new(big.Rat).SetString(s)
if !ok {
return 0, false
}
r.Mul(r, hundred)
if r.Denom().Cmp(one) != 0 {
return 0, false
}
return DC(r.Num().Int64()), true
}
// TR for tax rate. Value is an an exact rational.
type TR struct {
*big.Rat
}
func NewTR() TR {
return TR{new(big.Rat)}
}
// SetString overrides Rat.SetString to return the TR type.
func (tr TR) SetString(s string) (TR, bool) {
if _, ok := tr.Rat.SetString(s); !ok {
return TR{}, false
}
return tr, true
}
var half = big.NewRat(1, 2)
// Tax computes a tax amount, rounding to the nearest cent.
func (tr TR) Tax(dc DC) DC {
r := big.NewRat(int64(dc), 1)
r.Add(r.Mul(r, tr.Rat), half)
return DC(new(big.Int).Div(r.Num(), r.Denom()).Int64())
}
func main() {
hamburgerPrice, ok := ParseDC("5.50")
if !ok {
log.Fatal("Invalid hamburger price")
}
milkshakePrice, ok := ParseDC("2.86")
if !ok {
log.Fatal("Invalid milkshake price")
}
taxRate, ok := NewTR().SetString("0.0765")
if !ok {
log.Fatal("Invalid tax rate")
}
totalBeforeTax := hamburgerPrice.Extend(4000000000000000) +
milkshakePrice.Extend(2)
tax := taxRate.Tax(totalBeforeTax)
total := totalBeforeTax + tax
fmt.Printf("Total before tax: %22s\n", totalBeforeTax)
fmt.Printf(" Tax: %22s\n", tax)
fmt.Printf(" Total: %22s\n", total)
} |
Currying | Go | {{Wikipedia|Currying}}
;Task:
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| package main
import (
"fmt"
"math"
)
func PowN(b float64) func(float64) float64 {
return func(e float64) float64 { return math.Pow(b, e) }
}
func PowE(e float64) func(float64) float64 {
return func(b float64) float64 { return math.Pow(b, e) }
}
type Foo int
func (f Foo) Method(b int) int {
return int(f) + b
}
func main() {
pow2 := PowN(2)
cube := PowE(3)
fmt.Println("2^8 =", pow2(8))
fmt.Println("4³ =", cube(4))
var a Foo = 2
fn1 := a.Method // A "method value", like currying 'a'
fn2 := Foo.Method // A "method expression", like uncurrying
fmt.Println("2 + 2 =", a.Method(2)) // regular method call
fmt.Println("2 + 3 =", fn1(3))
fmt.Println("2 + 4 =", fn2(a, 4))
fmt.Println("3 + 5 =", fn2(Foo(3), 5))
} |
Curzon numbers | Go from Wren | A '''Curzon number''' is defined to be a positive integer '''n''' for which '''2n + 1''' is evenly divisible by '''2 x n + 1'''.
'''Generalized Curzon numbers''' are those where the positive integer '''n''', using a base integer '''k''', satisfy the condition that '''kn + 1''' is evenly divisible by '''k x n + 1'''.
''Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.''
Generalized Curzon numbers only exist for even base integers.
;Task
* Find and show the first '''50 Generalized Curzon numbers''' for even base integers from '''2''' through '''10'''.
;Stretch
* Find and show the '''one thousandth'''.
;See also
;* Numbers Aplenty - Curzon numbers
;* OEIS:A224486 - Numbers k such that 2*k+1 divides 2^k+1 (Curzon numbers)
''and even though it is not specifically mentioned that they are Curzon numbers:''
;* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)
| package main
import (
"fmt"
"math/big"
)
func main() {
zero := big.NewInt(0)
one := big.NewInt(1)
for k := int64(2); k <= 10; k += 2 {
bk := big.NewInt(k)
fmt.Println("The first 50 Curzon numbers using a base of", k, ":")
count := 0
n := int64(1)
pow := big.NewInt(k)
z := new(big.Int)
var curzon50 []int64
for {
z.Add(pow, one)
d := k*n + 1
bd := big.NewInt(d)
if z.Rem(z, bd).Cmp(zero) == 0 {
if count < 50 {
curzon50 = append(curzon50, n)
}
count++
if count == 50 {
for i := 0; i < len(curzon50); i++ {
fmt.Printf("%4d ", curzon50[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Print("\nOne thousandth: ")
}
if count == 1000 {
fmt.Println(n)
break
}
}
n++
pow.Mul(pow, bk)
}
fmt.Println()
}
} |
Cut a rectangle | Go from C | A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.
[[file:rect-cut.svg]]
Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.
Possibly related task: [[Maze generation]] for depth-first search.
| package main
import "fmt"
var grid []byte
var w, h, last int
var cnt int
var next [4]int
var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}
func walk(y, x int) {
if y == 0 || y == h || x == 0 || x == w {
cnt += 2
return
}
t := y*(w+1) + x
grid[t]++
grid[last-t]++
for i, d := range dir {
if grid[t+next[i]] == 0 {
walk(y+d[0], x+d[1])
}
}
grid[t]--
grid[last-t]--
}
func solve(hh, ww, recur int) int {
h = hh
w = ww
if h&1 != 0 {
h, w = w, h
}
switch {
case h&1 == 1:
return 0
case w == 1:
return 1
case w == 2:
return h
case h == 2:
return w
}
cy := h / 2
cx := w / 2
grid = make([]byte, (h+1)*(w+1))
last = len(grid) - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recur != 0 {
cnt = 0
}
for x := cx + 1; x < w; x++ {
t := cy*(w+1) + x
grid[t] = 1
grid[last-t] = 1
walk(cy-1, x)
}
cnt++
if h == w {
cnt *= 2
} else if w&1 == 0 && recur != 0 {
solve(w, h, 0)
}
return cnt
}
func main() {
for y := 1; y <= 10; y++ {
for x := 1; x <= y; x++ {
if x&1 == 0 || y&1 == 0 {
fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1))
}
}
}
} |
Cyclotomic polynomial | Go from Java | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.
;Task:
* Find and print the first 30 cyclotomic polynomials.
* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.
;See also
* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.
| package main
import (
"fmt"
"log"
"math"
"sort"
"strings"
)
const (
algo = 2
maxAllFactors = 100000
)
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
type term struct{ coef, exp int }
func (t term) mul(t2 term) term {
return term{t.coef * t2.coef, t.exp + t2.exp}
}
func (t term) add(t2 term) term {
if t.exp != t2.exp {
log.Fatal("exponents unequal in term.add method")
}
return term{t.coef + t2.coef, t.exp}
}
func (t term) negate() term { return term{-t.coef, t.exp} }
func (t term) String() string {
switch {
case t.coef == 0:
return "0"
case t.exp == 0:
return fmt.Sprintf("%d", t.coef)
case t.coef == 1:
if t.exp == 1 {
return "x"
} else {
return fmt.Sprintf("x^%d", t.exp)
}
case t.exp == 1:
return fmt.Sprintf("%dx", t.coef)
}
return fmt.Sprintf("%dx^%d", t.coef, t.exp)
}
type poly struct{ terms []term }
// pass coef, exp in pairs as parameters
func newPoly(values ...int) poly {
le := len(values)
if le == 0 {
return poly{[]term{term{0, 0}}}
}
if le%2 != 0 {
log.Fatalf("odd number of parameters (%d) passed to newPoly function", le)
}
var terms []term
for i := 0; i < le; i += 2 {
terms = append(terms, term{values[i], values[i+1]})
}
p := poly{terms}.tidy()
return p
}
func (p poly) hasCoefAbs(coef int) bool {
for _, t := range p.terms {
if iabs(t.coef) == coef {
return true
}
}
return false
}
func (p poly) add(p2 poly) poly {
p3 := newPoly()
le, le2 := len(p.terms), len(p2.terms)
for le > 0 || le2 > 0 {
if le == 0 {
p3.terms = append(p3.terms, p2.terms[le2-1])
le2--
} else if le2 == 0 {
p3.terms = append(p3.terms, p.terms[le-1])
le--
} else {
t := p.terms[le-1]
t2 := p2.terms[le2-1]
if t.exp == t2.exp {
t3 := t.add(t2)
if t3.coef != 0 {
p3.terms = append(p3.terms, t3)
}
le--
le2--
} else if t.exp < t2.exp {
p3.terms = append(p3.terms, t)
le--
} else {
p3.terms = append(p3.terms, t2)
le2--
}
}
}
return p3.tidy()
}
func (p poly) addTerm(t term) poly {
q := newPoly()
added := false
for i := 0; i < len(p.terms); i++ {
ct := p.terms[i]
if ct.exp == t.exp {
added = true
if ct.coef+t.coef != 0 {
q.terms = append(q.terms, ct.add(t))
}
} else {
q.terms = append(q.terms, ct)
}
}
if !added {
q.terms = append(q.terms, t)
}
return q.tidy()
}
func (p poly) mulTerm(t term) poly {
q := newPoly()
for i := 0; i < len(p.terms); i++ {
ct := p.terms[i]
q.terms = append(q.terms, ct.mul(t))
}
return q.tidy()
}
func (p poly) div(v poly) poly {
q := newPoly()
lcv := v.leadingCoef()
dv := v.degree()
for p.degree() >= v.degree() {
lcp := p.leadingCoef()
s := lcp / lcv
t := term{s, p.degree() - dv}
q = q.addTerm(t)
p = p.add(v.mulTerm(t.negate()))
}
return q.tidy()
}
func (p poly) leadingCoef() int {
return p.terms[0].coef
}
func (p poly) degree() int {
return p.terms[0].exp
}
func (p poly) String() string {
var sb strings.Builder
first := true
for _, t := range p.terms {
if first {
sb.WriteString(t.String())
first = false
} else {
sb.WriteString(" ")
if t.coef > 0 {
sb.WriteString("+ ")
sb.WriteString(t.String())
} else {
sb.WriteString("- ")
sb.WriteString(t.negate().String())
}
}
}
return sb.String()
}
// in place descending sort by term.exp
func (p poly) sortTerms() {
sort.Slice(p.terms, func(i, j int) bool {
return p.terms[i].exp > p.terms[j].exp
})
}
// sort terms and remove any unnecesary zero terms
func (p poly) tidy() poly {
p.sortTerms()
if p.degree() == 0 {
return p
}
for i := len(p.terms) - 1; i >= 0; i-- {
if p.terms[i].coef == 0 {
copy(p.terms[i:], p.terms[i+1:])
p.terms[len(p.terms)-1] = term{0, 0}
p.terms = p.terms[:len(p.terms)-1]
}
}
if len(p.terms) == 0 {
p.terms = append(p.terms, term{0, 0})
}
return p
}
func getDivisors(n int) []int {
var divs []int
sqrt := int(math.Sqrt(float64(n)))
for i := 1; i <= sqrt; i++ {
if n%i == 0 {
divs = append(divs, i)
d := n / i
if d != i && d != n {
divs = append(divs, d)
}
}
}
return divs
}
var (
computed = make(map[int]poly)
allFactors = make(map[int]map[int]int)
)
func init() {
f := map[int]int{2: 1}
allFactors[2] = f
}
func getFactors(n int) map[int]int {
if f, ok := allFactors[n]; ok {
return f
}
factors := make(map[int]int)
if n%2 == 0 {
factorsDivTwo := getFactors(n / 2)
for k, v := range factorsDivTwo {
factors[k] = v
}
factors[2]++
if n < maxAllFactors {
allFactors[n] = factors
}
return factors
}
prime := true
sqrt := int(math.Sqrt(float64(n)))
for i := 3; i <= sqrt; i += 2 {
if n%i == 0 {
prime = false
for k, v := range getFactors(n / i) {
factors[k] = v
}
factors[i]++
if n < maxAllFactors {
allFactors[n] = factors
}
return factors
}
}
if prime {
factors[n] = 1
if n < maxAllFactors {
allFactors[n] = factors
}
}
return factors
}
func cycloPoly(n int) poly {
if p, ok := computed[n]; ok {
return p
}
if n == 1 {
// polynomial: x - 1
p := newPoly(1, 1, -1, 0)
computed[1] = p
return p
}
factors := getFactors(n)
cyclo := newPoly()
if _, ok := factors[n]; ok {
// n is prime
for i := 0; i < n; i++ {
cyclo.terms = append(cyclo.terms, term{1, i})
}
} else if len(factors) == 2 && factors[2] == 1 && factors[n/2] == 1 {
// n == 2p
prime := n / 2
coef := -1
for i := 0; i < prime; i++ {
coef *= -1
cyclo.terms = append(cyclo.terms, term{coef, i})
}
} else if len(factors) == 1 {
if h, ok := factors[2]; ok {
// n == 2^h
cyclo.terms = append(cyclo.terms, term{1, 1 << (h - 1)}, term{1, 0})
} else if _, ok := factors[n]; !ok {
// n == p ^ k
p := 0
for prime := range factors {
p = prime
}
k := factors[p]
for i := 0; i < p; i++ {
pk := int(math.Pow(float64(p), float64(k-1)))
cyclo.terms = append(cyclo.terms, term{1, i * pk})
}
}
} else if len(factors) == 2 && factors[2] != 0 {
// n = 2^h * p^k
p := 0
for prime := range factors {
if prime != 2 {
p = prime
}
}
coef := -1
twoExp := 1 << (factors[2] - 1)
k := factors[p]
for i := 0; i < p; i++ {
coef *= -1
pk := int(math.Pow(float64(p), float64(k-1)))
cyclo.terms = append(cyclo.terms, term{coef, i * twoExp * pk})
}
} else if factors[2] != 0 && ((n/2)%2 == 1) && (n/2) > 1 {
// CP(2m)[x] == CP(-m)[x], n odd integer > 1
cycloDiv2 := cycloPoly(n / 2)
for _, t := range cycloDiv2.terms {
t2 := t
if t.exp%2 != 0 {
t2 = t.negate()
}
cyclo.terms = append(cyclo.terms, t2)
}
} else if algo == 0 {
// slow - uses basic definition
divs := getDivisors(n)
// polynomial: x^n - 1
cyclo = newPoly(1, n, -1, 0)
for _, i := range divs {
p := cycloPoly(i)
cyclo = cyclo.div(p)
}
} else if algo == 1 {
// faster - remove max divisor (and all divisors of max divisor)
// only one divide for all divisors of max divisor
divs := getDivisors(n)
maxDiv := math.MinInt32
for _, d := range divs {
if d > maxDiv {
maxDiv = d
}
}
var divsExceptMax []int
for _, d := range divs {
if maxDiv%d != 0 {
divsExceptMax = append(divsExceptMax, d)
}
}
// polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
cyclo = newPoly(1, n, -1, 0)
cyclo = cyclo.div(newPoly(1, maxDiv, -1, 0))
for _, i := range divsExceptMax {
p := cycloPoly(i)
cyclo = cyclo.div(p)
}
} else if algo == 2 {
// fastest
// let p, q be primes such that p does not divide n, and q divides n
// then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
m := 1
cyclo = cycloPoly(m)
var primes []int
for prime := range factors {
primes = append(primes, prime)
}
sort.Ints(primes)
for _, prime := range primes {
// CP(m)[x]
cycloM := cyclo
// compute CP(m)[x^p]
var terms []term
for _, t := range cycloM.terms {
terms = append(terms, term{t.coef, t.exp * prime})
}
cyclo = newPoly()
cyclo.terms = append(cyclo.terms, terms...)
cyclo = cyclo.tidy()
cyclo = cyclo.div(cycloM)
m *= prime
}
// now, m is the largest square free divisor of n
s := n / m
// Compute CP(n)[x] = CP(m)[x^s]
var terms []term
for _, t := range cyclo.terms {
terms = append(terms, term{t.coef, t.exp * s})
}
cyclo = newPoly()
cyclo.terms = append(cyclo.terms, terms...)
} else {
log.Fatal("invalid algorithm")
}
cyclo = cyclo.tidy()
computed[n] = cyclo
return cyclo
}
func main() {
fmt.Println("Task 1: cyclotomic polynomials for n <= 30:")
for i := 1; i <= 30; i++ {
p := cycloPoly(i)
fmt.Printf("CP[%2d] = %s\n", i, p)
}
fmt.Println("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
n := 0
for i := 1; i <= 10; i++ {
for {
n++
cyclo := cycloPoly(n)
if cyclo.hasCoefAbs(i) {
fmt.Printf("CP[%d] has coefficient with magnitude = %d\n", n, i)
n--
break
}
}
}
} |
Damm algorithm | Go | The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
;Task:
Verify the checksum, stored as last digit of an input.
| package main
import "fmt"
var table = [10][10]byte{
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
}
func damm(input string) bool {
var interim byte
for _, c := range []byte(input) {
interim = table[interim][c-'0']
}
return interim == 0
}
func main() {
for _, s := range []string{"5724", "5727", "112946", "112949"} {
fmt.Printf("%6s %t\n", s, damm(s))
}
} |
De Bruijn sequences | Go | {{DISPLAYTITLE:de Bruijn sequences}}
The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.
A note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized
unless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.
In combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on
a size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every
possible length-''n'' string (computer science, formal theory) on ''A'' occurs
exactly once as a contiguous substring.
Such a sequence is denoted by ''B''(''k'', ''n'') and has
length ''k''''n'', which is also the number of distinct substrings of
length ''n'' on ''A'';
de Bruijn sequences are therefore optimally short.
There are:
(k!)k(n-1) / kn
distinct de Bruijn sequences ''B''(''k'', ''n'').
;Task:
For this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on
a PIN-like code lock that does not have an "enter"
key and accepts the last ''n'' digits entered.
Note: automated teller machines (ATMs) used to work like
this, but their software has been updated to not allow a brute-force attack.
;Example:
A digital door lock with a 4-digit code would
have ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).
Therefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to
open the lock.
Trying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.
;Task requirements:
:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
:::* Show the length of the generated de Bruijn sequence.
:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).
:::* Show the first and last '''130''' digits of the de Bruijn sequence.
:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.
:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).
:* Reverse the de Bruijn sequence.
:* Again, perform the (above) verification test.
:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
:::* Perform the verification test (again). There should be four PIN codes missing.
(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list
any and all missing PIN codes.)
Show all output here, on this page.
;References:
:* Wikipedia entry: de Bruijn sequence.
:* MathWorld entry: de Bruijn sequence.
:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.
| package main
import (
"bytes"
"fmt"
"strconv"
"strings"
)
const digits = "0123456789"
func deBruijn(k, n int) string {
alphabet := digits[0:k]
a := make([]byte, k*n)
var seq []byte
var db func(int, int) // recursive closure
db = func(t, p int) {
if t > n {
if n%p == 0 {
seq = append(seq, a[1:p+1]...)
}
} else {
a[t] = a[t-p]
db(t+1, p)
for j := int(a[t-p] + 1); j < k; j++ {
a[t] = byte(j)
db(t+1, t)
}
}
}
db(1, 1)
var buf bytes.Buffer
for _, i := range seq {
buf.WriteByte(alphabet[i])
}
b := buf.String()
return b + b[0:n-1] // as cyclic append first (n-1) digits
}
func allDigits(s string) bool {
for _, b := range s {
if b < '0' || b > '9' {
return false
}
}
return true
}
func validate(db string) {
le := len(db)
found := make([]int, 10000)
var errs []string
// Check all strings of 4 consecutive digits within 'db'
// to see if all 10,000 combinations occur without duplication.
for i := 0; i < le-3; i++ {
s := db[i : i+4]
if allDigits(s) {
n, _ := strconv.Atoi(s)
found[n]++
}
}
for i := 0; i < 10000; i++ {
if found[i] == 0 {
errs = append(errs, fmt.Sprintf(" PIN number %04d missing", i))
} else if found[i] > 1 {
errs = append(errs, fmt.Sprintf(" PIN number %04d occurs %d times", i, found[i]))
}
}
lerr := len(errs)
if lerr == 0 {
fmt.Println(" No errors found")
} else {
pl := "s"
if lerr == 1 {
pl = ""
}
fmt.Printf(" %d error%s found:\n", lerr, pl)
fmt.Println(strings.Join(errs, "\n"))
}
}
func reverse(s string) string {
bytes := []byte(s)
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
return string(bytes)
}
func main() {
db := deBruijn(10, 4)
le := len(db)
fmt.Println("The length of the de Bruijn sequence is", le)
fmt.Println("\nThe first 130 digits of the de Bruijn sequence are:")
fmt.Println(db[0:130])
fmt.Println("\nThe last 130 digits of the de Bruijn sequence are:")
fmt.Println(db[le-130:])
fmt.Println("\nValidating the de Bruijn sequence:")
validate(db)
fmt.Println("\nValidating the reversed de Bruijn sequence:")
dbr := reverse(db)
validate(dbr)
bytes := []byte(db)
bytes[4443] = '.'
db = string(bytes)
fmt.Println("\nValidating the overlaid de Bruijn sequence:")
validate(db)
} |
Deepcopy | Go | Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.
This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.
If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.
The task should show:
* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.
* Any limitations of the method.
* That the structure and its copy are different.
* Suitable links to external documentation for common libraries.
| package main
import "fmt"
// a type that allows cyclic structures
type node []*node
// recursively print the contents of a node
func (n *node) list() {
if n == nil {
fmt.Println(n)
return
}
listed := map[*node]bool{nil: true}
var r func(*node)
r = func(n *node) {
listed[n] = true
fmt.Printf("%p -> %v\n", n, *n)
for _, m := range *n {
if !listed[m] {
r(m)
}
}
}
r(n)
}
// construct a deep copy of a node
func (n *node) ccopy() *node {
if n == nil {
return n
}
cc := map[*node]*node{nil: nil}
var r func(*node) *node
r = func(n *node) *node {
c := make(node, len(*n))
cc[n] = &c
for i, m := range *n {
d, ok := cc[m]
if !ok {
d = r(m)
}
c[i] = d
}
return &c
}
return r(n)
}
func main() {
a := node{nil}
c := &node{&node{&a}}
a[0] = c
c.list()
cc := c.ccopy()
fmt.Println("copy:")
cc.list()
fmt.Println("original:")
c.list()
} |
Deming's funnel | Go from Python | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
'''Stretch goal 2''': Show scatter plots of all four results.
;Further information:
* Further explanation and interpretation
* Video demonstration of the funnel experiment at the Mayo Clinic.
| package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
} |
Department numbers | Go from Kotlin | There is a highly organized city that has decided to assign a number to each of their departments:
::* police department
::* sanitation department
::* fire department
Each department can have a number between '''1''' and '''7''' (inclusive).
The three department numbers are to be unique (different from each other) and must add up to '''12'''.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
;Task:
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| package main
import "fmt"
func main() {
fmt.Println("Police Sanitation Fire")
fmt.Println("------ ---------- ----")
count := 0
for i := 2; i < 7; i += 2 {
for j := 1; j < 8; j++ {
if j == i { continue }
for k := 1; k < 8; k++ {
if k == i || k == j { continue }
if i + j + k != 12 { continue }
fmt.Printf(" %d %d %d\n", i, j, k)
count++
}
}
}
fmt.Printf("\n%d valid combinations\n", count)
} |
Detect division by zero | Go | Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
| package main
import "fmt"
func divCheck(x, y int) (q int, ok bool) {
defer func() {
recover()
}()
q = x / y
return q, true
}
func main() {
fmt.Println(divCheck(3, 2))
fmt.Println(divCheck(3, 0))
} |
Determinant and permanent | Go | permanent of the matrix.
The determinant is given by
:: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i}
while the permanent is given by
:: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i}
In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.
;Related task:
* [[Permutations by swapping]]
| package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += float64(s) * pr
}
return
}
func permanent(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
d += pr
}
return
}
var m2 = [][]float64{
{1, 2},
{3, 4}}
var m3 = [][]float64{
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}}
func main() {
fmt.Println(determinant(m2), permanent(m2))
fmt.Println(determinant(m3), permanent(m3))
} |
Determine if a string has all the same characters | Go | Given a character string (which may be empty, or have a length of zero characters):
::* create a function/procedure/routine to:
::::* determine if all the characters in the string are the same
::::* indicate if or which character is different from the previous character
::* display each string and its length (as the strings are being examined)
::* a zero-length (empty) string shall be considered as all the same character(s)
::* process the strings from left-to-right
::* if all the same character, display a message saying such
::* if not all the same character, then:
::::* display a message saying such
::::* display what character is different
::::* only the 1st different character need be displayed
::::* display where the different character is in the string
::::* the above messages can be part of a single message
::::* display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
:::* a string of length 0 (an empty string)
:::* a string of length 3 which contains three blanks
:::* a string of length 1 which contains: '''2'''
:::* a string of length 3 which contains: '''333'''
:::* a string of length 3 which contains: '''.55'''
:::* a string of length 6 which contains: '''tttTTT'''
:::* a string of length 9 with a blank in the middle: '''4444 444k'''
Show all output here on this page.
| package main
import "fmt"
func analyze(s string) {
chars := []rune(s)
le := len(chars)
fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
if le > 1 {
for i := 1; i < le; i++ {
if chars[i] != chars[i-1] {
fmt.Println(" Not all characters in the string are the same.")
fmt.Printf(" %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1)
return
}
}
}
fmt.Println(" All characters in the string are the same.\n")
}
func main() {
strings := []string{
"",
" ",
"2",
"333",
".55",
"tttTTT",
"4444 444k",
"pépé",
"🐶🐶🐺🐶",
"🎄🎄🎄🎄",
}
for _, s := range strings {
analyze(s)
}
} |
Determine if a string has all unique characters | Go | Given a character string (which may be empty, or have a length of zero characters):
::* create a function/procedure/routine to:
::::* determine if all the characters in the string are unique
::::* indicate if or which character is duplicated and where
::* display each string and its length (as the strings are being examined)
::* a zero-length (empty) string shall be considered as unique
::* process the strings from left-to-right
::* if unique, display a message saying such
::* if not unique, then:
::::* display a message saying such
::::* display what character is duplicated
::::* only the 1st non-unique character need be displayed
::::* display where "both" duplicated characters are in the string
::::* the above messages can be part of a single message
::::* display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
:::* a string of length 0 (an empty string)
:::* a string of length 1 which is a single period ('''.''')
:::* a string of length 6 which contains: '''abcABC'''
:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''
:::* a string of length 36 which ''doesn't'' contain the letter "oh":
:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''
Show all output here on this page.
| package main
import "fmt"
func analyze(s string) {
chars := []rune(s)
le := len(chars)
fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
if le > 1 {
for i := 0; i < le-1; i++ {
for j := i + 1; j < le; j++ {
if chars[j] == chars[i] {
fmt.Println(" Not all characters in the string are unique.")
fmt.Printf(" %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)
return
}
}
}
}
fmt.Println(" All characters in the string are unique.\n")
}
func main() {
strings := []string{
"",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡",
}
for _, s := range strings {
analyze(s)
}
} |
Determine if a string is collapsible | Go | Determine if a character string is ''collapsible''.
And if so, collapse the string (by removing ''immediately repeated'' characters).
If a character string has ''immediately repeated'' character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An ''immediately repeated'' character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been ''duplicated character'', but that
might have ruled out (to some readers) triplicated characters *** or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}
;Examples:
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after ''collapsing'' the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
;Task:
Write a subroutine/function/procedure/routine*** to
locate ''repeated'' characters and ''collapse'' (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
:* the original string and its length
:* the resultant string and its length
:* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks)
;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>>
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
++
1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)
2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |
3 |..1111111111111111111111111111111111111111111111111111111111111117777888|
4 |I never give 'em hell, I just tell the truth, and they think it's hell. |
5 | --- Harry S Truman | <###### has many repeated blanks
+------------------------------------------------------------------------+
| package main
import "fmt"
// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
func collapse(s string) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings:= []string {
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
for _, s := range strings {
cs, olen, clen := collapse(s)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
} |
Determine if a string is squeezable | Go | Determine if a character string is ''squeezable''.
And if so, squeeze the string (by removing any number of
a ''specified'' ''immediately repeated'' character).
This task is very similar to the task '''Determine if a character string is collapsible''' except
that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.
If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified ''immediately repeated'' character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been ''duplicated
character'', but that might have ruled out (to some readers) triplicated characters *** or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) '''PL/I''' BIF: '''squeeze'''.}
;Examples:
In the following character string with a specified ''immediately repeated'' character of '''e''':
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd '''e''' is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after ''squeezing'' the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character '''s''':
headmistressship
The "squeezed" string would be:
headmistreship
;Task:
Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character
and ''squeeze'' (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
:* the specified repeated character (to be searched for and possibly ''squeezed''):
:* the original string and its length
:* the resultant string and its length
:* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks)
;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>>
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( | a blank, a minus, a seven, a period)
++
1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)
2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-'
3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'
4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'
5 | --- Harry S Truman | (below) <###### has many repeated blanks
+------------------------------------------------------------------------+ |
|
|
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
* a blank
* a minus
* a lowercase '''r'''
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
| package main
import "fmt"
// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
} |
Determine if two triangles overlap | Go from Kotlin | Determining if two triangles in the same plane overlap is an important topic in collision detection.
;Task:
Determine which of these pairs of triangles overlap in 2D:
:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| package main
import "fmt"
type point struct {
x, y float64
}
func (p point) String() string {
return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y)
}
type triangle struct {
p1, p2, p3 point
}
func (t *triangle) String() string {
return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3)
}
func (t *triangle) det2D() float64 {
return t.p1.x * (t.p2.y - t.p3.y) +
t.p2.x * (t.p3.y - t.p1.y) +
t.p3.x * (t.p1.y - t.p2.y)
}
func (t *triangle) checkTriWinding(allowReversed bool) {
detTri := t.det2D()
if detTri < 0.0 {
if allowReversed {
a := t.p3
t.p3 = t.p2
t.p2 = a
} else {
panic("Triangle has wrong winding direction.")
}
}
}
func boundaryCollideChk(t *triangle, eps float64) bool {
return t.det2D() < eps
}
func boundaryDoesntCollideChk(t *triangle, eps float64) bool {
return t.det2D() <= eps
}
func triTri2D(t1, t2 *triangle, eps float64, allowReversed, onBoundary bool) bool {
// Triangles must be expressed anti-clockwise.
t1.checkTriWinding(allowReversed)
t2.checkTriWinding(allowReversed)
// 'onBoundary' determines whether points on boundary are considered as colliding or not.
var chkEdge func (*triangle, float64) bool
if onBoundary {
chkEdge = boundaryCollideChk
} else {
chkEdge = boundaryDoesntCollideChk
}
lp1 := [3]point{t1.p1, t1.p2, t1.p3}
lp2 := [3]point{t2.p1, t2.p2, t2.p3}
// for each edge E of t1
for i := 0; i < 3; i++ {
j := (i + 1) % 3
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
tri1 := &triangle{lp1[i], lp1[j], lp2[0]}
tri2 := &triangle{lp1[i], lp1[j], lp2[1]}
tri3 := &triangle{lp1[i], lp1[j], lp2[2]}
if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {
return false
}
}
// for each edge E of t2
for i := 0; i < 3; i++ {
j := (i + 1) % 3
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
tri1 := &triangle{lp2[i], lp2[j], lp1[0]}
tri2 := &triangle{lp2[i], lp2[j], lp1[1]}
tri3 := &triangle{lp2[i], lp2[j], lp1[2]}
if chkEdge(tri1, eps) && chkEdge(tri2, eps) && chkEdge(tri3, eps) {
return false
}
}
// The triangles overlap.
return true
}
func iff(cond bool, s1, s2 string) string {
if cond {
return s1
}
return s2
}
func main() {
t1 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}
t2 := &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 6.0}}
fmt.Printf("%s and\n%s\n", t1, t2)
overlapping := triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
// Need to allow reversed for this pair to avoid panic.
t1 = &triangle{point{0.0, 0.0}, point{0.0, 5.0}, point{5.0, 0.0}}
t2 = t1
fmt.Printf("\n%s and\n%s\n", t1, t2)
overlapping = triTri2D(t1, t2, 0.0, true, true)
fmt.Println(iff(overlapping, "overlap (reversed)", "do not overlap"))
t1 = &triangle{point{0.0, 0.0}, point{5.0, 0.0}, point{0.0, 5.0}}
t2 = &triangle{point{-10.0, 0.0}, point{-5.0, 0.0}, point{-1.0, 6.0}}
fmt.Printf("\n%s and\n%s\n", t1, t2)
overlapping = triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
t1.p3 = point{2.5, 5.0}
t2 = &triangle{point{0.0, 4.0}, point{2.5, -1.0}, point{5.0, 4.0}}
fmt.Printf("\n%s and\n%s\n", t1, t2)
overlapping = triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
t1 = &triangle{point{0.0, 0.0}, point{1.0, 1.0}, point{0.0, 2.0}}
t2 = &triangle{point{2.0, 1.0}, point{3.0, 0.0}, point{3.0, 2.0}}
fmt.Printf("\n%s and\n%s\n", t1, t2)
overlapping = triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
t2 = &triangle{point{2.0, 1.0}, point{3.0, -2.0}, point{3.0, 4.0}}
fmt.Printf("\n%s and\n%s\n", t1, t2)
overlapping = triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
t1 = &triangle{point{0.0, 0.0}, point{1.0, 0.0}, point{0.0, 1.0}}
t2 = &triangle{point{1.0, 0.0}, point{2.0, 0.0}, point{1.0, 1.1}}
fmt.Printf("\n%s and\n%s\n", t1, t2)
println("which have only a single corner in contact, if boundary points collide")
overlapping = triTri2D(t1, t2, 0.0, false, true)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
fmt.Printf("\n%s and\n%s\n", t1, t2)
fmt.Println("which have only a single corner in contact, if boundary points do not collide")
overlapping = triTri2D(t1, t2, 0.0, false, false)
fmt.Println(iff(overlapping, "overlap", "do not overlap"))
} |
Dice game probabilities | Go from C | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| package main
import(
"math"
"fmt"
)
func minOf(x, y uint) uint {
if x < y {
return x
}
return y
}
func throwDie(nSides, nDice, s uint, counts []uint) {
if nDice == 0 {
counts[s]++
return
}
for i := uint(1); i <= nSides; i++ {
throwDie(nSides, nDice - 1, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1) // all elements zero by default
throwDie(nSides1, nDice1, 0, c1)
len2 := (nSides2 + 1) * nDice2
c2 := make([]uint, len2)
throwDie(nSides2, nDice2, 0, c2)
p12 := math.Pow(float64(nSides1), float64(nDice1)) *
math.Pow(float64(nSides2), float64(nDice2))
tot := 0.0
for i := uint(0); i < len1; i++ {
for j := uint(0); j < minOf(i, len2); j++ {
tot += float64(c1[i] * c2[j]) / p12
}
}
return tot
}
func main() {
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
} |
Digital root | Go | The digital root, X, of a number, n, is calculated:
: find X as the sum of the digits of n
: find a new X by summing the digits of X, repeating until X has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
:627615 has additive persistence 2 and digital root of 9;
:39390 has additive persistence 2 and digital root of 6;
:588225 has additive persistence 2 and digital root of 3;
:393900588225 has additive persistence 2 and digital root of 9;
The digital root may be calculated in bases other than 10.
;See:
* [[Casting out nines]] for this wiki's use of this procedure.
* [[Digital root/Multiplicative digital root]]
* [[Sum digits of an integer]]
* Digital root sequence on OEIS
* Additive persistence sequence on OEIS
* [[Iterated digits squaring]]
| package main
import (
"fmt"
"log"
"strconv"
)
func Sum(i uint64, base int) (sum int) {
b64 := uint64(base)
for ; i > 0; i /= b64 {
sum += int(i % b64)
}
return
}
func DigitalRoot(n uint64, base int) (persistence, root int) {
root = int(n)
for x := n; x >= uint64(base); x = uint64(root) {
root = Sum(x, base)
persistence++
}
return
}
// Normally the below would be moved to a *_test.go file and
// use the testing package to be runnable as a regular test.
var testCases = []struct {
n string
base int
persistence int
root int
}{
{"627615", 10, 2, 9},
{"39390", 10, 2, 6},
{"588225", 10, 2, 3},
{"393900588225", 10, 2, 9},
{"1", 10, 0, 1},
{"11", 10, 1, 2},
{"e", 16, 0, 0xe},
{"87", 16, 1, 0xf},
// From Applesoft BASIC example:
{"DigitalRoot", 30, 2, 26}, // 26 is Q base 30
// From C++ example:
{"448944221089", 10, 3, 1},
{"7e0", 16, 2, 0x6},
{"14e344", 16, 2, 0xf},
{"d60141", 16, 2, 0xa},
{"12343210", 16, 2, 0x1},
// From the D example:
{"1101122201121110011000000", 3, 3, 1},
}
func main() {
for _, tc := range testCases {
n, err := strconv.ParseUint(tc.n, tc.base, 64)
if err != nil {
log.Fatal(err)
}
p, r := DigitalRoot(n, tc.base)
fmt.Printf("%12v (base %2d) has additive persistence %d and digital root %s\n",
tc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))
if p != tc.persistence || r != tc.root {
log.Fatalln("bad result:", tc, p, r)
}
}
} |
Disarium numbers | Go from Wren | A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
;E.G.
'''135''' is a '''Disarium number''':
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of '''Disarium numbers'''.
;Task
* Find and display the first 18 '''Disarium numbers'''.
;Stretch
* Find and display all 20 '''Disarium numbers'''.
;See also
;* Geeks for Geeks - Disarium numbers
;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
;* Related task: Narcissistic decimal number
;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
| package main
import (
"fmt"
"strconv"
)
const DMAX = 20 // maximum digits
const LIMIT = 20 // maximum number of disariums to find
func main() {
// Pre-calculated exponential and power serials
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
EXP[1] = make([]uint64, 11)
POW[0] = make([]uint64, 11)
POW[1] = make([]uint64, 11)
for i := uint64(1); i <= 10; i++ {
EXP[1][i] = i
}
for i := uint64(1); i <= 9; i++ {
POW[1][i] = i
}
POW[1][10] = 9
for i := 2; i <= DMAX; i++ {
EXP[i] = make([]uint64, 11)
POW[i] = make([]uint64, 11)
}
for i := 1; i < DMAX; i++ {
for j := 0; j <= 9; j++ {
EXP[i+1][j] = EXP[i][j] * 10
POW[i+1][j] = POW[i][j] * uint64(j)
}
EXP[i+1][10] = EXP[i][10] * 10
POW[i+1][10] = POW[i][10] + POW[i+1][9]
}
// Digits of candidate and values of known low bits
DIGITS := make([]int, 1+DMAX) // Digits form
Exp := make([]uint64, 1+DMAX) // Number form
Pow := make([]uint64, 1+DMAX) // Powers form
var exp, pow, min, max uint64
start := 1
final := DMAX
count := 0
for digit := start; digit <= final; digit++ {
fmt.Println("# of digits:", digit)
level := 1
DIGITS[0] = 0
for {
// Check limits derived from already known low bit values
// to find the most possible candidates
for 0 < level && level < digit {
// Reset path to try next if checking in level is done
if DIGITS[level] > 9 {
DIGITS[level] = 0
level--
DIGITS[level]++
continue
}
// Update known low bit values
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
// Max possible value
pow = Pow[level] + POW[digit-level][10]
if pow < EXP[digit][1] { // Try next since upper limit is invalidly low
DIGITS[level]++
continue
}
max = pow % EXP[level][10]
pow -= max
if max < Exp[level] {
pow -= EXP[level][10]
}
max = pow + Exp[level]
if max < EXP[digit][1] { // Try next since upper limit is invalidly low
DIGITS[level]++
continue
}
// Min possible value
exp = Exp[level] + EXP[digit][1]
pow = Pow[level] + 1
if exp > max || max < pow { // Try next since upper limit is invalidly low
DIGITS[level]++
continue
}
if pow > exp {
min = pow % EXP[level][10]
pow -= min
if min > Exp[level] {
pow += EXP[level][10]
}
min = pow + Exp[level]
} else {
min = exp
}
// Check limits existence
if max < min {
DIGITS[level]++ // Try next number since current limits invalid
} else {
level++ // Go for further level checking since limits available
}
}
// All checking is done, escape from the main check loop
if level < 1 {
break
}
// Finally check last bit of the most possible candidates
// Update known low bit values
Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]]
Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]
// Loop to check all last bits of candidates
for DIGITS[level] < 10 {
// Print out new Disarium number
if Exp[level] == Pow[level] {
s := ""
for i := DMAX; i > 0; i-- {
s += fmt.Sprintf("%d", DIGITS[i])
}
n, _ := strconv.ParseUint(s, 10, 64)
fmt.Println(n)
count++
if count == LIMIT {
fmt.Println("\nFound the first", LIMIT, "Disarium numbers.")
return
}
}
// Go to followed last bit candidate
DIGITS[level]++
Exp[level] += EXP[level][1]
Pow[level]++
}
// Reset to try next path
DIGITS[level] = 0
level--
DIGITS[level]++
}
fmt.Println()
}
} |
Display a linear combination | Go from Kotlin | Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots).
Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is:
:\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots
where \alpha^{i_k}\neq 0
The output must comply to the following rules:
* don't show null terms, unless the whole combination is null.
::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.
* don't show scalars when they are equal to one or minus one.
::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.
* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| package main
import (
"fmt"
"strings"
)
func linearCombo(c []int) string {
var sb strings.Builder
for i, n := range c {
if n == 0 {
continue
}
var op string
switch {
case n < 0 && sb.Len() == 0:
op = "-"
case n < 0:
op = " - "
case n > 0 && sb.Len() == 0:
op = ""
default:
op = " + "
}
av := n
if av < 0 {
av = -av
}
coeff := fmt.Sprintf("%d*", av)
if av == 1 {
coeff = ""
}
sb.WriteString(fmt.Sprintf("%s%se(%d)", op, coeff, i+1))
}
if sb.Len() == 0 {
return "0"
} else {
return sb.String()
}
}
func main() {
combos := [][]int{
{1, 2, 3},
{0, 1, 2, 3},
{1, 0, 3, 4},
{1, 2, 0},
{0, 0, 0},
{0},
{1, 1, 1},
{-1, -1, -1},
{-1, -2, 0, -3},
{-1},
}
for _, c := range combos {
t := strings.Replace(fmt.Sprint(c), " ", ", ", -1)
fmt.Printf("%-15s -> %s\n", t, linearCombo(c))
}
} |
Display an outline as a nested table | Go | {| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
| |
| |
| |
| |
| style="background: #f0fff0; " | (The sum of the widths of its children)
| |
| |
|}
The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.
;Task:
Given a outline with at least 3 levels of indentation, for example:
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.
The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:
{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
| |
| |
| |
| |
| style="background: #f0fff0; " | (The sum of the widths of its children)
| |
| |
|}
;Extra credit:
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.
;Output:
Display your nested table on this page.
| package main
import (
"fmt"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(iNodes); i++ {
if iNodes[i].level == level+1 {
c := nNode{iNodes[i].name, nil}
toNest(iNodes, i, level+1, &c)
n.children = append(n.children, c)
} else if iNodes[i].level <= level {
return
}
}
}
func makeIndent(outline string, tab int) []iNode {
lines := strings.Split(outline, "\n")
iNodes := make([]iNode, len(lines))
for i, line := range lines {
line2 := strings.TrimLeft(line, " ")
le, le2 := len(line), len(line2)
level := (le - le2) / tab
iNodes[i] = iNode{level, line2}
}
return iNodes
}
func toMarkup(n nNode, cols []string, depth int) string {
var span int
var colSpan func(nn nNode)
colSpan = func(nn nNode) {
for i, c := range nn.children {
if i > 0 {
span++
}
colSpan(c)
}
}
for _, c := range n.children {
span = 1
colSpan(c)
}
var lines []string
lines = append(lines, `{| class="wikitable" style="text-align: center;"`)
const l1, l2 = "|-", "| |"
lines = append(lines, l1)
span = 1
colSpan(n)
s := fmt.Sprintf(`| style="background: %s " colSpan=%d | %s`, cols[0], span, n.name)
lines = append(lines, s, l1)
var nestedFor func(nn nNode, level, maxLevel, col int)
nestedFor = func(nn nNode, level, maxLevel, col int) {
if level == 1 && maxLevel > level {
for i, c := range nn.children {
nestedFor(c, 2, maxLevel, i)
}
} else if level < maxLevel {
for _, c := range nn.children {
nestedFor(c, level+1, maxLevel, col)
}
} else {
if len(nn.children) > 0 {
for i, c := range nn.children {
span = 1
colSpan(c)
cn := col + 1
if maxLevel == 1 {
cn = i + 1
}
s := fmt.Sprintf(`| style="background: %s " colspan=%d | %s`, cols[cn], span, c.name)
lines = append(lines, s)
}
} else {
lines = append(lines, l2)
}
}
}
for maxLevel := 1; maxLevel < depth; maxLevel++ {
nestedFor(n, 1, maxLevel, 0)
if maxLevel < depth-1 {
lines = append(lines, l1)
}
}
lines = append(lines, "|}")
return strings.Join(lines, "\n")
}
func main() {
const outline = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.`
const (
yellow = "#ffffe6;"
orange = "#ffebd2;"
green = "#f0fff0;"
blue = "#e6ffff;"
pink = "#ffeeff;"
)
cols := []string{yellow, orange, green, blue, pink}
iNodes := makeIndent(outline, 4)
var n nNode
toNest(iNodes, 0, 0, &n)
fmt.Println(toMarkup(n, cols, 4))
fmt.Println("\n")
const outline2 = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
Propagating the sums upward as necessary.
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
Optionally add color to the nodes.`
cols2 := []string{blue, yellow, orange, green, pink}
var n2 nNode
iNodes2 := makeIndent(outline2, 4)
toNest(iNodes2, 0, 0, &n2)
fmt.Println(toMarkup(n2, cols2, 4))
} |
Diversity prediction theorem | Go | The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''.
Therefore, when the diversity in a group is large, the error of the crowd is small.
;Definitions:
::* Average Individual Error: Average of the individual squared errors
::* Collective Error: Squared error of the collective prediction
::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then
:::::: Collective Error = Average Individual Error - Prediction Diversity
;Task:
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
:::* the true value and the crowd estimates
:::* the average error
:::* the crowd error
:::* the prediction diversity
Use (at least) these two examples:
:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''
:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''
;Also see:
:* Wikipedia entry: Wisdom of the crowd
:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
| package main
import "fmt"
func averageSquareDiff(f float64, preds []float64) (av float64) {
for _, pred := range preds {
av += (pred - f) * (pred - f)
}
av /= float64(len(preds))
return
}
func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
av := 0.0
for _, pred := range preds {
av += pred
}
av /= float64(len(preds))
avErr := averageSquareDiff(truth, preds)
crowdErr := (truth - av) * (truth - av)
div := averageSquareDiff(av, preds)
return avErr, crowdErr, div
}
func main() {
predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}
truth := 49.0
for _, preds := range predsArray {
avErr, crowdErr, div := diversityTheorem(truth, preds)
fmt.Printf("Average-error : %6.3f\n", avErr)
fmt.Printf("Crowd-error : %6.3f\n", crowdErr)
fmt.Printf("Diversity : %6.3f\n\n", div)
}
} |
Doomsday rule | Go from Wren | About the task
John Conway (1937-2020), was a mathematician who also invented several mathematically
oriented computer pastimes, such as the famous Game of Life cellular automaton program.
Dr. Conway invented a simple algorithm for finding the day of the week, given any date.
The algorithm was based on calculating the distance of a given date from certain
"anchor days" which follow a pattern for the day of the week upon which they fall.
; Algorithm
The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and
doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7
which, for 2021, is 0 (Sunday).
To calculate the day of the week, we then count days from a close doomsday,
with these as charted here by month, then add the doomsday for the year,
then get the remainder after dividing by 7. This should give us the number
corresponding to the day of the week for that date.
Month Doomsday Dates for Month
--------------------------------------------
January (common years) 3, 10, 17, 24, 31
January (leap years) 4, 11, 18, 25
February (common years) 7, 14, 21, 28
February (leap years) 1, 8, 15, 22, 29
March 7, 14, 21, 28
April 4, 11, 18, 25
May 2, 9, 16, 23, 30
June 6, 13, 20, 27
July 4, 11, 18, 25
August 1, 8, 15, 22, 29
September 5, 12, 19, 26
October 3, 10, 17, 24, 31
November 7, 14, 21, 28
December 5, 12, 19, 26
; Task
Given the following dates:
* 1800-01-06 (January 6, 1800)
* 1875-03-29 (March 29, 1875)
* 1915-12-07 (December 7, 1915)
* 1970-12-23 (December 23, 1970)
* 2043-05-14 (May 14, 2043)
* 2077-02-12 (February 12, 2077)
* 2101-04-02 (April 2, 2101)
Use Conway's Doomsday rule to calculate the day of the week for each date.
; see also
* Doomsday rule
* Tomorrow is the Day After Doomsday (p.28)
| package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
} |
Dot product | Go | Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
:::: [1, 3, -5] and
:::: [4, -2, -1]
If implementing the dot product of two vectors directly:
:::* each vector must be the same length
:::* multiply corresponding terms from each vector
:::* sum the products (to produce the answer)
;Related task:
* [[Vector products]]
| package main
import (
"errors"
"fmt"
"log"
)
var (
v1 = []int{1, 3, -5}
v2 = []int{4, -2, -1}
)
func dot(x, y []int) (r int, err error) {
if len(x) != len(y) {
return 0, errors.New("incompatible lengths")
}
for i, xi := range x {
r += xi * y[i]
}
return
}
func main() {
d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})
if err != nil {
log.Fatal(err)
}
fmt.Println(d)
} |
Draw a clock | Go | Draw a clock.
More specific:
# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
;Key points
* animate simple object
* timed event
* polling system resources
* code clarity
| <!DOCTYPE html>
<meta charset="utf-8" />
<title>Clock</title>
<script language="javascript" type="text/javascript">
var connurl = "ws://{{.Host}}:{{.Port}}/ws";
//var ctx;
var secondhand;
var minutehand;
var hourhand;
function wsConnect()
{
//get contexts for drawing
//var canvas = document.getElementById( "canvas" );
//ctx = canvas.getContext( '2d' );
var canvas = document.getElementById("rim");
//draw circle for rim
rim = canvas.getContext('2d');
rim.beginPath();
rim.arc(256,256,256,0,2*Math.PI);
rim.stroke();
//minute hand
canvas = document.getElementById("minutehand");
minutehand = canvas.getContext('2d');
//hour hand
canvas = document.getElementById("hourhand");
hourhand = canvas.getContext('2d');
//second hand
canvas = document.getElementById("secondhand");
secondhand = canvas.getContext('2d');
ws = new WebSocket( connurl );
ws.onopen = function( e ) {
console.log( "CONNECTED" );
ws.send( "READY" );
};
/*ws.onclose = function( e ) {
console.log( "DISCONNECTED" );
};*/
ws.onmessage = function( e ) {
var data = e.data.split("\n");
for ( var line in data ) {
var msg = data[line].split(" ");
var cmd = msg[0];
if (cmd =="CLEAR"){
minutehand.clearRect(0,0,512,512);
secondhand.clearRect(0,0,512,512);
hourhand.clearRect(0,0,512,512);
}else if (cmd === "HOUR"){
renderline(hourhand, msg);
}else if (cmd === "MIN"){
renderline(minutehand, msg);
}else if (cmd === "SEC"){
renderline(secondhand, msg);
}else if (cmd ===""){
cmd = "";
}else{
console.log("BAD COMMAND: "+cmd + "; "+msg);
}
}
};
ws.onerror = function( e ) {
console.log( 'WS Error: ' + e.data );
};
}
//render line given paramets
function renderline(ctx, msg){
ctx.clearRect(0,0,512,512);
ctx.width = ctx.width;
var x = parseInt(msg[1],10);
var y = parseInt(msg[2],10);
var color = msg[3];
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(256,256);
ctx.lineTo(x,y);
ctx.stroke();
}
window.addEventListener( "load", wsConnect, false );
</script>
<body>
<h2>Clock</h2>
<canvas id="rim" width="512" height="512" style="position: absolute; left: 0; top: 0; z-index: 0;">
Sorry, your browser does not support Canvas
</canvas>
<canvas id="hourhand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 1;">
Sorry, your browser does not support Canvas
</canvas>
<canvas id="minutehand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 2;">
Sorry, your browser does not support Canvas
</canvas>
<canvas id="secondhand" width="512" height="512"style="position: absolute; left: 0; top: 0; z-index: 3;">
Sorry, your browser does not support Canvas
</canvas>
</body>
</html> |
Draw a rotating cube | Go | Task
Draw a rotating cube.
It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.
;Related tasks
* Draw a cuboid
* write language name in 3D ASCII
| package main
import (
"image"
"image/color"
"image/gif"
"log"
"math"
"os"
)
const (
width, height = 640, 640
offset = height / 2
fileName = "rotatingCube.gif"
)
var nodes = [][]float64{{-100, -100, -100}, {-100, -100, 100}, {-100, 100, -100}, {-100, 100, 100},
{100, -100, -100}, {100, -100, 100}, {100, 100, -100}, {100, 100, 100}}
var edges = [][]int{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
{6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}
func main() {
var images []*image.Paletted
fgCol := color.RGBA{0xff, 0x00, 0xff, 0xff}
var palette = []color.Color{color.RGBA{0x00, 0x00, 0x00, 0xff}, fgCol}
var delays []int
imgFile, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer imgFile.Close()
rotateCube(math.Pi/4, math.Atan(math.Sqrt(2)))
var frame float64
for frame = 0; frame < 360; frame++ {
img := image.NewPaletted(image.Rect(0, 0, width, height), palette)
images = append(images, img)
delays = append(delays, 5)
for _, edge := range edges {
xy1 := nodes[edge[0]]
xy2 := nodes[edge[1]]
drawLine(int(xy1[0])+offset, int(xy1[1])+offset, int(xy2[0])+offset, int(xy2[1])+offset, img, fgCol)
}
rotateCube(math.Pi/180, 0)
}
if err := gif.EncodeAll(imgFile, &gif.GIF{Image: images, Delay: delays}); err != nil {
imgFile.Close()
log.Fatal(err)
}
}
func rotateCube(angleX, angleY float64) {
sinX := math.Sin(angleX)
cosX := math.Cos(angleX)
sinY := math.Sin(angleY)
cosY := math.Cos(angleY)
for _, node := range nodes {
x := node[0]
y := node[1]
z := node[2]
node[0] = x*cosX - z*sinX
node[2] = z*cosX + x*sinX
z = node[2]
node[1] = y*cosY - z*sinY
node[2] = z*cosY + y*sinY
}
}
func drawLine(x0, y0, x1, y1 int, img *image.Paletted, col color.RGBA) {
dx := abs(x1 - x0)
dy := abs(y1 - y0)
var sx, sy int = -1, -1
if x0 < x1 {
sx = 1
}
if y0 < y1 {
sy = 1
}
err := dx - dy
for {
img.Set(x0, y0, col)
if x0 == x1 && y0 == y1 {
break
}
e2 := 2 * err
if e2 > -dy {
err -= dy
x0 += sx
}
if e2 < dx {
err += dx
y0 += sy
}
}
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
} |
Draw a sphere | Go from C | {{requires|Graphics}}
;Task:
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
;Related tasks:
* draw a cuboid
* draw a rotating cube
* write language name in 3D ASCII
* draw a Deathstar
| package main
import (
"fmt"
"image"
"image/color"
"image/png"
"math"
"os"
)
type vector [3]float64
func normalize(v *vector) {
invLen := 1 / math.Sqrt(dot(v, v))
v[0] *= invLen
v[1] *= invLen
v[2] *= invLen
}
func dot(x, y *vector) float64 {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
}
func drawSphere(r int, k, amb float64, dir *vector) *image.Gray {
w, h := r*4, r*3
img := image.NewGray(image.Rect(-w/2, -h/2, w/2, h/2))
vec := new(vector)
for x := -r; x < r; x++ {
for y := -r; y < r; y++ {
if z := r*r - x*x - y*y; z >= 0 {
vec[0] = float64(x)
vec[1] = float64(y)
vec[2] = math.Sqrt(float64(z))
normalize(vec)
s := dot(dir, vec)
if s < 0 {
s = 0
}
lum := 255 * (math.Pow(s, k) + amb) / (1 + amb)
if lum < 0 {
lum = 0
} else if lum > 255 {
lum = 255
}
img.SetGray(x, y, color.Gray{uint8(lum)})
}
}
}
return img
}
func main() {
dir := &vector{-30, -30, 50}
normalize(dir)
img := drawSphere(200, 1.5, .2, dir)
f, err := os.Create("sphere.png")
if err != nil {
fmt.Println(err)
return
}
if err = png.Encode(f, img); err != nil {
fmt.Println(err)
}
if err = f.Close(); err != nil {
fmt.Println(err)
}
} |
Dutch national flag problem | Go | The Dutch national flag is composed of three coloured bands in the order:
::* red (top)
::* then white, and
::* lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...
;Task
# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.
# Sort the balls in a way idiomatic to your language.
# Check the sorted balls ''are'' in the order of the Dutch national flag.
;C.f.:
* Dutch national flag problem
* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
| package main
import (
"fmt"
"math/rand"
"time"
)
// constants define order of colors in Dutch national flag
const (
red = iota
white
blue
nColors
)
// zero object of type is valid red ball.
type ball struct {
color int
}
// order of balls based on DNF
func (b1 ball) lt(b2 ball) bool {
return b1.color < b2.color
}
// type for arbitrary ordering of balls
type ordering []ball
// predicate tells if balls are ordered by DNF
func (o ordering) ordered() bool {
var b0 ball
for _, b := range o {
if b.lt(b0) {
return false
}
b0 = b
}
return true
}
func init() {
rand.Seed(time.Now().Unix())
}
// constructor returns new ordering of balls which is randomized but
// guaranteed to be not in DNF order. function panics for n < 2.
func outOfOrder(n int) ordering {
if n < 2 {
panic(fmt.Sprintf("%d invalid", n))
}
r := make(ordering, n)
for {
for i, _ := range r {
r[i].color = rand.Intn(nColors)
}
if !r.ordered() {
break
}
}
return r
}
// O(n) algorithm
// http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/
func (a ordering) sort3() {
lo, mid, hi := 0, 0, len(a)-1
for mid <= hi {
switch a[mid].color {
case red:
a[lo], a[mid] = a[mid], a[lo]
lo++
mid++
case white:
mid++
default:
a[mid], a[hi] = a[hi], a[mid]
hi--
}
}
}
func main() {
f := outOfOrder(12)
fmt.Println(f)
f.sort3()
fmt.Println(f)
} |
EKG sequence convergence | Go | The sequence is from the natural numbers and is defined by:
* a(1) = 1;
* a(2) = Start = 2;
* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.
The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).
Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call:
* The sequence described above , starting 1, 2, ... the EKG(2) sequence;
* the sequence starting 1, 3, ... the EKG(3) sequence;
* ... the sequence starting 1, N, ... the EKG(N) sequence.
;Convergence
If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.
EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).
;Task:
# Calculate and show here the first 10 members of EKG(2).
# Calculate and show here the first 10 members of EKG(5).
# Calculate and show here the first 10 members of EKG(7).
# Calculate and show here the first 10 members of EKG(9).
# Calculate and show here the first 10 members of EKG(10).
# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').
;Related Tasks:
# [[Greatest common divisor]]
# [[Sieve of Eratosthenes]]
;Reference:
* The EKG Sequence and the Tree of Numbers. (Video).
| package main
import (
"fmt"
"sort"
)
func contains(a []int, b int) bool {
for _, j := range a {
if j == b {
return true
}
}
return false
}
func gcd(a, b int) int {
for a != b {
if a > b {
a -= b
} else {
b -= a
}
}
return a
}
func areSame(s, t []int) bool {
le := len(s)
if le != len(t) {
return false
}
sort.Ints(s)
sort.Ints(t)
for i := 0; i < le; i++ {
if s[i] != t[i] {
return false
}
}
return true
}
func main() {
const limit = 100
starts := [5]int{2, 5, 7, 9, 10}
var ekg [5][limit]int
for s, start := range starts {
ekg[s][0] = 1
ekg[s][1] = start
for n := 2; n < limit; n++ {
for i := 2; ; i++ {
// a potential sequence member cannot already have been used
// and must have a factor in common with previous member
if !contains(ekg[s][:n], i) && gcd(ekg[s][n-1], i) > 1 {
ekg[s][n] = i
break
}
}
}
fmt.Printf("EKG(%2d): %v\n", start, ekg[s][:30])
}
// now compare EKG5 and EKG7 for convergence
for i := 2; i < limit; i++ {
if ekg[1][i] == ekg[2][i] && areSame(ekg[1][:i], ekg[2][:i]) {
fmt.Println("\nEKG(5) and EKG(7) converge at term", i+1)
return
}
}
fmt.Println("\nEKG5(5) and EKG(7) do not converge within", limit, "terms")
} |
Eban numbers | Go | Definition:
An '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.
Or more literally, spelled numbers that contain the letter '''e''' are banned.
The American version of spelling numbers will be used here (as opposed to the British).
'''2,000,000,000''' is two billion, ''not'' two milliard.
Only numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.
This will allow optimizations to be used.
;Task:
:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count
:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count
:::* show a count of all eban numbers up and including '''10,000'''
:::* show a count of all eban numbers up and including '''100,000'''
:::* show a count of all eban numbers up and including '''1,000,000'''
:::* show a count of all eban numbers up and including '''10,000,000'''
:::* show all output here.
;See also:
:* The MathWorld entry: eban numbers.
:* The OEIS entry: A6933, eban numbers.
:* [[Number names]].
| package main
import "fmt"
type Range struct {
start, end uint64
print bool
}
func main() {
rgs := []Range{
{2, 1000, true},
{1000, 4000, true},
{2, 1e4, false},
{2, 1e5, false},
{2, 1e6, false},
{2, 1e7, false},
{2, 1e8, false},
{2, 1e9, false},
}
for _, rg := range rgs {
if rg.start == 2 {
fmt.Printf("eban numbers up to and including %d:\n", rg.end)
} else {
fmt.Printf("eban numbers between %d and %d (inclusive):\n", rg.start, rg.end)
}
count := 0
for i := rg.start; i <= rg.end; i += 2 {
b := i / 1000000000
r := i % 1000000000
m := r / 1000000
r = i % 1000000
t := r / 1000
r %= 1000
if m >= 30 && m <= 66 {
m %= 10
}
if t >= 30 && t <= 66 {
t %= 10
}
if r >= 30 && r <= 66 {
r %= 10
}
if b == 0 || b == 2 || b == 4 || b == 6 {
if m == 0 || m == 2 || m == 4 || m == 6 {
if t == 0 || t == 2 || t == 4 || t == 6 {
if r == 0 || r == 2 || r == 4 || r == 6 {
if rg.print {
fmt.Printf("%d ", i)
}
count++
}
}
}
}
}
if rg.print {
fmt.Println()
}
fmt.Println("count =", count, "\n")
}
} |
Eertree | Go | An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.
The data structure has commonalities to both ''tries'' and ''suffix trees''.
See links below.
;Task:
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.
;See also:
* Wikipedia entry: trie.
* Wikipedia entry: suffix tree
* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.
| package main
import "fmt"
func main() {
tree := eertree([]byte("eertree"))
fmt.Println(subPalindromes(tree))
}
type edges map[byte]int
type node struct {
length int
edges
suffix int
}
const evenRoot = 0
const oddRoot = 1
func eertree(s []byte) []node {
tree := []node{
evenRoot: {length: 0, suffix: oddRoot, edges: edges{}},
oddRoot: {length: -1, suffix: oddRoot, edges: edges{}},
}
suffix := oddRoot
var n, k int
for i, c := range s {
for n = suffix; ; n = tree[n].suffix {
k = tree[n].length
if b := i - k - 1; b >= 0 && s[b] == c {
break
}
}
if e, ok := tree[n].edges[c]; ok {
suffix = e
continue
}
suffix = len(tree)
tree = append(tree, node{length: k + 2, edges: edges{}})
tree[n].edges[c] = suffix
if tree[suffix].length == 1 {
tree[suffix].suffix = 0
continue
}
for {
n = tree[n].suffix
if b := i - tree[n].length - 1; b >= 0 && s[b] == c {
break
}
}
tree[suffix].suffix = tree[n].edges[c]
}
return tree
}
func subPalindromes(tree []node) (s []string) {
var children func(int, string)
children = func(n int, p string) {
for c, n := range tree[n].edges {
c := string(c)
p := c + p + c
s = append(s, p)
children(n, p)
}
}
children(0, "")
for c, n := range tree[1].edges {
c := string(c)
s = append(s, c)
children(n, c)
}
return
} |
Egyptian division | Go from Kotlin | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of [[Ethiopian multiplication]]
'''Algorithm:'''
Given two numbers where the '''dividend''' is to be divided by the '''divisor''':
# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
# Continue with successive i'th rows of 2^i and 2^i * divisor.
# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''
# Consider each row of the table, in the ''reverse'' order of its construction.
# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).
'''Example: 580 / 34'''
''' Table creation: '''
::: {| class="wikitable"
! powers_of_2
! doublings
|-
| 1
| 34
|-
| 2
| 68
|-
| 4
| 136
|-
| 8
| 272
|-
| 16
| 544
|}
''' Initialization of sums: '''
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| 16
| 544
|
|
|-
|
|
| 0
| 0
|}
''' Considering table rows, bottom-up: '''
When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
| 16
| 544
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
| 16
| 544
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
|
|
|-
| 4
| 136
| 16
| 544
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|
|
|-
| 2
| 68
| 16
| 544
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| '''1'''
| '''34'''
| 17
| 578
|-
| 2
| 68
|
|
|-
| 4
| 136
|
|
|-
| 8
| 272
|
|
|-
| '''16'''
| '''544'''
|
|
|}
;Answer:
So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.
;Task:
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.
* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.
;Related tasks:
:* Egyptian fractions
;References:
:* Egyptian Number System
| package main
import "fmt"
func egyptianDivide(dividend, divisor int) (quotient, remainder int) {
if dividend < 0 || divisor <= 0 {
panic("Invalid argument(s)")
}
if dividend < divisor {
return 0, dividend
}
powersOfTwo := []int{1}
doublings := []int{divisor}
doubling := divisor
for {
doubling *= 2
if doubling > dividend {
break
}
l := len(powersOfTwo)
powersOfTwo = append(powersOfTwo, powersOfTwo[l-1]*2)
doublings = append(doublings, doubling)
}
answer := 0
accumulator := 0
for i := len(doublings) - 1; i >= 0; i-- {
if accumulator+doublings[i] <= dividend {
accumulator += doublings[i]
answer += powersOfTwo[i]
if accumulator == dividend {
break
}
}
}
return answer, dividend - accumulator
}
func main() {
dividend := 580
divisor := 34
quotient, remainder := egyptianDivide(dividend, divisor)
fmt.Println(dividend, "divided by", divisor, "is", quotient, "with remainder", remainder)
} |
Elementary cellular automaton | Go | An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.
The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.
;Task:
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.
The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.
This task is basically a generalization of [[one-dimensional cellular automata]].
;See also
* Cellular automata (natureofcode.com)
| package main
import (
"fmt"
"math/big"
"math/rand"
"strings"
)
func main() {
const cells = 20
const generations = 9
fmt.Println("Single 1, rule 90:")
a := big.NewInt(1)
a.Lsh(a, cells/2)
elem(90, cells, generations, a)
fmt.Println("Random intial state, rule 30:")
a = big.NewInt(1)
a.Rand(rand.New(rand.NewSource(3)), a.Lsh(a, cells))
elem(30, cells, generations, a)
}
func elem(rule uint, cells, generations int, a *big.Int) {
output := func() {
fmt.Println(strings.Replace(strings.Replace(
fmt.Sprintf("%0*b", cells, a), "0", " ", -1), "1", "#", -1))
}
output()
a1 := new(big.Int)
set := func(cell int, k uint) {
a1.SetBit(a1, cell, rule>>k&1)
}
last := cells - 1
for r := 0; r < generations; r++ {
k := a.Bit(last) | a.Bit(0)<<1 | a.Bit(1)<<2
set(0, k)
for c := 1; c < last; c++ {
k = k>>1 | a.Bit(c+1)<<2
set(c, k)
}
set(last, k>>1|a.Bit(0)<<2)
a, a1 = a1, a
output()
}
} |
Elementary cellular automaton/Infinite length | Go from C++ | The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.
To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.
Examples:
1 -> ..., 0, 0, 1, 0, 0, ...
0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...
1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...
More complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.
| package main
import (
"fmt"
"strings"
)
func btoi(b bool) int {
if b {
return 1
}
return 0
}
func evolve(l, rule int) {
fmt.Printf(" Rule #%d:\n", rule)
cells := "O"
for x := 0; x < l; x++ {
cells = addNoCells(cells)
width := 40 + (len(cells) >> 1)
fmt.Printf("%*s\n", width, cells)
cells = step(cells, rule)
}
}
func step(cells string, rule int) string {
newCells := new(strings.Builder)
for i := 0; i < len(cells)-2; i++ {
bin := 0
b := uint(2)
for n := i; n < i+3; n++ {
bin += btoi(cells[n] == 'O') << b
b >>= 1
}
a := '.'
if rule&(1<<uint(bin)) != 0 {
a = 'O'
}
newCells.WriteRune(a)
}
return newCells.String()
}
func addNoCells(cells string) string {
l, r := "O", "O"
if cells[0] == 'O' {
l = "."
}
if cells[len(cells)-1] == 'O' {
r = "."
}
cells = l + cells + r
cells = l + cells + r
return cells
}
func main() {
for _, r := range []int{90, 30} {
evolve(25, r)
fmt.Println()
}
} |
Elementary cellular automaton/Random number generator | Go from C | Mathematica software for its default random number generator.
Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.
The purpose of this task is to demonstrate this. With the code written in the most significant.
You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.
For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.
;Reference:
* Cellular automata: Is Rule 30 random? (PDF).
| package main
import "fmt"
const n = 64
func pow2(x uint) uint64 {
return uint64(1) << x
}
func evolve(state uint64, rule int) {
for p := 0; p < 10; p++ {
b := uint64(0)
for q := 7; q >= 0; q-- {
st := state
b |= (st & 1) << uint(q)
state = 0
for i := uint(0); i < n; i++ {
var t1, t2, t3 uint64
if i > 0 {
t1 = st >> (i - 1)
} else {
t1 = st >> 63
}
if i == 0 {
t2 = st << 1
} else if i == 1 {
t2 = st << 63
} else {
t2 = st << (n + 1 - i)
}
t3 = 7 & (t1 | t2)
if (uint64(rule) & pow2(uint(t3))) != 0 {
state |= pow2(i)
}
}
}
fmt.Printf("%d ", b)
}
fmt.Println()
}
func main() {
evolve(1, 30)
} |
Elliptic curve arithmetic | Go from C | digital signatures.
The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol.
In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:
:::: y^2 = x^3 + a x + b
'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used.
For this particular task, we'll use the following parameters:
:::: a=0, b=7
The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it.
To do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:
:::: P + Q + R = 0
Here '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry.
We'll also assume here that this infinity point is unique and defines the neutral element of the addition.
This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:
Given any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.
Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).
'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.
The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.
You will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.
''Hint'': You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''.
''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).
| package main
import (
"fmt"
"math"
)
const bCoeff = 7
type pt struct{ x, y float64 }
func zero() pt {
return pt{math.Inf(1), math.Inf(1)}
}
func is_zero(p pt) bool {
return p.x > 1e20 || p.x < -1e20
}
func neg(p pt) pt {
return pt{p.x, -p.y}
}
func dbl(p pt) pt {
if is_zero(p) {
return p
}
L := (3 * p.x * p.x) / (2 * p.y)
x := L*L - 2*p.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func add(p, q pt) pt {
if p.x == q.x && p.y == q.y {
return dbl(p)
}
if is_zero(p) {
return q
}
if is_zero(q) {
return p
}
L := (q.y - p.y) / (q.x - p.x)
x := L*L - p.x - q.x
return pt{
x: x,
y: L*(p.x-x) - p.y,
}
}
func mul(p pt, n int) pt {
r := zero()
for i := 1; i <= n; i <<= 1 {
if i&n != 0 {
r = add(r, p)
}
p = dbl(p)
}
return r
}
func show(s string, p pt) {
fmt.Printf("%s", s)
if is_zero(p) {
fmt.Println("Zero")
} else {
fmt.Printf("(%.3f, %.3f)\n", p.x, p.y)
}
}
func from_y(y float64) pt {
return pt{
x: math.Cbrt(y*y - bCoeff),
y: y,
}
}
func main() {
a := from_y(1)
b := from_y(2)
show("a = ", a)
show("b = ", b)
c := add(a, b)
show("c = a + b = ", c)
d := neg(c)
show("d = -c = ", d)
show("c + d = ", add(c, d))
show("a + b + d = ", add(a, add(b, d)))
show("a * 12345 = ", mul(a, 12345))
} |
Empty directory | Go | Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
| package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
empty, err := IsEmptyDir("/tmp")
if err != nil {
log.Fatalln(err)
}
if empty {
fmt.Printf("/tmp is empty\n")
} else {
fmt.Printf("/tmp is not empty\n")
}
}
func IsEmptyDir(name string) (bool, error) {
entries, err := ioutil.ReadDir(name)
if err != nil {
return false, err
}
return len(entries) == 0, nil
}
|
Empty string | Go | Languages may have features for dealing specifically with empty strings
(those containing no characters).
;Task:
::* Demonstrate how to assign an empty string to a variable.
::* Demonstrate how to check that a string is empty.
::* Demonstrate how to check that a string is not empty.
| package main
import (
"fmt"
)
func test(s string) {
if len(s) == 0 {
fmt.Println("empty")
} else {
fmt.Println("not empty")
}
}
func main() {
// assign an empty string to a variable.
str1 := ""
str2 := " "
// check if a string is empty.
test(str1) // prt empty
// check that a string is not empty.
test(str2) // prt not empty
} |
Entropy/Narcissist | Go | Write a computer program that computes and shows its own [[entropy]].
;Related Tasks:
:* [[Fibonacci_word]]
:* [[Entropy]]
| package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"runtime"
)
func main() {
_, src, _, _ := runtime.Caller(0)
fmt.Println("Source file entropy:", entropy(src))
fmt.Println("Binary file entropy:", entropy(os.Args[0]))
}
func entropy(file string) float64 {
d, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
var f [256]float64
for _, b := range d {
f[b]++
}
hm := 0.
for _, c := range f {
if c > 0 {
hm += c * math.Log2(c)
}
}
l := float64(len(d))
return math.Log2(l) - hm/l
} |
Equilibrium index | Go | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence A:
::::: A_0 = -7
::::: A_1 = 1
::::: A_2 = 5
::::: A_3 = 2
::::: A_4 = -4
::::: A_5 = 3
::::: A_6 = 0
3 is an equilibrium index, because:
::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6
6 is also an equilibrium index, because:
::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0
(sum of zero elements is zero)
7 is not an equilibrium index, because it is not a valid index of sequence A.
;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).
Assume that the sequence may be very long.
| package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
fmt.Println(ex([]int32{-7, 1, 5, 2, -4, 3, 0}))
// sequence of 1,000,000 random numbers, with values
// chosen so that it will be likely to have a couple
// of equalibrium indexes.
rand.Seed(time.Now().UnixNano())
verylong := make([]int32, 1e6)
for i := range verylong {
verylong[i] = rand.Int31n(1001) - 500
}
fmt.Println(ex(verylong))
}
func ex(s []int32) (eq []int) {
var r, l int64
for _, el := range s {
r += int64(el)
}
for i, el := range s {
r -= int64(el)
if l == r {
eq = append(eq, i)
}
l += int64(el)
}
return
} |
Erdős-Nicolas numbers | Go from C++ | Definition
An perfect but is equal to the sum of its first '''k''' divisors (arranged in ascending order and including one) for some value of '''k''' greater than one.
;Examples
24 is an Erdos-Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.
6 is not an Erdos-Nicolas number because it is perfect (1 + 2 + 3 = 6).
48 is not an Erdos-Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.
;Task
Find and show here the first 8 Erdos-Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.
;Stretch
Do the same for any further Erdos-Nicolas numbers which you have the patience for.
;Note
As all known Erdos-Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.
;Reference
* OEIS:A194472 - Erdos-Nicolas numbers
| package main
import "fmt"
func main() {
const maxNumber = 100000000
dsum := make([]int, maxNumber+1)
dcount := make([]int, maxNumber+1)
for i := 0; i <= maxNumber; i++ {
dsum[i] = 1
dcount[i] = 1
}
for i := 2; i <= maxNumber; i++ {
for j := i + i; j <= maxNumber; j += i {
if dsum[j] == j {
fmt.Printf("%8d equals the sum of its first %d divisors\n", j, dcount[j])
}
dsum[j] += i
dcount[j]++
}
}
} |
Esthetic numbers | Go | An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.
;E.G.
:* '''12''' is an esthetic number. One and two differ by 1.
:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.
:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.
These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.
Esthetic numbers are also sometimes referred to as stepping numbers.
;Task
:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.
:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)
:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.
:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.
;Related task:
* numbers with equal rises and falls
;See also:
:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
:;*Numbers Aplenty - Esthetic numbers
:;*Geeks for Geeks - Stepping numbers
| package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
return false
}
n /= b
i = j
}
return true
}
var esths []uint64
func dfs(n, m, i uint64) {
if i >= n && i <= m {
esths = append(esths, i)
}
if i == 0 || i > m {
return
}
d := i % 10
i1 := i*10 + d - 1
i2 := i1 + 2
if d == 0 {
dfs(n, m, i2)
} else if d == 9 {
dfs(n, m, i1)
} else {
dfs(n, m, i1)
dfs(n, m, i2)
}
}
func listEsths(n, n2, m, m2 uint64, perLine int, all bool) {
esths = esths[:0]
for i := uint64(0); i < 10; i++ {
dfs(n2, m2, i)
}
le := len(esths)
fmt.Printf("Base 10: %s esthetic numbers between %s and %s:\n",
commatize(uint64(le)), commatize(n), commatize(m))
if all {
for c, esth := range esths {
fmt.Printf("%d ", esth)
if (c+1)%perLine == 0 {
fmt.Println()
}
}
} else {
for i := 0; i < perLine; i++ {
fmt.Printf("%d ", esths[i])
}
fmt.Println("\n............\n")
for i := le - perLine; i < le; i++ {
fmt.Printf("%d ", esths[i])
}
}
fmt.Println("\n")
}
func commatize(n uint64) 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() {
for b := uint64(2); b <= 16; b++ {
fmt.Printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4*b, 6*b)
for n, c := uint64(1), uint64(0); c < 6*b; n++ {
if isEsthetic(n, b) {
c++
if c >= 4*b {
fmt.Printf("%s ", strconv.FormatUint(n, int(b)))
}
}
}
fmt.Println("\n")
}
// the following all use the obvious range limitations for the numbers in question
listEsths(1000, 1010, 9999, 9898, 16, true)
listEsths(1e8, 101_010_101, 13*1e7, 123_456_789, 9, true)
listEsths(1e11, 101_010_101_010, 13*1e10, 123_456_789_898, 7, false)
listEsths(1e14, 101_010_101_010_101, 13*1e13, 123_456_789_898_989, 5, false)
listEsths(1e17, 101_010_101_010_101_010, 13*1e16, 123_456_789_898_989_898, 4, false)
} |
Euler's identity | Go | {{Wikipedia|Euler's_identity}}
In mathematics, ''Euler's identity'' is the equality:
ei\pi + 1 = 0
where
e is Euler's number, the base of natural logarithms,
''i'' is the imaginary unit, which satisfies ''i''2 = -1, and
\pi is pi, the ratio of the circumference of a circle to its diameter.
Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:
The number 0.
The number 1.
The number \pi (\pi = 3.14159+),
The number e (e = 2.71828+), which occurs widely in mathematical analysis.
The number ''i'', the imaginary unit of the complex numbers.
;Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.
Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.
If that is the case, or there is some other limitation, show
that ei\pi + 1 is ''approximately'' equal to zero and
show the amount of error in the calculation.
If your language is capable of symbolic calculations, show
that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
| package main
import (
"fmt"
"math"
"math/cmplx"
)
func main() {
fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0)
} |
Euler's sum of powers conjecture | Go from Python | There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.
This conjecture is called Euler's sum of powers conjecture and can be stated as such:
:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.
In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.
The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.
Related tasks are:
* [[Pythagorean quadruples]].
* [[Pythagorean triples]].
| package main
import (
"fmt"
"log"
)
func main() {
fmt.Println(eulerSum())
}
func eulerSum() (x0, x1, x2, x3, y int) {
var pow5 [250]int
for i := range pow5 {
pow5[i] = i * i * i * i * i
}
for x0 = 4; x0 < len(pow5); x0++ {
for x1 = 3; x1 < x0; x1++ {
for x2 = 2; x2 < x1; x2++ {
for x3 = 1; x3 < x2; x3++ {
sum := pow5[x0] +
pow5[x1] +
pow5[x2] +
pow5[x3]
for y = x0 + 1; y < len(pow5); y++ {
if sum == pow5[y] {
return
}
}
}
}
}
}
log.Fatal("no solution")
return
} |
Even or odd | Go | Test whether an integer is even or odd.
There is more than one way to solve this task:
* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.
* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.
* Use modular congruences:
** ''i'' 0 (mod 2) iff ''i'' is even.
** ''i'' 1 (mod 2) iff ''i'' is odd.
| package main
import (
"fmt"
"math/big"
)
func main() {
test(-2)
test(-1)
test(0)
test(1)
test(2)
testBig("-222222222222222222222222222222222222")
testBig("-1")
testBig("0")
testBig("1")
testBig("222222222222222222222222222222222222")
}
func test(n int) {
fmt.Printf("Testing integer %3d: ", n)
// & 1 is a good way to test
if n&1 == 0 {
fmt.Print("even ")
} else {
fmt.Print(" odd ")
}
// Careful when using %: negative n % 2 returns -1. So, the code below
// works, but can be broken by someone thinking they can reverse the
// test by testing n % 2 == 1. The valid reverse test is n % 2 != 0.
if n%2 == 0 {
fmt.Println("even")
} else {
fmt.Println(" odd")
}
}
func testBig(s string) {
b, _ := new(big.Int).SetString(s, 10)
fmt.Printf("Testing big integer %v: ", b)
// the Bit function is the only sensible test for big ints.
if b.Bit(0) == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
} |
Evolutionary algorithm | Go | Starting with:
* The target string: "METHINKS IT IS LIKE A WEASEL".
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
* A fitness function that computes the 'closeness' of its argument to the target string.
* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
:* repeat until the parent converges, (hopefully), to the target.
;See also:
* Wikipedia entry: Weasel algorithm.
* Wikipedia entry: Evolutionary algorithm.
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions
A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"
(:* repeat until the parent converges, (hopefully), to the target.
Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!
As illustration of this error, the code for 8th has the following remark.
Create a new string based on the TOS, '''changing randomly any characters which
don't already match the target''':
''NOTE:'' this has been changed, the 8th version is completely random now
Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!
To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
| package main
import (
"fmt"
"math/rand"
"time"
)
var target = []byte("METHINKS IT IS LIKE A WEASEL")
var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ")
var parent []byte
func init() {
rand.Seed(time.Now().UnixNano())
parent = make([]byte, len(target))
for i := range parent {
parent[i] = set[rand.Intn(len(set))]
}
}
// fitness: 0 is perfect fit. greater numbers indicate worse fit.
func fitness(a []byte) (h int) {
// (hamming distance)
for i, tc := range target {
if a[i] != tc {
h++
}
}
return
}
// set m to mutation of p, with each character of p mutated with probability r
func mutate(p, m []byte, r float64) {
for i, ch := range p {
if rand.Float64() < r {
m[i] = set[rand.Intn(len(set))]
} else {
m[i] = ch
}
}
}
func main() {
const c = 20 // number of times to copy and mutate parent
copies := make([][]byte, c)
for i := range copies {
copies[i] = make([]byte, len(parent))
}
fmt.Println(string(parent))
for best := fitness(parent); best > 0; {
for _, cp := range copies {
mutate(parent, cp, .05)
}
for _, cp := range copies {
fm := fitness(cp)
if fm < best {
best = fm
copy(parent, cp)
fmt.Println(string(parent))
}
}
}
} |
Executable library | Go | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
'''Task detail'''
* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number.
* The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task:
:: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
:: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
* Create a second executable to calculate the following:
** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000.
* Explain any extra setup/run steps needed to complete the task.
'''Notes:'''
* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment.
* Interpreters are present in the runtime environment.
| // modulino.go
package main
import "fmt"
// Function borrowed from Hailstone sequence task.
// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
func hailstone(n int, recycle []int) []int {
s := append(recycle[:0], n)
for n > 1 {
if n&1 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
s = append(s, n)
}
return s
}
func libMain() {
seq := hailstone(27, nil)
fmt.Println("\nHailstone sequence for the number 27:")
fmt.Println(" has", len(seq), "elements")
fmt.Println(" starts with", seq[0:4])
fmt.Println(" ends with", seq[len(seq)-4:])
var longest, length int
for i := 1; i < 100000; i++ {
if le := len(hailstone(i, nil)); le > length {
longest = i
length = le
}
}
fmt.Printf("\n%d has the longest Hailstone sequence, its length being %d.\n", longest, length)
} |
Execute Brain**** | Go | Brainf***}}
RCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.
Below are links to each of the versions of RCBF.
An implementation need only properly implement the following instructions:
{| class="wikitable"
!Command
!Description
|-
| style="text-align:center"| > || Move the pointer to the right
|-
| style="text-align:center"| < || Move the pointer to the left
|-
| style="text-align:center"| + || Increment the memory cell under the pointer
|-
| style="text-align:center"| - || Decrement the memory cell under the pointer
|-
| style="text-align:center"| . || Output the character signified by the cell at the pointer
|-
| style="text-align:center"| , || Input a character and store it in the cell at the pointer
|-
| style="text-align:center"| [ || Jump past the matching ] if the cell under the pointer is 0
|-
| style="text-align:center"| ] || Jump back to the matching [ if the cell under the pointer is nonzero
|}
Any cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.
| package main
import "fmt"
func main() {
// example program is current Brain**** solution to
// Hello world/Text task. only requires 10 bytes of data store!
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byte, dLen) // data store
var dp int // data pointer
for ip := 0; ip < len(is); ip++ {
switch is[ip] {
case '>':
dp++
case '<':
dp--
case '+':
ds[dp]++
case '-':
ds[dp]--
case '.':
fmt.Printf("%c", ds[dp])
case ',':
fmt.Scanf("%c", &ds[dp])
case '[':
if ds[dp] == 0 {
for nc := 1; nc > 0; {
ip++
if is[ip] == '[' {
nc++
} else if is[ip] == ']' {
nc--
}
}
}
case ']':
if ds[dp] != 0 {
for nc := 1; nc > 0; {
ip--
if is[ip] == ']' {
nc++
} else if is[ip] == '[' {
nc--
}
}
}
}
}
} |
Execute Computer/Zero | Go | Computer/zero Assembly}}
;Task:
Create a [[Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.
:* The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.
:* For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it.
;Bonus Points: Run all 5 sample programs at the aforementioned website and output their results.
| package main
import (
"bufio"
"fmt"
"io"
"regexp"
"strconv"
"strings"
)
const (
NOP = iota
LDA
STA
ADD
SUB
BRZ
JMP
STP
)
var opcodes = map[string]int{
"NOP": NOP,
"LDA": LDA,
"STA": STA,
"ADD": ADD,
"SUB": SUB,
"BRZ": BRZ,
"JMP": JMP,
"STP": STP,
}
var reIns = regexp.MustCompile(
`\s*(?:(\w+):)?\s*` + // label
`(NOP|LDA|STA|ADD|SUB|BRZ|JMP|STP)?\s*` + // opcode
`(\w+)?\s*` + // argument
`(?:;([\w\s]+))?`) // comment
type ByteCode [32]int
type instruction struct {
Label string
Opcode string
Arg string
}
type Program struct {
Instructions []instruction
Labels map[string]int
}
func newInstruction(line string) (*instruction, error) {
match := reIns.FindStringSubmatch(line)
if match == nil {
return nil, fmt.Errorf("syntax error: '%s'", line)
}
return &instruction{Label: match[1], Opcode: match[2], Arg: match[3]}, nil
}
func Parse(asm io.Reader) (*Program, error) {
var p Program
p.Labels = make(map[string]int, 32)
scanner := bufio.NewScanner(asm)
lineNumber := 0
for scanner.Scan() {
if instruction, err := newInstruction(scanner.Text()); err != nil {
return &p, err
} else {
if instruction.Label != "" {
p.Labels[instruction.Label] = lineNumber
}
p.Instructions = append(p.Instructions, *instruction)
lineNumber++
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &p, nil
}
func (p *Program) Compile() (ByteCode, error) {
var bytecode ByteCode
var arg int
for i, ins := range p.Instructions {
if ins.Arg == "" {
arg = 0
} else if addr, err := strconv.Atoi(ins.Arg); err == nil {
arg = addr
} else if addr, ok := p.Labels[ins.Arg]; ok {
arg = addr
} else {
return bytecode, fmt.Errorf("unknown label %v", ins.Arg)
}
if opcode, ok := opcodes[ins.Opcode]; ok {
bytecode[i] = opcode<<5 | arg
} else {
bytecode[i] = arg
}
}
return bytecode, nil
}
func floorMod(a, b int) int {
return ((a % b) + b) % b
}
func Run(bytecode ByteCode) (int, error) {
acc := 0
pc := 0
mem := bytecode
var op int
var arg int
loop:
for pc < 32 {
op = mem[pc] >> 5
arg = mem[pc] & 31
pc++
switch op {
case NOP:
continue
case LDA:
acc = mem[arg]
case STA:
mem[arg] = acc
case ADD:
acc = floorMod(acc+mem[arg], 256)
case SUB:
acc = floorMod(acc-mem[arg], 256)
case BRZ:
if acc == 0 {
pc = arg
}
case JMP:
pc = arg
case STP:
break loop
default:
return acc, fmt.Errorf("runtime error: %v %v", op, arg)
}
}
return acc, nil
}
func Execute(asm string) (int, error) {
program, err := Parse(strings.NewReader(asm))
if err != nil {
return 0, fmt.Errorf("assembly error: %v", err)
}
bytecode, err := program.Compile()
if err != nil {
return 0, fmt.Errorf("compilation error: %v", err)
}
result, err := Run(bytecode)
if err != nil {
return 0, err
}
return result, nil
}
func main() {
examples := []string{
`LDA x
ADD y ; accumulator = x + y
STP
x: 2
y: 2`,
`loop: LDA prodt
ADD x
STA prodt
LDA y
SUB one
STA y
BRZ done
JMP loop
done: LDA prodt ; to display it
STP
x: 8
y: 7
prodt: 0
one: 1`,
`loop: LDA n
STA temp
ADD m
STA n
LDA temp
STA m
LDA count
SUB one
BRZ done
STA count
JMP loop
done: LDA n ; to display it
STP
m: 1
n: 1
temp: 0
count: 8 ; valid range: 1-11
one: 1`,
`start: LDA load
ADD car ; head of list
STA ldcar
ADD one
STA ldcdr ; next CONS cell
ldcar: NOP
STA value
ldcdr: NOP
BRZ done ; 0 stands for NIL
STA car
JMP start
done: LDA value ; CAR of last CONS
STP
load: LDA 0
value: 0
car: 28
one: 1
; order of CONS cells
; in memory
; does not matter
6
0 ; 0 stands for NIL
2 ; (CADR ls)
26 ; (CDDR ls) -- etc.
5
20
3
30
1 ; value of (CAR ls)
22 ; points to (CDR ls)
4
24`,
`LDA 3
SUB 4
STP 0
0
255`,
`LDA 3
SUB 4
STP 0
0
1`,
`LDA 3
ADD 4
STP 0
1
255`,
}
for _, asm := range examples {
if result, err := Execute(asm); err == nil {
fmt.Println(result)
} else {
fmt.Println(err)
}
}
}
|
Exponentiation order | Go | This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.
(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)
;Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):
::::* 5**3**2
::::* (5**3)**2
::::* 5**(3**2)
If there are other methods (or formats) of multiple exponentiations, show them as well.
;See also:
* MathWorld entry: exponentiation
;Related tasks:
* exponentiation operator
* arbitrary-precision integers (included)
* [[Exponentiation with infix operators in (or operating on) the base]]
| package main
import "fmt"
import "math"
func main() {
var a, b, c float64
a = math.Pow(5, math.Pow(3, 2))
b = math.Pow(math.Pow(5, 3), 2)
c = math.Pow(5, math.Pow(3, 2))
fmt.Printf("5^3^2 = %.0f\n", a)
fmt.Printf("(5^3)^2 = %.0f\n", b)
fmt.Printf("5^(3^2) = %.0f\n", c)
} |
Exponentiation with infix operators in (or operating on) the base | Go | (Many programming languages, especially those with extended-precision integer arithmetic, usually
support one of **, ^, | or some such for exponentiation.)
Some languages treat/honor infix operators when performing exponentiation (raising
numbers to some power by the language's exponentiation operator, if the computer
programming language has one).
Other programming languages may make use of the '''POW''' or some other BIF
('''B'''uilt-'''I'''n '''F'''function), or some other library service.
If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.
This task will deal with the case where there is some form of an ''infix operator'' operating
in (or operating on) the base.
;Example:
A negative five raised to the 3rd power could be specified as:
-5 ** 3 or as
-(5) ** 3 or as
(-5) ** 3 or as something else
(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).
;Task:
:* compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.
:* Raise the following numbers (integer or real):
:::* -5 and
:::* +5
:* to the following powers:
:::* 2nd and
:::* 3rd
:* using the following expressions (if applicable in your language):
:::* -x**p
:::* -(x)**p
:::* (-x)**p
:::* -(x**p)
:* Show here (on this page) the four (or more) types of symbolic expressions for each number and power.
Try to present the results in the same format/manner as the other programming entries to make any differences apparent.
The variables may be of any type(s) that is/are applicable in your language.
;Related tasks:
* [[Exponentiation order]]
* [[Exponentiation operator]]
* [[Arbitrary-precision integers (included)]]
* [[Parsing/RPN to infix conversion]]
* [[Operator precedence]]
;References:
* Wikipedia: Order of operations in Programming languages
| package main
import (
"fmt"
"math"
)
type float float64
func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }
func main() {
ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"}
for _, x := range []float{float(-5), float(5)} {
for _, e := range []float{float(2), float(3)} {
fmt.Printf("x = %2.0f e = %0.0f | ", x, e)
fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e))
fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e))
fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e))
fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e)))
}
}
} |
Extend your language | Go from Kotlin | {{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| package main
import "fmt"
type F func()
type If2 struct {cond1, cond2 bool}
func (i If2) else1(f F) If2 {
if i.cond1 && !i.cond2 {
f()
}
return i
}
func (i If2) else2(f F) If2 {
if i.cond2 && !i.cond1 {
f()
}
return i
}
func (i If2) else0(f F) If2 {
if !i.cond1 && !i.cond2 {
f()
}
return i
}
func if2(cond1, cond2 bool, f F) If2 {
if cond1 && cond2 {
f()
}
return If2{cond1, cond2}
}
func main() {
a, b := 0, 1
if2 (a == 1, b == 3, func() {
fmt.Println("a = 1 and b = 3")
}).else1 (func() {
fmt.Println("a = 1 and b <> 3")
}).else2 (func() {
fmt.Println("a <> 1 and b = 3")
}).else0 (func() {
fmt.Println("a <> 1 and b <> 3")
})
// It's also possible to omit any (or all) of the 'else' clauses or to call them out of order
a, b = 1, 0
if2 (a == 1, b == 3, func() {
fmt.Println("a = 1 and b = 3")
}).else0 (func() {
fmt.Println("a <> 1 and b <> 3")
}).else1 (func() {
fmt.Println("a = 1 and b <> 3")
})
} |
Extreme floating point values | Go | The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
Print the values of these variables if possible; and show some arithmetic with these values and variables.
If your language can directly enter these extreme floating point values then show it.
;See also:
* What Every Computer Scientist Should Know About Floating-Point Arithmetic
;Related tasks:
* [[Infinity]]
* [[Detect division by zero]]
* [[Literals/Floating point]]
| package main
import (
"fmt"
"math"
)
func main() {
// compute "extreme values" from non-extreme values
var zero float64 // zero is handy.
var negZero, posInf, negInf, nan float64 // values to compute.
negZero = zero * -1
posInf = 1 / zero
negInf = -1 / zero
nan = zero / zero
// print extreme values stored in variables
fmt.Println(negZero, posInf, negInf, nan)
// directly obtain extreme values
fmt.Println(math.Float64frombits(1<<63),
math.Inf(1), math.Inf(-1), math.NaN())
// validate some arithmetic on extreme values
fmt.Println()
validateNaN(negInf+posInf, "-Inf + Inf")
validateNaN(0*posInf, "0 * Inf")
validateNaN(posInf/posInf, "Inf / Inf")
// mod is specifically named in "What every computer scientist..."
// Go math package doc lists many special cases for other package functions.
validateNaN(math.Mod(posInf, 1), "Inf % 1")
validateNaN(1+nan, "1 + NaN")
validateZero(1/posInf, "1 / Inf")
validateGT(posInf, math.MaxFloat64, "Inf > max value")
validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value")
validateNE(nan, nan, "NaN != NaN")
validateEQ(negZero, 0, "-0 == 0")
}
func validateNaN(n float64, op string) {
if math.IsNaN(n) {
fmt.Println(op, "-> NaN")
} else {
fmt.Println("!!! Expected NaN from", op, " Found", n)
}
}
func validateZero(n float64, op string) {
if n == 0 {
fmt.Println(op, "-> 0")
} else {
fmt.Println("!!! Expected 0 from", op, " Found", n)
}
}
func validateGT(a, b float64, op string) {
if a > b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
}
func validateNE(a, b float64, op string) {
if a == b {
fmt.Println("!!! Expected", op, " Found not true.")
} else {
fmt.Println(op)
}
}
func validateEQ(a, b float64, op string) {
if a == b {
fmt.Println(op)
} else {
fmt.Println("!!! Expected", op, " Found not true.")
}
} |
FASTA format | Go | In FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
;Task:
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
| package main
import (
"bufio"
"fmt"
"os"
)
func main() {
f, err := os.Open("rc.fasta")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
s := bufio.NewScanner(f)
headerFound := false
for s.Scan() {
line := s.Text()
switch {
case line == "":
continue
case line[0] != '>':
if !headerFound {
fmt.Println("missing header")
return
}
fmt.Print(line)
case headerFound:
fmt.Println()
fallthrough
default:
fmt.Printf("%s: ", line[1:])
headerFound = true
}
}
if headerFound {
fmt.Println()
}
if err := s.Err(); err != nil {
fmt.Println(err)
}
} |
Faces from a mesh | Go | A mesh defining a surface has uniquely numbered vertices, and named,
simple-polygonal faces described usually by an ordered list of edge numbers
going around the face,
For example:
External image of two faces
Rough textual version without edges:
1
17
7 A
B
11
23
* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or
any of all the rotations of those ordered vertices.
1
7 A
11
* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any
of their rotations.
1
17
B
11
23
Let's call the above the '''perimeter format''' as it traces around the perimeter.
;A second format:
A separate algorithm returns polygonal faces consisting of a face name and an unordered
set of edge definitions for each face.
* A single edge is described by the vertex numbers at its two ends, always in
ascending order.
* All edges for the face are given, but in an undefined order.
For example face A could be described by the edges (1, 11), (7, 11), and (1, 7)
(The order of each vertex number in an edge is ascending, but the order in
which the edges are stated is arbitrary).
Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23),
and (1, 11) in arbitrary order of the edges.
Let's call this second format the '''edge format'''.
;Task:
'''1.''' Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:
Q: (8, 1, 3)
R: (1, 3, 8)
U: (18, 8, 14, 10, 12, 17, 19)
V: (8, 14, 10, 12, 17, 19, 18)
'''2.''' Write a routine and use it to transform the following faces from edge to perimeter format.
E: {(1, 11), (7, 11), (1, 7)}
F: {(11, 23), (1, 17), (17, 23), (1, 11)}
G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}
H: {(1, 3), (9, 11), (3, 11), (1, 11)}
Show your output here.
| package main
import (
"fmt"
"sort"
)
// Check a slice contains a value.
func contains(s []int, f int) bool {
for _, e := range s {
if e == f {
return true
}
}
return false
}
// Assumes s1, s2 are of same length.
func sliceEqual(s1, s2 []int) bool {
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
return false
}
}
return true
}
// Reverses slice in place.
func reverse(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
// Check two perimeters are equal.
func perimEqual(p1, p2 []int) bool {
le := len(p1)
if le != len(p2) {
return false
}
for _, p := range p1 {
if !contains(p2, p) {
return false
}
}
// use copy to avoid mutating 'p1'
c := make([]int, le)
copy(c, p1)
for r := 0; r < 2; r++ {
for i := 0; i < le; i++ {
if sliceEqual(c, p2) {
return true
}
// do circular shift to right
t := c[le-1]
copy(c[1:], c[0:le-1])
c[0] = t
}
// now process in opposite direction
reverse(c)
}
return false
}
type edge [2]int
// Translates a face to perimeter format.
func faceToPerim(face []edge) []int {
// use copy to avoid mutating 'face'
le := len(face)
if le == 0 {
return nil
}
edges := make([]edge, le)
for i := 0; i < le; i++ {
// check edge pairs are in correct order
if face[i][1] <= face[i][0] {
return nil
}
edges[i] = face[i]
}
// sort edges in ascending order
sort.Slice(edges, func(i, j int) bool {
if edges[i][0] != edges[j][0] {
return edges[i][0] < edges[j][0]
}
return edges[i][1] < edges[j][1]
})
var perim []int
first, last := edges[0][0], edges[0][1]
perim = append(perim, first, last)
// remove first edge
copy(edges, edges[1:])
edges = edges[0 : le-1]
le--
outer:
for le > 0 {
for i, e := range edges {
found := false
if e[0] == last {
perim = append(perim, e[1])
last, found = e[1], true
} else if e[1] == last {
perim = append(perim, e[0])
last, found = e[0], true
}
if found {
// remove i'th edge
copy(edges[i:], edges[i+1:])
edges = edges[0 : le-1]
le--
if last == first {
if le == 0 {
break outer
} else {
return nil
}
}
continue outer
}
}
}
return perim[0 : len(perim)-1]
}
func main() {
fmt.Println("Perimeter format equality checks:")
areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8})
fmt.Printf(" Q == R is %t\n", areEqual)
areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18})
fmt.Printf(" U == V is %t\n", areEqual)
e := []edge{{7, 11}, {1, 11}, {1, 7}}
f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}}
g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}
h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}}
fmt.Println("\nEdge to perimeter format translations:")
for i, face := range [][]edge{e, f, g, h} {
perim := faceToPerim(face)
if perim == nil {
fmt.Printf(" %c => Invalid edge format\n", i + 'E')
} else {
fmt.Printf(" %c => %v\n", i + 'E', perim)
}
}
} |
Factorial base numbers indexing permutations of a collection | Go | You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.
The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0
Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.
I want to produce a 1 to 1 mapping between these numbers and permutations:-
0.0.0 -> 0123
0.0.1 -> 0132
0.1.0 -> 0213
0.1.1 -> 0231
0.2.0 -> 0312
0.2.1 -> 0321
1.0.0 -> 1023
1.0.1 -> 1032
1.1.0 -> 1203
1.1.1 -> 1230
1.2.0 -> 1302
1.2.1 -> 1320
2.0.0 -> 2013
2.0.1 -> 2031
2.1.0 -> 2103
2.1.1 -> 2130
2.2.0 -> 2301
2.2.1 -> 2310
3.0.0 -> 3012
3.0.1 -> 3021
3.1.0 -> 3102
3.1.1 -> 3120
3.2.0 -> 3201
3.2.1 -> 3210
The following psudo-code will do this:
Starting with m=0 and O, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.
If g is greater than zero, rotate the elements from m to m+g in O (see example)
Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted.
For example: using the factorial base number 2.0.1 and O = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.
Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3
Step 2: m=1 g=0; No action.
Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1
Let me work 2.0.1 and 0123
step 1 n=0 g=2 O=2013
step 2 n=1 g=0 so no action
step 3 n=2 g=1 O=2031
The task:
First use your function to recreate the above table.
Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with
methods in rc's permutations task.
Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:
39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0
51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1
use your function to crate the corresponding permutation of the following shoe of cards:
AKQJ1098765432AKQJ1098765432AKQJ1098765432AKQJ1098765432
Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
| package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func genFactBaseNums(size int, countOnly bool) ([][]int, int) {
var results [][]int
count := 0
for n := 0; ; n++ {
radix := 2
var res []int = nil
if !countOnly {
res = make([]int, size)
}
k := n
for k > 0 {
div := k / radix
rem := k % radix
if !countOnly {
if radix <= size+1 {
res[size-radix+1] = rem
}
}
k = div
radix++
}
if radix > size+2 {
break
}
count++
if !countOnly {
results = append(results, res)
}
}
return results, count
}
func mapToPerms(factNums [][]int) [][]int {
var perms [][]int
psize := len(factNums[0]) + 1
start := make([]int, psize)
for i := 0; i < psize; i++ {
start[i] = i
}
for _, fn := range factNums {
perm := make([]int, psize)
copy(perm, start)
for m := 0; m < len(fn); m++ {
g := fn[m]
if g == 0 {
continue
}
first := m
last := m + g
for i := 1; i <= g; i++ {
temp := perm[first]
for j := first + 1; j <= last; j++ {
perm[j-1] = perm[j]
}
perm[last] = temp
}
}
perms = append(perms, perm)
}
return perms
}
func join(is []int, sep string) string {
ss := make([]string, len(is))
for i := 0; i < len(is); i++ {
ss[i] = strconv.Itoa(is[i])
}
return strings.Join(ss, sep)
}
func undot(s string) []int {
ss := strings.Split(s, ".")
is := make([]int, len(ss))
for i := 0; i < len(ss); i++ {
is[i], _ = strconv.Atoi(ss[i])
}
return is
}
func main() {
rand.Seed(time.Now().UnixNano())
// Recreate the table.
factNums, _ := genFactBaseNums(3, false)
perms := mapToPerms(factNums)
for i, fn := range factNums {
fmt.Printf("%v -> %v\n", join(fn, "."), join(perms[i], ""))
}
// Check that the number of perms generated is equal to 11! (this takes a while).
_, count := genFactBaseNums(10, true)
fmt.Println("\nPermutations generated =", count)
fmt.Println("compared to 11! which =", factorial(11))
fmt.Println()
// Generate shuffles for the 2 given 51 digit factorial base numbers.
fbn51s := []string{
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0",
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1",
}
factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}
perms = mapToPerms(factNums)
shoe := []rune("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣")
cards := make([]string, 52)
for i := 0; i < 52; i++ {
cards[i] = string(shoe[2*i : 2*i+2])
if cards[i][0] == 'T' {
cards[i] = "10" + cards[i][1:]
}
}
for i, fbn51 := range fbn51s {
fmt.Println(fbn51)
for _, d := range perms[i] {
fmt.Print(cards[d])
}
fmt.Println("\n")
}
// Create a random 51 digit factorial base number and produce a shuffle from that.
fbn51 := make([]int, 51)
for i := 0; i < 51; i++ {
fbn51[i] = rand.Intn(52 - i)
}
fmt.Println(join(fbn51, "."))
perms = mapToPerms([][]int{fbn51})
for _, d := range perms[0] {
fmt.Print(cards[d])
}
fmt.Println()
} |
Factorions | Go | Definition:
A factorion is a natural number that equals the sum of the factorials of its digits.
;Example:
'''145''' is a factorion in base '''10''' because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base '''10''' can exceed '''1,499,999'''.
;Task:
Write a program in your language to demonstrate, by calculating and printing out the factorions, that:
:* There are '''3''' factorions in base '''9'''
:* There are '''4''' factorions in base '''10'''
:* There are '''5''' factorions in base '''11'''
:* There are '''2''' factorions in base '''12''' (up to the same upper bound as for base '''10''')
;See also:
:* '''Wikipedia article'''
:* '''OEIS:A014080 - Factorions in base 10'''
:* '''OEIS:A193163 - Factorions in base n'''
| package main
import (
"fmt"
"strconv"
)
func main() {
// cache factorials from 0 to 11
var fact [12]uint64
fact[0] = 1
for n := uint64(1); n < 12; n++ {
fact[n] = fact[n-1] * n
}
for b := 9; b <= 12; b++ {
fmt.Printf("The factorions for base %d are:\n", b)
for i := uint64(1); i < 1500000; i++ {
digits := strconv.FormatUint(i, b)
sum := uint64(0)
for _, digit := range digits {
if digit < 'a' {
sum += fact[digit-'0']
} else {
sum += fact[digit+10-'a']
}
}
if sum == i {
fmt.Printf("%d ", i)
}
}
fmt.Println("\n")
}
} |
Fairshare between two and more | Go | The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''
;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''
;Task
Counting from zero; using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.
Show the first 25 terms of the fairshare sequence:
:* For two people:
:* For three people
:* For five people
:* For eleven people
;Related tasks:
:* [[Non-decimal radices/Convert]]
:* [[Thue-Morse]]
;See also:
:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
| package main
import (
"fmt"
"sort"
"strconv"
"strings"
)
func fairshare(n, base int) []int {
res := make([]int, n)
for i := 0; i < n; i++ {
j := i
sum := 0
for j > 0 {
sum += j % base
j /= base
}
res[i] = sum % base
}
return res
}
func turns(n int, fss []int) string {
m := make(map[int]int)
for _, fs := range fss {
m[fs]++
}
m2 := make(map[int]int)
for _, v := range m {
m2[v]++
}
res := []int{}
sum := 0
for k, v := range m2 {
sum += v
res = append(res, k)
}
if sum != n {
return fmt.Sprintf("only %d have a turn", sum)
}
sort.Ints(res)
res2 := make([]string, len(res))
for i := range res {
res2[i] = strconv.Itoa(res[i])
}
return strings.Join(res2, " or ")
}
func main() {
for _, base := range []int{2, 3, 5, 11} {
fmt.Printf("%2d : %2d\n", base, fairshare(25, base))
}
fmt.Println("\nHow many times does each get a turn in 50000 iterations?")
for _, base := range []int{191, 1377, 49999, 50000, 50001} {
t := turns(base, fairshare(50000, base))
fmt.Printf(" With %d people: %s\n", base, t)
}
} |
Farey sequence | Go | The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.
The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''.
Each Farey sequence:
:::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1}
:::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}.
The Farey sequences of orders '''1''' to '''5''' are:
:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}
;Task
* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).
* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.
* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
::::::::::: 3 x n2 / \pi2
;See also:
* OEIS sequence A006842 numerators of Farey series of order 1, 2, ***
* OEIS sequence A006843 denominators of Farey series of order 1, 2, ***
* OEIS sequence A005728 number of fractions in Farey series of order n
* MathWorld entry Farey sequence
* Wikipedia entry Farey sequence
| package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {
// task 1. solution by recursive generation of mediants
for n := 1; n <= 11; n++ {
l := frac{0, 1}
r := frac{1, 1}
fmt.Printf("F(%d): %s ", n, l)
f(l, r, n)
fmt.Println(r)
}
// task 2. direct solution by summing totient function
// 2.1 generate primes to 1000
var composite [1001]bool
for _, p := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} {
for n := p * 2; n <= 1000; n += p {
composite[n] = true
}
}
// 2.2 generate totients to 1000
var tot [1001]int
for i := range tot {
tot[i] = 1
}
for n := 2; n <= 1000; n++ {
if !composite[n] {
tot[n] = n - 1
for a := n * 2; a <= 1000; a += n {
f := n - 1
for r := a / n; r%n == 0; r /= n {
f *= n
}
tot[a] *= f
}
}
}
// 2.3 sum totients
for n, sum := 1, 1; n <= 1000; n++ {
sum += tot[n]
if n%100 == 0 {
fmt.Printf("|F(%d)|: %d\n", n, sum)
}
}
} |
Fast Fourier transform | Go | Calculate the FFT (Fast Fourier Transform) of an input sequence.
The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result.
The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| package main
import (
"fmt"
"math"
"math/cmplx"
)
func ditfft2(x []float64, y []complex128, n, s int) {
if n == 1 {
y[0] = complex(x[0], 0)
return
}
ditfft2(x, y, n/2, 2*s)
ditfft2(x[s:], y[n/2:], n/2, 2*s)
for k := 0; k < n/2; k++ {
tf := cmplx.Rect(1, -2*math.Pi*float64(k)/float64(n)) * y[k+n/2]
y[k], y[k+n/2] = y[k]+tf, y[k]-tf
}
}
func main() {
x := []float64{1, 1, 1, 1, 0, 0, 0, 0}
y := make([]complex128, len(x))
ditfft2(x, y, len(x), 1)
for _, c := range y {
fmt.Printf("%8.4f\n", c)
}
} |
Feigenbaum constant calculation | Go from Ring | Calculate the Feigenbaum constant.
;See:
:* Details in the Wikipedia article: Feigenbaum constant.
| package main
import "fmt"
func feigenbaum() {
maxIt, maxItJ := 13, 10
a1, a2, d1 := 1.0, 0.0, 3.2
fmt.Println(" i d")
for i := 2; i <= maxIt; i++ {
a := a1 + (a1-a2)/d1
for j := 1; j <= maxItJ; j++ {
x, y := 0.0, 0.0
for k := 1; k <= 1<<uint(i); k++ {
y = 1.0 - 2.0*y*x
x = a - x*x
}
a -= x / y
}
d := (a1 - a2) / (a - a1)
fmt.Printf("%2d %.8f\n", i, d)
d1, a2, a1 = d, a1, a
}
}
func main() {
feigenbaum()
} |
Fibonacci n-step number sequences | Go | These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}
For small values of n, Greek numeric prefixes are sometimes used to individually name each series.
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}
Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.
;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
;Related tasks:
* [[Fibonacci sequence]]
* Wolfram Mathworld
* [[Hofstadter Q sequence]]
* [[Leonardo numbers]]
;Also see:
* Lucas Numbers - Numberphile (Video)
* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
* Wikipedia, Lucas number
* MathWorld, Fibonacci Number
* Some identities for r-Fibonacci numbers
* OEIS Fibonacci numbers
* OEIS Lucas numbers
| package main
import "fmt"
func g(i []int, c chan<- int) {
var sum int
b := append([]int(nil), i...) // make a copy
for _, t := range b {
c <- t
sum += t
}
for {
for j, t := range b {
c <- sum
b[j], sum = sum, sum+sum-t
}
}
}
func main() {
for _, s := range [...]struct {
seq string
i []int
}{
{"Fibonacci", []int{1, 1}},
{"Tribonacci", []int{1, 1, 2}},
{"Tetranacci", []int{1, 1, 2, 4}},
{"Lucas", []int{2, 1}},
} {
fmt.Printf("%10s:", s.seq)
c := make(chan int)
// Note/warning: these goroutines are leaked.
go g(s.i, c)
for j := 0; j < 10; j++ {
fmt.Print(" ", <-c)
}
fmt.Println()
}
} |
Fibonacci word | Go | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as '''1'''
Define F_Word2 as '''0'''
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
;Task:
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words '''1''' to '''37''' which shows:
::* The number of characters in the word
::* The word's [[Entropy]]
;Related tasks:
* Fibonacci word/fractal
* [[Entropy]]
* [[Entropy/Narcissist]]
| package main
import (
"fmt"
"math"
)
// From http://rosettacode.org/wiki/Entropy#Go
func entropy(s string) float64 {
m := map[rune]float64{}
for _, r := range s {
m[r]++
}
hm := 0.
for _, c := range m {
hm += c * math.Log2(c)
}
l := float64(len(s))
return math.Log2(l) - hm/l
}
const F_Word1 = "1"
const F_Word2 = "0"
func FibonacciWord(n int) string {
a, b := F_Word1, F_Word2
for ; n > 1; n-- {
a, b = b, b+a
}
return a
}
func FibonacciWordGen() <-chan string {
ch := make(chan string)
go func() {
a, b := F_Word1, F_Word2
for {
ch <- a
a, b = b, b+a
}
}()
return ch
}
func main() {
fibWords := FibonacciWordGen()
fmt.Printf("%3s %9s %-18s %s\n", "N", "Length", "Entropy", "Word")
n := 1
for ; n < 10; n++ {
s := <-fibWords
// Just to show the function and generator do the same thing:
if s2 := FibonacciWord(n); s != s2 {
fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2)
}
fmt.Printf("%3d %9d %.16f %s\n", n, len(s), entropy(s), s)
}
for ; n <= 37; n++ {
s := <-fibWords
fmt.Printf("%3d %9d %.16f\n", n, len(s), entropy(s))
}
} |
File extension is in extensions list | Go | Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.
It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.
For these reasons, this task exists in addition to the [[Extract file extension]] task.
;Related tasks:
* [[Extract file extension]]
* [[String matching]]
| package main
import (
"fmt"
"strings"
)
var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}
func fileExtInList(filename string) (bool, string) {
filename2 := strings.ToLower(filename)
for _, ext := range extensions {
ext2 := "." + strings.ToLower(ext)
if strings.HasSuffix(filename2, ext2) {
return true, ext
}
}
s := strings.Split(filename, ".")
if len(s) > 1 {
t := s[len(s)-1]
if t != "" {
return false, t
} else {
return false, "<empty>"
}
} else {
return false, "<none>"
}
}
func main() {
fmt.Println("The listed extensions are:")
fmt.Println(extensions, "\n")
tests := []string{
"MyData.a##", "MyData.tar.Gz", "MyData.gzip",
"MyData.7z.backup", "MyData...", "MyData",
"MyData_v1.0.tar.bz2", "MyData_v1.0.bz2",
}
for _, test := range tests {
ok, ext := fileExtInList(test)
fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext)
}
} |
File size distribution | Go from Kotlin | Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
| package main
import (
"fmt"
"log"
"math"
"os"
"path/filepath"
)
func commatize(n int64) 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 fileSizeDistribution(root string) {
var sizes [12]int
files := 0
directories := 0
totalSize := int64(0)
walkFunc := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
files++
if info.IsDir() {
directories++
}
size := info.Size()
if size == 0 {
sizes[0]++
return nil
}
totalSize += size
logSize := math.Log10(float64(size))
index := int(math.Floor(logSize))
sizes[index+1]++
return nil
}
err := filepath.Walk(root, walkFunc)
if err != nil {
log.Fatal(err)
}
fmt.Printf("File size distribution for '%s' :-\n\n", root)
for i := 0; i < len(sizes); i++ {
if i == 0 {
fmt.Print(" ")
} else {
fmt.Print("+ ")
}
fmt.Printf("Files less than 10 ^ %-2d bytes : %5d\n", i, sizes[i])
}
fmt.Println(" -----")
fmt.Printf("= Total number of files : %5d\n", files)
fmt.Printf(" including directories : %5d\n", directories)
c := commatize(totalSize)
fmt.Println("\n Total size of files :", c, "bytes")
}
func main() {
fileSizeDistribution("./")
} |
Find Chess960 starting position identifier | Go from Wren | Starting Position Identifier number ("SP-ID"), and generate the corresponding position.
;Task:
This task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array '''QNRBBNKR''' (or '''''' or ''''''), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.
You may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.
;Algorithm:
The derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).
1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0='''NN---''', 1='''N-N--''', 2='''N--N-''', 3='''N---N''', 4='''-NN--''', etc; our pair is combination number 5. Call this number N. '''N=5'''
2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, '''Q=2'''.
3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 ('''D=1'''), and the light bishop is on square 2 ('''L=2''').
4. Then the position number is given by '''4(4(6N + Q)+D)+L''', which reduces to '''96N + 16Q + 4D + L'''. In our example, that's 96x5 + 16x2 + 4x1 + 2 = 480 + 32 + 4 + 2 = 518.
Note that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.
RQNBBKRN = 601
RNQBBKRN = 617
| package main
import (
"fmt"
"log"
"strings"
)
var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔")
var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"}
var g2lMap = map[rune]string{
'♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K",
'♖': "R", '♘': "N", '♗': "B", '♕': "Q", '♔': "K",
}
var ntable = map[string]int{"01": 0, "02": 1, "03": 2, "04": 3, "12": 4, "13": 5, "14": 6, "23": 7, "24": 8, "34": 9}
func g2l(pieces string) string {
lets := ""
for _, p := range pieces {
lets += g2lMap[p]
}
return lets
}
func spid(pieces string) int {
pieces = g2l(pieces) // convert glyphs to letters
/* check for errors */
if len(pieces) != 8 {
log.Fatal("There must be exactly 8 pieces.")
}
for _, one := range "KQ" {
count := 0
for _, p := range pieces {
if p == one {
count++
}
}
if count != 1 {
log.Fatalf("There must be one %s.", names[one])
}
}
for _, two := range "RNB" {
count := 0
for _, p := range pieces {
if p == two {
count++
}
}
if count != 2 {
log.Fatalf("There must be two %s.", names[two])
}
}
r1 := strings.Index(pieces, "R")
r2 := strings.Index(pieces[r1+1:], "R") + r1 + 1
k := strings.Index(pieces, "K")
if k < r1 || k > r2 {
log.Fatal("The king must be between the rooks.")
}
b1 := strings.Index(pieces, "B")
b2 := strings.Index(pieces[b1+1:], "B") + b1 + 1
if (b2-b1)%2 == 0 {
log.Fatal("The bishops must be on opposite color squares.")
}
/* compute SP_ID */
piecesN := strings.ReplaceAll(pieces, "Q", "")
piecesN = strings.ReplaceAll(piecesN, "B", "")
n1 := strings.Index(piecesN, "N")
n2 := strings.Index(piecesN[n1+1:], "N") + n1 + 1
np := fmt.Sprintf("%d%d", n1, n2)
N := ntable[np]
piecesQ := strings.ReplaceAll(pieces, "B", "")
Q := strings.Index(piecesQ, "Q")
D := strings.Index("0246", fmt.Sprintf("%d", b1))
L := strings.Index("1357", fmt.Sprintf("%d", b2))
if D == -1 {
D = strings.Index("0246", fmt.Sprintf("%d", b2))
L = strings.Index("1357", fmt.Sprintf("%d", b1))
}
return 96*N + 16*Q + 4*D + L
}
func main() {
for _, pieces := range []string{"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♖♕♘♗♗♔♖♘", "♖♘♕♗♗♔♖♘"} {
fmt.Printf("%s or %s has SP-ID of %d\n", pieces, g2l(pieces), spid(pieces))
}
} |
Find duplicate files | Go | In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.
;Task:
Create a program which, given a minimum size and a folder/directory, will find all files of at least ''size'' bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.
The program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.
Specify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.
Identify hard links (filenames referencing the same content) in the output if applicable for the filesystem.
For extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files.
| package main
import (
"fmt"
"crypto/md5"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"time"
)
type fileData struct {
filePath string
info os.FileInfo
}
type hash [16]byte
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func checksum(filePath string) hash {
bytes, err := ioutil.ReadFile(filePath)
check(err)
return hash(md5.Sum(bytes))
}
func findDuplicates(dirPath string, minSize int64) [][2]fileData {
var dups [][2]fileData
m := make(map[hash]fileData)
werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Size() >= minSize {
h := checksum(path)
fd, ok := m[h]
fd2 := fileData{path, info}
if !ok {
m[h] = fd2
} else {
dups = append(dups, [2]fileData{fd, fd2})
}
}
return nil
})
check(werr)
return dups
}
func main() {
dups := findDuplicates(".", 1)
fmt.Println("The following pairs of files have the same size and the same hash:\n")
fmt.Println("File name Size Date last modified")
fmt.Println("==========================================================")
sort.Slice(dups, func(i, j int) bool {
return dups[i][0].info.Size() > dups[j][0].info.Size() // in order of decreasing size
})
for _, dup := range dups {
for i := 0; i < 2; i++ {
d := dup[i]
fmt.Printf("%-20s %8d %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
}
fmt.Println()
}
} |
Find if a point is within a triangle | Go from Wren | Find if a point is within a triangle.
;Task:
::* Assume points are on a plane defined by (x, y) real number coordinates.
::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
::* You may use any algorithm.
::* Bonus: explain why the algorithm you chose works.
;Related tasks:
* [[Determine_if_two_triangles_overlap]]
;Also see:
:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]
:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]
:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]
:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]
| package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
} |
Find limit of recursion | Go | {{selection|Short Circuit|Console Program Basics}}
;Task:
Find the limit of recursion.
| package main
import (
"flag"
"fmt"
"runtime/debug"
)
func main() {
stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
flag.Parse()
if *stack > 0 {
debug.SetMaxStack(*stack)
}
r(1)
}
func r(l int) {
if l%1000 == 0 {
fmt.Println(l)
}
r(l + 1)
} |
Find palindromic numbers in both binary and ternary bases | Go from C | * Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':
:::* base 2
:::* base 3
* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.
* Optionally, show the decimal number found in its binary and ternary form.
* Show all output here.
It's permissible to assume the first two numbers and simply list them.
;See also
* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
| package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
} |
Find the intersection of a line with a plane | Go from Kotlin | Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.
;Task:
Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
| package main
import "fmt"
type Vector3D struct{ x, y, z float64 }
func (v *Vector3D) Add(w *Vector3D) *Vector3D {
return &Vector3D{v.x + w.x, v.y + w.y, v.z + w.z}
}
func (v *Vector3D) Sub(w *Vector3D) *Vector3D {
return &Vector3D{v.x - w.x, v.y - w.y, v.z - w.z}
}
func (v *Vector3D) Mul(s float64) *Vector3D {
return &Vector3D{s * v.x, s * v.y, s * v.z}
}
func (v *Vector3D) Dot(w *Vector3D) float64 {
return v.x*w.x + v.y*w.y + v.z*w.z
}
func (v *Vector3D) String() string {
return fmt.Sprintf("(%v, %v, %v)", v.x, v.y, v.z)
}
func intersectPoint(rayVector, rayPoint, planeNormal, planePoint *Vector3D) *Vector3D {
diff := rayPoint.Sub(planePoint)
prod1 := diff.Dot(planeNormal)
prod2 := rayVector.Dot(planeNormal)
prod3 := prod1 / prod2
return rayPoint.Sub(rayVector.Mul(prod3))
}
func main() {
rv := &Vector3D{0.0, -1.0, -1.0}
rp := &Vector3D{0.0, 0.0, 10.0}
pn := &Vector3D{0.0, 0.0, 1.0}
pp := &Vector3D{0.0, 0.0, 5.0}
ip := intersectPoint(rv, rp, pn, pp)
fmt.Println("The ray intersects the plane at", ip)
} |
Find the intersection of two lines | Go | Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]
;Task:
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| package main
import (
"fmt"
"errors"
)
type Point struct {
x float64
y float64
}
type Line struct {
slope float64
yint float64
}
func CreateLine (a, b Point) Line {
slope := (b.y-a.y) / (b.x-a.x)
yint := a.y - slope*a.x
return Line{slope, yint}
}
func EvalX (l Line, x float64) float64 {
return l.slope*x + l.yint
}
func Intersection (l1, l2 Line) (Point, error) {
if l1.slope == l2.slope {
return Point{}, errors.New("The lines do not intersect")
}
x := (l2.yint-l1.yint) / (l1.slope-l2.slope)
y := EvalX(l1, x)
return Point{x, y}, nil
}
func main() {
l1 := CreateLine(Point{4, 0}, Point{6, 10})
l2 := CreateLine(Point{0, 3}, Point{10, 7})
if result, err := Intersection(l1, l2); err == nil {
fmt.Println(result)
} else {
fmt.Println("The lines do not intersect")
}
}
|
Find the last Sunday of each month | Go | Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29
;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]
| package main
import (
"fmt"
"time"
)
func main() {
var year int
var t time.Time
var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }
for {
fmt.Print("Please select a year: ")
_, err := fmt.Scanf("%d", &year)
if err != nil {
fmt.Println(err)
continue
} else {
break
}
}
fmt.Println("Last Sundays of each month of", year)
fmt.Println("==================================")
for i := 1;i < 13; i++ {
j := lastDay[i-1]
if i == 2 {
if time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC).Month() == time.Date(int(year), time.Month(i), j-1, 0, 0, 0, 0, time.UTC).Month() {
j = 29
} else {
j = 28
}
}
for {
t = time.Date(int(year), time.Month(i), j, 0, 0, 0, 0, time.UTC)
if t.Weekday() == 0 {
fmt.Printf("%s: %d\n", time.Month(i), j)
break
}
j = j - 1
}
}
}
|
Find the missing permutation | Go | ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB
Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed.
;Task:
Find that missing permutation.
;Methods:
* Obvious method:
enumerate all permutations of '''A''', '''B''', '''C''', and '''D''',
and then look for the missing permutation.
* alternate method:
Hint: if all permutations were shown above, how many
times would '''A''' appear in each position?
What is the ''parity'' of this number?
* another alternate method:
Hint: if you add up the letter values of each column,
does a missing letter '''A''', '''B''', '''C''', and '''D''' from each
column cause the total value for each column to be unique?
;Related task:
* [[Permutations]])
| package main
import (
"fmt"
"strings"
)
var given = strings.Split(`ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB`, "\n")
func main() {
b := make([]byte, len(given[0]))
for i := range b {
m := make(map[byte]int)
for _, p := range given {
m[p[i]]++
}
for char, count := range m {
if count&1 == 1 {
b[i] = char
break
}
}
}
fmt.Println(string(b))
} |
First-class functions/Use numbers analogously | Go | In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
x = 2.0
xi = 0.5
y = 4.0
yi = 0.25
z = x + y
zi = 1.0 / ( x + y )
Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
new_function = multiplier(n1,n2)
# where new_function(m) returns the result of n1 * n2 * m
Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.
To paraphrase the task description: Do what was done before, but with numbers rather than functions
| package main
import "fmt"
func main() {
x := 2.
xi := .5
y := 4.
yi := .25
z := func() float64 { return x + y }
zi := func() float64 { return 1 / (x + y) }
// point A
numbers := []interface{}{&x, &y, z}
inverses := []interface{}{&xi, &yi, zi}
// point B
mfs := make([]func(n interface{}) float64, len(numbers))
for i := range mfs {
mfs[i] = multiplier(numbers[i], inverses[i])
}
// pointC
for _, mf := range mfs {
fmt.Println(mf(1.))
}
}
func multiplier(n1, n2 interface{}) func(interface{}) float64 {
return func(m interface{}) float64 {
// close on interface objects n1, n2, and m
return eval(n1) * eval(n2) * eval(m)
}
}
// utility function for evaluating multiplier interface objects
func eval(n interface{}) float64 {
switch n.(type) {
case float64:
return n.(float64)
case *float64:
return *n.(*float64)
case func() float64:
return n.(func() float64)()
}
panic("unsupported multiplier type")
return 0 // never reached
} |
First perfect square in base n with n unique digits | Go | Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.
E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').
You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.
;Task
* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.
* (optional) Do the same for bases '''13''' through '''16'''.
* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)
;See also:
;* OEIS A260182: smallest square that is pandigital in base n.
;Related task
;* [[Casting out nines]]
| package main
import (
"fmt"
"math/big"
"strconv"
"time"
)
const maxBase = 27
const minSq36 = "1023456789abcdefghijklmnopqrstuvwxyz"
const minSq36x = "10123456789abcdefghijklmnopqrstuvwxyz"
var bigZero = new(big.Int)
var bigOne = new(big.Int).SetUint64(1)
func containsAll(sq string, base int) bool {
var found [maxBase]byte
le := len(sq)
reps := 0
for _, r := range sq {
d := r - 48
if d > 38 {
d -= 39
}
found[d]++
if found[d] > 1 {
reps++
if le-reps < base {
return false
}
}
}
return true
}
func sumDigits(n, base *big.Int) *big.Int {
q := new(big.Int).Set(n)
r := new(big.Int)
sum := new(big.Int).Set(bigZero)
for q.Cmp(bigZero) == 1 {
q.QuoRem(q, base, r)
sum.Add(sum, r)
}
return sum
}
func digitalRoot(n *big.Int, base int) int {
root := new(big.Int)
b := big.NewInt(int64(base))
for i := new(big.Int).Set(n); i.Cmp(b) >= 0; i.Set(root) {
root.Set(sumDigits(i, b))
}
return int(root.Int64())
}
func minStart(base int) (string, uint64, int) {
nn := new(big.Int)
ms := minSq36[:base]
nn.SetString(ms, base)
bdr := digitalRoot(nn, base)
var drs []int
var ixs []uint64
for n := uint64(1); n < uint64(2*base); n++ {
nn.SetUint64(n * n)
dr := digitalRoot(nn, base)
if dr == 0 {
dr = int(n * n)
}
if dr == bdr {
ixs = append(ixs, n)
}
if n < uint64(base) && dr >= bdr {
drs = append(drs, dr)
}
}
inc := uint64(1)
if len(ixs) >= 2 && base != 3 {
inc = ixs[1] - ixs[0]
}
if len(drs) == 0 {
return ms, inc, bdr
}
min := drs[0]
for _, dr := range drs[1:] {
if dr < min {
min = dr
}
}
rd := min - bdr
if rd == 0 {
return ms, inc, bdr
}
if rd == 1 {
return minSq36x[:base+1], 1, bdr
}
ins := string(minSq36[rd])
return (minSq36[:rd] + ins + minSq36[rd:])[:base+1], inc, bdr
}
func main() {
start := time.Now()
var nb, nn big.Int
for n, k, base := uint64(2), uint64(1), 2; ; n += k {
if base > 2 && n%uint64(base) == 0 {
continue
}
nb.SetUint64(n)
sq := nb.Mul(&nb, &nb).Text(base)
if !containsAll(sq, base) {
continue
}
ns := strconv.FormatUint(n, base)
tt := time.Since(start).Seconds()
fmt.Printf("Base %2d:%15s² = %-27s in %8.3fs\n", base, ns, sq, tt)
if base == maxBase {
break
}
base++
ms, inc, bdr := minStart(base)
k = inc
nn.SetString(ms, base)
nb.Sqrt(&nn)
if nb.Uint64() < n+1 {
nb.SetUint64(n + 1)
}
if k != 1 {
for {
nn.Mul(&nb, &nb)
dr := digitalRoot(&nn, base)
if dr == bdr {
n = nb.Uint64() - k
break
}
nb.Add(&nb, bigOne)
}
} else {
n = nb.Uint64() - k
}
}
} |
First power of 2 that has leading decimal digits of 12 | Go from Pascal | (This task is taken from a ''Project Euler'' problem.)
(All numbers herein are expressed in base ten.)
'''27 = 128''' and '''7''' is
the first power of '''2''' whose leading decimal digits are '''12'''.
The next power of '''2''' whose leading decimal digits
are '''12''' is '''80''',
'''280 = 1208925819614629174706176'''.
Define ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest
value of ''' ''j'' ''' such that the base ten representation
of '''2''j''''' begins with the digits of ''' ''L'' '''.
So ''p''(12, 1) = 7 and
''p''(12, 2) = 80
You are also given that:
''p''(123, 45) = 12710
;Task:
::* find:
:::::* ''' ''p''(12, 1) '''
:::::* ''' ''p''(12, 2) '''
:::::* ''' ''p''(123, 45) '''
:::::* ''' ''p''(123, 12345) '''
:::::* ''' ''p''(123, 678910) '''
::* display the results here, on this page.
| package main
import (
"fmt"
"math"
"time"
)
const ld10 = math.Ln2 / math.Ln10
func commatize(n uint64) 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 p(L, n uint64) uint64 {
i := L
digits := uint64(1)
for i >= 10 {
digits *= 10
i /= 10
}
count := uint64(0)
for i = 0; count < n; i++ {
e := math.Exp(math.Ln10 * math.Mod(float64(i)*ld10, 1))
if uint64(math.Trunc(e*float64(digits))) == L {
count++
}
}
return i - 1
}
func main() {
start := time.Now()
params := [][2]uint64{{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}}
for _, param := range params {
fmt.Printf("p(%d, %d) = %s\n", param[0], param[1], commatize(p(param[0], param[1])))
}
fmt.Printf("\nTook %s\n", time.Since(start))
} |
Fivenum | Go from Perl | Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.
For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.
;Task:
Given an array of numbers, compute the five-number summary.
;Note:
While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data.
Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
| package main
import (
"fmt"
"math"
"sort"
)
func fivenum(a []float64) (n5 [5]float64) {
sort.Float64s(a)
n := float64(len(a))
n4 := float64((len(a)+3)/2) / 2
d := []float64{1, n4, (n + 1) / 2, n + 1 - n4, n}
for e, de := range d {
floor := int(de - 1)
ceil := int(math.Ceil(de - 1))
n5[e] = .5 * (a[floor] + a[ceil])
}
return
}
var (
x1 = []float64{36, 40, 7, 39, 41, 15}
x2 = []float64{15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}
x3 = []float64{
0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,
0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,
0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,
0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578,
}
)
func main() {
fmt.Println(fivenum(x1))
fmt.Println(fivenum(x2))
fmt.Println(fivenum(x3))
} |
Fixed length records | Go | Fixed length read/write
Before terminals, computers commonly used punch card readers or paper tape input.
A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.
These input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.
These devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).
;Task:
Write a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.
Samples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.
'''Note:''' There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.
These fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression ''logical record length''.
;Sample data:
To create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of '''dd''' support blocking and unblocking records with a conversion byte size.
Line 1...1.........2.........3.........4.........5.........6.........7.........8
Line 2
Line 3
Line 4
Line 6
Line 7
Indented line 8............................................................
Line 9 RT MARGIN
prompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block will create a fixed length record file of 80 bytes given newline delimited text input.
prompt$ dd if=infile.dat cbs=80 conv=unblock will display a file with 80 byte logical record lengths to standard out as standard text with newlines.
;Bonus round:
Forth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).
Write a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.
Also demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.
The COBOL example uses forth.txt and forth.blk filenames.
| package main
import (
"fmt"
"log"
"os"
"os/exec"
)
func reverseBytes(bytes []byte) {
for i, j := 0, len(bytes)-1; i < j; i, j = i+1, j-1 {
bytes[i], bytes[j] = bytes[j], bytes[i]
}
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
in, err := os.Open("infile.dat")
check(err)
defer in.Close()
out, err := os.Create("outfile.dat")
check(err)
record := make([]byte, 80)
empty := make([]byte, 80)
for {
n, err := in.Read(record)
if err != nil {
if n == 0 {
break // EOF reached
} else {
out.Close()
log.Fatal(err)
}
}
reverseBytes(record)
out.Write(record)
copy(record, empty)
}
out.Close()
// Run dd from within program to write output.dat
// to standard output as normal text with newlines.
cmd := exec.Command("dd", "if=outfile.dat", "cbs=80", "conv=unblock")
bytes, err := cmd.Output()
check(err)
fmt.Println(string(bytes))
} |
Flatten a list | Go | Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
;Related task:
* [[Tree traversal]]
| package main
import "fmt"
func list(s ...interface{}) []interface{} {
return s
}
func main() {
s := list(list(1),
2,
list(list(3, 4), 5),
list(list(list())),
list(list(list(6))),
7,
8,
list(),
)
fmt.Println(s)
fmt.Println(flatten(s))
}
func flatten(s []interface{}) (r []int) {
for _, e := range s {
switch i := e.(type) {
case int:
r = append(r, i)
case []interface{}:
r = append(r, flatten(i)...)
}
}
return
} |
Flipping bits game | Go | The game:
Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.
;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).
# The number of moves taken so far should be shown.
Show an example of a short game here, on this page, for a '''3x3''' array of bits.
| package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
var n int = 3 // Change to define board size
var moves int = 0
a := make([][]int, n)
for i := range a {
a[i] = make([]int, n)
for j := range a {
a[i][j] = rand.Intn(2)
}
}
b := make([][]int, len(a))
for i := range a {
b[i] = make([]int, len(a[i]))
copy(b[i], a[i])
}
for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
b = flipCol(b, rand.Intn(n) + 1)
b = flipRow(b, rand.Intn(n) + 1)
}
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
var rc rune
var num int
for {
for{
fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n)
_, err := fmt.Scanf("%c%d", &rc, &num)
if err != nil {
fmt.Println(err)
continue
}
if num < 1 || num > n {
fmt.Println("Wrong command!")
continue
}
break
}
switch rc {
case 'c':
fmt.Printf("Column %v will be flipped\n", num)
flipCol(b, num)
case 'r':
fmt.Printf("Row %v will be flipped\n", num)
flipRow(b, num)
default:
fmt.Println("Wrong command!")
continue
}
moves++
fmt.Println("\nMoves taken: ", moves)
fmt.Println("Target:")
drawBoard(a)
fmt.Println("\nBoard:")
drawBoard(b)
if compareSlices(a, b) {
fmt.Printf("Finished. You win with %d moves!\n", moves)
break
}
}
}
func drawBoard (m [][]int) {
fmt.Print(" ")
for i := range m {
fmt.Printf("%d ", i+1)
}
for i := range m {
fmt.Println()
fmt.Printf("%d ", i+1)
for _, val := range m[i] {
fmt.Printf(" %d", val)
}
}
fmt.Print("\n")
}
func flipRow(m [][]int, row int) ([][]int) {
for j := range m {
m[row-1][j] ^= 1
}
return m
}
func flipCol(m [][]int, col int) ([][]int) {
for j := range m {
m[j][col-1] ^= 1
}
return m
}
func compareSlices(m [][]int, n[][]int) bool {
o := true
for i := range m {
for j := range m {
if m[i][j] != n[i][j] { o = false }
}
}
return o
} |
Floyd's triangle | Go | Floyd's triangle lists the natural numbers in a right triangle aligned to the left where
* the first row is '''1''' (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.
The first few lines of a Floyd triangle looks like this:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
;Task:
:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
| package main
import "fmt"
func main() {
floyd(5)
floyd(14)
}
func floyd(n int) {
fmt.Printf("Floyd %d:\n", n)
lowerLeftCorner := n*(n-1)/2 + 1
lastInColumn := lowerLeftCorner
lastInRow := 1
for i, row := 1, 1; row <= n; i++ {
w := len(fmt.Sprint(lastInColumn))
if i < lastInRow {
fmt.Printf("%*d ", w, i)
lastInColumn++
} else {
fmt.Printf("%*d\n", w, i)
row++
lastInRow += row
lastInColumn = lowerLeftCorner
}
}
} |
Four bit adder | Go | "''Simulate''" a four-bit adder.
This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;
Finally a half adder can be made using an ''xor'' gate and an ''and'' gate.
The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.
'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.
If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.
Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones.
{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
! (A half adder)
! (A full adder)
! (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}
Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".
It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.
To test the implementation, show the sum of two four-bit numbers (in binary).
| package main
import "fmt"
func xor(a, b byte) byte {
return a&(^b) | b&(^a)
}
func ha(a, b byte) (s, c byte) {
return xor(a, b), a & b
}
func fa(a, b, c0 byte) (s, c1 byte) {
sa, ca := ha(a, c0)
s, cb := ha(sa, b)
c1 = ca | cb
return
}
func add4(a3, a2, a1, a0, b3, b2, b1, b0 byte) (v, s3, s2, s1, s0 byte) {
s0, c0 := fa(a0, b0, 0)
s1, c1 := fa(a1, b1, c0)
s2, c2 := fa(a2, b2, c1)
s3, v = fa(a3, b3, c2)
return
}
func main() {
// add 10+9 result should be 1 0 0 1 1
fmt.Println(add4(1, 0, 1, 0, 1, 0, 0, 1))
} |
Four is magic | Go | Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.
Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word.
Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.
For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.'''
'''Three is five, five is four, four is magic.'''
For reference, here are outputs for 0 through 9.
Zero is four, four is magic.
One is three, three is five, five is four, four is magic.
Two is three, three is five, five is four, four is magic.
Three is five, five is four, four is magic.
Four is magic.
Five is four, four is magic.
Six is three, three is five, five is four, four is magic.
Seven is five, five is four, four is magic.
Eight is five, five is four, four is magic.
Nine is four, four is magic.
;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)
:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.
:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.
:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.
:* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.
You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.
If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)
Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.
;Related tasks:
:* [[Four is the number of_letters in the ...]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Summarize and say sequence]]
:* [[Spelling of ordinal numbers]]
:* [[De Bruijn sequences]]
| package main
import (
"fmt"
"math"
"strings"
)
func main() {
for _, n := range [...]int64{
0, 4, 6, 11, 13, 75, 100, 337, -164,
math.MaxInt64,
} {
fmt.Println(fourIsMagic(n))
}
}
func fourIsMagic(n int64) string {
s := say(n)
s = strings.ToUpper(s[:1]) + s[1:]
t := s
for n != 4 {
n = int64(len(s))
s = say(n)
t += " is " + s + ", " + s
}
t += " is magic."
return t
}
// Following is from https://rosettacode.org/wiki/Number_names#Go
var small = [...]string{"zero", "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen",
"fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}
var tens = [...]string{"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"}
var illions = [...]string{"", " thousand", " million", " billion",
" trillion", " quadrillion", " quintillion"}
func say(n int64) string {
var t string
if n < 0 {
t = "negative "
// Note, for math.MinInt64 this leaves n negative.
n = -n
}
switch {
case n < 20:
t += small[n]
case n < 100:
t += tens[n/10]
s := n % 10
if s > 0 {
t += "-" + small[s]
}
case n < 1000:
t += small[n/100] + " hundred"
s := n % 100
if s > 0 {
t += " " + say(s)
}
default:
// work right-to-left
sx := ""
for i := 0; n > 0; i++ {
p := n % 1000
n /= 1000
if p > 0 {
ix := say(p) + illions[i]
if sx != "" {
ix += " " + sx
}
sx = ix
}
}
t += sx
}
return t
} |
Four is the number of letters in the ... | Go | The '''Four is ...''' sequence is based on the counting of the number of
letters in the words of the (never-ending) sentence:
Four is the number of letters in the first word of this sentence, two in the second,
three in the third, six in the fourth, two in the fifth, seven in the sixth, ***
;Definitions and directives:
:* English is to be used in spelling numbers.
:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').
:* Commas are not counted, nor are hyphens (dashes or minus signs).
:* '''twenty-three''' has eleven letters.
:* '''twenty-three''' is considered one word (which is hyphenated).
:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.
:* The American version of numbers will be used here in this task (as opposed to the British version).
'''2,000,000,000''' is two billion, ''not'' two milliard.
;Task:
:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:
'''4 2 3 6 2 7'''
:* Only construct as much as is needed for the never-ending sentence.
:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.
:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.
:* Show all output here.
;Test cases:
Display the first 201 numbers in the sequence (and the total number of characters in the sentence).
Display the number of letters (and the word itself) of the 1,000th word.
Display the number of letters (and the word itself) of the 10,000th word.
Display the number of letters (and the word itself) of the 100,000th word.
Display the number of letters (and the word itself) of the 1,000,000th word.
Display the number of letters (and the word itself) of the 10,000,000th word (optional).
;Related tasks:
:* [[Four is magic]]
:* [[Look-and-say sequence]]
:* [[Number names]]
:* [[Self-describing numbers]]
:* [[Self-referential sequence]]
:* [[Spelling of ordinal numbers]]
;Also see:
:* See the OEIS sequence A72425 "Four is the number of letters...".
:* See the OEIS sequence A72424 "Five's the number of letters..."
| package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := NewFourIsSeq()
fmt.Print("The lengths of the first 201 words are:")
for i := 1; i <= 201; i++ {
if i%25 == 1 {
fmt.Printf("\n%3d: ", i)
}
_, n := f.WordLen(i)
fmt.Printf(" %2d", n)
}
fmt.Println()
fmt.Println("Length of sentence so far:", f.TotalLength())
/* For debugging:
log.Println("sentence:", strings.Join(f.words, " "))
for i, w := range f.words {
log.Printf("%3d: %2d %q\n", i, countLetters(w), w)
}
log.Println(f.WordLen(2202))
log.Println("len(f.words):", len(f.words))
log.Println("sentence:", strings.Join(f.words, " "))
*/
for i := 1000; i <= 1e7; i *= 10 {
w, n := f.WordLen(i)
fmt.Printf("Word %8d is %q, with %d letters.", i, w, n)
fmt.Println(" Length of sentence so far:", f.TotalLength())
}
}
type FourIsSeq struct {
i int // index of last word processed
words []string // strings.Join(words," ") gives the sentence so far
}
func NewFourIsSeq() *FourIsSeq {
return &FourIsSeq{
//words: strings.Fields("Four is the number of letters in the first word of this sentence,"),
words: []string{
"Four", "is", "the", "number",
"of", "letters", "in", "the",
"first", "word", "of", "this", "sentence,",
},
}
}
// WordLen returns the w'th word and its length (only counting letters).
func (f *FourIsSeq) WordLen(w int) (string, int) {
for len(f.words) < w {
f.i++
n := countLetters(f.words[f.i])
ns := say(int64(n))
os := sayOrdinal(int64(f.i+1)) + ","
// append something like: "two in the second,"
f.words = append(f.words, strings.Fields(ns)...)
f.words = append(f.words, "in", "the")
f.words = append(f.words, strings.Fields(os)...)
}
word := f.words[w-1]
return word, countLetters(word)
}
// TotalLength returns the total number of characters (including blanks,
// commas, and punctuation) of the sentence so far constructed.
func (f FourIsSeq) TotalLength() int {
cnt := 0
for _, w := range f.words {
cnt += len(w) + 1
}
return cnt - 1
}
func countLetters(s string) int {
cnt := 0
for _, r := range s {
if unicode.IsLetter(r) {
cnt++
}
}
return cnt
}
// ...
// the contents of
// https://rosettacode.org/wiki/Spelling_of_ordinal_numbers#Go
// omitted from this listing
// ...
|
French Republican calendar | Go from BBC Basic | Write a program to convert dates between the French Republican calendar.
The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fete de la vertu / Virtue Day, Fete du genie / Talent Day, Fete du travail / Labour Day, Fete de l'opinion / Opinion Day, and Fete des recompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fete de la Revolution / Revolution Day.
As a minimum, your program should give correct results for dates in the range from 1 Vendemiaire 1 = 22 September 1792 to 10 Nivose 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)
Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:
* 1 Vendemiaire 1 = 22 September 1792
* 1 Prairial 3 = 20 May 1795
* 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)
* Fete de la Revolution 11 = 23 September 1803
* 10 Nivose 14 = 31 December 1805
| package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
var (
gregorianStr = []string{"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"}
gregorian = []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
republicanStr = []string{"Vendemiaire", "Brumaire", "Frimaire",
"Nivose", "Pluviose", "Ventose",
"Germinal", "Floreal", "Prairial",
"Messidor", "Thermidor", "Fructidor"}
sansculottidesStr = []string{"Fete de la vertu", "Fete du genie",
"Fete du travail", "Fete de l'opinion",
"Fete des recompenses", "Fete de la Revolution"}
)
func main() {
fmt.Println("*** French Republican ***")
fmt.Println("*** calendar converter ***")
fmt.Println("Enter a date to convert, in the format 'day month year'")
fmt.Println("e.g.: 1 Prairial 3,")
fmt.Println(" 20 May 1795.")
fmt.Println("For Sansculottides, use 'day year'")
fmt.Println("e.g.: Fete de l'opinion 9.")
fmt.Println("Or just press 'RETURN' to exit the program.")
fmt.Println()
for sc := bufio.NewScanner(os.Stdin); ; {
fmt.Print("> ")
sc.Scan()
src := sc.Text()
if src == "" {
return
}
day, month, year := split(src)
if year < 1792 {
day, month, year = dayToGre(repToDay(day, month, year))
fmt.Println(day, gregorianStr[month-1], year)
} else {
day, month, year := dayToRep(greToDay(day, month, year))
if month == 13 {
fmt.Println(sansculottidesStr[day-1], year)
} else {
fmt.Println(day, republicanStr[month-1], year)
}
}
}
}
func split(s string) (d, m, y int) {
if strings.HasPrefix(s, "Fete") {
m = 13
for i, sc := range sansculottidesStr {
if strings.HasPrefix(s, sc) {
d = i + 1
y, _ = strconv.Atoi(s[len(sc)+1:])
}
}
} else {
d, _ = strconv.Atoi(s[:strings.Index(s, " ")])
my := s[strings.Index(s, " ")+1:]
mStr := my[:strings.Index(my, " ")]
y, _ = strconv.Atoi(my[strings.Index(my, " ")+1:])
months := gregorianStr
if y < 1792 {
months = republicanStr
}
for i, mn := range months {
if mn == mStr {
m = i + 1
}
}
}
return
}
func greToDay(d, m, y int) int {
if m < 3 {
y--
m += 12
}
return y*36525/100 - y/100 + y/400 + 306*(m+1)/10 + d - 654842
}
func repToDay(d, m, y int) int {
if m == 13 {
m--
d += 30
}
if repLeap(y) {
d--
}
return 365*y + (y+1)/4 - (y+1)/100 + (y+1)/400 + 30*m + d - 395
}
func dayToGre(day int) (d, m, y int) {
y = day * 100 / 36525
d = day - y*36525/100 + 21
y += 1792
d += y/100 - y/400 - 13
m = 8
for d > gregorian[m] {
d -= gregorian[m]
m++
if m == 12 {
m = 0
y++
if greLeap(y) {
gregorian[1] = 29
} else {
gregorian[1] = 28
}
}
}
m++
return
}
func dayToRep(day int) (d, m, y int) {
y = (day-1) * 100 / 36525
if repLeap(y) {
y--
}
d = day - (y+1)*36525/100 + 365 + (y+1)/100 - (y+1)/400
y++
m = 1
sansculottides := 5
if repLeap(y) {
sansculottides = 6
}
for d > 30 {
d -= 30
m += 1
if m == 13 {
if d > sansculottides {
d -= sansculottides
m = 1
y++
sansculottides = 5
if repLeap(y) {
sansculottides = 6
}
}
}
}
return
}
func repLeap(year int) bool {
return (year+1)%4 == 0 && ((year+1)%100 != 0 || (year+1)%400 == 0)
}
func greLeap(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
} |
Function prototype | Go | Some languages provide the facility to declare functions and subroutines through the use of function prototyping.
;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:
* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above
Languages that do not provide function prototyping facilities should be omitted from this task.
| func a() // function with no arguments
func b(x, y int) // function with two arguments
func c(...int) // varargs are called "variadic parameters" in Go. |
Functional coverage tree | Go from Kotlin | Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.
This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.
;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.
She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.
The overall hierarchy of (sub)tasks is as follows,
cleaning
house1
bedrooms
bathrooms
bathroom1
bathroom2
outside lavatory
attic
kitchen
living rooms
lounge
dining room
conservatory
playroom
basement
garage
garden
house2
upstairs
bedrooms
suite 1
suite 2
bedroom 3
bedroom 4
bathroom
toilet
attics
groundfloor
kitchen
living rooms
lounge
dining room
conservatory
playroom
wet room & toilet
garage
garden
hot tub suite
basement
cellars
wine cellar
cinema
The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.
Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY |WEIGHT |COVERAGE |
cleaning | | |
house1 |40 | |
bedrooms | |0.25 |
bathrooms | | |
bathroom1 | |0.5 |
bathroom2 | | |
outside_lavatory | |1 |
attic | |0.75 |
kitchen | |0.1 |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | |1 |
basement | | |
garage | | |
garden | |0.8 |
house2 |60 | |
upstairs | | |
bedrooms | | |
suite_1 | | |
suite_2 | | |
bedroom_3 | | |
bedroom_4 | | |
bathroom | | |
toilet | | |
attics | |0.6 |
groundfloor | | |
kitchen | | |
living_rooms | | |
lounge | | |
dining_room | | |
conservatory | | |
playroom | | |
wet_room_&_toilet | | |
garage | | |
garden | |0.9 |
hot_tub_suite | |1 |
basement | | |
cellars | |1 |
wine_cellar | |1 |
cinema | |0.75 |
;Calculation:
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.
'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.
;Extra Credit:
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.
The pseudo code would be:
method delta_calculation(this, power):
sum_of_weights = sum(node.weight for node in children)
this.delta = (1 - this.coverage) * power
for node in self.children:
node.delta_calculation(power * node.weight / sum_of_weights)
return this.delta
Followed by a call to:
top.delta_calculation(power=1)
'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
| package main
import "fmt"
type FCNode struct {
name string
weight int
coverage float64
children []*FCNode
parent *FCNode
}
func newFCN(name string, weight int, coverage float64) *FCNode {
return &FCNode{name, weight, coverage, nil, nil}
}
func (n *FCNode) addChildren(nodes []*FCNode) {
for _, node := range nodes {
node.parent = n
n.children = append(n.children, node)
}
n.updateCoverage()
}
func (n *FCNode) setCoverage(value float64) {
if n.coverage != value {
n.coverage = value
// update any parent's coverage
if n.parent != nil {
n.parent.updateCoverage()
}
}
}
func (n *FCNode) updateCoverage() {
v1 := 0.0
v2 := 0
for _, node := range n.children {
v1 += float64(node.weight) * node.coverage
v2 += node.weight
}
n.setCoverage(v1 / float64(v2))
}
func (n *FCNode) show(level int) {
indent := level * 4
nl := len(n.name) + indent
fmt.Printf("%*s%*s %3d | %8.6f |\n", nl, n.name, 32-nl, "|", n.weight, n.coverage)
if len(n.children) == 0 {
return
}
for _, child := range n.children {
child.show(level + 1)
}
}
var houses = []*FCNode{
newFCN("house1", 40, 0),
newFCN("house2", 60, 0),
}
var house1 = []*FCNode{
newFCN("bedrooms", 1, 0.25),
newFCN("bathrooms", 1, 0),
newFCN("attic", 1, 0.75),
newFCN("kitchen", 1, 0.1),
newFCN("living_rooms", 1, 0),
newFCN("basement", 1, 0),
newFCN("garage", 1, 0),
newFCN("garden", 1, 0.8),
}
var house2 = []*FCNode{
newFCN("upstairs", 1, 0),
newFCN("groundfloor", 1, 0),
newFCN("basement", 1, 0),
}
var h1Bathrooms = []*FCNode{
newFCN("bathroom1", 1, 0.5),
newFCN("bathroom2", 1, 0),
newFCN("outside_lavatory", 1, 1),
}
var h1LivingRooms = []*FCNode{
newFCN("lounge", 1, 0),
newFCN("dining_room", 1, 0),
newFCN("conservatory", 1, 0),
newFCN("playroom", 1, 1),
}
var h2Upstairs = []*FCNode{
newFCN("bedrooms", 1, 0),
newFCN("bathroom", 1, 0),
newFCN("toilet", 1, 0),
newFCN("attics", 1, 0.6),
}
var h2Groundfloor = []*FCNode{
newFCN("kitchen", 1, 0),
newFCN("living_rooms", 1, 0),
newFCN("wet_room_&_toilet", 1, 0),
newFCN("garage", 1, 0),
newFCN("garden", 1, 0.9),
newFCN("hot_tub_suite", 1, 1),
}
var h2Basement = []*FCNode{
newFCN("cellars", 1, 1),
newFCN("wine_cellar", 1, 1),
newFCN("cinema", 1, 0.75),
}
var h2UpstairsBedrooms = []*FCNode{
newFCN("suite_1", 1, 0),
newFCN("suite_2", 1, 0),
newFCN("bedroom_3", 1, 0),
newFCN("bedroom_4", 1, 0),
}
var h2GroundfloorLivingRooms = []*FCNode{
newFCN("lounge", 1, 0),
newFCN("dining_room", 1, 0),
newFCN("conservatory", 1, 0),
newFCN("playroom", 1, 0),
}
func main() {
cleaning := newFCN("cleaning", 1, 0)
house1[1].addChildren(h1Bathrooms)
house1[4].addChildren(h1LivingRooms)
houses[0].addChildren(house1)
h2Upstairs[0].addChildren(h2UpstairsBedrooms)
house2[0].addChildren(h2Upstairs)
h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)
house2[1].addChildren(h2Groundfloor)
house2[2].addChildren(h2Basement)
houses[1].addChildren(house2)
cleaning.addChildren(houses)
topCoverage := cleaning.coverage
fmt.Printf("TOP COVERAGE = %8.6f\n\n", topCoverage)
fmt.Println("NAME HIERARCHY | WEIGHT | COVERAGE |")
cleaning.show(0)
h2Basement[2].setCoverage(1) // change Cinema node coverage to 1
diff := cleaning.coverage - topCoverage
fmt.Println("\nIf the coverage of the Cinema node were increased from 0.75 to 1")
fmt.Print("the top level coverage would increase by ")
fmt.Printf("%8.6f to %8.6f\n", diff, topCoverage+diff)
h2Basement[2].setCoverage(0.75) // restore to original value if required
} |
Fusc sequence | Go | Definitions:
The '''fusc''' integer sequence is defined as:
::* fusc(0) = 0
::* fusc(1) = 1
::* for '''n'''>1, the '''n'''th term is defined as:
::::* if '''n''' is even; fusc(n) = fusc(n/2)
::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
;An observation:
:::::* fusc(A) = fusc(B)
where '''A''' is some non-negative integer expressed in binary, and
where '''B''' is the binary value of '''A''' reversed.
Fusc numbers are also known as:
::* fusc function (named by Dijkstra, 1982)
::* Stern's Diatomic series (although it starts with unity, not zero)
::* Stern-Brocot sequence (although it starts with unity, not zero)
;Task:
::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.
::* show the fusc number (and its index) whose length is greater than any previous fusc number length.
::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)
::* show all numbers with commas (if appropriate).
::* show all output here.
;Related task:
::* RosettaCode Stern-Brocot sequence
;Also see:
::* the MathWorld entry: Stern's Diatomic Series.
::* the OEIS entry: A2487.
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue // avoid expensive strconv operation where possible
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
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() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000) // examine first twenty million numbers say
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
} |
Gapful numbers | Go | Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as '''gapful numbers'''.
''Evenly divisible'' means divisible with no remainder.
All one- and two-digit numbers have this property and are trivially excluded. Only
numbers >= '''100''' will be considered for this Rosetta Code task.
;Example:
'''187''' is a '''gapful''' number because it is evenly divisible by the
number '''17''' which is formed by the first and last decimal digits
of '''187'''.
About 7.46% of positive integers are ''gapful''.
;Task:
:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page
:* Show the first '''30''' gapful numbers
:* Show the first '''15''' gapful numbers >= '''1,000,000'''
:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''
;Related tasks:
:* Harshad or Niven series.
:* palindromic gapful numbers.
:* largest number divisible by its digits.
;Also see:
:* The OEIS entry: A108343 gapful numbers.
:* numbersaplenty gapful numbers
| program gapful;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
sysutils // IntToStr
{$IFDEF FPC}
,strUtils // Numb2USA aka commatize
{$ENDIF};
const
cIdx = 5;
starts: array[0..cIdx - 1] of Uint64 = (100, 1000 * 1000, 10 * 1000 * 1000,
1000 * 1000 * 1000, 7123);
counts: array[0..cIdx - 1] of Uint64 = (30, 15, 15, 10, 25);
//100| 74623687 => 1000*1000*1000
//100| 746236131 => 10*1000*1000*1000
//100|7462360431 =>100*1000*1000*1000
Base = 10;
var
ModsHL: array[0..99] of NativeUint;
Pow10: Uint64; //global, seldom used
countLmt: NativeUint; //Uint64; only for extreme counting
{$IFNDEF FPC}
function Numb2USA(const S: string): string;
var
i, NA: Integer;
begin
i := Length(S);
Result := S;
NA := 0;
while (i > 0) do
begin
if ((Length(Result) - i + 1 - NA) mod 3 = 0) and (i <> 1) then
begin
insert(',', Result, i);
inc(NA);
end;
Dec(i);
end;
end;
{$ENDIF}
procedure OutHeader(i: NativeInt);
begin
writeln('First ', counts[i], ', gapful numbers starting at ', Numb2USA(IntToStr
(starts[i])));
end;
procedure OutNum(n: Uint64);
begin
write(' ', n);
end;
procedure InitMods(n: Uint64; H_dgt: NativeUint);
//calculate first mod of n, when it reaches n
var
i, j: NativeInt;
begin
j := H_dgt; //= H_dgt+i
for i := 0 to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure InitMods2(n: Uint64; H_dgt, L_Dgt: NativeUint);
//calculate first mod of n, when it reaches n
//beware, that the lower n are reached in the next base round
var
i, j: NativeInt;
begin
j := H_dgt;
n := n - L_Dgt;
for i := 0 to L_Dgt - 1 do
begin
ModsHL[j] := (n + base) mod j;
inc(n);
inc(j);
end;
for i := L_Dgt to Base - 1 do
begin
ModsHL[j] := n mod j;
inc(n);
inc(j);
end;
end;
procedure Main(TestNum: Uint64; Cnt: NativeUint);
var
LmtNextNewHiDgt: Uint64;
tmp, LowDgt, GapNum: NativeUint;
begin
countLmt := Cnt;
Pow10 := Base * Base;
LmtNextNewHiDgt := Base * Pow10;
while LmtNextNewHiDgt <= TestNum do
begin
Pow10 := LmtNextNewHiDgt;
LmtNextNewHiDgt := LmtNextNewHiDgt * Base;
end;
LowDgt := TestNum mod Base;
GapNum := TestNum div Pow10;
LmtNextNewHiDgt := (GapNum + 1) * Pow10;
GapNum := Base * GapNum;
if LowDgt <> 0 then
InitMods2(TestNum, GapNum, LowDgt)
else
InitMODS(TestNum, GapNum);
GapNum := GapNum + LowDgt;
repeat
// if TestNum MOD (GapNum) = 0 then
if ModsHL[GapNum] = 0 then
begin
tmp := countLmt - 1;
if tmp < 32 then
OutNum(TestNum);
countLmt := tmp;
// Test and BREAK only if something has changed
if tmp = 0 then
BREAK;
end;
tmp := Base + ModsHL[GapNum];
//translate into "if-less" version 3.35s -> 1.85s
//bad branch prediction :-(
//if tmp >= GapNum then tmp -= GapNum;
tmp := tmp - (-ORD(tmp >= GapNum) and GapNum);
ModsHL[GapNum] := tmp;
TestNum := TestNum + 1;
tmp := LowDgt + 1;
inc(GapNum);
if tmp >= Base then
begin
tmp := 0;
GapNum := GapNum - Base;
end;
LowDgt := tmp;
//next Hi Digit
if TestNum >= LmtNextNewHiDgt then
begin
LowDgt := 0;
GapNum := GapNum + Base;
LmtNextNewHiDgt := LmtNextNewHiDgt + Pow10;
//next power of 10
if GapNum >= Base * Base then
begin
Pow10 := Pow10 * Base;
LmtNextNewHiDgt := 2 * Pow10;
GapNum := Base;
end;
initMods(TestNum, GapNum);
end;
until false;
end;
var
i: integer;
begin
for i := 0 to High(starts) do
begin
OutHeader(i);
Main(starts[i], counts[i]);
writeln(#13#10);
end;
{$IFNDEF LINUX} readln; {$ENDIF}
end. |
Subsets and Splits