title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Gauss-Jordan matrix inversion
Go from Kotlin
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
package main import "fmt" type vector = []float64 type matrix []vector func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vector, 2*le) copy(aug[i], m[i]) // augment by identity matrix to right aug[i][i+le] = 1 } aug.toReducedRowEchelonForm() inv := make(matrix, le) // remove identity matrix to left for i := 0; i < le; i++ { inv[i] = make(vector, le) copy(inv[i], aug[i][le:]) } return inv } // note: this mutates the matrix in place func (m matrix) toReducedRowEchelonForm() { lead := 0 rowCount, colCount := len(m), len(m[0]) for r := 0; r < rowCount; r++ { if colCount <= lead { return } i := r for m[i][lead] == 0 { i++ if rowCount == i { i = r lead++ if colCount == lead { return } } } m[i], m[r] = m[r], m[i] if div := m[r][lead]; div != 0 { for j := 0; j < colCount; j++ { m[r][j] /= div } } for k := 0; k < rowCount; k++ { if k != r { mult := m[k][lead] for j := 0; j < colCount; j++ { m[k][j] -= m[r][j] * mult } } } lead++ } } func (m matrix) print(title string) { fmt.Println(title) for _, v := range m { fmt.Printf("% f\n", v) } fmt.Println() } func main() { a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}} a.inverse().print("Inverse of A is:\n") b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}} b.inverse().print("Inverse of B is:\n") }
Gauss-Jordan matrix inversion
Go from PowerShell
Invert matrix '''A''' using Gauss-Jordan method. '''A''' being an '''n''' x '''n''' matrix.
package main import ( "fmt" "math" ) type vector = []float64 type matrix []vector func (m matrix) print(title string) { fmt.Println(title) for _, v := range m { fmt.Printf("% f\n", v) } } func I(n int) matrix { b := make(matrix, n) for i := 0; i < n; i++ { b[i] = make(vector, n) b[i][i] = 1 } return b } func (m matrix) inverse() matrix { n := len(m) for _, v := range m { if n != len(v) { panic("Not a square matrix") } } b := I(n) a := make(matrix, n) for i, v := range m { a[i] = make(vector, n) copy(a[i], v) } for k := range a { iMax := 0 max := -1. for i := k; i < n; i++ { row := a[i] // compute scale factor s = max abs in row s := -1. for j := k; j < n; j++ { x := math.Abs(row[j]) if x > s { s = x } } if s == 0 { panic("Irregular matrix") } // scale the abs used to pick the pivot. if abs := math.Abs(row[k]) / s; abs > max { iMax = i max = abs } } if k != iMax { a[k], a[iMax] = a[iMax], a[k] b[k], b[iMax] = b[iMax], b[k] } akk := a[k][k] for j := 0; j < n; j++ { a[k][j] /= akk b[k][j] /= akk } for i := 0; i < n; i++ { if (i != k) { aik := a[i][k] for j := 0; j < n; j++ { a[i][j] -= a[k][j] * aik b[i][j] -= b[k][j] * aik } } } } return b } func main() { a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}} a.inverse().print("Inverse of A is:\n") b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}} b.inverse().print("Inverse of B is:\n") }
Gaussian elimination
Go
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
package main import ( "errors" "fmt" "log" "math" ) type testCase struct { a [][]float64 b []float64 x []float64 } var tc = testCase{ // common RC example. Result x computed with rational arithmetic then // converted to float64, and so should be about as close to correct as // float64 represention allows. a: [][]float64{ {1.00, 0.00, 0.00, 0.00, 0.00, 0.00}, {1.00, 0.63, 0.39, 0.25, 0.16, 0.10}, {1.00, 1.26, 1.58, 1.98, 2.49, 3.13}, {1.00, 1.88, 3.55, 6.70, 12.62, 23.80}, {1.00, 2.51, 6.32, 15.88, 39.90, 100.28}, {1.00, 3.14, 9.87, 31.01, 97.41, 306.02}}, b: []float64{-0.01, 0.61, 0.91, 0.99, 0.60, 0.02}, x: []float64{-0.01, 1.602790394502114, -1.6132030599055613, 1.2454941213714368, -0.4909897195846576, 0.065760696175232}, } // result from above test case turns out to be correct to this tolerance. const ε = 1e-13 func main() { x, err := GaussPartial(tc.a, tc.b) if err != nil { log.Fatal(err) } fmt.Println(x) for i, xi := range x { if math.Abs(tc.x[i]-xi) > ε { log.Println("out of tolerance") log.Fatal("expected", tc.x) } } } func GaussPartial(a0 [][]float64, b0 []float64) ([]float64, error) { // make augmented matrix m := len(b0) a := make([][]float64, m) for i, ai := range a0 { row := make([]float64, m+1) copy(row, ai) row[m] = b0[i] a[i] = row } // WP algorithm from Gaussian elimination page // produces row-eschelon form for k := range a { // Find pivot for column k: iMax := k max := math.Abs(a[k][k]) for i := k + 1; i < m; i++ { if abs := math.Abs(a[i][k]); abs > max { iMax = i max = abs } } if a[iMax][k] == 0 { return nil, errors.New("singular") } // swap rows(k, i_max) a[k], a[iMax] = a[iMax], a[k] // Do for all rows below pivot: for i := k + 1; i < m; i++ { // Do for all remaining elements in current row: for j := k + 1; j <= m; j++ { a[i][j] -= a[k][j] * (a[i][k] / a[k][k]) } // Fill lower triangular matrix with zeros: a[i][k] = 0 } } // end of WP algorithm. // now back substitute to get result. x := make([]float64, m) for i := m - 1; i >= 0; i-- { x[i] = a[i][m] for j := i + 1; j < m; j++ { x[i] -= a[i][j] * x[j] } x[i] /= a[i][i] } return x, nil }
Generate Chess960 starting position
Go from Ruby
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
Generate random chess position
Go from Java
Generate a random chess position in FEN format. The position does not have to be realistic or even balanced, but it must comply to the following rules: :* there is one and only one king of each color (one black king and one white king); :* the kings must not be placed on adjacent squares; :* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank); :* including the kings, up to 32 pieces of either color can be placed. :* There is no requirement for material balance between sides. :* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. :* it is white's turn. :* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
Generator/Exponential
Go
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
package main import ( "fmt" "math" ) // note: exponent not limited to ints func newPowGen(e float64) func() float64 { var i float64 return func() (r float64) { r = math.Pow(i, e) i++ return } } // given two functions af, bf, both monotonically increasing, return a // new function that returns values of af not returned by bf. func newMonoIncA_NotMonoIncB_Gen(af, bf func() float64) func() float64 { a, b := af(), bf() return func() (r float64) { for { if a < b { r = a a = af() break } if b == a { a = af() } b = bf() } return } } func main() { fGen := newMonoIncA_NotMonoIncB_Gen(newPowGen(2), newPowGen(3)) for i := 0; i < 20; i++ { fGen() } for i := 0; i < 10; i++ { fmt.Print(fGen(), " ") } fmt.Println() }
Get system command output
Go
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). ;Related task * Execute a system command
package main import ( "fmt" "log" "os/exec" ) func main() { output, err := exec.Command("ls", "-l").CombinedOutput() if err != nil { log.Fatal(err) } fmt.Print(string(output)) }
Giuga numbers
Go from Wren
Definition A '''Giuga number''' is a composite number '''n''' which is such that each of its distinct prime factors '''f''' divide (n/f - 1) exactly. All known Giuga numbers are even though it is not known for certain that there are no odd examples. ;Example 30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and: * 30/2 - 1 = 14 is divisible by 2 * 30/3 - 1 = 9 is divisible by 3 * 30/5 - 1 = 5 is divisible by 5 ;Task Determine and show here the first four Giuga numbers. ;Stretch Determine the fifth Giuga number and any more you have the patience for. ;References * Wikipedia: Giuga number * OEIS:A007850 - Giuga numbers
package main import "fmt" var factors []int var inc = []int{4, 2, 4, 2, 4, 6, 2, 6} // Assumes n is even with exactly one factor of 2. // Empties 'factors' if any other prime factor is repeated. func primeFactors(n int) { factors = factors[:0] factors = append(factors, 2) last := 2 n /= 2 for n%3 == 0 { if last == 3 { factors = factors[:0] return } last = 3 factors = append(factors, 3) n /= 3 } for n%5 == 0 { if last == 5 { factors = factors[:0] return } last = 5 factors = append(factors, 5) n /= 5 } for k, i := 7, 0; k*k <= n; { if n%k == 0 { if last == k { factors = factors[:0] return } last = k factors = append(factors, k) n /= k } else { k += inc[i] i = (i + 1) % 8 } } if n > 1 { factors = append(factors, n) } } func main() { const limit = 5 var giuga []int // n can't be 2 or divisible by 4 for n := 6; len(giuga) < limit; n += 4 { primeFactors(n) // can't be prime or semi-prime if len(factors) > 2 { isGiuga := true for _, f := range factors { if (n/f-1)%f != 0 { isGiuga = false break } } if isGiuga { giuga = append(giuga, n) } } } fmt.Println("The first", limit, "Giuga numbers are:") fmt.Println(giuga) }
Globally replace text in several files
Go
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
package main import ( "bytes" "io/ioutil" "log" "os" ) func main() { gRepNFiles("Goodbye London!", "Hello New York!", []string{ "a.txt", "b.txt", "c.txt", }) } func gRepNFiles(olds, news string, files []string) { oldb := []byte(olds) newb := []byte(news) for _, fn := range files { if err := gRepFile(oldb, newb, fn); err != nil { log.Println(err) } } } func gRepFile(oldb, newb []byte, fn string) (err error) { var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } if bytes.Index(b, oldb) < 0 { return } r := bytes.Replace(b, oldb, newb, -1) if err = f.Truncate(0); err != nil { return } _, err = f.WriteAt(r, 0) return }
Graph colouring
Go
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected. Only unconnected nodes ''need'' a separate description. For example, 0-1 1-2 2-0 3 Describes the following graph. Note that node 3 has no neighbours ;Example graph: +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ A useful internal datastructure for a graph and for later graph algorithms is as a mapping between each node and the set/list of its neighbours. In the above example: 0 maps-to 1 and 2 1 maps to 2 and 0 2 maps-to 1 and 0 3 maps-to ;Graph colouring task: Colour the vertices of a given graph so that no edge is between verticies of the same colour. * Integers may be used to denote different colours. * Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is '''not''' a requirement). * Show for each edge, the colours assigned on each vertex. * Show the total number of nodes, edges, and colours used for each graph. ;Use the following graphs: ;Ex1: 0-1 1-2 2-0 3 +---+ | 3 | +---+ +-------------------+ | | +---+ +---+ +---+ | 0 | --- | 1 | --- | 2 | +---+ +---+ +---+ ;Ex2: The wp articles left-side graph 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7 +----------------------------------+ | | | +---+ | | +-----------------| 3 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 6 | --- | 4 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 7 | --- | 2 | --- | 5 | -+ | +---+ +---+ +---+ | | +-------------------+ ;Ex3: The wp articles right-side graph which is the same graph as Ex2, but with different node orderings and namings. 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6 +----------------------------------+ | | | +---+ | | +-----------------| 5 | ------+----+ | | +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ +---+ | | | 8 | --- | 1 | --- | 4 | --- | 7 | | | +---+ +---+ +---+ +---+ | | | | | | | | | | | | | | | | | | +---+ +---+ +---+ | +----+------ | 6 | --- | 3 | --- | 2 | -+ | +---+ +---+ +---+ | | +-------------------+ ;Ex4: This is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x. This might alter the node order used in the greedy algorithm leading to differing numbers of colours. 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7 +-------------------------------------------------+ | | | | +-------------------+---------+ | | | | | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 | +---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+ | | | | | | +---------+-----------------------------+---------+ | | | | | | | | | | +-----------------------------+-------------------+ | | | | | +-----------------------------+ ;References: * Greedy coloring Wikipedia. * Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain.
package main import ( "fmt" "sort" ) type graph struct { nn int // number of nodes st int // node numbering starts from nbr [][]int // neighbor list for each node } type nodeval struct { n int // number of node v int // valence of node i.e. number of neighbors } func contains(s []int, n int) bool { for _, e := range s { if e == n { return true } } return false } func newGraph(nn, st int) graph { nbr := make([][]int, nn) return graph{nn, st, nbr} } // Note that this creates a single 'virtual' edge for an isolated node. func (g graph) addEdge(n1, n2 int) { n1, n2 = n1-g.st, n2-g.st // adjust to starting node number g.nbr[n1] = append(g.nbr[n1], n2) if n1 != n2 { g.nbr[n2] = append(g.nbr[n2], n1) } } // Uses 'greedy' algorithm. func (g graph) greedyColoring() []int { // create a slice with a color for each node, starting with color 0 cols := make([]int, g.nn) // all zero by default including the first node for i := 1; i < g.nn; i++ { cols[i] = -1 // mark all nodes after the first as having no color assigned (-1) } // create a bool slice to keep track of which colors are available available := make([]bool, g.nn) // all false by default // assign colors to all nodes after the first for i := 1; i < g.nn; i++ { // iterate through neighbors and mark their colors as available for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = true } } // find the first available color c := 0 for ; c < g.nn; c++ { if !available[c] { break } } cols[i] = c // assign it to the current node // reset the neighbors' colors to unavailable // before the next iteration for _, j := range g.nbr[i] { if cols[j] != -1 { available[cols[j]] = false } } } return cols } // Uses Welsh-Powell algorithm. func (g graph) wpColoring() []int { // create nodeval for each node nvs := make([]nodeval, g.nn) for i := 0; i < g.nn; i++ { v := len(g.nbr[i]) if v == 1 && g.nbr[i][0] == i { // isolated node v = 0 } nvs[i] = nodeval{i, v} } // sort the nodevals in descending order by valence sort.Slice(nvs, func(i, j int) bool { return nvs[i].v > nvs[j].v }) // create colors slice with entries for each node cols := make([]int, g.nn) for i := range cols { cols[i] = -1 // set all nodes to no color (-1) initially } currCol := 0 // start with color 0 for f := 0; f < g.nn-1; f++ { h := nvs[f].n if cols[h] != -1 { // already assigned a color continue } cols[h] = currCol // assign same color to all subsequent uncolored nodes which are // not connected to a previous colored one outer: for i := f + 1; i < g.nn; i++ { j := nvs[i].n if cols[j] != -1 { // already colored continue } for k := f; k < i; k++ { l := nvs[k].n if cols[l] == -1 { // not yet colored continue } if contains(g.nbr[j], l) { continue outer // node j is connected to an earlier colored node } } cols[j] = currCol } currCol++ } return cols } func main() { fns := [](func(graph) []int){graph.greedyColoring, graph.wpColoring} titles := []string{"'Greedy'", "Welsh-Powell"} nns := []int{4, 8, 8, 8} starts := []int{0, 1, 1, 1} edges1 := [][2]int{{0, 1}, {1, 2}, {2, 0}, {3, 3}} edges2 := [][2]int{{1, 6}, {1, 7}, {1, 8}, {2, 5}, {2, 7}, {2, 8}, {3, 5}, {3, 6}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} edges3 := [][2]int{{1, 4}, {1, 6}, {1, 8}, {3, 2}, {3, 6}, {3, 8}, {5, 2}, {5, 4}, {5, 8}, {7, 2}, {7, 4}, {7, 6}} edges4 := [][2]int{{1, 6}, {7, 1}, {8, 1}, {5, 2}, {2, 7}, {2, 8}, {3, 5}, {6, 3}, {3, 8}, {4, 5}, {4, 6}, {4, 7}} for j, fn := range fns { fmt.Println("Using the", titles[j], "algorithm:\n") for i, edges := range [][][2]int{edges1, edges2, edges3, edges4} { fmt.Println(" Example", i+1) g := newGraph(nns[i], starts[i]) for _, e := range edges { g.addEdge(e[0], e[1]) } cols := fn(g) ecount := 0 // counts edges for _, e := range edges { if e[0] != e[1] { fmt.Printf(" Edge %d-%d -> Color %d, %d\n", e[0], e[1], cols[e[0]-g.st], cols[e[1]-g.st]) ecount++ } else { fmt.Printf(" Node %d -> Color %d\n", e[0], cols[e[0]-g.st]) } } maxCol := 0 // maximum color number used for _, col := range cols { if col > maxCol { maxCol = col } } fmt.Println(" Number of nodes :", nns[i]) fmt.Println(" Number of edges :", ecount) fmt.Println(" Number of colors :", maxCol+1) fmt.Println() } } }
Gray code
Go from Euphoria
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
package main import "fmt" func enc(b int) int { return b ^ b>>1 } func dec(g int) (b int) { for ; g != 0; g >>= 1 { b ^= g } return } func main() { fmt.Println("decimal binary gray decoded") for b := 0; b < 32; b++ { g := enc(b) d := dec(g) fmt.Printf(" %2d %05b %05b %05b %2d\n", b, b, g, d, d) } }
Greatest subsequential sum
Go
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
package main import "fmt" func gss(s []int) ([]int, int) { var best, start, end, sum, sumStart int for i, x := range s { sum += x switch { case sum > best: best = sum start = sumStart end = i + 1 case sum < 0: sum = 0 sumStart = i + 1 } } return s[start:end], best } var testCases = [][]int{ {-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}, {-1, 1, 2, -5, -6}, {}, {-1, -2, -1}, } func main() { for _, c := range testCases { fmt.Println("Input: ", c) subSeq, sum := gss(c) fmt.Println("Sub seq:", subSeq) fmt.Println("Sum: ", sum, "\n") } }
Greedy algorithm for Egyptian fractions
Go from Kotlin
An Egyptian fraction is the sum of distinct unit fractions such as: :::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48}) Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement :::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil} (simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function). For this task, Proper and improper fractions must be able to be expressed. Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n'']. ;Task requirements: * show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59} * for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has: ::* the largest number of terms, ::* the largest denominator. * for all one-, two-, and three-digit integers, find and show (as above). {extra credit} ;Also see: * Wolfram MathWorld(tm) entry: Egyptian fraction
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(), br.Num(), irem) if irem.Cmp(zero) > 0 { iquo.Add(iquo, one) } rquo := new(big.Rat).SetFrac(one, iquo) fracs = append(fracs, rquo) num2 := new(big.Int).Neg(br.Denom()) num2.Rem(num2, br.Num()) if num2.Cmp(zero) < 0 { num2.Add(num2, br.Num()) } denom2 := new(big.Int) denom2.Mul(br.Denom(), iquo) f := new(big.Rat).SetFrac(num2, denom2) if f.Num().Cmp(one) == 0 { fracs = append(fracs, f) return fracs } fracs = toEgyptianRecursive(f, fracs) return fracs } func toEgyptian(rat *big.Rat) []*big.Rat { if rat.Num().Cmp(zero) == 0 { return []*big.Rat{rat} } var fracs []*big.Rat if rat.Num().CmpAbs(rat.Denom()) >= 0 { iquo := new(big.Int) iquo.Quo(rat.Num(), rat.Denom()) rquo := new(big.Rat).SetFrac(iquo, one) rrem := new(big.Rat) rrem.Sub(rat, rquo) fracs = append(fracs, rquo) fracs = toEgyptianRecursive(rrem, fracs) } else { fracs = toEgyptianRecursive(rat, fracs) } return fracs } func main() { fracs := []*big.Rat{big.NewRat(43, 48), big.NewRat(5, 121), big.NewRat(2014, 59)} for _, frac := range fracs { list := toEgyptian(frac) if list[0].Denom().Cmp(one) == 0 { first := fmt.Sprintf("[%v]", list[0].Num()) temp := make([]string, len(list)-1) for i := 1; i < len(list); i++ { temp[i-1] = list[i].String() } rest := strings.Join(temp, " + ") fmt.Printf("%v -> %v + %s\n", frac, first, rest) } else { temp := make([]string, len(list)) for i := 0; i < len(list); i++ { temp[i] = list[i].String() } all := strings.Join(temp, " + ") fmt.Printf("%v -> %s\n", frac, all) } } for _, r := range [2]int{98, 998} { if r == 98 { fmt.Println("\nFor proper fractions with 1 or 2 digits:") } else { fmt.Println("\nFor proper fractions with 1, 2 or 3 digits:") } maxSize := 0 var maxSizeFracs []*big.Rat maxDen := zero var maxDenFracs []*big.Rat var sieve = make([][]bool, r+1) // to eliminate duplicates for i := 0; i <= r; i++ { sieve[i] = make([]bool, r+2) } for i := 1; i <= r; i++ { for j := i + 1; j <= r+1; j++ { if sieve[i][j] { continue } f := big.NewRat(int64(i), int64(j)) list := toEgyptian(f) listSize := len(list) if listSize > maxSize { maxSize = listSize maxSizeFracs = maxSizeFracs[0:0] maxSizeFracs = append(maxSizeFracs, f) } else if listSize == maxSize { maxSizeFracs = append(maxSizeFracs, f) } listDen := list[len(list)-1].Denom() if listDen.Cmp(maxDen) > 0 { maxDen = listDen maxDenFracs = maxDenFracs[0:0] maxDenFracs = append(maxDenFracs, f) } else if listDen.Cmp(maxDen) == 0 { maxDenFracs = append(maxDenFracs, f) } if i < r/2 { k := 2 for { if j*k > r+1 { break } sieve[i*k][j*k] = true k++ } } } } fmt.Println(" largest number of items =", maxSize) fmt.Println(" fraction(s) with this number :", maxSizeFracs) md := maxDen.String() fmt.Print(" largest denominator = ", len(md), " digits, ") fmt.Print(md[0:20], "...", md[len(md)-20:], "\b\n") fmt.Println(" fraction(s) with this denominator :", maxDenFracs) } }
Greyscale bars/Display
Go from Java
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
package main import ( "github.com/fogleman/gg" "math" ) func greyBars(dc *gg.Context) { run := 0 colorComp := 0.0 // component of the color for colCount := 8; colCount < 128; colCount *= 2 { // by this gap we change the background color colorGap := 255.0 / float64(colCount-1) colWidth := float64(dc.Width() / colCount) colHeight := float64(dc.Height() / 4) // switches color directions with each iteration of for loop if run%2 == 0 { colorComp = 0.0 } else { colorComp = 255.0 colorGap = -colorGap } xstart, ystart := 0.0, colHeight*float64(run) for i := 0; i < colCount; i++ { icolor := int(math.Round(colorComp)) // round to nearer integer dc.SetRGB255(icolor, icolor, icolor) dc.DrawRectangle(xstart, ystart, colWidth, colHeight) dc.Fill() xstart += colWidth colorComp += colorGap } run++ } } func main() { dc := gg.NewContext(640, 320) greyBars(dc) dc.SavePNG("greybars.png") }
Hailstone sequence
Go
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # 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 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
package main import "fmt" // 1st arg is the number to generate the sequence for. // 2nd arg is a slice to recycle, to reduce garbage. func hs(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 main() { seq := hs(27, nil) fmt.Printf("hs(27): %d elements: [%d %d %d %d ... %d %d %d %d]\n", len(seq), seq[0], seq[1], seq[2], seq[3], seq[len(seq)-4], seq[len(seq)-3], seq[len(seq)-2], seq[len(seq)-1]) var maxN, maxLen int for n := 1; n < 100000; n++ { seq = hs(n, seq) if len(seq) > maxLen { maxN = n maxLen = len(seq) } } fmt.Printf("hs(%d): %d elements\n", maxN, maxLen) }
Halt and catch fire
Go
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an internal corruption has been detected and it would be dangerous and irresponsible to continue. ;References * Wikipedia: Halt and Catch Fire ;Related Tasks * [[Program termination]]
package main; import "fmt"; func main(){a, b := 0, 0; fmt.Println(a/b)}
Harmonic series
Go from Wren
{{Wikipedia|Harmonic number}} In mathematics, the '''n-th''' harmonic number is the sum of the reciprocals of the first '''n''' natural numbers: '''H''n'' = 1 + 1/2 + 1/3 + ... + 1/n''' The series of harmonic numbers thus obtained is often loosely referred to as the harmonic series. Harmonic numbers are closely related to the Euler-Mascheroni constant. The harmonic series is divergent, albeit quite slowly, and grows toward infinity. ;Task * Write a function (routine, procedure, whatever it may be called in your language) to generate harmonic numbers. * Use that procedure to show the values of the first 20 harmonic numbers. * Find and show the position in the series of the first value greater than the integers 1 through 5 ;Stretch * Find and show the position in the series of the first value greater than the integers 6 through 10 ;Related * [[Egyptian fractions]]
package main import ( "fmt" "math/big" ) func harmonic(n int) *big.Rat { sum := new(big.Rat) for i := int64(1); i <= int64(n); i++ { r := big.NewRat(1, i) sum.Add(sum, r) } return sum } func main() { fmt.Println("The first 20 harmonic numbers and the 100th, expressed in rational form, are:") numbers := make([]int, 21) for i := 1; i <= 20; i++ { numbers[i-1] = i } numbers[20] = 100 for _, i := range numbers { fmt.Printf("%3d : %s\n", i, harmonic(i)) } fmt.Println("\nThe first harmonic number to exceed the following integers is:") const limit = 10 for i, n, h := 1, 1, 0.0; i <= limit; n++ { h += 1.0 / float64(n) if h > float64(i) { fmt.Printf("integer = %2d -> n = %6d -> harmonic number = %9.6f (to 6dp)\n", i, n, h) i++ } } }
Harshad or Niven series
Go
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
package main import "fmt" type is func() int func newSum() is { var ms is ms = func() int { ms = newSum() return ms() } var msd, d int return func() int { if d < 9 { d++ } else { d = 0 msd = ms() } return msd + d } } func newHarshard() is { i := 0 sum := newSum() return func() int { for i++; i%sum() != 0; i++ { } return i } } func main() { h := newHarshard() fmt.Print(h()) for i := 1; i < 20; i++ { fmt.Print(" ", h()) } fmt.Println() h = newHarshard() n := h() for ; n <= 1000; n = h() { } fmt.Println(n) }
Hash join
Go
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory", "Buffy"}, } // hash phase h := map[string][]int{} for i, r := range tableA { h[r.key] = append(h[r.key], i) } // join phase for _, x := range tableB { for _, a := range h[x.key] { fmt.Println(tableA[a], x) } } }
Haversine formula
Go
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
package main import ( "fmt" "math" ) func haversine(θ float64) float64 { return .5 * (1 - math.Cos(θ)) } type pos struct { φ float64 // latitude, radians ψ float64 // longitude, radians } func degPos(lat, lon float64) pos { return pos{lat * math.Pi / 180, lon * math.Pi / 180} } const rEarth = 6372.8 // km func hsDist(p1, p2 pos) float64 { return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.φ-p1.φ)+ math.Cos(p1.φ)*math.Cos(p2.φ)*haversine(p2.ψ-p1.ψ))) } func main() { fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40))) }
Hello world/Line printer
Go
Cause a line printer attached to the computer to print a line containing the message: Hello World! ;Note: A line printer is not the same as standard output. A line printer was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
package main import ( "fmt" "os" ) func main() { lp0, err := os.Create("/dev/lp0") if err != nil { panic(err) } defer lp0.Close() fmt.Fprintln(lp0, "Hello World!") }
Hello world/Newbie
Go
Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the [[Hello world/Text]] task. * Assume the language-newbie is a programmer in another language. * Assume the language-newbie is competent in installing software for the platform. * Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor). * Refer to, (and link to), already existing documentation as much as possible (but provide a summary here). * Remember to state where to view the output. * If particular IDE's or editors are required that are not standard, then point to/explain their installation too. ;Note: * If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated. * You may use sub-headings if giving instructions for multiple platforms.
Currently supported platforms are FreeBSD, Linux, Mac OS X, and Windows. From the landing page http://golang.org click the blue box "Download Go" (under the big gopher drawing.) This takes you to [http://golang.org/doc/install Getting Started], a fairly concise page that is very close to satisfying this task. The first section, Download, has a link to a downloads page but also mentions two other options, building from source and using GCC. I personally like building from source and have found it usually goes without a hitch. GCC isn't just C anymore and includes a number of language front ends. Go is one of them. There are links there to separate pages of instructions for building from source and using GCC. Continuing with instructions for the precompiled binaries though, there is a section "System Requirements" and then a section "Install the Go tools", which means tools including the Go compiler. You need to follow some steps here. Follow the instructions for your operating system. (The steps are few, standard, and easy.) Pay attention to the paragraph "Installing to a custom location" if you are installing on a system where you do not have root or sudo access. Setting GOROOT as described is essential in this case. If you are installing to the standard location, you should not set this environment variable. (Setting it when it doesn't need to be set can lead to problems. Just don't.) You're ready to test the installation with Hello World! The RC Task mentions [[Editor|texteditor]]s. You will want an editor that can edit Unicode UTF-8. Go source is specified to be UTF-8 and before long you will want an editor that does this. This task is all ASCII however, and any editor that can save plain ASCII text will do for the moment. Actually you probably don't even need an editor. From a Linux command line for example, you can type $ cat >hello.go Cut and paste the code from [[Hello_world/Text#Go]], press ^D, and you should have the program. To run it type $ go run hello.go This compiles to a temporary executable file and runs it, displaying output right there in the same window. If you want a copy to give to your friends, $ go build hello.go will create an executable called hello in the current directory. This completes the RC task, but if at any point in the future you will use Go for more than Hello World, you really really should continue through the next section "Set up your work environment." This covers setting GOPATH, which is essential to standard workflow with Go.
Heronian triangles
Go
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
package main import ( "fmt" "math" "sort" ) const ( n = 200 header = "\nSides P A" ) func gcd(a, b int) int { leftover := 1 var dividend, divisor int if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a } for (leftover != 0) { leftover = dividend % divisor if (leftover > 0) { dividend, divisor = divisor, leftover } } return divisor } func is_heron(h float64) bool { return h > 0 && math.Mod(h, 1) == 0.0 } // by_area_perimeter implements sort.Interface for [][]int based on the area first and perimeter value type by_area_perimeter [][]int func (a by_area_perimeter) Len() int { return len(a) } func (a by_area_perimeter) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a by_area_perimeter) Less(i, j int) bool { return a[i][4] < a[j][4] || a[i][4] == a[j][4] && a[i][3] < a[j][3] } func main() { var l [][]int for c := 1; c <= n; c++ { for b := 1; b <= c; b++ { for a := 1; a <= b; a++ { if (gcd(gcd(a, b), c) == 1) { p := a + b + c s := float64(p) / 2.0 area := math.Sqrt(s * (s - float64(a)) * (s - float64(b)) * (s - float64(c))) if (is_heron(area)) { l = append(l, []int{a, b, c, p, int(area)}) } } } } } fmt.Printf("Number of primitive Heronian triangles with sides up to %d: %d", n, len(l)) sort.Sort(by_area_perimeter(l)) fmt.Printf("\n\nFirst ten when ordered by increasing area, then perimeter:" + header) for i := 0; i < 10; i++ { fmt.Printf("\n%3d", l[i]) } a := 210 fmt.Printf("\n\nArea = %d%s", a, header) for _, it := range l { if (it[4] == a) { fmt.Printf("\n%3d", it) } } }
Hickerson series of almost integers
Go
The following function, due to D. Hickerson, is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.) The function is: h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}} It is said to produce "almost integers" for '''n''' between '''1''' and '''17'''. The purpose of the task is to verify this assertion. Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation ;Task: Calculate all values of the function checking and stating which are "almost integers". Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example: h(18) = 3385534663256845326.39...
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
History variables
Go
''Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' ''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables. '' "History Variables: The Semantics, Formal Correctness, and Implementation of History Variables in an Imperative Programming Language" by Mallon and Takaoka Concept also discussed on LtU and Patents.com. ;Task: Demonstrate History variable support: * enable history variable support (if needed) * define a history variable * assign three values * non-destructively display the history * recall the three values. For extra points, if the language of choice does not support history variables, demonstrate how this might be implemented.
package main import ( "fmt" "sort" "sync" "time" ) // data type for history variable (its an int) type history struct { timestamp tsFunc hs []hset } // data type for timestamp generator type tsFunc func() time.Time // data type for a "set" event type hset struct { int // new value t time.Time // timestamp } // newHistory creates a history variable func newHistory(ts tsFunc) history { return history{ts, []hset{{t: ts()}}} } // int returns the current value func (h history) int() int { return h.hs[len(h.hs)-1].int } // set does what you expect and returns the timestamp recorded for the event func (h *history) set(x int) time.Time { t := h.timestamp() h.hs = append(h.hs, hset{x, t}) return t } // dump displays a complete history func (h history) dump() { for _, hs := range h.hs { fmt.Println(hs.t.Format(time.StampNano), hs.int) } } // recall recalls the value stored in the history variable at time t. // if the variable had not been created yet, ok is false. func (h history) recall(t time.Time) (int, /*ok*/ bool) { i := sort.Search(len(h.hs), func(i int) bool { return h.hs[i].t.After(t) }) if i > 0 { return h.hs[i-1].int, true } return 0, false } // newTimestamper returns a function that generates unique timestamps. // Use a single timestamper for multiple history variables to preserve // an unambiguous sequence of assignments across the multiple history // variables within a single goroutine. func newTimestamper() tsFunc { var last time.Time return func() time.Time { if t := time.Now(); t.After(last) { last = t } else { last.Add(1) } return last } } // newProtectedTimestamper generates unique timestamps for concurrent // goroutines. func newProtectedTimestamper() tsFunc { var last time.Time var m sync.Mutex return func() (t time.Time) { t = time.Now() m.Lock() // m protects last if t.After(last) { last = t } else { last.Add(1) t = last } m.Unlock() return } } func main() { // enable history variable support appropriate for single goroutine. ts := newTimestamper() // define a history variable h := newHistory(ts) // assign three values. (timestamps kept for future reference.) ref := []time.Time{h.set(3), h.set(1), h.set(4)} // non-destructively display history fmt.Println("History of variable h:") h.dump() // recall the three values. (this is non-destructive as well, but // different than the dump in that values are recalled by time.) fmt.Println("Recalling values:") for _, t := range ref { rv, _ := h.recall(t) fmt.Println(rv) } }
Hofstadter-Conway $10,000 sequence
Go
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
package main import ( "fmt" ) func main() { a := []int{0, 1, 1} // ignore 0 element. work 1 based. x := 1 // last number in list n := 2 // index of last number in list = len(a)-1 mallow := 0 for p := 1; p < 20; p++ { max := 0. for nextPot := n*2; n < nextPot; { n = len(a) // advance n x = a[x]+a[n-x] a = append(a, x) f := float64(x)/float64(n) if f > max { max = f } if f >= .55 { mallow = n } } fmt.Printf("max between 2^%d and 2^%d was %f\n", p, p+1, max) } fmt.Println("winning number", mallow) }
Hofstadter Figure-Figure sequences
Go
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
package main import "fmt" var ffr, ffs func(int) int // The point of the init function is to encapsulate r and s. If you are // not concerned about that or do not want that, r and s can be variables at // package level and ffr and ffs can be ordinary functions at package level. func init() { // task 1, 2 r := []int{0, 1} s := []int{0, 2} ffr = func(n int) int { for len(r) <= n { nrk := len(r) - 1 // last n for which r(n) is known rNxt := r[nrk] + s[nrk] // next value of r: r(nrk+1) r = append(r, rNxt) // extend sequence r by one element for sn := r[nrk] + 2; sn < rNxt; sn++ { s = append(s, sn) // extend sequence s up to rNext } s = append(s, rNxt+1) // extend sequence s one past rNext } return r[n] } ffs = func(n int) int { for len(s) <= n { ffr(len(r)) } return s[n] } } func main() { // task 3 for n := 1; n <= 10; n++ { fmt.Printf("r(%d): %d\n", n, ffr(n)) } // task 4 var found [1001]int for n := 1; n <= 40; n++ { found[ffr(n)]++ } for n := 1; n <= 960; n++ { found[ffs(n)]++ } for i := 1; i <= 1000; i++ { if found[i] != 1 { fmt.Println("task 4: FAIL") return } } fmt.Println("task 4: PASS") }
Hofstadter Q sequence
Go
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
package main import "fmt" var m map[int]int func initMap() { m = make(map[int]int) m[1] = 1 m[2] = 1 } func q(n int) (r int) { if r = m[n]; r == 0 { r = q(n-q(n-1)) + q(n-q(n-2)) m[n] = r } return } func main() { initMap() // task for n := 1; n <= 10; n++ { showQ(n) } // task showQ(1000) // extra credit count, p := 0, 1 for n := 2; n <= 1e5; n++ { qn := q(n) if qn < p { count++ } p = qn } fmt.Println("count:", count) // extra credit initMap() showQ(1e6) } func showQ(n int) { fmt.Printf("Q(%d) = %d\n", n, q(n)) }
Horner's rule for polynomial evaluation
Go
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
package main import "fmt" func horner(x int64, c []int64) (acc int64) { for i := len(c) - 1; i >= 0; i-- { acc = acc*x + c[i] } return } func main() { fmt.Println(horner(3, []int64{-19, 7, -4, 6})) }
I'm a software engineer, get me out of here
Go from Phix
Your latest contract has hit a snag. You came to update the army payroll system, but awoke this morning to the sound of mortars landing not far away and panicked generals banging on you door. The President has loaded his gold on trucks and needs to find the shortest route to safety. You are given the following map. The top left hand corner is (0,0). You and The President are located at HQ in the centre of the country (11,11). Cells marked 0 indicate safety. Numbers other than 0 indicate the number of cells that his party will travel in a day in any direction up, down, left, right, or diagonally. 00000 00003130000 000321322221000 00231222432132200 0041433223233211100 0232231612142618530 003152122326114121200 031252235216111132210 022211246332311115210 00113232262121317213200 03152118212313211411110 03231234121132221411410 03513213411311414112320 00427534125412213211400 013322444412122123210 015132331312411123120 003333612214233913300 0219126511415312570 0021321524341325100 00211415413523200 000122111322000 00001120000 00000 Part 1 Use Dijkstra's algorithm to find a list of the shortest routes from HQ to safety. Part 2 Six days later and you are called to another briefing. The good news is The President and his gold are safe, so your invoice may be paid if you can get out of here. To do this a number of troop repositions will be required. It is concluded that you need to know the shortest route from each cell to every other cell. You decide to use Floyd's algorithm. Print the shortest route from (21,11) to (1,11) and from (1,11) to (21,11), and the longest shortest route between any two points. Extra Credit # Is there any cell in the country that can not be reached from HQ? # Which cells will it take longest to send reinforcements to from HQ? Related tasks: # [[Dijkstra's algorithm]] # [[Floyd-Warshall algorithm]]
package main import ( "fmt" "strings" ) var gmooh = strings.Split( `.........00000......... ......00003130000...... ....000321322221000.... ...00231222432132200... ..0041433223233211100.. ..0232231612142618530.. .003152122326114121200. .031252235216111132210. .022211246332311115210. 00113232262121317213200 03152118212313211411110 03231234121132221411410 03513213411311414112320 00427534125412213211400 .013322444412122123210. .015132331312411123120. .003333612214233913300. ..0219126511415312570.. ..0021321524341325100.. ...00211415413523200... ....000122111322000.... ......00001120000...... .........00000.........`, "\n") var width, height = len(gmooh[0]), len(gmooh) type pyx [2]int // {y, x} var d = []pyx{{-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1}} type route [3]int // {cost, fromy, fromx} var zeroRoute = route{0, 0, 0} var routes [][]route // route for each gmooh[][] func (p pyx) destruct() (int, int) { return p[0], p[1] } func (r route) destruct() (int, int, int) { return r[0], r[1], r[2] } func search(y, x int) { // Simple breadth-first search, populates routes. // This isn't strictly Dijkstra because graph edges are not weighted. cost := 0 routes = make([][]route, height) for i := 0; i < width; i++ { routes[i] = make([]route, width) } routes[y][x] = route{0, y, x} // zero-cost, the starting point var next []route for { n := int(gmooh[y][x] - '0') for di := 0; di < len(d); di++ { dx, dy := d[di].destruct() rx, ry := x+n*dx, y+n*dy if rx >= 0 && rx < width && ry >= 0 && ry < height && gmooh[rx][ry] >= '0' { ryx := routes[ry][rx] if ryx == zeroRoute || ryx[0] > cost+1 { routes[ry][rx] = route{cost + 1, y, x} if gmooh[ry][rx] > '0' { next = append(next, route{cost + 1, ry, rx}) // If the graph was weighted, at this point // that would get shuffled up into place. } } } } if len(next) == 0 { break } cost, y, x = next[0].destruct() next = next[1:] } } func getRoute(y, x int) []pyx { cost := 0 res := []pyx{{y, x}} for { cost, y, x = routes[y][x].destruct() if cost == 0 { break } res = append(res, pyx{0, 0}) copy(res[1:], res[0:]) res[0] = pyx{y, x} } return res } func showShortest() { shortest := 9999 var res []pyx for x := 0; x < width; x++ { for y := 0; y < height; y++ { if gmooh[y][x] == '0' { ryx := routes[y][x] if ryx != zeroRoute { cost := ryx[0] if cost <= shortest { if cost < shortest { res = res[:0] shortest = cost } res = append(res, pyx{y, x}) } } } } } areis, s := "is", "" if len(res) > 1 { areis = "are" s = "s" } fmt.Printf("There %s %d shortest route%s of %d days to safety:\n", areis, len(res), s, shortest) for _, r := range res { fmt.Println(getRoute(r[0], r[1])) } } func showUnreachable() { var res []pyx for x := 0; x < width; x++ { for y := 0; y < height; y++ { if gmooh[y][x] >= '0' && routes[y][x] == zeroRoute { res = append(res, pyx{y, x}) } } } fmt.Println("\nThe following cells are unreachable:") fmt.Println(res) } func showLongest() { longest := 0 var res []pyx for x := 0; x < width; x++ { for y := 0; y < height; y++ { if gmooh[y][x] >= '0' { ryx := routes[y][x] if ryx != zeroRoute { rl := ryx[0] if rl >= longest { if rl > longest { res = res[:0] longest = rl } res = append(res, pyx{y, x}) } } } } } fmt.Printf("\nThere are %d cells that take %d days to send reinforcements to:\n", len(res), longest) for _, r := range res { fmt.Println(getRoute(r[0], r[1])) } } func main() { search(11, 11) showShortest() search(21, 11) fmt.Println("\nThe shortest route from {21,11} to {1,11}:") fmt.Println(getRoute(1, 11)) search(1, 11) fmt.Println("\nThe shortest route from {1,11} to {21,11}:") fmt.Println(getRoute(21, 11)) search(11, 11) showUnreachable() showLongest() }
ISBN13 check digit
Go
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
package main import ( "fmt" "strings" "unicode/utf8" ) func checkIsbn13(isbn string) bool { // remove any hyphens or spaces isbn = strings.ReplaceAll(strings.ReplaceAll(isbn, "-", ""), " ", "") // check length == 13 le := utf8.RuneCountInString(isbn) if le != 13 { return false } // check only contains digits and calculate weighted sum sum := int32(0) for i, c := range isbn { if c < '0' || c > '9' { return false } if i%2 == 0 { sum += c - '0' } else { sum += 3 * (c - '0') } } return sum%10 == 0 } func main() { isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"} for _, isbn := range isbns { res := "bad" if checkIsbn13(isbn) { res = "good" } fmt.Printf("%s: %s\n", isbn, res) } }
I before E except after C
Go
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei int for s.Scan() { line := s.Text() if strings.Contains(line, "cie") { cie++ } if strings.Contains(line, "cei") { cei++ } if rie.MatchString(line) { ie++ } if rei.MatchString(line) { ei++ } } err = s.Err() if err != nil { log.Fatalln(err) } if check(ie, ei, "I before E when not preceded by C") && check(cei, cie, "E before I when preceded by C") { fmt.Println("Both plausable.") fmt.Println(`"I before E, except after C" is plausable.`) } else { fmt.Println("One or both implausable.") fmt.Println(`"I before E, except after C" is implausable.`) } } // check checks if a statement is plausible. Something is plausible if a is more // than two times b. func check(a, b int, s string) bool { switch { case a > b*2: fmt.Printf("%q is plausible (%d vs %d).\n", s, a, b) return true case a >= b: fmt.Printf("%q is implausible (%d vs %d).\n", s, a, b) default: fmt.Printf("%q is implausible and contra-indicated (%d vs %d).\n", s, a, b) } return false }
Identity matrix
Go
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func eye(n int) *mat.Dense { m := mat.NewDense(n, n, nil) for i := 0; i < n; i++ { m.Set(i, i, 1) } return m } func main() { fmt.Println(mat.Formatted(eye(3))) }
Idiomatically determine all the characters that can be used for symbols
Go
Idiomatically determine all the characters that can be used for ''symbols''. The word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''. The method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. You may want to mention what hardware architecture is being used, and if applicable, the operating system. Note that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned). ;See also * Idiomatically determine all the lowercase and uppercase letters.
package main import ( "fmt" "go/ast" "go/parser" "strings" "unicode" ) func isValidIdentifier(identifier string) bool { node, err := parser.ParseExpr(identifier) if err != nil { return false } ident, ok := node.(*ast.Ident) return ok && ident.Name == identifier } type runeRanges struct { ranges []string hasStart bool start rune end rune } func (r *runeRanges) add(cp rune) { if !r.hasStart { r.hasStart = true r.start = cp r.end = cp return } if cp == r.end+1 { r.end = cp return } r.writeTo(&r.ranges) r.start = cp r.end = cp } func (r *runeRanges) writeTo(ranges *[]string) { if r.hasStart { if r.start == r.end { *ranges = append(*ranges, fmt.Sprintf("%U", r.end)) } else { *ranges = append(*ranges, fmt.Sprintf("%U-%U", r.start, r.end)) } } } func (r *runeRanges) String() string { ranges := r.ranges r.writeTo(&ranges) return strings.Join(ranges, ", ") } func main() { var validFirst runeRanges var validFollow runeRanges var validOnlyFollow runeRanges for r := rune(0); r <= unicode.MaxRune; r++ { first := isValidIdentifier(string([]rune{r})) follow := isValidIdentifier(string([]rune{'_', r})) if first { validFirst.add(r) } if follow { validFollow.add(r) } if follow && !first { validOnlyFollow.add(r) } } _, _ = fmt.Println("Valid first:", validFirst.String()) _, _ = fmt.Println("Valid follow:", validFollow.String()) _, _ = fmt.Println("Only follow:", validOnlyFollow.String()) }
Idiomatically determine all the lowercase and uppercase letters
Go
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all: ::::::* lowercase letters ::::::* uppercase letters that can be used (allowed) by the computer program, where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. You may want to mention what hardware architecture is being used, and if applicable, the operating system. ;See also * Idiomatically determine all the characters that can be used for symbols.
package main import ( "fmt" "unicode" ) const ( lcASCII = "abcdefghijklmnopqrstuvwxyz" ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) func main() { fmt.Println("ASCII lower case:") fmt.Println(lcASCII) for l := 'a'; l <= 'z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nASCII upper case:") fmt.Println(ucASCII) for l := 'A'; l <= 'Z'; l++ { fmt.Print(string(l)) } fmt.Println() fmt.Println("\nUnicode version " + unicode.Version) showRange16("Lower case 16-bit code points:", unicode.Lower.R16) showRange32("Lower case 32-bit code points:", unicode.Lower.R32) showRange16("Upper case 16-bit code points:", unicode.Upper.R16) showRange32("Upper case 32-bit code points:", unicode.Upper.R32) } func showRange16(hdr string, rList []unicode.Range16) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } } func showRange32(hdr string, rList []unicode.Range32) { fmt.Print("\n", hdr, "\n") fmt.Printf("%d ranges:\n", len(rList)) for _, rng := range rList { fmt.Printf("%U: ", rng.Lo) for r := rng.Lo; r <= rng.Hi; r += rng.Stride { fmt.Printf("%c", r) } fmt.Println() } }
Imaginary base numbers
Go from Kotlin
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. ''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]'' Other imaginary bases are possible too but are not as widely discussed and aren't specifically named. '''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. At a minimum, support quater-imaginary (base 2i). For extra kudos, support positive or negative bases 2i through 6i (or higher). As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base. See Wikipedia: Quater-imaginary_base for more details. For reference, here are some some decimal and complex numbers converted to quater-imaginary. Base 10 Base 2i 1 1 2 2 3 3 4 10300 5 10301 6 10302 7 10303 8 10200 9 10201 10 10202 11 10203 12 10100 13 10101 14 10102 15 10103 16 10000 Base 10 Base 2i -1 103 -2 102 -3 101 -4 100 -5 203 -6 202 -7 201 -8 200 -9 303 -10 302 -11 301 -12 300 -13 1030003 -14 1030002 -15 1030001 -16 1030000 Base 10 Base 2i 1i 10.2 2i 10.0 3i 20.2 4i 20.0 5i 30.2 6i 30.0 7i 103000.2 8i 103000.0 9i 103010.2 10i 103010.0 11i 103020.2 12i 103020.0 13i 103030.2 14i 103030.0 15i 102000.2 16i 102000.0 Base 10 Base 2i -1i 0.2 -2i 1030.0 -3i 1030.2 -4i 1020.0 -5i 1020.2 -6i 1010.0 -7i 1010.2 -8i 1000.0 -9i 1000.2 -10i 2030.0 -11i 2030.2 -12i 2020.0 -13i 2020.2 -14i 2010.0 -15i 2010.2 -16i 2000.0
package main import ( "fmt" "math" "strconv" "strings" ) const ( twoI = 2.0i invTwoI = 1.0 / twoI ) type quaterImaginary struct { b2i string } func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func newQuaterImaginary(b2i string) quaterImaginary { b2i = strings.TrimSpace(b2i) _, err := strconv.ParseFloat(b2i, 64) if err != nil { panic("invalid Base 2i number") } return quaterImaginary{b2i} } func toComplex(q quaterImaginary) complex128 { pointPos := strings.Index(q.b2i, ".") var posLen int if pointPos != -1 { posLen = pointPos } else { posLen = len(q.b2i) } sum := 0.0i prod := complex(1.0, 0.0) for j := 0; j < posLen; j++ { k := float64(q.b2i[posLen-1-j] - '0') if k > 0.0 { sum += prod * complex(k, 0.0) } prod *= twoI } if pointPos != -1 { prod = invTwoI for j := posLen + 1; j < len(q.b2i); j++ { k := float64(q.b2i[j] - '0') if k > 0.0 { sum += prod * complex(k, 0.0) } prod *= invTwoI } } return sum } func (q quaterImaginary) String() string { return q.b2i } // only works properly if 'real' and 'imag' are both integral func toQuaterImaginary(c complex128) quaterImaginary { if c == 0i { return quaterImaginary{"0"} } re := int(real(c)) im := int(imag(c)) fi := -1 var sb strings.Builder for re != 0 { rem := re % -4 re /= -4 if rem < 0 { rem += 4 re++ } sb.WriteString(strconv.Itoa(rem)) sb.WriteString("0") } if im != 0 { f := real(complex(0.0, imag(c)) / 2.0i) im = int(math.Ceil(f)) f = -4.0 * (f - float64(im)) index := 1 for im != 0 { rem := im % -4 im /= -4 if rem < 0 { rem += 4 im++ } if index < sb.Len() { bs := []byte(sb.String()) bs[index] = byte(rem + 48) sb.Reset() sb.Write(bs) } else { sb.WriteString("0") sb.WriteString(strconv.Itoa(rem)) } index += 2 } fi = int(f) } s := reverse(sb.String()) if fi != -1 { s = fmt.Sprintf("%s.%d", s, fi) } s = strings.TrimLeft(s, "0") if s[0] == '.' { s = "0" + s } return newQuaterImaginary(s) } func main() { for i := 1; i <= 16; i++ { c1 := complex(float64(i), 0.0) qi := toQuaterImaginary(c1) c2 := toComplex(qi) fmt.Printf("%4.0f -> %8s -> %4.0f ", real(c1), qi, real(c2)) c1 = -c1 qi = toQuaterImaginary(c1) c2 = toComplex(qi) fmt.Printf("%4.0f -> %8s -> %4.0f\n", real(c1), qi, real(c2)) } fmt.Println() for i := 1; i <= 16; i++ { c1 := complex(0.0, float64(i)) qi := toQuaterImaginary(c1) c2 := toComplex(qi) fmt.Printf("%3.0fi -> %8s -> %3.0fi ", imag(c1), qi, imag(c2)) c1 = -c1 qi = toQuaterImaginary(c1) c2 = toComplex(qi) fmt.Printf("%3.0fi -> %8s -> %3.0fi\n", imag(c1), qi, imag(c2)) } }
Include a file
Go
Demonstrate the language's ability to include source code from other files. ;See Also * [[Compiler/Simple file inclusion pre processor]]
// main.go package main import "fmt" func hello() { fmt.Println("Hello from main.go") } func main() { hello() hello2() }
Increasing gaps between consecutive Niven numbers
Go
Note: '''Niven''' numbers are also called '''Harshad''' numbers. :::: They are also called '''multidigital''' numbers. '''Niven''' numbers are positive integers which are evenly divisible by the sum of its digits (expressed in base ten). ''Evenly divisible'' means ''divisible with no remainder''. ;Task: :* find the gap (difference) of a Niven number from the previous Niven number :* if the gap is ''larger'' than the (highest) previous gap, then: :::* show the index (occurrence) of the gap (the 1st gap is '''1''') :::* show the index of the Niven number that starts the gap (1st Niven number is '''1''', 33rd Niven number is '''100''') :::* show the Niven number that starts the gap :::* show all numbers with comma separators where appropriate (optional) :::* I.E.: the gap size of '''60''' starts at the 33,494th Niven number which is Niven number '''297,864''' :* show all increasing gaps up to the ten millionth ('''10,000,000th''') Niven number :* (optional) show all gaps up to whatever limit is feasible/practical/realistic/reasonable/sensible/viable on your computer :* show all output here, on this page ;Related task: :* Harshad or Niven series. ;Also see: :* Journal of Integer Sequences, Vol. 6 (2004), Article 03.2.5, Large and Small Gaps Between Consecutive Niven Numbers. :* (PDF) version of the (above) article by Doyon.
package main import "fmt" type is func() uint64 func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } return msd + d } } func newHarshard() is { i := uint64(0) sum := newSum() return func() uint64 { for i++; i%sum() != 0; i++ { } return i } } 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() { fmt.Println("Gap Index of gap Starting Niven") fmt.Println("=== ============= ==============") h := newHarshard() pg := uint64(0) // previous highest gap pn := h() // previous Niven number for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() { g := n - pn if g > pg { fmt.Printf("%3d %13s %14s\n", g, commatize(i), commatize(pn)) pg = g } pn = n } }
Index finite lists of positive integers
Go
It is known that the set of finite lists of positive integers is countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. ;Task: Implement such a mapping: :* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers. :* write a function ''unrank'' which is the ''rank'' inverse function. Demonstrate your solution by: :* picking a random-length list of random positive integers :* turn it into an integer, and :* get the list back. There are many ways to do this. Feel free to choose any one you like. ;Extra credit: Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
package main import ( "fmt" "math/big" ) func rank(l []uint) (r big.Int) { for _, n := range l { r.Lsh(&r, n+1) r.SetBit(&r, int(n), 1) } return } func unrank(n big.Int) (l []uint) { m := new(big.Int).Set(&n) for a := m.BitLen(); a > 0; { m.SetBit(m, a-1, 0) b := m.BitLen() l = append(l, uint(a-b-1)) a = b } return } func main() { var b big.Int for i := 0; i <= 10; i++ { b.SetInt64(int64(i)) u := unrank(b) r := rank(u) fmt.Println(i, u, &r) } b.SetString("12345678901234567890", 10) u := unrank(b) r := rank(u) fmt.Printf("\n%v\n%d\n%d\n", &b, u, &r) }
Integer overflow
Go
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
package main import "fmt" func main() { // Go's builtin integer types are: // int, int8, int16, int32, int64 // uint, uint8, uint16, uint32, uint64 // byte, rune, uintptr // // int is either 32 or 64 bit, depending on the system // uintptr is large enough to hold the bit pattern of any pointer // byte is 8 bits like int8 // rune is 32 bits like int32 // // Overflow and underflow is silent. The math package defines a number // of constants that can be helpfull, e.g.: // math.MaxInt64 = 1<<63 - 1 // math.MinInt64 = -1 << 63 // math.MaxUint64 = 1<<64 - 1 // // The math/big package implements multi-precision // arithmetic (big numbers). // // In all cases assignment from one type to another requires // an explicit cast, even if the types are otherwise identical // (e.g. rune and int32 or int and either int32 or int64). // Casts silently truncate if required. // // Invalid: // var i int = int32(0) // var r rune = int32(0) // var b byte = int8(0) // // Valid: var i64 int64 = 42 var i32 int32 = int32(i64) var i16 int16 = int16(i64) var i8 int8 = int8(i16) var i int = int(i8) var r rune = rune(i) var b byte = byte(r) var u64 uint64 = uint64(b) var u32 uint32 //const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit const c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped i64 = c //i32 = c // Compiler error //i32 = -(-2147483647 - 1) // Compiler error i32 = -2147483647 i32 = -(-i32 - 1) fmt.Println("32 bit signed integers") fmt.Printf(" -(-2147483647 - 1) = %d, got %d\n", i64, i32) i64 = 2000000000 + 2000000000 //i32 = 2000000000 + 2000000000 // Compiler error i32 = 2000000000 i32 = i32 + i32 fmt.Printf(" 2000000000 + 2000000000 = %d, got %d\n", i64, i32) i64 = -2147483647 - 2147483647 i32 = 2147483647 i32 = -i32 - i32 fmt.Printf(" -2147483647 - 2147483647 = %d, got %d\n", i64, i32) i64 = 46341 * 46341 i32 = 46341 i32 = i32 * i32 fmt.Printf(" 46341 * 46341 = %d, got %d\n", i64, i32) i64 = (-2147483647 - 1) / -1 i32 = -2147483647 i32 = (i32 - 1) / -1 fmt.Printf(" (-2147483647-1) / -1 = %d, got %d\n", i64, i32) fmt.Println("\n64 bit signed integers") i64 = -9223372036854775807 fmt.Printf(" -(%d - 1): %d\n", i64, -(i64 - 1)) i64 = 5000000000000000000 fmt.Printf(" %d + %d: %d\n", i64, i64, i64+i64) i64 = 9223372036854775807 fmt.Printf(" -%d - %d: %d\n", i64, i64, -i64-i64) i64 = 3037000500 fmt.Printf(" %d * %d: %d\n", i64, i64, i64*i64) i64 = -9223372036854775807 fmt.Printf(" (%d - 1) / -1: %d\n", i64, (i64-1)/-1) fmt.Println("\n32 bit unsigned integers:") //u32 = -4294967295 // Compiler error u32 = 4294967295 fmt.Printf(" -%d: %d\n", u32, -u32) u32 = 3000000000 fmt.Printf(" %d + %d: %d\n", u32, u32, u32+u32) a := uint32(2147483647) u32 = 4294967295 fmt.Printf(" %d - %d: %d\n", a, u32, a-u32) u32 = 65537 fmt.Printf(" %d * %d: %d\n", u32, u32, u32*u32) fmt.Println("\n64 bit unsigned integers:") u64 = 18446744073709551615 fmt.Printf(" -%d: %d\n", u64, -u64) u64 = 10000000000000000000 fmt.Printf(" %d + %d: %d\n", u64, u64, u64+u64) aa := uint64(9223372036854775807) u64 = 18446744073709551615 fmt.Printf(" %d - %d: %d\n", aa, u64, aa-u64) u64 = 4294967296 fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64) }
Integer sequence
Go
Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library. If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
package main import ( "big" "fmt" ) func main() { one := big.NewInt(1) for i := big.NewInt(1);; i.Add(i, one) { fmt.Println(i) } }
Intersecting number wheels
Go
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.Atoi(s) w.next = (w.next + 1) % len(w.values) wheels[start] = w if err == nil { fmt.Printf("%d ", v) count++ if count == maxCount { fmt.Println("...\n") return } } else { for { w2 := wheels[s] ss := s s = w2.values[w2.next] w2.next = (w2.next + 1) % len(w2.values) wheels[ss] = w2 v, err = strconv.Atoi(s) if err == nil { fmt.Printf("%d ", v) count++ if count == maxCount { fmt.Println("...\n") return } break } } } } } func printWheels(wheels wheelMap) { var names []string for name := range wheels { names = append(names, name) } sort.Strings(names) fmt.Println("Intersecting Number Wheel group:") for _, name := range names { fmt.Printf(" %s: %v\n", name, wheels[name].values) } fmt.Print(" Generates:\n ") } func main() { wheelMaps := []wheelMap{ { "A": {0, []string{"1", "2", "3"}}, }, { "A": {0, []string{"1", "B", "2"}}, "B": {0, []string{"3", "4"}}, }, { "A": {0, []string{"1", "D", "D"}}, "D": {0, []string{"6", "7", "8"}}, }, { "A": {0, []string{"1", "B", "C"}}, "B": {0, []string{"3", "4"}}, "C": {0, []string{"5", "B"}}, }, } for _, wheels := range wheelMaps { printWheels(wheels) generate(wheels, "A", 20) } }
Inverted syntax
Go
'''Inverted syntax with conditional expressions''' In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumbrella=true IF raining=true '''Inverted syntax with assignment''' In traditional syntax, assignments are usually expressed with the variable appearing before the expression: a = 6 In inverted syntax, the expression appears before the variable: 6 = a '''Task''' The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
package main import "fmt" type ibool bool const itrue ibool = true func (ib ibool) iif(cond bool) bool { if cond { return bool(ib) } return bool(!ib) } func main() { var needUmbrella bool raining := true // normal syntax if raining { needUmbrella = true } fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella) // inverted syntax raining = false needUmbrella = itrue.iif(raining) fmt.Printf("Is it raining? %t. Do I need an umbrella? %t\n", raining, needUmbrella) }
Isqrt (integer square root) of X
Go
Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a real non-negative number. Often '''X''' is actually a non-negative integer. For the purposes of this task, '''X''' can be an integer or a real number, but if it simplifies things in your computer programming language, assume it's an integer. One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or primes) up to the X of that integer, either to find the factors of that integer, or to determine primality. An alternative method for finding the '''Isqrt''' of a number is to calculate: floor( sqrt(X) ) ::* where '''sqrt''' is the square root function for non-negative real numbers, and ::* where '''floor''' is the floor function for real numbers. If the hardware supports the computation of (real) square roots, the above method might be a faster method for small numbers that don't have very many significant (decimal) digits. However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support. ;Pseudo-code using quadratic residue: For this task, the integer square root of a non-negative number will be computed using a version of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are used, only integer arithmetic. Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions. The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support. Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers): q <-- 1 /*initialize Q to unity. */ /*find a power of 4 that's greater than X.*/ perform while q <= x /*perform while Q <= X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ /*Q is now greater than X.*/ z <-- x /*set Z to the value of X.*/ r <-- 0 /*initialize R to zero. */ perform while q > 1 /*perform while Q > unity. */ q <-- q / 4 /*integer divide by four. */ t <-- z - r - q /*compute value of T. */ r <-- r / 2 /*integer divide by two. */ if t >= 0 then do z <-- t /*set Z to value of T. */ r <-- r + q /*compute new value of R. */ end end /*perform*/ /*R is now the Isqrt(X). */ /* Sidenote: Also, Z is now the remainder after square root (i.e. */ /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */ Another version for the (above) 1st '''perform''' is: perform until q > X /*perform until Q > X. */ q <-- q * 4 /*multiply Q by four. */ end /*perform*/ Integer square roots of some values: Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9 Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10 Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10 Isqrt( 3) is 1 Isqrt(63) is 7 Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10 Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11 Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11 Isqrt( 7) is 2 Isqrt(67) is 8 Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11 Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12 Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12 ;Task: Compute and show all output here (on this page) for: ::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format. ::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format. ::* use commas in the displaying of larger numbers. You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code. If your computer programming language only supports smaller integers, show what you can. ;Related tasks: :* sequence of non-squares :* integer roots :* square root by hand
package main import ( "fmt" "log" "math/big" ) var zero = big.NewInt(0) var one = big.NewInt(1) func isqrt(x *big.Int) *big.Int { if x.Cmp(zero) < 0 { log.Fatal("Argument cannot be negative.") } q := big.NewInt(1) for q.Cmp(x) <= 0 { q.Lsh(q, 2) } z := new(big.Int).Set(x) r := big.NewInt(0) for q.Cmp(one) > 0 { q.Rsh(q, 2) t := new(big.Int) t.Add(t, z) t.Sub(t, r) t.Sub(t, q) r.Rsh(r, 1) if t.Cmp(zero) >= 0 { z.Set(t) r.Add(r, q) } } return r } func commatize(s string) string { le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { fmt.Println("The integer square roots of integers from 0 to 65 are:") for i := int64(0); i <= 65; i++ { fmt.Printf("%d ", isqrt(big.NewInt(i))) } fmt.Println() fmt.Println("\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\n") fmt.Println("power 7 ^ power integer square root") fmt.Println("----- --------------------------------------------------------------------------------- -----------------------------------------") pow7 := big.NewInt(7) bi49 := big.NewInt(49) for i := 1; i <= 73; i += 2 { fmt.Printf("%2d %84s %41s\n", i, commatize(pow7.String()), commatize(isqrt(pow7).String())) pow7.Mul(pow7, bi49) } }
Iterated digits squaring
Go
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
package main import ( "fmt" ) func main() { var d, n, o, u, u89 int64 for n = 1; n < 100000000; n++ { o = n for { u = 0 for { d = o%10 o = (o - d) / 10 u += d*d if o == 0 { break } } if u == 89 || u == 1 { if u == 89 { u89++ } break } o = u } } fmt.Println(u89) }
JSON
Go
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
package main import "encoding/json" import "fmt" func main() { var data interface{} err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data) if err == nil { fmt.Println(data) } else { fmt.Println(err) } sample := map[string]interface{}{ "blue": []interface{}{1, 2}, "ocean": "water", } json_string, err := json.Marshal(sample) if err == nil { fmt.Println(string(json_string)) } else { fmt.Println(err) } }
Jacobi symbol
Go
The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) * (a | p) 1 if a is a square (mod p) * (a | p) -1 if a is not a square (mod p) * (a | p) 0 if a 0 If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n). ;Task: Calculate the Jacobi symbol (a | n). ;Reference: * Wikipedia article on Jacobi symbol.
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { result = -result } } a, n = n, a if a%4 == 3 && n%4 == 3 { result = -result } a %= n } if n == 1 { return result } return 0 } func main() { fmt.Println("Using hand-coded version:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { fmt.Printf(" % d", jacobi(a, n)) } fmt.Println() } ba, bn := new(big.Int), new(big.Int) fmt.Println("\nUsing standard library function:") fmt.Println("n/a 0 1 2 3 4 5 6 7 8 9") fmt.Println("---------------------------------") for n := uint64(1); n <= 17; n += 2 { fmt.Printf("%2d ", n) for a := uint64(0); a <= 9; a++ { ba.SetUint64(a) bn.SetUint64(n) fmt.Printf(" % d", big.Jacobi(ba, bn)) } fmt.Println() } }
Jacobsthal numbers
Go
'''Jacobsthal numbers''' are an integer sequence related to Fibonacci numbers. Similar to Fibonacci, where each term is the sum of the previous two terms, each term is the sum of the previous, plus twice the one before that. Traditionally the sequence starts with the given terms 0, 1. J0 = 0 J1 = 1 Jn = Jn-1 + 2 x Jn-2 Terms may be calculated directly using one of several possible formulas: Jn = ( 2n - (-1)n ) / 3 '''Jacobsthal-Lucas numbers''' are very similar. They have the same recurrence relationship, the only difference is an initial starting value '''J0 = 2''' rather than '''J0 = 0'''. Terms may be calculated directly using one of several possible formulas: JLn = 2n + (-1)n '''Jacobsthal oblong numbers''' is the sequence obtained from multiplying each '''Jacobsthal number''' '''Jn''' by its direct successor '''Jn+1'''. '''Jacobsthal primes''' are '''Jacobsthal numbers''' that are prime. ;Task * Find and display the first 30 '''Jacobsthal numbers''' * Find and display the first 30 '''Jacobsthal-Lucas numbers''' * Find and display the first 20 '''Jacobsthal oblong numbers''' * Find and display at least the first 10 '''Jacobsthal primes''' ;See also ;* Wikipedia: Jacobsthal number ;* Numbers Aplenty - Jacobsthal number ;* OEIS:A001045 - Jacobsthal sequence (or Jacobsthal numbers) ;* OEIS:A014551 - Jacobsthal-Lucas numbers. ;* OEIS:A084175 - Jacobsthal oblong numbers ;* OEIS:A049883 - Primes in the Jacobsthal sequence ;* Related task: Fibonacci sequence ;* Related task: Leonardo numbers
package main import ( "fmt" "math/big" ) func jacobsthal(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) s := big.NewInt(1) if n%2 != 0 { s.Neg(s) } t.Sub(t, s) return t.Div(t, big.NewInt(3)) } func jacobsthalLucas(n uint) *big.Int { t := big.NewInt(1) t.Lsh(t, n) a := big.NewInt(1) if n%2 != 0 { a.Neg(a) } return t.Add(t, a) } func main() { jac := make([]*big.Int, 30) fmt.Println("First 30 Jacobsthal numbers:") for i := uint(0); i < 30; i++ { jac[i] = jacobsthal(i) fmt.Printf("%9d ", jac[i]) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 Jacobsthal-Lucas numbers:") for i := uint(0); i < 30; i++ { fmt.Printf("%9d ", jacobsthalLucas(i)) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal oblong numbers:") for i := uint(0); i < 20; i++ { t := big.NewInt(0) fmt.Printf("%11d ", t.Mul(jac[i], jac[i+1])) if (i+1)%5 == 0 { fmt.Println() } } fmt.Println("\nFirst 20 Jacobsthal primes:") for n, count := uint(0), 0; count < 20; n++ { j := jacobsthal(n) if j.ProbablyPrime(10) { fmt.Println(j) count++ } } }
Jaro similarity
Go
The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match. ;;Definition The Jaro similarity d_j of two given strings s_1 and s_2 is : d_j = \left\{ \begin{array}{l l} 0 & \text{if }m = 0\\ \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right. Where: * m is the number of ''matching characters''; * t is half the number of ''transpositions''. Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters. Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one. ;;Example Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find: * m = 4 * |s_1| = 6 * |s_2| = 5 * t = 0 We find a Jaro score of: : d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822 ;Task Implement the Jaro algorithm and show the similarity scores for each of the following pairs: * ("MARTHA", "MARHTA") * ("DIXON", "DICKSONX") * ("JELLYFISH", "SMELLYFISH") ; See also * Jaro-Winkler distance on Wikipedia.
package main import "fmt" func jaro(str1, str2 string) float64 { if len(str1) == 0 && len(str2) == 0 { return 1 } if len(str1) == 0 || len(str2) == 0 { return 0 } match_distance := len(str1) if len(str2) > match_distance { match_distance = len(str2) } match_distance = match_distance/2 - 1 str1_matches := make([]bool, len(str1)) str2_matches := make([]bool, len(str2)) matches := 0. transpositions := 0. for i := range str1 { start := i - match_distance if start < 0 { start = 0 } end := i + match_distance + 1 if end > len(str2) { end = len(str2) } for k := start; k < end; k++ { if str2_matches[k] { continue } if str1[i] != str2[k] { continue } str1_matches[i] = true str2_matches[k] = true matches++ break } } if matches == 0 { return 0 } k := 0 for i := range str1 { if !str1_matches[i] { continue } for !str2_matches[k] { k++ } if str1[i] != str2[k] { transpositions++ } k++ } transpositions /= 2 return (matches/float64(len(str1)) + matches/float64(len(str2)) + (matches-transpositions)/matches) / 3 } func main() { fmt.Printf("%f\n", jaro("MARTHA", "MARHTA")) fmt.Printf("%f\n", jaro("DIXON", "DICKSONX")) fmt.Printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")) }
Jewels and stones
Go
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
package main import ( "fmt" "strings" ) func js(stones, jewels string) (n int) { for _, b := range []byte(stones) { if strings.IndexByte(jewels, b) >= 0 { n++ } } return } func main() { fmt.Println(js("aAAbbbb", "aA")) }
Julia set
Go
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
package main import ( "image" "image/color" "image/png" "log" "os" "sync" ) func main() { const ( width, height = 800.0, 600.0 maxIter = 255 cX, cY = -0.7, 0.27015 fileName = "julia.png" ) img := image.NewNRGBA(image.Rect(0, 0, width, height)) var wg sync.WaitGroup wg.Add(width) for x := 0; x < width; x++ { thisx := float64(x) go func() { var tmp, zx, zy float64 var i uint8 for y := 0.0; y < height; y++ { zx = 1.5 * (thisx - width/2) / (0.5 * width) zy = (y - height/2) / (0.5 * height) i = maxIter for zx*zx+zy*zy < 4.0 && i > 0 { tmp = zx*zx - zy*zy + cX zy = 2.0*zx*zy + cY zx = tmp i-- } img.Set(int(thisx), int(y), color.RGBA{i, i, i << 3, 255}) } wg.Done() }() } wg.Wait() imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } }
Jump anywhere
Go
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
package main import "fmt" func main() { outer: for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if i + j == 4 { continue outer } if i + j == 5 { break outer } fmt.Println(i + j) } } k := 3 if k == 3 { goto later } fmt.Println(k) // never executed later: k++ fmt.Println(k) }
K-d tree
Go
{{wikipedia|K-d tree}} A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead. '''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets: # The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)]. # 1000 3-d points uniformly distributed in a 3-d cube. For the Wikipedia example, find the nearest neighbor to point (9, 2) For the random data, pick a random location and find the nearest neighbor. In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed. Output should show the point searched for, the point found, the distance to the point, and the number of nodes visited. There are variant algorithms for constructing the tree. You can use a simple median strategy or implement something more efficient. Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. You do not have to implement these. The requirement for this task is specifically the nearest single neighbor. Also there are algorithms for inserting, deleting, and balancing k-d trees. These are also not required for the task.
// Implmentation following pseudocode from "An intoductory tutorial on kd-trees" // by Andrew W. Moore, Carnegie Mellon University, PDF accessed from // http://www.autonlab.org/autonweb/14665 package main import ( "fmt" "math" "math/rand" "sort" "time" ) // point is a k-dimensional point. type point []float64 // sqd returns the square of the euclidean distance. func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } // kdNode following field names in the paper. // rangeElt would be whatever data is associated with the point. we don't // bother with it for this example. type kdNode struct { domElt point split int left, right *kdNode } type kdTree struct { n *kdNode bounds hyperRect } type hyperRect struct { min, max point } // Go slices are reference objects. The data must be copied if you want // to modify one without modifying the original. func (hr hyperRect) copy() hyperRect { return hyperRect{append(point{}, hr.min...), append(point{}, hr.max...)} } // newKd constructs a kdTree from a list of points, also associating the // bounds of the tree. The bounds could be computed of course, but in this // example we know them already. The algorithm is table 6.3 in the paper. func newKd(pts []point, bounds hyperRect) kdTree { var nk2 func([]point, int) *kdNode nk2 = func(exset []point, split int) *kdNode { if len(exset) == 0 { return nil } // pivot choosing procedure. we find median, then find largest // index of points with median value. this satisfies the // inequalities of steps 6 and 7 in the algorithm. sort.Sort(part{exset, split}) m := len(exset) / 2 d := exset[m] for m+1 < len(exset) && exset[m+1][split] == d[split] { m++ } // next split s2 := split + 1 if s2 == len(d) { s2 = 0 } return &kdNode{d, split, nk2(exset[:m], s2), nk2(exset[m+1:], s2)} } return kdTree{nk2(pts, 0), bounds} } // a container type used for sorting. it holds the points to sort and // the dimension to use for the sort key. type part struct { pts []point dPart int } // satisfy sort.Interface func (p part) Len() int { return len(p.pts) } func (p part) Less(i, j int) bool { return p.pts[i][p.dPart] < p.pts[j][p.dPart] } func (p part) Swap(i, j int) { p.pts[i], p.pts[j] = p.pts[j], p.pts[i] } // nearest. find nearest neighbor. return values are: // nearest neighbor--the point within the tree that is nearest p. // square of the distance to that point. // a count of the nodes visited in the search. func (t kdTree) nearest(p point) (best point, bestSqd float64, nv int) { return nn(t.n, p, t.bounds, math.Inf(1)) } // algorithm is table 6.4 from the paper, with the addition of counting // the number nodes visited. func nn(kd *kdNode, target point, hr hyperRect, maxDistSqd float64) (nearest point, distSqd float64, nodesVisited int) { if kd == nil { return nil, math.Inf(1), 0 } nodesVisited++ s := kd.split pivot := kd.domElt leftHr := hr.copy() rightHr := hr.copy() leftHr.max[s] = pivot[s] rightHr.min[s] = pivot[s] targetInLeft := target[s] <= pivot[s] var nearerKd, furtherKd *kdNode var nearerHr, furtherHr hyperRect if targetInLeft { nearerKd, nearerHr = kd.left, leftHr furtherKd, furtherHr = kd.right, rightHr } else { nearerKd, nearerHr = kd.right, rightHr furtherKd, furtherHr = kd.left, leftHr } var nv int nearest, distSqd, nv = nn(nearerKd, target, nearerHr, maxDistSqd) nodesVisited += nv if distSqd < maxDistSqd { maxDistSqd = distSqd } d := pivot[s] - target[s] d *= d if d > maxDistSqd { return } if d = pivot.sqd(target); d < distSqd { nearest = pivot distSqd = d maxDistSqd = distSqd } tempNearest, tempSqd, nv := nn(furtherKd, target, furtherHr, maxDistSqd) nodesVisited += nv if tempSqd < distSqd { nearest = tempNearest distSqd = tempSqd } return } func main() { rand.Seed(time.Now().Unix()) kd := newKd([]point{{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}}, hyperRect{point{0, 0}, point{10, 10}}) showNearest("WP example data", kd, point{9, 2}) kd = newKd(randomPts(3, 1000), hyperRect{point{0, 0, 0}, point{1, 1, 1}}) showNearest("1000 random 3d points", kd, randomPt(3)) } func randomPt(dim int) point { p := make(point, dim) for d := range p { p[d] = rand.Float64() } return p } func randomPts(dim, n int) []point { p := make([]point, n) for i := range p { p[i] = randomPt(dim) } return p } func showNearest(heading string, kd kdTree, p point) { fmt.Println() fmt.Println(heading) fmt.Println("point: ", p) nn, ssq, nv := kd.nearest(p) fmt.Println("nearest neighbor:", nn) fmt.Println("distance: ", math.Sqrt(ssq)) fmt.Println("nodes visited: ", nv) }
Kaprekar numbers
Go
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } // extra credit max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) // extra extra credit const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) // optional extra extra credit } }
Kernighans large earthquake problem
Go
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { f, err := os.Open("data.txt") if err != nil { fmt.Println("Unable to open the file") return } defer f.Close() fmt.Println("Those earthquakes with a magnitude > 6.0 are:\n") input := bufio.NewScanner(f) for input.Scan() { line := input.Text() fields := strings.Fields(line) mag, err := strconv.ParseFloat(fields[2], 64) if err != nil { fmt.Println("Unable to parse magnitude of an earthquake") return } if mag > 6.0 { fmt.Println(line) } } }
Knight's tour
Go
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
package main import ( "fmt" "math/rand" "time" ) // input, 0-based start position const startRow = 0 const startCol = 0 func main() { rand.Seed(time.Now().Unix()) for !knightTour() { } } var moves = []struct{ dr, dc int }{ {2, 1}, {2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {-2, 1}, {-2, -1}, } // Attempt knight tour starting at startRow, startCol using Warnsdorff's rule // and random tie breaking. If a tour is found, print it and return true. // Otherwise no backtracking, just return false. func knightTour() bool { // 8x8 board. squares hold 1-based visit order. 0 means unvisited. board := make([][]int, 8) for i := range board { board[i] = make([]int, 8) } r := startRow c := startCol board[r][c] = 1 // first move for move := 2; move <= 64; move++ { minNext := 8 var mr, mc, nm int candidateMoves: for _, cm := range moves { cr := r + cm.dr if cr < 0 || cr >= 8 { // off board continue } cc := c + cm.dc if cc < 0 || cc >= 8 { // off board continue } if board[cr][cc] > 0 { // already visited continue } // cr, cc candidate legal move. p := 0 // count possible next moves. for _, m2 := range moves { r2 := cr + m2.dr if r2 < 0 || r2 >= 8 { continue } c2 := cc + m2.dc if c2 < 0 || c2 >= 8 { continue } if board[r2][c2] > 0 { continue } p++ if p > minNext { // bail out as soon as it's eliminated continue candidateMoves } } if p < minNext { // it's better. keep it. minNext = p // new min possible next moves nm = 1 // number of candidates with this p mr = cr // best candidate move mc = cc continue } // it ties for best so far. // keep it with probability 1/(number of tying moves) nm++ // number of tying moves if rand.Intn(nm) == 0 { // one chance to keep it mr = cr mc = cc } } if nm == 0 { // no legal move return false } // make selected move r = mr c = mc board[r][c] = move } // tour complete. print board. for _, r := range board { for _, m := range r { fmt.Printf("%3d", m) } fmt.Println() } return true }
Knuth's algorithm S
Go
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). ;The algorithm: :* Select the first n items as the sample as they become available; :* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. :* Repeat 2nd step for any subsequent items. ;The Task: :* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. :* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. :* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: :::# Use the s_of_n_creator with n == 3 to generate an s_of_n. :::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. Note: A class taking n and generating a callable instance/function might also be used. ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 ;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]]
package main import ( "fmt" "math/rand" "time" ) func sOfNCreator(n int) func(byte) []byte { s := make([]byte, 0, n) m := n return func(item byte) []byte { if len(s) < n { s = append(s, item) } else { m++ if rand.Intn(m) < n { s[rand.Intn(n)] = item } } return s } } func main() { rand.Seed(time.Now().UnixNano()) var freq [10]int for r := 0; r < 1e5; r++ { sOfN := sOfNCreator(3) for d := byte('0'); d < '9'; d++ { sOfN(d) } for _, d := range sOfN('9') { freq[d-'0']++ } } fmt.Println(freq) }
Koch curve
Go from Ring
Draw a Koch curve. See details: Koch curve
package main import ( "github.com/fogleman/gg" "math" ) var dc = gg.NewContext(512, 512) func koch(x1, y1, x2, y2 float64, iter int) { angle := math.Pi / 3 // 60 degrees x3 := (x1*2 + x2) / 3 y3 := (y1*2 + y2) / 3 x4 := (x1 + x2*2) / 3 y4 := (y1 + y2*2) / 3 x5 := x3 + (x4-x3)*math.Cos(angle) + (y4-y3)*math.Sin(angle) y5 := y3 - (x4-x3)*math.Sin(angle) + (y4-y3)*math.Cos(angle) if iter > 0 { iter-- koch(x1, y1, x3, y3, iter) koch(x3, y3, x5, y5, iter) koch(x5, y5, x4, y4, iter) koch(x4, y4, x2, y2, iter) } else { dc.LineTo(x1, y1) dc.LineTo(x3, y3) dc.LineTo(x5, y5) dc.LineTo(x4, y4) dc.LineTo(x2, y2) } } func main() { dc.SetRGB(1, 1, 1) // White background dc.Clear() koch(100, 100, 400, 400, 4) dc.SetRGB(0, 0, 1) // Blue curve dc.SetLineWidth(2) dc.Stroke() dc.SavePNG("koch.png") }
Kolakoski sequence
Go from Kotlin
The natural numbers, (excluding zero); with the property that: : ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''. ;Example: This is ''not'' a Kolakoski sequence: 1,1,2,2,2,1,2,2,1,2,... Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this: : Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ... The above gives the RLE of: 2, 3, 1, 2, 1, ... The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''. ;Creating a Kolakoski sequence: Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,.... # We start the sequence s with the first item from the cycle c: 1 # An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s. We started s with 1 and therefore s[k] states that it should appear only the 1 time. Increment k Get the next item from c and append it to the end of sequence s. s will then become: 1, 2 k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2 Increment k Append the next item from the cycle to the list: 1, 2,2, 1 k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1 increment k ... '''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case. ;Task: # Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle. # Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence. # Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE). # Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 20 members of the sequence generated from (2, 1) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2) # Check the sequence againt its RLE. # Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1) # Check the sequence againt its RLE. (There are rules on generating Kolakoski sequences from this method that are broken by the last example)
package main import "fmt" func nextInCycle(c []int, index int) int { return c[index % len(c)] } func kolakoski(c []int, slen int) []int { s := make([]int, slen) i, k := 0, 0 for { s[i] = nextInCycle(c, k) if s[k] > 1 { for j := 1; j < s[k]; j++ { i++ if i == slen { return s } s[i] = s[i - 1] } } i++ if i == slen { return s } k++ } } func possibleKolakoski(s []int) bool { slen := len(s) rle := make([]int, 0, slen) prev := s[0] count := 1 for i := 1; i < slen; i++ { if s[i] == prev { count++ } else { rle = append(rle, count) count = 1 prev = s[i] } } // no point adding final 'count' to rle as we're not going to compare it anyway for i := 0; i < len(rle); i++ { if rle[i] != s[i] { return false } } return true } func printInts(ia []int, suffix string) { fmt.Print("[") alen := len(ia) for i := 0; i < alen; i++ { fmt.Print(ia[i]) if i < alen - 1 { fmt.Print(", ") } } fmt.Printf("]%s\n", suffix) } func main() { ias := make([][]int, 4) ias[0] = []int{1, 2} ias[1] = []int{2, 1} ias[2] = []int{1, 3, 1, 2} ias[3] = []int{1, 3, 2, 1} slens := []int{20, 20, 30, 30} for i, ia := range ias { slen := slens[i] kol := kolakoski(ia, slen) fmt.Printf("First %d members of the sequence generated by ", slen) printInts(ia, ":") printInts(kol, "") p := possibleKolakoski(kol) poss := "Yes" if !p { poss = "No" } fmt.Println("Possible Kolakoski sequence?", poss, "\n") } }
Kosaraju
Go
{{wikipedia|Graph}} Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph. For this task consider the directed graph with these connections: 0 -> 1 1 -> 2 2 -> 0 3 -> 1, 3 -> 2, 3 -> 4 4 -> 3, 4 -> 5 5 -> 2, 5 -> 6 6 -> 5 7 -> 4, 7 -> 6, 7 -> 7 And report the kosaraju strongly connected component for each node. ;References: * The article on Wikipedia.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { // 1. For each vertex u of the graph, mark u as unvisited. Let L be empty. vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(L) // index for filling L in reverse order t := make([][]int, len(g)) // transpose graph // 2. recursive subroutine: var Visit func(int) Visit = func(u int) { if !vis[u] { vis[u] = true for _, v := range g[u] { Visit(v) t[v] = append(t[v], u) // construct transpose } x-- L[x] = u } } // 2. For each vertex u of the graph do Visit(u) for u := range g { Visit(u) } c := make([]int, len(g)) // result, the component assignment // 3: recursive subroutine: var Assign func(int, int) Assign = func(u, root int) { if vis[u] { // repurpose vis to mean "unassigned" vis[u] = false c[u] = root for _, v := range t[u] { Assign(v, root) } } } // 3: For each element u of L in order, do Assign(u,u) for _, u := range L { Assign(u, u) } return c }
Lah numbers
Go
Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets. Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them. Lah numbers obey the identities and relations: L(n, 0), L(0, k) = 0 # for n, k > 0 L(n, n) = 1 L(n, 1) = n! L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers ''or'' L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers ;Task: :* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that. :* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n). :* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''. ;See also: :* '''Wikipedia - Lah number''' :* '''OEIS:A105278 - Unsigned Lah numbers''' :* '''OEIS:A008297 - Signed Lah numbers''' ;Related Tasks: :* '''Stirling numbers of the first kind''' :* '''Stirling numbers of the second kind''' :* '''Bell numbers'''
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } l[n][n].SetInt64(int64(1)) if n != 1 { l[n][1].MulRange(int64(2), int64(n)) } } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.Mul(l[n][1], l[n-1][1]) t.Quo(&t, l[k][1]) t.Quo(&t, l[k-1][1]) t.Quo(&t, l[n-k][1]) l[n][k].Set(&t) if !unsigned && (n%2 == 1) { l[n][k].Neg(l[n][k]) } } } fmt.Println("Unsigned Lah numbers: l(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%10d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("-----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%10d ", l[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the l(100, *) row:") max := new(big.Int).Set(l[limit][0]) for k := 1; k <= limit; k++ { if l[limit][k].Cmp(max) > 0 { max.Set(l[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
Largest int from concatenated ints
Go
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
// Variation of method 3. Repeat digits to at least the size of the longest, // then sort as strings. package main import ( "fmt" "math/big" "sort" "strconv" "strings" ) type c struct { i int s, rs string } type cc []*c func (c cc) Len() int { return len(c) } func (c cc) Less(i, j int) bool { return c[j].rs < c[i].rs } func (c cc) Swap(i, j int) { c[i], c[j] = c[j], c[i] } // Function required by task. Takes a list of integers, returns big int. func li(is ...int) *big.Int { ps := make(cc, len(is)) ss := make([]c, len(is)) ml := 0 for j, i := range is { p := &ss[j] ps[j] = p p.i = i p.s = strconv.Itoa(i) if len(p.s) > ml { ml = len(p.s) } } for _, p := range ps { p.rs = strings.Repeat(p.s, (ml+len(p.s)-1)/len(p.s)) } sort.Sort(ps) s := make([]string, len(ps)) for i, p := range ps { s[i] = p.s } b, _ := new(big.Int).SetString(strings.Join(s, ""), 10) return b } func main() { fmt.Println(li(1, 34, 3, 98, 9, 76, 45, 4)) fmt.Println(li(54, 546, 548, 60)) }
Largest number divisible by its digits
Go from Kotlin
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
package main import ( "fmt" "strconv" "strings" ) func divByAll(num int, digits []byte) bool { for _, digit := range digits { if num%int(digit-'0') != 0 { return false } } return true } func main() { magic := 9 * 8 * 7 high := 9876432 / magic * magic for i := high; i >= magic; i -= magic { if i%10 == 0 { continue // can't end in '0' } s := strconv.Itoa(i) if strings.ContainsAny(s, "05") { continue // can't contain '0'or '5' } var set = make(map[byte]bool) var sd []byte // distinct digits for _, b := range []byte(s) { if !set[b] { set[b] = true sd = append(sd, b) } } if len(sd) != len(s) { continue // digits must be unique } if divByAll(i, sd) { fmt.Println("Largest decimal number is", i) return } } }
Largest proper divisor of n
Go
a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.
package main import "fmt" func largestProperDivisor(n int) int { for i := 2; i*i <= n; i++ { if n%i == 0 { return n / i } } return 1 } func main() { fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:") fmt.Print(" 1 ") for n := 2; n <= 100; n++ { if n%2 == 0 { fmt.Printf("%2d ", n/2) } else { fmt.Printf("%2d ", largestProperDivisor(n)) } if n%10 == 0 { fmt.Println() } } }
Last Friday of each month
Go
Write a program or a script that returns the date of the last Fridays 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_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 ;Related tasks * [[Five weekends]] * [[Day of the week]] * [[Find the last Sunday of each month]]
package main import ( "fmt" "os" "strconv" "time" ) func main() { y := time.Now().Year() if len(os.Args) == 2 { if i, err := strconv.Atoi(os.Args[1]); err == nil { y = i } } for m := time.January; m <= time.December; m++ { d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour) d = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour) fmt.Println(d.Format("2006-01-02")) } }
Last letter-first letter
Go
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
package main import ( "fmt" "strings" ) var pokemon = `audino bagon baltoy...67 names omitted...` func main() { // split text into slice representing directed graph var d []string for _, l := range strings.Split(pokemon, "\n") { d = append(d, strings.Fields(l)...) } fmt.Println("searching", len(d), "names...") // try each name as possible start for i := range d { d[0], d[i] = d[i], d[0] search(d, 1, len(d[0])) d[0], d[i] = d[i], d[0] } fmt.Println("maximum path length:", len(ex)) fmt.Println("paths of that length:", nMax) fmt.Print("example path of that length:") for i, n := range ex { if i%6 == 0 { fmt.Print("\n ") } fmt.Print(n, " ") } fmt.Println() } var ex []string var nMax int func search(d []string, i, ncPath int) { // tally statistics if i == len(ex) { nMax++ } else if i > len(ex) { nMax = 1 ex = append(ex[:0], d[:i]...) } // recursive search lastName := d[i-1] lastChar := lastName[len(lastName)-1] for j := i; j < len(d); j++ { if d[j][0] == lastChar { d[i], d[j] = d[j], d[i] search(d, i+1, ncPath+1+len(d[i])) d[i], d[j] = d[j], d[i] } } }
Latin Squares in reduced form
Go
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained. For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row. Demonstrate by: * displaying the four reduced Latin Squares of order 4. * for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
package main import ( "fmt" "sort" ) type matrix [][]int // generate derangements of first n numbers, with 'start' in first place. func dList(n, start int) (r matrix) { start-- // use 0 basing a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] sort.Ints(a[1:]) first := a[1] // recursive closure permutes a[1:] var recurse func(last int) recurse = func(last int) { if last == first { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged. for j, v := range a[1:] { // j starts from 0, not 1 if j+1 == v { return // no, ignore it } } // yes, save a copy b := make([]int, n) copy(b, a) for i := range b { b[i]++ // change back to 1 basing } r = append(r, b) return } for i := last; i >= 1; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } func reducedLatinSquare(n int, echo bool) uint64 { if n <= 0 { if echo { fmt.Println("[]\n") } return 0 } else if n == 1 { if echo { fmt.Println("[1]\n") } return 1 } rlatin := make(matrix, n) for i := 0; i < n; i++ { rlatin[i] = make([]int, n) } // first row for j := 0; j < n; j++ { rlatin[0][j] = j + 1 } count := uint64(0) // recursive closure to compute reduced latin squares and count or print them var recurse func(i int) recurse = func(i int) { rows := dList(n, i) // get derangements of first n numbers, with 'i' first. outer: for r := 0; r < len(rows); r++ { copy(rlatin[i-1], rows[r]) for k := 0; k < i-1; k++ { for j := 1; j < n; j++ { if rlatin[k][j] == rlatin[i-1][j] { if r < len(rows)-1 { continue outer } else if i > 2 { return } } } } if i < n { recurse(i + 1) } else { count++ if echo { printSquare(rlatin, n) } } } return } // remaining rows recurse(2) return count } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func factorial(n uint64) uint64 { if n == 0 { return 1 } prod := uint64(1) for i := uint64(2); i <= n; i++ { prod *= i } return prod } func main() { fmt.Println("The four reduced latin squares of order 4 are:\n") reducedLatinSquare(4, true) fmt.Println("The size of the set of reduced latin squares for the following orders") fmt.Println("and hence the total number of latin squares of these orders are:\n") for n := uint64(1); n <= 6; n++ { size := reducedLatinSquare(int(n), false) f := factorial(n - 1) f *= f * n * size fmt.Printf("Order %d: Size %-4d x %d! x %d! => Total %d\n", n, size, n, n-1, f) } }
Law of cosines - triples
Go
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
package main import "fmt" type triple struct{ a, b, c int } var squares13 = make(map[int]int, 13) var squares10000 = make(map[int]int, 10000) func init() { for i := 1; i <= 13; i++ { squares13[i*i] = i } for i := 1; i <= 10000; i++ { squares10000[i*i] = i } } func solve(angle, maxLen int, allowSame bool) []triple { var solutions []triple for a := 1; a <= maxLen; a++ { for b := a; b <= maxLen; b++ { lhs := a*a + b*b if angle != 90 { switch angle { case 60: lhs -= a * b case 120: lhs += a * b default: panic("Angle must be 60, 90 or 120 degrees") } } switch maxLen { case 13: if c, ok := squares13[lhs]; ok { if !allowSame && a == b && b == c { continue } solutions = append(solutions, triple{a, b, c}) } case 10000: if c, ok := squares10000[lhs]; ok { if !allowSame && a == b && b == c { continue } solutions = append(solutions, triple{a, b, c}) } default: panic("Maximum length must be either 13 or 10000") } } } return solutions } func main() { fmt.Print("For sides in the range [1, 13] ") fmt.Println("where they can all be of the same length:-\n") angles := []int{90, 60, 120} var solutions []triple for _, angle := range angles { solutions = solve(angle, 13, true) fmt.Printf(" For an angle of %d degrees", angle) fmt.Println(" there are", len(solutions), "solutions, namely:") fmt.Printf(" %v\n", solutions) fmt.Println() } fmt.Print("For sides in the range [1, 10000] ") fmt.Println("where they cannot ALL be of the same length:-\n") solutions = solve(60, 10000, false) fmt.Print(" For an angle of 60 degrees") fmt.Println(" there are", len(solutions), "solutions.") }
Least common multiple
Go
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
package main import ( "fmt" "math/big" ) var m, n, z big.Int func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) } func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
Left factorials
Go
'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; the same notation can be confusingly seen being used for the two different definitions. Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: :::::::* !''n''` :::::::* !''n'' :::::::* ''n''! (It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''': ::::: !n = \sum_{k=0}^{n-1} k! :::: where ::::: !0 = 0 ;Task Display the left factorials for: * zero through ten (inclusive) * 20 through 110 (inclusive) by tens Display the length (in decimal digits) of the left factorials for: * 1,000 through 10,000 (inclusive), by thousands. ;Also see: * The OEIS entry: A003422 left factorials * The MathWorld entry: left factorial * The MathWorld entry: factorial sums * The MathWorld entry: subfactorial ;Related task: * permutations/derangements (subfactorials)
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through !10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int64() == 10 { break } } fmt.Println() for { for i := 0; i < 10; i++ { next() } fmt.Printf("!%d: %d\n", n, l) if n.Int64() == 110 { break } } fmt.Println("Lengths of !1000 through !10000 by thousands:") for i := 110; i < 1000; i++ { next() } for { fmt.Print(" ", len(l.String())) if n.Int64() == 10000 { break } for i := 0; i < 1000; i++ { next() } } fmt.Println() }
Levenshtein distance
Go
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
package main import "fmt" func main() { fmt.Println(ld("kitten", "sitting")) } func ld(s, t string) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) } for i := range d { d[i][0] = i } for j := range d[0] { d[0][j] = j } for j := 1; j <= len(t); j++ { for i := 1; i <= len(s); i++ { if s[i-1] == t[j-1] { d[i][j] = d[i-1][j-1] } else { min := d[i-1][j] if d[i][j-1] < min { min = d[i][j-1] } if d[i-1][j-1] < min { min = d[i-1][j-1] } d[i][j] = min + 1 } } } return d[len(s)][len(t)] }
Levenshtein distance
Go from C
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
package main import "fmt" func levenshtein(s, t string) int { if s == "" { return len(t) } if t == "" { return len(s) } if s[0] == t[0] { return levenshtein(s[1:], t[1:]) } a := levenshtein(s[1:], t[1:]) b := levenshtein(s, t[1:]) c := levenshtein(s[1:], t) if a > b { a = b } if a > c { a = c } return a + 1 } func main() { s1 := "rosettacode" s2 := "raisethysword" fmt.Printf("distance between %s and %s: %d\n", s1, s2, levenshtein(s1, s2)) }
List rooted trees
Go from C
You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical. If we use a matching pair of parentheses to represent a bag, the ways are: For 1 bag, there's one way: () <- a bag for 2 bags, there's one way: (()) <- one bag in another for 3 bags, there are two: ((())) <- 3 bags nested Russian doll style (()()) <- 2 bags side by side, inside the third for 4 bags, four: (()()()) ((())()) ((()())) (((()))) Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration. It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81. ;Task: Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive. This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size. As an example output, run 5 bags. There should be 9 ways.
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { paren = '(' } else { paren = ')' } fmt.Printf("%c", paren) } } func listTrees(n uint) { for i := offset[n]; i < offset[n+1]; i++ { show(list[i], n*2) fmt.Println() } } /* assemble tree from subtrees n: length of tree we want to make t: assembled parts so far sl: length of subtree we are looking at pos: offset of subtree we are looking at rem: remaining length to be put together */ func assemble(n uint, t tree, sl, pos, rem uint) { if rem == 0 { add(t) return } if sl > rem { // need smaller sub-trees sl = rem pos = offset[sl] } else if pos >= offset[sl+1] { // used up sl-trees, try smaller ones sl-- if sl == 0 { return } pos = offset[sl] } assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl) assemble(n, t, sl, pos+1, rem) } func mktrees(n uint) { if offset[n+1] > 0 { return } if n > 0 { mktrees(n - 1) } assemble(n, 0, n-1, offset[n-1], n-1) offset[n+1] = uint(len(list)) } func main() { if len(os.Args) != 2 { log.Fatal("There must be exactly 1 command line argument") } n, err := strconv.Atoi(os.Args[1]) if err != nil { log.Fatal("Argument is not a valid number") } if n <= 0 || n > 19 { // stack overflow for n == 20 n = 5 } // init 1-tree add(0) mktrees(uint(n)) fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n]) listTrees(uint(n)) }
Long literals, with continuations
Go
This task is about writing a computer program that has long literals (character literals that may require specifying the words/tokens on more than one (source) line, either with continuations or some other method, such as abutments or concatenations (or some other mechanisms). The literal is to be in the form of a "list", a literal that contains many words (tokens) separated by a blank (space), in this case (so as to have a common list), the (English) names of the chemical elements of the periodic table. The list is to be in (ascending) order of the (chemical) element's atomic number: ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...'' ... up to the last known (named) chemical element (at this time). Do not include any of the "unnamed" chemical element names such as: ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium'' To make computer programming languages comparable, the statement widths should be restricted to less than '''81''' bytes (characters), or less if a computer programming language has more restrictive limitations or standards. Also mention what column the programming statements can start in if ''not'' in column one. The list ''may'' have leading/embedded/trailing blanks during the declaration (the actual program statements), this is allow the list to be more readable. The "final" list shouldn't have any leading/trailing or superfluous blanks (when stored in the program's "memory"). This list should be written with the idea in mind that the program ''will'' be updated, most likely someone other than the original author, as there will be newer (discovered) elements of the periodic table being added (possibly in the near future). These future updates should be one of the primary concerns in writing these programs and it should be "easy" for someone else to add chemical elements to the list (within the computer program). Attention should be paid so as to not exceed the ''clause length'' of continued or specified statements, if there is such a restriction. If the limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here. ;Task: :* Write a computer program (by whatever name) to contain a list of the known elements. :* The program should eventually contain a long literal of words (the elements). :* The literal should show how one could create a long list of blank-delineated words. :* The "final" (stored) list should only have a single blank between elements. :* Try to use the most idiomatic approach(es) in creating the final list. :* Use continuation if possible, and/or show alternatives (possibly using concatenation). :* Use a program comment to explain what the continuation character is if it isn't obvious. :* The program should contain a variable that has the date of the last update/revision. :* The program, when run, should display with verbiage: :::* The last update/revision date (and should be unambiguous). :::* The number of chemical elements in the list. :::* The name of the highest (last) element name. Show all output here, on this page.
package main import ( "fmt" "regexp" "strings" ) // Uses a 'raw string literal' which is a character sequence enclosed in back quotes. // Within the quotes any character (including new line) may appear except // back quotes themselves. var elements = ` hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson ` func main() { lastRevDate := "March 24th, 2020" re := regexp.MustCompile(`\s+`) // split on one or more whitespace characters els := re.Split(strings.TrimSpace(elements), -1) numEls := len(els) // Recombine as a single string with elements separated by a single space. elements2 := strings.Join(els, " ") // Required output. fmt.Println("Last revision Date: ", lastRevDate) fmt.Println("Number of elements: ", numEls) // The compiler complains that 'elements2' is unused if we don't use // something like this to get the last element rather than just els[numEls-1]. lix := strings.LastIndex(elements2, " ") // get index of last space fmt.Println("Last element : ", elements2[lix+1:]) }
Long year
Go
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the %s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
Longest common subsequence
Go from Java
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
func lcs(a, b string) string { arunes := []rune(a) brunes := []rune(b) aLen := len(arunes) bLen := len(brunes) lengths := make([][]int, aLen+1) for i := 0; i <= aLen; i++ { lengths[i] = make([]int, bLen+1) } // row 0 and column 0 are initialized to 0 already for i := 0; i < aLen; i++ { for j := 0; j < bLen; j++ { if arunes[i] == brunes[j] { lengths[i+1][j+1] = lengths[i][j] + 1 } else if lengths[i+1][j] > lengths[i][j+1] { lengths[i+1][j+1] = lengths[i+1][j] } else { lengths[i+1][j+1] = lengths[i][j+1] } } } // read the substring out from the matrix s := make([]rune, 0, lengths[aLen][bLen]) for x, y := aLen, bLen; x != 0 && y != 0; { if lengths[x][y] == lengths[x-1][y] { x-- } else if lengths[x][y] == lengths[x][y-1] { y-- } else { s = append(s, arunes[x-1]) x-- y-- } } // reverse string for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } return string(s) }
Longest common substring
Go from C#
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
package main import "fmt" func lcs(a, b string) (output string) { lengths := make([]int, len(a)*len(b)) greatestLength := 0 for i, x := range a { for j, y := range b { if x == y { if i == 0 || j == 0 { lengths[i*len(b)+j] = 1 } else { lengths[i*len(b)+j] = lengths[(i-1)*len(b)+j-1] + 1 } if lengths[i*len(b)+j] > greatestLength { greatestLength = lengths[i*len(b)+j] output = a[i-greatestLength+1 : i+1] } } } } return } func main() { fmt.Println(lcs("thisisatest", "testing123testing")) }
Longest increasing subsequence
Go
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node // sort into piles for _, x := range n { j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x }) node := &Node{ x, nil } if j != 0 { node.back = pileTops[j-1] } if j != len(pileTops) { pileTops[j] = node } else { pileTops = append(pileTops, node) } } if len(pileTops) == 0 { return []int{} } for node := pileTops[len(pileTops)-1]; node != nil; node = node.back { result = append(result, node.val) } // reverse for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return } func main() { for _, d := range [][]int{{3, 2, 6, 4, 5, 1}, {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} { fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d)) } }
Lucky and even lucky numbers
Go from Kotlin
Note that in the following explanation list indices are assumed to start at ''one''. ;Definition of lucky numbers ''Lucky numbers'' are positive integers that are formed by: # Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ... # Return the first number from the list (which is '''1'''). # (Loop begins here) #* Note then return the second number from the list (which is '''3'''). #* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''7'''). #* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ... #* Note then return the 4th number from the list (which is '''9'''). #* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ... #* Take the 5th, i.e. '''13'''. Remove every 13th. #* Take the 6th, i.e. '''15'''. Remove every 15th. #* Take the 7th, i.e. '''21'''. Remove every 21th. #* Take the 8th, i.e. '''25'''. Remove every 25th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above ''except for the very first step'': # Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ... # Return the first number from the list (which is '''2'''). # (Loop begins here) #* Note then return the second number from the list (which is '''4'''). #* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''6'''). #* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ... #* Take the 4th, i.e. '''10'''. Remove every 10th. #* Take the 5th, i.e. '''12'''. Remove every 12th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Task requirements * Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' * Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: ** missing arguments ** too many arguments ** number (or numbers) aren't legal ** misspelled argument ('''lucky''' or '''evenLucky''') * The command line handling should: ** support mixed case handling of the (non-numeric) arguments ** support printing a particular number ** support printing a range of numbers by their index ** support printing a range of numbers by their values * The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) +-------------------+----------------------------------------------------+ | j | Jth lucky number | | j , lucky | Jth lucky number | | j , evenLucky | Jth even lucky number | | | | | j k | Jth through Kth (inclusive) lucky numbers | | j k lucky | Jth through Kth (inclusive) lucky numbers | | j k evenLucky | Jth through Kth (inclusive) even lucky numbers | | | | | j -k | all lucky numbers in the range j --> |k| | | j -k lucky | all lucky numbers in the range j --> |k| | | j -k evenLucky | all even lucky numbers in the range j --> |k| | +-------------------+----------------------------------------------------+ where |k| is the absolute value of k Demonstrate the program by: * showing the first twenty ''lucky'' numbers * showing the first twenty ''even lucky'' numbers * showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive) * showing all ''even lucky'' numbers in the same range as above * showing the 10,000th ''lucky'' number (extra credit) * showing the 10,000th ''even lucky'' number (extra credit) ;See also: * This task is related to the [[Sieve of Eratosthenes]] task. * OEIS Wiki Lucky numbers. * Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. * Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. * Entry lucky numbers on The Eric Weisstein's World of Mathematics.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLuckyOdd() { for n := 2; n < len(luckyOdd); n++ { m := luckyOdd[n-1] end := (len(luckyOdd)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyOdd[j:], luckyOdd[j+1:]) luckyOdd = luckyOdd[:len(luckyOdd)-1] } } } func filterLuckyEven() { for n := 2; n < len(luckyEven); n++ { m := luckyEven[n-1] end := (len(luckyEven)/m)*m - 1 for j := end; j >= m-1; j -= m { copy(luckyEven[j:], luckyEven[j+1:]) luckyEven = luckyEven[:len(luckyEven)-1] } } } func printSingle(j int, odd bool) error { if odd { if j >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky number", j, "=", luckyOdd[j-1]) } else { if j >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", j) } fmt.Println("Lucky even number", j, "=", luckyEven[j-1]) } return nil } func printRange(j, k int, odd bool) error { if odd { if k >= len(luckyOdd) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky numbers", j, "to", k, "are:") fmt.Println(luckyOdd[j-1 : k]) } else { if k >= len(luckyEven) { return fmt.Errorf("the argument, %d, is too big", k) } fmt.Println("Lucky even numbers", j, "to", k, "are:") fmt.Println(luckyEven[j-1 : k]) } return nil } func printBetween(j, k int, odd bool) error { var r []int if odd { max := luckyOdd[len(luckyOdd)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyOdd { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky numbers between", j, "and", k, "are:") fmt.Println(r) } else { max := luckyEven[len(luckyEven)-1] if j > max || k > max { return fmt.Errorf("at least one argument, %d or %d, is too big", j, k) } for _, num := range luckyEven { if num < j { continue } if num > k { break } r = append(r, num) } fmt.Println("Lucky even numbers between", j, "and", k, "are:") fmt.Println(r) } return nil } func main() { nargs := len(os.Args) if nargs < 2 || nargs > 4 { log.Fatal("there must be between 1 and 3 command line arguments") } filterLuckyOdd() filterLuckyEven() j, err := strconv.Atoi(os.Args[1]) if err != nil || j < 1 { log.Fatalf("first argument, %s, must be a positive integer", os.Args[1]) } if nargs == 2 { if err := printSingle(j, true); err != nil { log.Fatal(err) } return } if nargs == 3 { k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatalf("second argument, %s, must be an integer", os.Args[2]) } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, true); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, true); err != nil { log.Fatal(err) } } return } var odd bool switch lucky := strings.ToLower(os.Args[3]); lucky { case "lucky": odd = true case "evenlucky": odd = false default: log.Fatalf("third argument, %s, is invalid", os.Args[3]) } if os.Args[2] == "," { if err := printSingle(j, odd); err != nil { log.Fatal(err) } return } k, err := strconv.Atoi(os.Args[2]) if err != nil { log.Fatal("second argument must be an integer or a comma") } if k >= 0 { if j > k { log.Fatalf("second argument, %d, can't be less than first, %d", k, j) } if err := printRange(j, k, odd); err != nil { log.Fatal(err) } } else { l := -k if j > l { log.Fatalf("second argument, %d, can't be less in absolute value than first, %d", k, j) } if err := printBetween(j, l, odd); err != nil { log.Fatal(err) } } }
Lychrel numbers
Go
::# Take an integer n, greater than zero. ::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n. ::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly. ;Example: If n0 = 12 we get 12 12 + 21 = 33, a palindrome! And if n0 = 55 we get 55 55 + 55 = 110 110 + 011 = 121, a palindrome! Notice that the check for a palindrome happens ''after'' an addition. Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called '''Lychrel numbers'''. For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. ;Seed and related Lychrel numbers: Any integer produced in the sequence of a Lychrel number is also a Lychrel number. In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin: 196 196 + 691 = 887 887 + 788 = 1675 1675 + 5761 = 7436 7436 + 6347 = 13783 13783 + 38731 = 52514 52514 + 41525 = 94039 ... 689 689 + 986 = 1675 1675 + 5761 = 7436 ... So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number. ;Task: * Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500). * Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found. * Print any seed Lychrel or related number that is itself a palindrome. Show all output here. ;References: * What's special about 196? Numberphile video. * A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed). * Status of the 196 conjecture? Mathoverflow.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) // approximate var ten = big.NewInt(10) // Reverse sets `result` to the value of the base ten digits of `v` in // reverse order and returns `result`. // Only handles positive integers. func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { // optimize small values that fit within uint64 result.SetUint64(reverseUint64(v.Uint64())) } else { if true { // Reverse the string representation s := reverseString(v.String()) result.SetString(s, 10) } else { // This has fewer allocations but is slower: // Use a copy of `v` since we mutate it. v := new(big.Int).Set(v) digit := new(big.Int) result.SetUint64(0) for v.BitLen() > 0 { v.QuoRem(v, ten, digit) result.Mul(result, ten) result.Add(result, digit) } } } return result } func reverseUint64(v uint64) uint64 { var r uint64 for v > 0 { r *= 10 r += v % 10 v /= 10 } return r } func reverseString(s string) string { b := make([]byte, len(s)) for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { b[i] = s[j] } return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { v, r := new(big.Int).SetUint64(n), new(big.Int) reverseInt(v, r) seen := make(map[string]bool) isLychrel = true isSeed = true for i := iter; i > 0; i-- { str := v.String() if seen[str] { //log.Println("found a loop with", n, "at", str) isLychrel = true break } if ans, ok := known[str]; ok { //log.Println("already know:", str, ans) isLychrel = ans isSeed = false break } seen[str] = true v = v.Add(v, r) //log.Printf("%v + %v = %v\n", str, r, v) reverseInt(v, r) if v.Cmp(r) == 0 { //log.Println(v, "is a palindrome,", n, "is not a Lychrel number") isLychrel = false isSeed = false break } } for k := range seen { known[k] = isLychrel } //if isLychrel { log.Printf("%v may be a Lychrel number\n", n) } return isLychrel, isSeed } func main() { max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) var seeds []uint64 var related int var pals []uint64 for i := uint64(1); i <= *max; i++ { if l, s := Lychrel(i, *iter); l { if s { seeds = append(seeds, i) } else { related++ } if i == reverseUint64(i) { pals = append(pals, i) } } } fmt.Println(" Number of Lychrel seeds:", len(seeds)) fmt.Println(" Lychrel seeds:", seeds) fmt.Println(" Number of related:", related) fmt.Println("Number of Lychrel palindromes:", len(pals)) fmt.Println(" Lychrel palindromes:", pals) }
MAC vendor lookup
Go
Every connected device around the world comes with a unique Media Access Control address, or a MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. ;Task: Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. '''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
package main import ( "net/http" "fmt" "io/ioutil" ) func macLookUp(mac string) (res string){ resp, _ := http.Get("http://api.macvendors.com/" + mac) body, _ := ioutil.ReadAll(resp.Body) res = string(body) return } func main() { fmt.Println(macLookUp("FC-A1-3E")) fmt.Println(macLookUp("FC:FB:FB:01:FA:21")) fmt.Println(macLookUp("BC:5F:F4")) }
Machine code
Go from C
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given for x86 (32 bit) architectures: mov EAX, [ESP+4] add EAX, [ESP+8] ret This would translate into the following opcode bytes: 139 68 36 4 3 68 36 8 195 Or in hexadecimal: 8B 44 24 04 03 44 24 08 C3 ;Task: If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language: * Poke the necessary opcodes into a memory location. * Provide a means to pass two values to the machine code. * Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19. * Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
package main import "fmt" /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <string.h> typedef unsigned char byte; typedef byte (*mcfunc) (byte, byte); void runMachineCode(void *buf, byte a, byte b) { mcfunc fp = (mcfunc)buf; printf("%d\n", fp(a, b)); } */ import "C" func main() { code := []byte{ 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3, } le := len(code) buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC, C.MAP_PRIVATE|C.MAP_ANON, -1, 0) codePtr := C.CBytes(code) C.memcpy(buf, codePtr, C.size_t(le)) var a, b byte = 7, 12 fmt.Printf("%d + %d = ", a, b) C.runMachineCode(buf, C.byte(a), C.byte(b)) C.munmap(buf, C.size_t(le)) C.free(codePtr) }
Mad Libs
Go
{{wikipedia}} Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. ;Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: went for a walk in the park. found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
package main import ( "bufio" "fmt" "io/ioutil" "log" "os" "regexp" "strings" ) func main() { pat := regexp.MustCompile("<.+?>") if len(os.Args) != 2 { fmt.Println("usage: madlib <story template file>") return } b, err := ioutil.ReadFile(os.Args[1]) if err != nil { log.Fatal(err) } tmpl := string(b) s := []string{} // patterns in order of appearance m := map[string]string{} // mapping from patterns to replacements for _, p := range pat.FindAllString(tmpl, -1) { if _, ok := m[p]; !ok { m[p] = "" s = append(s, p) } } fmt.Println("Enter replacements:") br := bufio.NewReader(os.Stdin) for _, p := range s { for { fmt.Printf("%s: ", p[1:len(p)-1]) r, isPre, err := br.ReadLine() if err != nil { log.Fatal(err) } if isPre { log.Fatal("you're not playing right. :P") } s := strings.TrimSpace(string(r)) if s == "" { fmt.Println(" hmm?") continue } m[p] = s break } } fmt.Println("\nYour story:\n") fmt.Println(pat.ReplaceAllStringFunc(tmpl, func(p string) string { return m[p] })) }
Magic 8-ball
Go from Kotlin
Create Magic 8-Ball. See details at: Magic 8-Ball.
package main import ( "bufio" "bytes" "fmt" "log" "math/rand" "os" "time" ) func main() { rand.Seed(time.Now().UnixNano()) answers := [...]string{ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", } const prompt = "\n? : " fmt.Print("Please enter your question or a blank line to quit.\n" + prompt) sc := bufio.NewScanner(os.Stdin) for sc.Scan() { question := sc.Bytes() question = bytes.TrimSpace(question) if len(question) == 0 { break } answer := answers[rand.Intn(len(answers))] fmt.Printf("\n%s\n"+prompt, answer) } if err := sc.Err(); err != nil { log.Fatal(err) } }
Magic squares of doubly even order
Go
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). This means that the subsquares also have an even size, which plays a role in the construction. {| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%" |- |'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8''' |- |'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16''' |- |'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41''' |- |'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33''' |- |'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25''' |- |'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17''' |- |'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56''' |- |'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64''' |} ;Task Create a magic square of '''8 x 8'''. ;Related tasks * [[Magic squares of odd order]] * [[Magic squares of singly even order]] ;See also: * Doubly Even Magic Squares (1728.org)
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 // 0b1001011001101001 size := d * d mult := d / 4 for i, r := 0, 0; r < d; r++ { output = append(output, []int{}) for c := 0; c < d; i, c = i+1, c+1 { bitPos := c/mult + (r/mult)*4 if (bits & (1 << uint(bitPos))) != 0 { output[r] = append(output[r], i+1) } else { output[r] = append(output[r], size-i) } } } return output, nil } func arrayItoa(input []int) []string { var output []string for _, i := range input { output = append(output, fmt.Sprintf("%4d", i)) } return output } func main() { data, err := setupMagicSquareData(dimensions) if err != nil { log.Fatal(err) } magicConstant := (dimensions * (dimensions*dimensions + 1)) / 2 for _, row := range data { fmt.Println(strings.Join(arrayItoa(row), " ")) } fmt.Printf("\nMagic Constant: %d\n", magicConstant) }
Magic squares of odd order
Go from C
A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). The numbers are usually (but not always) the first '''N'''2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''. {| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%" |- | '''8''' || '''1''' || '''6''' |- | '''3''' || '''5''' || '''7''' |- | '''4''' || '''9''' || '''2''' |} ;Task For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. Optionally, show the ''magic number''. You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''. ; Related tasks * [[Magic squares of singly even order]] * [[Magic squares of doubly even order]] ; See also: * MathWorld(tm) entry: Magic_square * Odd Magic Squares (1728.org)
package main import ( "fmt" "log" ) func ms(n int) (int, []int) { M := func(x int) int { return (x + n - 1) % n } if n <= 0 || n&1 == 0 { n = 5 log.Println("forcing size", n) } m := make([]int, n*n) i, j := 0, n/2 for k := 1; k <= n*n; k++ { m[i*n+j] = k if m[M(i)*n+M(j)] != 0 { i = (i + 1) % n } else { i, j = M(i), M(j) } } return n, m } func main() { n, m := ms(5) i := 2 for j := 1; j <= n*n; j *= 10 { i++ } f := fmt.Sprintf("%%%dd", i) for i := 0; i < n; i++ { for j := 0; j < n; j++ { fmt.Printf(f, m[i*n+j]) } fmt.Println() } }
Magic squares of singly even order
Go from Java
A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction. ;Task Create a magic square of 6 x 6. ; Related tasks * [[Magic squares of odd order]] * [[Magic squares of doubly even order]] ; See also * Singly Even Magic Squares (1728.org)
package main import ( "fmt" "log" ) func magicSquareOdd(n int) ([][]int, error) { if n < 3 || n%2 == 0 { return nil, fmt.Errorf("base must be odd and > 2") } value := 1 gridSize := n * n c, r := n/2, 0 result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for value <= gridSize { result[r][c] = value if r == 0 { if c == n-1 { r++ } else { r = n - 1 c++ } } else if c == n-1 { r-- c = 0 } else if result[r-1][c+1] == 0 { r-- c++ } else { r++ } value++ } return result, nil } func magicSquareSinglyEven(n int) ([][]int, error) { if n < 6 || (n-2)%4 != 0 { return nil, fmt.Errorf("base must be a positive multiple of 4 plus 2") } size := n * n halfN := n / 2 subSquareSize := size / 4 subSquare, err := magicSquareOdd(halfN) if err != nil { return nil, err } quadrantFactors := [4]int{0, 2, 3, 1} result := make([][]int, n) for i := 0; i < n; i++ { result[i] = make([]int, n) } for r := 0; r < n; r++ { for c := 0; c < n; c++ { quadrant := r/halfN*2 + c/halfN result[r][c] = subSquare[r%halfN][c%halfN] result[r][c] += quadrantFactors[quadrant] * subSquareSize } } nColsLeft := halfN / 2 nColsRight := nColsLeft - 1 for r := 0; r < halfN; r++ { for c := 0; c < n; c++ { if c < nColsLeft || c >= n-nColsRight || (c == nColsLeft && r == nColsLeft) { if c == 0 && r == nColsLeft { continue } tmp := result[r][c] result[r][c] = result[r+halfN][c] result[r+halfN][c] = tmp } } } return result, nil } func main() { const n = 6 msse, err := magicSquareSinglyEven(n) if err != nil { log.Fatal(err) } for _, row := range msse { for _, x := range row { fmt.Printf("%2d ", x) } fmt.Println() } fmt.Printf("\nMagic constant: %d\n", (n*n+1)*n/2) }
Map range
Go
Given two ranges: :::* [a_1,a_2] and :::* [b_1,b_2]; :::* then a value s in range [a_1,a_2] :::* is linearly mapped to a value t in range [b_1,b_2] where: :::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)} ;Task: Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. Use this function to map values from the range [0, 10] to the range [-1, 0]. ;Extra credit: Show additional idiomatic ways of performing the mapping, using tools available to the language.
package main import "fmt" type rangeBounds struct { b1, b2 float64 } func mapRange(x, y rangeBounds, n float64) float64 { return y.b1 + (n - x.b1) * (y.b2 - y.b1) / (x.b2 - x.b1) } func main() { r1 := rangeBounds{0, 10} r2 := rangeBounds{-1, 0} for n := float64(0); n <= 10; n += 2 { fmt.Println(n, "maps to", mapRange(r1, r2, n)) } }
Maximum triangle path sum
Go
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You can compute the total of the numbers you have seen in such walk, in this case it's 205. Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321. ;Task: Find the maximum total in the triangle below: 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 Such numbers can be included in the solution code, or read from a "triangle.txt" file. This task is derived from the Euler Problem #18.
package main import ( "fmt" "strconv" "strings" ) const t = ` 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93` func main() { lines := strings.Split(t, "\n") f := strings.Fields(lines[len(lines)-1]) d := make([]int, len(f)) var err error for i, s := range f { if d[i], err = strconv.Atoi(s); err != nil { panic(err) } } d1 := d[1:] var l, r, u int for row := len(lines) - 2; row >= 0; row-- { l = d[0] for i, s := range strings.Fields(lines[row]) { if u, err = strconv.Atoi(s); err != nil { panic(err) } if r = d1[i]; l > r { d[i] = u + l } else { d[i] = u + r } l = r } } fmt.Println(d[0]) }
Mayan calendar
Go
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as '''The Calendar Round''', that meshes several sacred and civil cycles; the other is an offset calendar known as '''The Long Count''', similar in many ways to the Gregorian calendar. '''The Calendar Round''' '''The Calendar Round''' has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle. '''The Tzolk'in''' The sacred cycle in the Mayan calendar round was called the '''Tzolk'in'''. The '''Tzolk'in''' has a cycle of 20 day names: Imix' Ik' Ak'bal K'an Chikchan Kimi Manik' Lamat Muluk Ok Chuwen Eb Ben Hix Men K'ib' Kaban Etz'nab' Kawak Ajaw Intermeshed with the named days, the '''Tzolk'in''' has a cycle of 13 numbered days; 1 through 13. Every day has both a number and a name that repeat in a 260 day cycle. For example: 1 Imix' 2 Ik' 3 Ak'bal ... 11 Chuwen 12 Eb 13 Ben 1 Hix 2 Men 3 K'ib' ... and so on. '''The Haab'''' The Mayan civil calendar is called the '''Haab''''. This calendar has 365 days per year, and is sometimes called the 'vague year.' It is substantially the same as our year, but does not make leap year adjustments, so over long periods of time, gets out of synchronization with the seasons. It consists of 18 months with 20 days each, and the end of the year, a special month of only 5 days, giving a total of 365. The 5 days of the month of '''Wayeb'''' (the last month), are usually considered to be a time of bad luck. Each month in the '''Haab'''' has a name. The Mayan names for the civil months are: Pop Wo' Sip Sotz' Sek Xul Yaxk'in Mol Ch'en Yax Sak' Keh Mak K'ank'in Muwan Pax K'ayab Kumk'u Wayeb' (Short, "unlucky" month) The months function very much like ours do. That is, for any given month we count through all the days of that month, and then move on to the next month. Normally, the day '''1 Pop''' is considered the first day of the civil year, just as '''1 January''' is the first day of our year. In 2019, '''1 Pop''' falls on '''April 2nd'''. But, because of the leap year in 2020, '''1 Pop''' falls on '''April 1st''' in the years 2020-2023. The only really unusual aspect of the '''Haab'''' calendar is that, although there are 20 (or 5) days in each month, the last day of the month is not called the 20th (5th). Instead, the last day of the month is referred to as the 'seating,' or 'putting in place,' of the next month. (Much like how in our culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In the language of the ancient Maya, the word for seating was '''chum''', So you might have: ... 18 Pop (18th day of the first month) 19 Pop (19th day of the first month) Chum Wo' (20th day of the first month) 1 Wo' (1st day of the second month) ... and so on. Dates for any particular day are a combination of the '''Tzolk'in''' sacred date, and '''Haab'''' civil date. When put together we get the '''"Calendar Round."''' '''Calendar Round''' dates always have two numbers and two names, and they are always written in the same order: (1) the day number in the '''Tzolk'in''' (2) the day name in the '''Tzolk'in''' (3) the day of the month in the '''Haab'''' (4) the month name in the '''Haab'''' A calendar round is a repeating cycle with a period of just short of 52 Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days) '''Lords of the Night''' A third cycle of nine days honored the nine '''Lords of the Night'''; nine deities that were associated with each day in turn. The names of the nine deities are lost; they are now commonly referred to as '''G1''' through '''G9'''. The Lord of the Night may or may not be included in a Mayan date, if it is, it is typically just the appropriate '''G(''x'')''' at the end. '''The Long Count''' Mayans had a separate independent way of measuring time that did not run in cycles. (At least, not on normal human scales.) Instead, much like our yearly calendar, each day just gets a little further from the starting point. For the ancient Maya, the starting point was the 'creation date' of the current world. This date corresponds to our date of August 11, 3114 B.C. Dates are calculated by measuring how many days have transpired since this starting date; This is called '''"The Long Count."''' Rather than just an absolute count of days, the long count is broken up into unit blocks, much like our calendar has months, years, decades and centuries. The basic unit is a '''k'in''' - one day. A 20 day month is a '''winal'''. 18 '''winal''' (360 days) is a '''tun''' - sometimes referred to as a short year. 20 short years ('''tun''') is a '''k'atun''' 20 '''k'atun''' is a '''bak'tun''' There are longer units too: '''Piktun''' == 20 '''Bak'tun''' (8,000 short years) '''Kalabtun''' == 20 '''Piktun''' (160,000 short years) '''Kinchiltun''' == 20 '''Kalabtun''' (3,200,000 short years) For the most part, the Maya only used the blocks of time up to the '''bak'tun'''. One '''bak'tun''' is around 394 years, much more than a human life span, so that was all they usually needed to describe dates in this era, or this world. It is worth noting, the two calendars working together allow much more accurate and reliable notation for dates than is available in many other calendar systems; mostly due to the pragmatic choice to make the calendar simply track days, rather than trying to make it align with seasons and/or try to conflate it with the notion of time. '''Mayan Date correlations''' There is some controversy over finding a correlation point between the Gregorian and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep the calendar aligned with the seasons so is much more difficult to work with. The most commonly used correlation factor is The '''GMT: 584283'''. Julian 584283 is a day count corresponding '''Mon, Aug 11, 3114 BCE''' in the Gregorian calendar, and the final day in the last Mayan long count cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan calendar. There is nothing in known Mayan writing or history that suggests that a long count "cycle" resets ''every'' 13 '''bak'tun'''. Judging by their other practices, it would make much more sense for it to reset at 20, if at all. The reason there was much interest at all, outside historical scholars, in the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri, Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy theorists to predict a cataclysmic "end-of-the-world" scenario. '''Excerpts taken from, and recommended reading:''' *''From the website of the Foundation for the Advancement of Meso-America Studies, Inc.'' Pitts, Mark. The complete Writing in Maya Glyphs Book 2 - Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19. http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf *wikipedia: Maya calendar *wikipedia: Mesoamerican Long Count calendar '''The Task:''' Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. ''If desired, support other correlations.'' Using the GMT correlation, the following Gregorian and Mayan dates are equivalent: '''Dec 21, 2012''' (Gregorian) '''4 Ajaw 3 K'ank'in G9''' (Calendar round) '''13.0.0.0.0''' (Long count) Support looking up dates for at least 50 years before and after the Mayan Long Count '''13 bak'tun''' rollover: ''Dec 21, 2012''. ''(Will require taking into account Gregorian leap days.)'' Show the output here, on this page, for ''at least'' the following dates: ''(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)'' 2004-06-19 2012-12-18 2012-12-21 2019-01-19 2019-03-27 2020-02-29 2020-03-01
package main import ( "fmt" "strconv" "strings" "time" ) var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw") var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’") var ( date1 = time.Date(2012, time.December, 21, 0, 0, 0, 0, time.UTC) date2 = time.Date(2019, time.April, 2, 0, 0, 0, 0, time.UTC) ) func tzolkin(date time.Time) (int, string) { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 13 if rem < 0 { rem = 13 + rem } var num int if rem <= 9 { num = rem + 4 } else { num = rem - 9 } rem = diff % 20 if rem <= 0 { rem = 20 + rem } return num, sacred[rem-1] } func haab(date time.Time) (string, string) { diff := int(date.Sub(date2).Hours()) / 24 rem := diff % 365 if rem < 0 { rem = 365 + rem } month := civil[(rem+1)/20] last := 20 if month == "Wayeb’" { last = 5 } d := rem%20 + 1 if d < last { return strconv.Itoa(d), month } return "Chum", month } func longCount(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 diff += 13 * 400 * 360 baktun := diff / (400 * 360) diff %= 400 * 360 katun := diff / (20 * 360) diff %= 20 * 360 tun := diff / 360 diff %= 360 winal := diff / 20 kin := diff % 20 return fmt.Sprintf("%d.%d.%d.%d.%d", baktun, katun, tun, winal, kin) } func lord(date time.Time) string { diff := int(date.Sub(date1).Hours()) / 24 rem := diff % 9 if rem <= 0 { rem = 9 + rem } return fmt.Sprintf("G%d", rem) } func main() { const shortForm = "2006-01-02" dates := []string{ "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", } fmt.Println(" Gregorian Tzolk’in Haab’ Long Lord of") fmt.Println(" Date # Name Day Month Count the Night") fmt.Println("---------- -------- ------------- -------------- ---------") for _, dt := range dates { date, _ := time.Parse(shortForm, dt) n, s := tzolkin(date) d, m := haab(date) lc := longCount(date) l := lord(date) fmt.Printf("%s %2d %-8s %4s %-9s %-14s %s\n", dt, n, s, d, m, lc, l) } }
McNuggets problem
Go
From Wikipedia: The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number of McDonald's Chicken McNuggets in any number of boxes. In the United Kingdom, the original boxes (prior to the introduction of the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets. ;Task: Calculate (from 0 up to a limit of 100) the largest non-McNuggets number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n'' where ''x'', ''y'' and ''z'' are natural numbers).
package main import "fmt" func mcnugget(limit int) { sv := make([]bool, limit+1) // all false by default for s := 0; s <= limit; s += 6 { for n := s; n <= limit; n += 9 { for t := n; t <= limit; t += 20 { sv[t] = true } } } for i := limit; i >= 0; i-- { if !sv[i] { fmt.Println("Maximum non-McNuggets number is", i) return } } } func main() { mcnugget(100) }
Memory layout of a data structure
Go
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity. Pin Settings for Plug (Reverse order for socket.) __________________________________________ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 _________________ 1 2 3 4 5 6 7 8 9 25 pin 9 pin 1 - PG Protective ground 2 - TD Transmitted data 3 3 - RD Received data 2 4 - RTS Request to send 7 5 - CTS Clear to send 8 6 - DSR Data set ready 6 7 - SG Signal ground 5 8 - CD Carrier detect 1 9 - + voltage (testing) 10 - - voltage (testing) 11 - 12 - SCD Secondary CD 13 - SCS Secondary CTS 14 - STD Secondary TD 15 - TC Transmit clock 16 - SRD Secondary RD 17 - RC Receiver clock 18 - 19 - SRS Secondary RTS 20 - DTR Data terminal ready 4 21 - SQD Signal quality detector 22 - RI Ring indicator 9 23 - DRS Data rate select 24 - XTC External clock 25 -
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota // Carrier detect RD9 // Received data TD9 // Transmitted data DTR9 // Data terminal ready SG9 // signal ground DSR9 // Data set ready RTS9 // Request to send CTS9 // Clear to send RI9 // Ring indicator ) func main() { // set some nonsense bits just for example p := RI9 | TD9 | CD9 fmt.Printf("Type=%T value=%#04x\n", p, p) }
Metallic ratios
Go
Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series of related ratios that are referred to as the "'''Metallic ratios'''". The '''Golden ratio''' was discovered and named by ancient civilizations as it was thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was also known to the early Greeks, though was not named so until later as a nod to the '''Golden ratio''' to which it is closely related. The series has been extended to encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means''). ''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".'' '''Metallic ratios''' are the real roots of the general form equation: x2 - bx - 1 = 0 where the integer '''b''' determines which specific one it is. Using the quadratic equation: ( -b +- (b2 - 4ac) ) / 2a = x Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get: ( b +- (b2 + 4) ) ) / 2 = x We only want the real root: ( b + (b2 + 4) ) ) / 2 = x When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''. ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''. ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5''' are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as standard. After that there isn't really any attempt at standardized names. They are given names here on this page, but consider the names fanciful rather than canonical. Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''. We will refer to it here as the '''Platinum ratio''', though it is kind-of a degenerate case. '''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions: [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] So, The first ten '''Metallic ratios''' are: :::::: {| class="wikitable" style="text-align: center;" |+ Metallic ratios !Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link |- |Platinum||0||(0 + 4) / 2|| 1||-||- |- |Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]] |- |Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]] |- |Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]] |- |Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]] |- |Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]] |- |Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]] |- |Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]] |- |Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]] |- |Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]] |} There are other ways to find the '''Metallic ratios'''; one, (the focus of this task) is through '''successive approximations of Lucas sequences'''. A traditional '''Lucas sequence''' is of the form: x''n'' = P * x''n-1'' - Q * x''n-2'' and starts with the first 2 values '''0, 1'''. For our purposes in this task, to find the metallic ratios we'll use the form: x''n'' = b * x''n-1'' + x''n-2'' ( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' At any rate, when '''b = 1''' we get: x''n'' = x''n-1'' + x''n-2'' 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... more commonly known as the Fibonacci sequence. When '''b = 2''': x''n'' = 2 * x''n-1'' + x''n-2'' 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393... And so on. To find the ratio by successive approximations, divide the ('''n+1''')th term by the '''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio. For '''b = 1''' (Fibonacci sequence): 1/1 = 1 2/1 = 2 3/2 = 1.5 5/3 = 1.666667 8/5 = 1.6 13/8 = 1.625 21/13 = 1.615385 34/21 = 1.619048 55/34 = 1.617647 89/55 = 1.618182 etc. It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest possible convergence for any irrational number. ;Task For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''': * Generate the corresponding "Lucas" sequence. * Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence. * Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places. * Show the '''value''' of the '''approximation''' at the required accuracy. * Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?). Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places. You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change. ;See also * Wikipedia: Metallic mean * Wikipedia: Lucas sequence
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0, x1 int64 = 1, 1 fmt.Printf("%d, %d", x0, x1) for i := 1; i <= 13; i++ { x2 := b*x1 + x0 fmt.Printf(", %d", x2) x0, x1 = x1, x2 } fmt.Println() } func metallic(b int64, dp int) { x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b) ratio := big.NewRat(1, 1) iters := 0 prev := ratio.FloatString(dp) for { iters++ x2.Mul(bb, x1) x2.Add(x2, x0) this := ratio.SetFrac(x2, x1).FloatString(dp) if prev == this { plural := "s" if iters == 1 { plural = " " } fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this) return } prev = this x0.Set(x1) x1.Set(x2) } } func main() { for b := int64(0); b < 10; b++ { lucas(b) metallic(b, 32) } fmt.Println("Golden ratio, where b = 1:") metallic(1, 256) }
Metaprogramming
Go
{{omit from|BBC BASIC}} Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) /* is := []int{1, 2, 3} it := make([]int, 3) copy(it, is) */ }
Metronome
Go
The task is to implement a metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. However, the playing of the sounds should not interfere with the timing of the metronome. The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
package main import ( "fmt" "time" ) func main() { var bpm = 72.0 // Beats Per Minute var bpb = 4 // Beats Per Bar d := time.Duration(float64(time.Minute) / bpm) fmt.Println("Delay:", d) t := time.NewTicker(d) i := 1 for _ = range t.C { i-- if i == 0 { i = bpb fmt.Printf("\nTICK ") } else { fmt.Printf("tick ") } } }
Mian-Chowla sequence
Go
The Mian-Chowla sequence is an integer sequence defined recursively. Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences. The sequence starts with: ::a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ::ai + aj is distinct, for all i and j less than or equal to n. ;The Task: :* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence. :* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence. Demonstrating working through the first few terms longhand: ::a1 = 1 ::1 + 1 = 2 Speculatively try a2 = 2 ::1 + 1 = 2 ::1 + 2 = 3 ::2 + 2 = 4 There are no repeated sums so '''2''' is the next number in the sequence. Speculatively try a3 = 3 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 3 = 4 ::2 + 2 = 4 ::2 + 3 = 5 ::3 + 3 = 6 Sum of '''4''' is repeated so '''3''' is rejected. Speculatively try a3 = 4 ::1 + 1 = 2 ::1 + 2 = 3 ::1 + 4 = 5 ::2 + 2 = 4 ::2 + 4 = 6 ::4 + 4 = 8 There are no repeated sums so '''4''' is the next number in the sequence. And so on... ;See also: :* OEIS:A005282 Mian-Chowla sequence
package main import "fmt" func contains(is []int, s int) bool { for _, i := range is { if s == i { return true } } return false } func mianChowla(n int) []int { mc := make([]int, n) mc[0] = 1 is := []int{2} var sum int for i := 1; i < n; i++ { le := len(is) jloop: for j := mc[i-1] + 1; ; j++ { mc[i] = j for k := 0; k <= i; k++ { sum = mc[k] + j if contains(is, sum) { is = is[0:le] continue jloop } is = append(is, sum) } break } } return mc } func main() { mc := mianChowla(100) fmt.Println("The first 30 terms of the Mian-Chowla sequence are:") fmt.Println(mc[0:30]) fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:") fmt.Println(mc[90:100]) }
Middle three digits
Go
Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error: 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345 1, 2, -1, -10, 2002, -2002, 0 Show your output on this page.
package m3_test import ( "testing" "m3" ) func TestPassing(t *testing.T) { type s struct { i int m string } tcs := []s{ {123, "123"}, {12345, "234"}, {1234567, "345"}, {987654321, "654"}, {10001, "000"}, {-10001, "000"}, } for _, tc := range tcs { m, err := m3.Digits(tc.i) if err != nil { t.Fatalf("d(%d) returned %q.", tc.i, err) } if m != tc.m { t.Fatalf("d(%d) expected %q, got %q.", tc.i, tc.m, m) } t.Logf("d(%d) = %q.", tc.i, m) } } func TestFailing(t *testing.T) { type s struct { i int err error } tcs := []s{ {1, m3.ErrorLT3}, {2, m3.ErrorLT3}, {-1, m3.ErrorLT3}, {-10, m3.ErrorLT3}, {2002, m3.ErrorEven}, {-2002, m3.ErrorEven}, {0, m3.ErrorLT3}, } for _, tc := range tcs { m, err := m3.Digits(tc.i) if err == nil { t.Fatal("d(%d) expected error %q, got non-error %q.", tc.i, tc.err, m) } if err != tc.err { t.Fatal("d(d) expected error %q, got %q", tc.i, tc.err, err) } t.Logf("d(%d) returns %q", tc.i, err) } }
Mind boggling card trick
Go
Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video. ; 1. Cards. # Create a common deck of cards of 52 cards (which are half red, half black). # Give the pack a good shuffle. ; 2. Deal from the shuffled deck, you'll be creating three piles. # Assemble the cards face down. ## Turn up the ''top card'' and hold it in your hand. ### if the card is black, then add the ''next'' card (unseen) to the "black" pile. ### If the card is red, then add the ''next'' card (unseen) to the "red" pile. ## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness). # Repeat the above for the rest of the shuffled deck. ; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles. # Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch. # Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch. # Put the "red" bunch into the "black" pile. # Put the "black" bunch into the "red" pile. # (The above two steps complete the swap of '''X''' cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows). ; 4. Order from randomness? # Verify (or not) the mathematician's assertion that: '''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.''' (Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.
package main import ( "fmt" "math/rand" "time" ) func main() { // Create pack, half red, half black and shuffle it. var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) // Deal from pack into 3 stacks. var red, black, discard []byte for i := 0; i < 51; i += 2 { switch pack[i] { case 'B': black = append(black, pack[i+1]) case 'R': red = append(red, pack[i+1]) } discard = append(discard, pack[i]) } lr, lb, ld := len(red), len(black), len(discard) fmt.Println("After dealing the cards the state of the stacks is:") fmt.Printf(" Red : %2d cards -> %c\n", lr, red) fmt.Printf(" Black : %2d cards -> %c\n", lb, black) fmt.Printf(" Discard: %2d cards -> %c\n", ld, discard) // Swap the same, random, number of cards between the red and black stacks. min := lr if lb < min { min = lb } n := 1 + rand.Intn(min) rp := rand.Perm(lr)[:n] bp := rand.Perm(lb)[:n] fmt.Printf("\n%d card(s) are to be swapped.\n\n", n) fmt.Println("The respective zero-based indices of the cards(s) to be swapped are:") fmt.Printf(" Red : %2d\n", rp) fmt.Printf(" Black : %2d\n", bp) for i := 0; i < n; i++ { red[rp[i]], black[bp[i]] = black[bp[i]], red[rp[i]] } fmt.Println("\nAfter swapping, the state of the red and black stacks is:") fmt.Printf(" Red : %c\n", red) fmt.Printf(" Black : %c\n", black) // Check that the number of black cards in the black stack equals // the number of red cards in the red stack. rcount, bcount := 0, 0 for _, c := range red { if c == 'R' { rcount++ } } for _, c := range black { if c == 'B' { bcount++ } } fmt.Println("\nThe number of red cards in the red stack =", rcount) fmt.Println("The number of black cards in the black stack =", bcount) if rcount == bcount { fmt.Println("So the asssertion is correct!") } else { fmt.Println("So the asssertion is incorrect!") } }
Minimal steps down to 1
Go
Given: * A starting, positive integer (greater than one), N. * A selection of possible integer perfect divisors, D. * And a selection of possible subtractors, S. The goal is find the minimum number of steps necessary to reduce N down to one. At any step, the number may be: * Divided by any member of D if it is perfectly divided by D, (remainder zero). * OR have one of S subtracted from it, if N is greater than the member of S. There may be many ways to reduce the initial N down to 1. Your program needs to: * Find the ''minimum'' number of ''steps'' to reach 1. * Show '''one''' way of getting fron N to 1 in those minimum steps. ;Examples: No divisors, D. a single subtractor of 1. :Obviousely N will take N-1 subtractions of 1 to reach 1 Single divisor of 2; single subtractor of 1: :N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1 :N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1 Divisors 2 and 3; subtractor 1: :N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1 ;Task: Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1: :1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :2. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2: :3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1. :4. Show a count of, and the numbers that: have the maximum minimal_steps_to_1, in the range 1 to 2,000. ;Optional stretch goal: :2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20_000 ;Reference: * Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string ) // Assumes the numbers are presented in order up to 'limit'. func minsteps(n int) { if n == 1 { mins[1] = []string{} return } min := limit var p, q int var op byte for _, div := range divs { if n%div == 0 { d := n / div steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, div, '/' } } } for _, sub := range subs { if d := n - sub; d >= 1 { steps := len(mins[d]) + 1 if steps < min { min = steps p, q, op = d, sub, '-' } } } mins[n] = append(mins[n], fmt.Sprintf("%c%d -> %d", op, q, p)) mins[n] = append(mins[n], mins[p]...) } func main() { for r := 0; r < 2; r++ { divs = []int{2, 3} if r == 0 { subs = []int{1} } else { subs = []int{2} } mins = make([][]string, limit+1) fmt.Printf("With: Divisors: %v, Subtractors: %v =>\n", divs, subs) fmt.Println(" Minimum number of steps to diminish the following numbers down to 1 is:") for i := 1; i <= limit; i++ { minsteps(i) if i <= 10 { steps := len(mins[i]) plural := "s" if steps == 1 { plural = " " } fmt.Printf(" %2d: %d step%s: %s\n", i, steps, plural, strings.Join(mins[i], ", ")) } } for _, lim := range []int{2000, 20000, 50000} { max := 0 for _, min := range mins[0 : lim+1] { m := len(min) if m > max { max = m } } var maxs []int for i, min := range mins[0 : lim+1] { if len(min) == max { maxs = append(maxs, i) } } nums := len(maxs) verb, verb2, plural := "are", "have", "s" if nums == 1 { verb, verb2, plural = "is", "has", "" } fmt.Printf(" There %s %d number%s in the range 1-%d ", verb, nums, plural, lim) fmt.Printf("that %s maximum 'minimal steps' of %d:\n", verb2, max) fmt.Println(" ", maxs) } fmt.Println() } }
Minkowski question-mark function
Go from FreeBASIC
The '''Minkowski question-mark function''' converts the continued fraction representation {{math|[a0; a1, a2, a3, ...]}} of a number into a binary decimal representation in which the integer part {{math|a0}} is unchanged and the {{math|a1, a2, ...}} become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place of the first zero. Thus, {{math|?}}(31/7) = 71/16 because 31/7 has the continued fraction representation {{math|[4;2,3]}} giving the binary expansion {{math|4 + 0.01112}}. Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits. The question-mark function is continuous and monotonically increasing, so it has an inverse. * Produce a function for {{math|?(x)}}. Be careful: rational numbers have two possible continued fraction representations: :::* {{math|[a0;a1,... an-1,an]}} and :::* {{math|[a0;a1,... an-1,an-1,1]}} * Choose one of the above that will give a binary expansion ending with a '''1'''. * Produce the inverse function {{math|?-1(x)}} * Verify that {{math|?(ph)}} = 5/3, where {{math|ph}} is the Greek golden ratio. * Verify that {{math|?-1(-5/9)}} = (13 - 7)/6 * Verify that the two functions are inverses of each other by showing that {{math|?-1(?(x))}}={{math|x}} and {{math|?(?-1(y))}}={{math|y}} for {{math|x, y}} of your choice Don't worry about precision error in the last few digits. ;See also: * Wikipedia entry: Minkowski's question-mark function
package main import ( "fmt" "math" ) const MAXITER = 151 func minkowski(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowski(x-math.Floor(x)) } p := uint64(x) q := uint64(1) r := p + 1 s := uint64(1) d := 1.0 y := float64(p) for { d = d / 2 if y+d == y { break } m := p + r if m < 0 || p < 0 { break } n := q + s if n < 0 { break } if x < float64(m)/float64(n) { r = m s = n } else { y = y + d p = m q = n } } return y + d } func minkowskiInv(x float64) float64 { if x > 1 || x < 0 { return math.Floor(x) + minkowskiInv(x-math.Floor(x)) } if x == 1 || x == 0 { return x } contFrac := []uint32{0} curr := uint32(0) count := uint32(1) i := 0 for { x *= 2 if curr == 0 { if x < 1 { count++ } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 1 x-- } } else { if x > 1 { count++ x-- } else { i++ t := contFrac contFrac = make([]uint32, i+1) copy(contFrac, t) contFrac[i-1] = count count = 1 curr = 0 } } if x == math.Floor(x) { contFrac[i] = count break } if i == MAXITER { break } } ret := 1.0 / float64(contFrac[i]) for j := i - 1; j >= 0; j-- { ret = float64(contFrac[j]) + 1.0/ret } return 1.0 / ret } func main() { fmt.Printf("%19.16f %19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0) fmt.Printf("%19.16f %19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6) fmt.Printf("%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)), minkowskiInv(minkowski(0.1213141516171819))) }