title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Modified random distribution
Go from Wren
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x) taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier: while True: random1 = rgen() random2 = rgen() if random2 < modifier(random1): answer = random1 break endif endwhile ;Task: * Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example: modifier(x) = 2*(0.5 - x) if x < 0.5 else 2*(x - 0.5) * Create a generator of random numbers with probabilities modified by the above function. * Generate >= 10,000 random numbers subject to the probability modification. * Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated. Show your output here, on this page.
package main import ( "fmt" "math" "math/rand" "strings" "time" ) func rng(modifier func(x float64) float64) float64 { for { r1 := rand.Float64() r2 := rand.Float64() if r2 < modifier(r1) { return r1 } } } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { rand.Seed(time.Now().UnixNano()) modifier := func(x float64) float64 { if x < 0.5 { return 2 * (0.5 - x) } return 2 * (x - 0.5) } const ( N = 100000 NUM_BINS = 20 HIST_CHAR = "■" HIST_CHAR_SIZE = 125 ) bins := make([]int, NUM_BINS) // all zero by default binSize := 1.0 / NUM_BINS for i := 0; i < N; i++ { rn := rng(modifier) bn := int(math.Floor(rn / binSize)) bins[bn]++ } fmt.Println("Modified random distribution with", commatize(N), "samples in range [0, 1):\n") fmt.Println(" Range Number of samples within that range") for i := 0; i < NUM_BINS; i++ { hist := strings.Repeat(HIST_CHAR, int(math.Round(float64(bins[i])/HIST_CHAR_SIZE))) fi := float64(i) fmt.Printf("%4.2f ..< %4.2f %s %s\n", binSize*fi, binSize*(fi+1), hist, commatize(bins[i])) } }
Modular arithmetic
Go
equivalence relation called ''congruence''. For any positive integer p called the ''congruence modulus'', two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: :a = b + k\,p The corresponding set of multiplicative inverse for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. The purpose of this task is to show, if your programming language allows it, how to redefine operators so that they can be used transparently on modular integers. You can do it either by using a dedicated library, or by implementing your own class. You will use the following function for demonstration: :f(x) = x^{100} + x + 1 You will use 13 as the congruence modulus and you will compute f(10). It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.
package main import "fmt" // Define enough of a ring to meet the needs of the task. Addition and // multiplication are mentioned in the task; multiplicative identity is not // mentioned but is useful for the power function. type ring interface { add(ringElement, ringElement) ringElement mul(ringElement, ringElement) ringElement mulIdent() ringElement } type ringElement interface{} // Define a power function that works for any ring. func ringPow(r ring, a ringElement, p uint) (pow ringElement) { for pow = r.mulIdent(); p > 0; p-- { pow = r.mul(pow, a) } return } // The task function f has that constant 1 in it. // Define a special kind of ring that has this element. type oneRing interface { ring one() ringElement // return ring element corresponding to '1' } // Now define the required function f. // It works for any ring (that has a "one.") func f(r oneRing, x ringElement) ringElement { return r.add(r.add(ringPow(r, x, 100), x), r.one()) } // With rings and the function f defined in a general way, now define // the specific ring of integers modulo n. type modRing uint // value is congruence modulus n func (m modRing) add(a, b ringElement) ringElement { return (a.(uint) + b.(uint)) % uint(m) } func (m modRing) mul(a, b ringElement) ringElement { return (a.(uint) * b.(uint)) % uint(m) } func (modRing) mulIdent() ringElement { return uint(1) } func (modRing) one() ringElement { return uint(1) } // Demonstrate the general function f on the specific ring with the // specific values. func main() { fmt.Println(f(modRing(13), uint(10))) }
Modular exponentiation
Go
Find the last '''40''' decimal digits of a^b, where ::* a = 2988348162058574136915891421498819466320163312926952423791023078876139 ::* b = 2351399303373464486466122544523690094744975233415544072992656881240319 A computer is too slow to find the entire value of a^b. Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m. The algorithm must work for any integers a, b, m, where b \ge 0 and m > 0.
package main import ( "fmt" "math/big" ) func main() { a, _ := new(big.Int).SetString( "2988348162058574136915891421498819466320163312926952423791023078876139", 10) b, _ := new(big.Int).SetString( "2351399303373464486466122544523690094744975233415544072992656881240319", 10) m := big.NewInt(10) r := big.NewInt(40) m.Exp(m, r, nil) r.Exp(a, b, m) fmt.Println(r) }
Modular inverse
Go
From Wikipedia: In modulo ''m'' is an integer ''x'' such that ::a\,x \equiv 1 \pmod{m}. Or in other words, such that: ::\exists k \in\Z,\qquad a\, x = 1 + k\,m It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task. ;Task: Either by implementing the algorithm, by using a dedicated library or by using a built-in function in your language, compute the modular inverse of 42 modulo 2017.
package main import ( "fmt" "math/big" ) func main() { a := big.NewInt(42) m := big.NewInt(2017) k := new(big.Int).ModInverse(a, m) fmt.Println(k) }
Monads/List monad
Go
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping. Demonstrate in your programming language the following: #Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String #Compose the two functions with bind
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } return unit(lst2) } func double(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = 2 * v } return unit(lst2) } func main() { ml1 := unit([]int{3, 4, 5}) ml2 := ml1.bind(increment).bind(double) fmt.Printf("%v -> %v\n", ml1.value, ml2.value) }
Monads/Maybe monad
Go
Demonstrate in your programming language the following: #Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) #Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String #Compose the two functions with bind A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time. A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
package main import ( "fmt" "strconv" ) type maybe struct{ value *int } func (m maybe) bind(f func(p *int) maybe) maybe { return f(m.value) } func unit(p *int) maybe { return maybe{p} } func decrement(p *int) maybe { if p == nil { return unit(nil) } else { q := *p - 1 return unit(&q) } } func triple(p *int) maybe { if p == nil { return unit(nil) } else { q := (*p) * 3 return unit(&q) } } func main() { i, j, k := 3, 4, 5 for _, p := range []*int{&i, &j, nil, &k} { m1 := unit(p) m2 := m1.bind(decrement).bind(triple) var s1, s2 string = "none", "none" if m1.value != nil { s1 = strconv.Itoa(*m1.value) } if m2.value != nil { s2 = strconv.Itoa(*m2.value) } fmt.Printf("%4s -> %s\n", s1, s2) } }
Monads/Writer monad
Go from Kotlin
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming language the following: # Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides) # Write three simple functions: root, addOne, and half # Derive Writer monad versions of each of these functions # Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
package main import ( "fmt" "math" ) type mwriter struct { value float64 log string } func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n } func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)} } func root(v float64) mwriter { return unit(math.Sqrt(v), "Took square root") } func addOne(v float64) mwriter { return unit(v+1, "Added one") } func half(v float64) mwriter { return unit(v/2, "Divided by two") } func main() { mw1 := unit(5, "Initial value") mw2 := mw1.bind(root).bind(addOne).bind(half) fmt.Println("The Golden Ratio is", mw2.value) fmt.Println("\nThis was derived as follows:-") fmt.Println(mw2.log) }
Move-to-front algorithm
Go from Python
Given a symbol table of a ''zero-indexed'' array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms. ;Encoding algorithm: for each symbol of the input sequence: output the index of the symbol in the symbol table move that symbol to the front of the symbol table ;Decoding algorithm: # Using the same starting symbol table for each index of the input sequence: output the symbol at that index of the symbol table move that symbol to the front of the symbol table ;Example: Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z''' :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''b'''roood | 1 | 'abcdefghijklmnopqrstuvwxyz' |- | b'''r'''oood | 1 17 | 'bacdefghijklmnopqrstuvwxyz' |- | br'''o'''ood | 1 17 15 | 'rbacdefghijklmnopqstuvwxyz' |- | bro'''o'''od | 1 17 15 0 | 'orbacdefghijklmnpqstuvwxyz' |- | broo'''o'''d | 1 17 15 0 0 | 'orbacdefghijklmnpqstuvwxyz' |- | brooo'''d''' | 1 17 15 0 0 5 | 'orbacdefghijklmnpqstuvwxyz' |} Decoding the indices back to the original symbol order: :::::{| class="wikitable" border="1" |- ! Input ! Output ! SymbolTable |- | '''1''' 17 15 0 0 5 | b | 'abcdefghijklmnopqrstuvwxyz' |- | 1 '''17''' 15 0 0 5 | br | 'bacdefghijklmnopqrstuvwxyz' |- | 1 17 '''15''' 0 0 5 | bro | 'rbacdefghijklmnopqstuvwxyz' |- | 1 17 15 '''0''' 0 5 | broo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 '''0''' 5 | brooo | 'orbacdefghijklmnpqstuvwxyz' |- | 1 17 15 0 0 '''5''' | broood | 'orbacdefghijklmnpqstuvwxyz' |} ;Task: :* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. :* Show the strings and their encoding here. :* Add a check to ensure that the decoded string is the same as the original. The strings are: broood bananaaa hiphophiphop (Note the misspellings in the above strings.)
package main import ( "bytes" "fmt" ) type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq } func (symbols symbolTable) decode(seq []byte) string { chars := make([]byte, len(seq)) pad := []byte(symbols) for i, x := range seq { c := pad[x] chars[i] = c copy(pad[1:], pad[:x]) pad[0] = c } return string(chars) } func main() { m := symbolTable("abcdefghijklmnopqrstuvwxyz") for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} { enc := m.encode(s) dec := m.decode(enc) fmt.Println(s, enc, dec) if dec != s { panic("Whoops!") } } }
Multi-dimensional array
Go
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: # State the number and extent of each index to the array. # Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. # Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position. ;Task: * State if the language supports multi-dimensional arrays in its syntax and usual implementation. * State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage. * Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred. :* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice). * State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated. * If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them. Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
package main import "fmt" type md struct { dim []int ele []float64 } func newMD(dim ...int) *md { n := 1 for _, d := range dim { n *= d } return &md{append([]int{}, dim...), make([]float64, n)} } func (m *md) index(i ...int) (x int) { for d, dx := range m.dim { x = x*dx + i[d] } return } func (m *md) at(i ...int) float64 { return m.ele[m.index(i...)] } func (m *md) set(x float64, i ...int) { m.ele[m.index(i...)] = x } func (m *md) show(i ...int) { fmt.Printf("m%d = %g\n", i, m.at(i...)) } func main() { m := newMD(5, 4, 3, 2) m.show(4, 3, 2, 1) m.set(87, 4, 3, 2, 1) m.show(4, 3, 2, 1) for i := 0; i < m.dim[0]; i++ { for j := 0; j < m.dim[1]; j++ { for k := 0; k < m.dim[2]; k++ { for l := 0; l < m.dim[3]; l++ { x := m.index(i, j, k, l) m.set(float64(x)+.1, i, j, k, l) } } } } fmt.Println(m.ele[:10]) fmt.Println(m.ele[len(m.ele)-10:]) m.show(4, 3, 2, 1) }
Multifactorial
Go
The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1). Multifactorials generalize factorials as follows: : n! = n(n-1)(n-2)...(2)(1) : n!! = n(n-2)(n-4)... : n!! ! = n(n-3)(n-6)... : n!! !! = n(n-4)(n-8)... : n!! !! ! = n(n-5)(n-10)... In all cases, the terms in the products are positive integers. If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: # Write a function that given n and the degree, calculates the multifactorial. # Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. '''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
package main import "fmt" func multiFactorial(n, k int) int { r := 1 for ; n > 1; n -= k { r *= n } return r } func main() { for k := 1; k <= 5; k++ { fmt.Print("degree ", k, ":") for n := 1; n <= 10; n++ { fmt.Print(" ", multiFactorial(n, k)) } fmt.Println() } }
Multiple distinct objects
Go
Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize. By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type. This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary. This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages). See also: [[Closures/Value capture]]
func nxm(n, m int) [][]int { d1 := make([]int, m) d2 := make([][]int, n) for i := range d2 { d2[i] = d1 } return d2 }
Multisplit
Go
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=". For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. '''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
package main import ( "fmt" "strings" ) func ms(txt string, sep []string) (ans []string) { for txt > "" { sepMatch := "" posMatch := len(txt) for _, s := range sep { if p := strings.Index(txt, s); p >= 0 && p < posMatch { sepMatch = s posMatch = p } } ans = append(ans, txt[:posMatch]) txt = txt[posMatch+len(sepMatch):] } return } func main() { fmt.Printf("%q\n", ms("a!===b=!=c", []string{"==", "!=", "="})) }
Munchausen numbers
Go from Kotlin
A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''. ('''Munchausen''' is also spelled: '''Munchhausen'''.) For instance: 3435 = 33 + 44 + 33 + 55 ;Task Find all Munchausen numbers between '''1''' and '''5000'''. ;Also see: :* The OEIS entry: A046253 :* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
package main import( "fmt" "math" ) var powers [10]int func isMunchausen(n int) bool { if n < 0 { return false } n64 := int64(n) nn := n64 var sum int64 = 0 for nn > 0 { sum += int64(powers[nn % 10]) if sum > n64 { return false } nn /= 10 } return sum == n64 } func main() { // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose for i := 1; i <= 9; i++ { d := float64(i) powers[i] = int(math.Pow(d, d)) } // check numbers 0 to 500 million fmt.Println("The Munchausen numbers between 0 and 500 million are:") for i := 0; i <= 500000000; i++ { if isMunchausen(i) { fmt.Printf("%d ", i) } } fmt.Println() }
Musical scale
Go from Sparkling
Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege. For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed. For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
package main import ( "encoding/binary" "log" "math" "os" "strings" ) func main() { const ( sampleRate = 44100 duration = 8 dataLength = sampleRate * duration hdrSize = 44 fileLen = dataLength + hdrSize - 8 ) // buffers buf1 := make([]byte, 1) buf2 := make([]byte, 2) buf4 := make([]byte, 4) // WAV header var sb strings.Builder sb.WriteString("RIFF") binary.LittleEndian.PutUint32(buf4, fileLen) sb.Write(buf4) // file size - 8 sb.WriteString("WAVE") sb.WriteString("fmt ") binary.LittleEndian.PutUint32(buf4, 16) sb.Write(buf4) // length of format data (= 16) binary.LittleEndian.PutUint16(buf2, 1) sb.Write(buf2) // type of format (= 1 (PCM)) sb.Write(buf2) // number of channels (= 1) binary.LittleEndian.PutUint32(buf4, sampleRate) sb.Write(buf4) // sample rate sb.Write(buf4) // sample rate * bps(8) * channels(1) / 8 (= sample rate) sb.Write(buf2) // bps(8) * channels(1) / 8 (= 1) binary.LittleEndian.PutUint16(buf2, 8) sb.Write(buf2) // bits per sample (bps) (= 8) sb.WriteString("data") binary.LittleEndian.PutUint32(buf4, dataLength) sb.Write(buf4) // size of data section wavhdr := []byte(sb.String()) // write WAV header f, err := os.Create("notes.wav") if err != nil { log.Fatal(err) } defer f.Close() f.Write(wavhdr) // compute and write actual data freqs := [8]float64{261.6, 293.6, 329.6, 349.2, 392.0, 440.0, 493.9, 523.3} for j := 0; j < duration; j++ { freq := freqs[j] omega := 2 * math.Pi * freq for i := 0; i < dataLength/duration; i++ { y := 32 * math.Sin(omega*float64(i)/float64(sampleRate)) buf1[0] = byte(math.Round(y)) f.Write(buf1) } } }
Mutex
Go from E
{{requires|Concurrency}} A '''mutex''' (''abbreviated'' '''Mut'''ually '''Ex'''clusive access) is a synchronization object, a variant of [[semaphore]] with ''k''=1. A mutex is said to be seized by a [[task]] decreasing ''k''. It is released when the task restores ''k''. Mutexes are typically used to protect a shared resource from concurrent access. A [[task]] seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex. A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order). Entering the deadlock is usually aggravated by a [[race condition]] state, which leads to sporadic hangups, which are very difficult to track down. =Variants of mutexes= ==Global and local mutexes== Usually the [[OS]] provides various implementations of mutexes corresponding to the variants of [[task]]s available in the OS. For example, system-wide mutexes can be used by [[process]]es. Local mutexes can be used only by [[threads]] etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one. ==Reentrant mutex== A reentrant mutex can be seized by the same [[task]] multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it. ==Read write mutex== A read write mutex can be seized at two levels for ''read'' and for ''write''. The mutex can be seized for ''read'' by any number of tasks. Only one task may seize it for '''write''. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a [[task]] that has seized the mutex for ''write'' releases it while keeping seized for ''read''. Note that the reverse operation is potentially deadlocking and requires some additional access policy control. =Deadlock prevention= There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the [[Dining philosophers]] problem. =Sample implementations / APIs=
package main import ( "fmt" "sync" "time" ) var value int var m sync.Mutex var wg sync.WaitGroup func slowInc() { m.Lock() v := value time.Sleep(1e8) value = v+1 m.Unlock() wg.Done() } func main() { wg.Add(2) go slowInc() go slowInc() wg.Wait() fmt.Println(value) }
N-queens problem
Go
right Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''. For the number of solutions for small values of '''N''', see OEIS: A000170. ;Related tasks: * [[A* search algorithm]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Knight's tour]] * [[Peaceful chess queen armies]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
// A fairly literal translation of the example program on the referenced // WP page. Well, it happened to be the example program the day I completed // the task. It seems from the WP history that there has been some churn // in the posted example program. The example program of the day was in // Pascal and was credited to Niklaus Wirth, from his "Algorithms + // Data Structures = Programs." package main import "fmt" var ( i int q bool a [9]bool b [17]bool c [15]bool // offset by 7 relative to the Pascal version x [9]int ) func try(i int) { for j := 1; ; j++ { q = false if a[j] && b[i+j] && c[i-j+7] { x[i] = j a[j] = false b[i+j] = false c[i-j+7] = false if i < 8 { try(i + 1) if !q { a[j] = true b[i+j] = true c[i-j+7] = true } } else { q = true } } if q || j == 8 { break } } } func main() { for i := 1; i <= 8; i++ { a[i] = true } for i := 2; i <= 16; i++ { b[i] = true } for i := 0; i <= 14; i++ { c[i] = true } try(1) if q { for i := 1; i <= 8; i++ { fmt.Println(i, x[i]) } } }
Narcissist
Go
Quoting from the Esolangs wiki page: A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]]. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not. For concreteness, in this task we shall assume that symbol = character. The narcissist should be able to cope with any finite input, whatever its length. Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
package main; import "os"; import "fmt"; import "bytes"; import "io/ioutil"; func main() {ios := "os"; ifmt := "fmt"; ibytes := "bytes"; iioutil := "io/ioutil"; zero := "Reject"; one := "Accept"; x := "package main; import %q; import %q; import %q; import %q; func main() {ios := %q; ifmt := %q; ibytes := %q; iioutil := %q; zero := %q; one := %q; x := %q; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}\n"; s := fmt.Sprintf(x, ios, ifmt, ibytes, iioutil, ios, ifmt, ibytes, iioutil, zero, one, x); in, _ := ioutil.ReadAll(os.Stdin); if bytes.Equal(in, []byte(s)) {fmt.Println(one);} else {fmt.Println(zero);};}
Narcissistic decimal number
Go
A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. They are also known as '''Plus Perfect''' numbers. ;An example: ::::* if n is '''153''' ::::* then m, (the number of decimal digits) is '''3''' ::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' ::::* and so '''153''' is a narcissistic decimal number ;Task: Generate and show here the first '''25''' narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. ;See also: * the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers. * MathWorld entry: Narcissistic Number. * Wikipedia entry: Narcissistic number.
package main import "fmt" func narc(n int) []int { power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} limit := 10 result := make([]int, 0, n) for x := 0; len(result) < n; x++ { if x >= limit { for i := range power { power[i] *= i // i^m } limit *= 10 } sum := 0 for xx := x; xx > 0; xx /= 10 { sum += power[xx%10] } if sum == x { result = append(result, x) } } return result } func main() { fmt.Println(narc(25)) }
Nautical bell
Go
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type. ;Related task: * [[Sleep]]
package main import ( "fmt" "strings" "time" ) func main() { watches := []string{ "First", "Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First", } for { t := time.Now() h := t.Hour() m := t.Minute() s := t.Second() if (m == 0 || m == 30) && s == 0 { bell := 0 if m == 30 { bell = 1 } bells := (h*2 + bell) % 8 watch := h/4 + 1 if bells == 0 { bells = 8 watch-- } sound := strings.Repeat("\a", bells) pl := "s" if bells == 1 { pl = " " } w := watches[watch] + " watch" if watch == 5 { if bells < 5 { w = "First " + w } else { w = "Last " + w } } fmt.Printf("%s%02d:%02d = %d bell%s : %s\n", sound, h, m, bells, pl, w) } time.Sleep(1 * time.Second) } }
Negative base numbers
Go from Kotlin
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia ;Task: *Encode the decimal number 10 as negabinary (expect 11110) *Encode the decimal number 146 as negaternary (expect 21102) *Encode the decimal number 15 as negadecimal (expect 195) *In each of the above cases, convert the encoded number back to decimal. ;extra credit: * supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
package main import ( "fmt" "log" "strings" ) const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" func reverse(bs []byte) []byte { for i, j := 0, len(bs)-1; i < len(bs)/2; i, j = i+1, j-1 { bs[i], bs[j] = bs[j], bs[i] } return bs } func encodeNegBase(n, b int64) (string, error) { if b < -62 || b > -1 { return "", fmt.Errorf("base must be between -62 and -1 inclusive") } if n == 0 { return "0", nil } var out []byte for n != 0 { rem := n % b n /= b if rem < 0 { n++ rem -= b } out = append(out, digits[int(rem)]) } reverse(out) return string(out), nil } func decodeNegBase(ns string, b int64) (int64, error) { if b < -62 || b > -1 { return 0, fmt.Errorf("base must be between -62 and -1 inclusive") } if ns == "0" { return 0, nil } total := int64(0) bb := int64(1) bs := []byte(ns) reverse(bs) for _, c := range bs { total += int64(strings.IndexByte(digits, c)) * bb bb *= b } return total, nil } func main() { numbers := []int64{10, 146, 15, -942, 1488588316238} bases := []int64{-2, -3, -10, -62, -62} for i := 0; i < len(numbers); i++ { n := numbers[i] b := bases[i] ns, err := encodeNegBase(n, b) if err != nil { log.Fatal(err) } fmt.Printf("%13d encoded in base %-3d = %s\n", n, b, ns) n, err = decodeNegBase(ns, b) if err != nil { log.Fatal(err) } fmt.Printf("%13s decoded in base %-3d = %d\n\n", ns, b, n) } }
Nested function
Go
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. ;Task: Write a program consisting of two nested functions that prints the following text. 1. first 2. second 3. third The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function. The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter. ;References: :* Nested function
package main import "fmt" func makeList(separator string) string { counter := 1 makeItem := func(item string) string { result := fmt.Sprintf("%d%s%s\n", counter, separator, item) counter += 1 return result } return makeItem("first") + makeItem("second") + makeItem("third") } func main() { fmt.Print(makeList(". ")) }
Nested templated data
Go
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. ;Task Detail: Given the following input template t and list of payloads p: # Square brackets are used here to denote nesting but may be changed for other, # clear, visual representations of nested data appropriate to ones programming # language. t = [ [[1, 2], [3, 4, 1], 5]] p = 'Payload#0' ... 'Payload#6' The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow): [[['Payload#1', 'Payload#2'], ['Payload#3', 'Payload#4', 'Payload#1'], 'Payload#5']] 1. Generate the output for the above template, t. ;Optional Extended tasks: 2. Show which payloads remain unused. 3. Give some indication/handling of indices without a payload. ''Show output on this page.''
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ 0: "'Payload#0'", 1: "'Payload#1'", 2: "'Payload#2'", 3: "'Payload#3'", 4: "'Payload#4'", 5: "'Payload#5'", 6: "'Payload#6'", } tmpl := template.Must(template.New("").Parse(t)) tmpl.Execute(os.Stdout, s) var unused []int for k, _ := range s.P { if !strings.Contains(t, fmt.Sprintf("{{index .P %d}}", k)) { unused = append(unused, k) } } sort.Ints(unused) fmt.Println("\nThe unused payloads have indices of :", unused) }
Next highest int from digits
Go
Given a zero or positive integer, the task is to generate the next largest integer using only the given digits*1. * Numbers will not be padded to the left with zeroes. * Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result). * If there is no next highest integer return zero. :*1 Alternatively phrased as: "Find the smallest integer larger than the (positive or zero) integer '''N''' :: which can be obtained by reordering the (base ten) digits of '''N'''". ;Algorithm 1: # Generate all the permutations of the digits and sort into numeric order. # Find the number in the list. # Return the next highest number from the list. The above could prove slow and memory hungry for numbers with large numbers of digits, but should be easy to reason about its correctness. ;Algorithm 2: # Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it. # Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it. # Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) '''E.g.:''' n = 12453 12_4_53 12_5_43 12_5_34 return: 12534 This second algorithm is faster and more memory efficient, but implementations may be harder to test. One method of testing, (as used in developing the task), is to compare results from both algorithms for random numbers generated from a range that the first algorithm can handle. ;Task requirements: Calculate the next highest int from the digits of the following numbers: :* 0 :* 9 :* 12 :* 21 :* 12453 :* 738440 :* 45072010 :* 95322020 ;Optional stretch goal: :* 9589776899767587796600
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) // recursive closure rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := np - 1 pp := len(b) - np1 rc(np1) for i := pp; i > 0; i-- { b[i], b[i-1] = b[i-1], b[i] rc(np1) } w := b[0] copy(b, b[1:pp+1]) b[pp] = w } rc(len(b)) return res } func algorithm1(nums []string) { fmt.Println("Algorithm 1") fmt.Println("-----------") for _, num := range nums { perms := permute(num) le := len(perms) if le == 0 { // ignore blanks continue } sort.Strings(perms) ix := sort.SearchStrings(perms, num) next := "" if ix < le-1 { for i := ix + 1; i < le; i++ { if perms[i] > num { next = perms[i] break } } } if len(next) > 0 { fmt.Printf("%29s -> %s\n", commatize(num), commatize(next)) } else { fmt.Printf("%29s -> 0\n", commatize(num)) } } fmt.Println() } func algorithm2(nums []string) { fmt.Println("Algorithm 2") fmt.Println("-----------") outer: for _, num := range nums { b := []byte(num) le := len(b) if le == 0 { // ignore blanks continue } max := num[le-1] mi := le - 1 for i := le - 2; i >= 0; i-- { if b[i] < max { min := max - b[i] for j := mi + 1; j < le; j++ { min2 := b[j] - b[i] if min2 > 0 && min2 < min { min = min2 mi = j } } b[i], b[mi] = b[mi], b[i] c := (b[i+1:]) sort.Slice(c, func(i, j int) bool { return c[i] < c[j] }) next := string(b[0:i+1]) + string(c) fmt.Printf("%29s -> %s\n", commatize(num), commatize(next)) continue outer } else if b[i] > max { max = num[i] mi = i } } fmt.Printf("%29s -> 0\n", commatize(num)) } } 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() { nums := []string{"0", "9", "12", "21", "12453", "738440", "45072010", "95322020", "9589776899767587796600"} algorithm1(nums[:len(nums)-1]) // exclude the last one algorithm2(nums) // include the last one }
Nim game
Go
Nim is a simple game where the second player-if they know the trick-will always win. The game has only 3 rules: ::* start with '''12''' tokens ::* each player takes '''1, 2, or 3''' tokens in turn ::* the player who takes the last token wins. To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. ;Task: Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
package main import ( "bufio" "fmt" "os" "strconv" ) func showTokens(tokens int) { fmt.Println("Tokens remaining", tokens, "\n") } func main() { tokens := 12 scanner := bufio.NewScanner(os.Stdin) for { showTokens(tokens) fmt.Print(" How many tokens 1, 2 or 3? ") scanner.Scan() if scerr := scanner.Err(); scerr != nil { fmt.Println("Error reading standard input:", scerr) return } t, err := strconv.Atoi(scanner.Text()) if err != nil || t < 1 || t > 3 { fmt.Println("\nMust be a number between 1 and 3, try again.\n") } else { ct := 4 - t s := "s" if ct == 1 { s = "" } fmt.Print(" Computer takes ", ct, " token", s, "\n\n") tokens -= 4 } if tokens == 0 { showTokens(0) fmt.Println(" Computer wins!") return } } }
Non-transitive dice
Go from Wren
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the number of faces and the numbers on each face). Throwing dice will randomly select a face on each die with equal probability. To show which die of dice thrown multiple times is more likely to win over the others: # calculate all possible combinations of different faces from each die # Count how many times each die wins a combination # Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice. '''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively. ''' ;Example 1: If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its faces then the equal possibility outcomes from throwing both, and the winners is: X Y Winner = = ====== 1 2 Y 1 3 Y 1 4 Y 3 2 X 3 3 - 3 4 Y 6 2 X 6 3 X 6 4 X TOTAL WINS: X=4, Y=4 Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y ;Transitivity: In mathematics transitivity are rules like: if a op b and b op c then a op c If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers we get the familiar if a < b and b < c then a < c ;Non-transitive dice These are an ordered list of dice where the '>' operation between successive dice pairs applies but a comparison between the first and last of the list yields the opposite result, '<'. ''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).'' Three dice S, T, U with appropriate face values could satisfy S < T, T < U and yet S > U To be non-transitive. ;Notes: * The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms). * A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4 * '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions. ;Task: ;==== Find all the ordered lists of ''three'' non-transitive dice S, T, U of the form S < T, T < U and yet S > U; where the dice are selected from all ''four-faced die'' , (unique w.r.t the notes), possible by having selections from the integers ''one to four'' on any dies face. Solution can be found by generating all possble individual die then testing all possible permutations, (permutations are ordered), of three dice for non-transitivity. ;Optional stretch goal: Find lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal. Show the results here, on this page. ;References: * The Most Powerful Dice - Numberphile Video. * Nontransitive dice - Wikipedia.
package main import ( "fmt" "sort" ) func fourFaceCombs() (res [][4]int) { found := make([]bool, 256) for i := 1; i <= 4; i++ { for j := 1; j <= 4; j++ { for k := 1; k <= 4; k++ { for l := 1; l <= 4; l++ { c := [4]int{i, j, k, l} sort.Ints(c[:]) key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1) if !found[key] { found[key] = true res = append(res, c) } } } } } return } func cmp(x, y [4]int) int { xw := 0 yw := 0 for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { if x[i] > y[j] { xw++ } else if y[j] > x[i] { yw++ } } } if xw < yw { return -1 } else if xw > yw { return 1 } return 0 } func findIntransitive3(cs [][4]int) (res [][3][4]int) { var c = len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[i], cs[k]) if third == 1 { res = append(res, [3][4]int{cs[i], cs[j], cs[k]}) } } } } } } return } func findIntransitive4(cs [][4]int) (res [][4][4]int) { c := len(cs) for i := 0; i < c; i++ { for j := 0; j < c; j++ { for k := 0; k < c; k++ { for l := 0; l < c; l++ { first := cmp(cs[i], cs[j]) if first == -1 { second := cmp(cs[j], cs[k]) if second == -1 { third := cmp(cs[k], cs[l]) if third == -1 { fourth := cmp(cs[i], cs[l]) if fourth == 1 { res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]}) } } } } } } } } return } func main() { combs := fourFaceCombs() fmt.Println("Number of eligible 4-faced dice", len(combs)) it3 := findIntransitive3(combs) fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3)) for _, a := range it3 { fmt.Println(a) } it4 := findIntransitive4(combs) fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4)) for _, a := range it4 { fmt.Println(a) } }
Nonoblock
Go from Kotlin
Nonogram puzzle. ;Given: * The number of cells in a row. * The size of each, (space separated), connected block of cells to fit in the row, in left-to right order. ;Task: * show all possible positions. * show the number of positions of the blocks for the following cases within the row. * show all output on this page. * use a "neat" diagram of the block positions. ;Enumerate the following configurations: # '''5''' cells and '''[2, 1]''' blocks # '''5''' cells and '''[]''' blocks (no blocks) # '''10''' cells and '''[8]''' blocks # '''15''' cells and '''[2, 3, 2, 3]''' blocks # '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible) ;Example: Given a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as: |_|_|_|_|_| # 5 cells and [2, 1] blocks And would expand to the following 3 possible rows of block positions: |A|A|_|B|_| |A|A|_|_|B| |_|A|A|_|B| Note how the sets of blocks are always separated by a space. Note also that it is not necessary for each block to have a separate letter. Output approximating This: |#|#|_|#|_| |#|#|_|_|#| |_|#|#|_|#| This would also work: ##.#. ##..# .##.# ;An algorithm: * Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember). * The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks. * for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block. (This is the algorithm used in the [[Nonoblock#Python]] solution). ;Reference: * The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
package main import ( "fmt" "strings" ) func printBlock(data string, le int) { a := []byte(data) sumBytes := 0 for _, b := range a { sumBytes += int(b - 48) } fmt.Printf("\nblocks %c, cells %d\n", a, le) if le-sumBytes <= 0 { fmt.Println("No solution") return } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-48)) } for _, r := range genSequence(prep, le-sumBytes+1) { fmt.Println(r[1:]) } } func genSequence(ones []string, numZeros int) []string { if len(ones) == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-len(ones)+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } func main() { printBlock("21", 5) printBlock("", 5) printBlock("8", 10) printBlock("2323", 15) printBlock("23", 5) }
Nonogram solver
Go from Java
nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only these lengths you should find one valid configuration of empty and occupied cells, or show a failure message. ;Example Problem: Solution: . . . . . . . . 3 . # # # . . . . 3 . . . . . . . . 2 1 # # . # . . . . 2 1 . . . . . . . . 3 2 . # # # . . # # 3 2 . . . . . . . . 2 2 . . # # . . # # 2 2 . . . . . . . . 6 . . # # # # # # 6 . . . . . . . . 1 5 # . # # # # # . 1 5 . . . . . . . . 6 # # # # # # . . 6 . . . . . . . . 1 . . . . # . . . 1 . . . . . . . . 2 . . . # # . . . 2 1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3 2 1 5 1 2 1 5 1 The problem above could be represented by two lists of lists: x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]] y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]] A more compact representation of the same problem uses strings, where the letters represent the numbers, A=1, B=2, etc: x = "C BA CB BB F AE F A B" y = "AB CA AE GA E C D C" ;Task For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content (the blank lines are separators): C BA CB BB F AE F A B AB CA AE GA E C D C F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM '''Extra credit''': generate nonograms with unique solutions, of desired height and width. This task is the problem n.98 of the "99 Prolog Problems" by Werner Hett (also thanks to Paul Singleton for the idea and the examples). ; Related tasks * [[Nonoblock]]. ;See also * Arc Consistency Algorithm * http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell) * http://twanvl.nl/blog/haskell/Nonograms (Haskell) * http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
package main import ( "fmt" "strings" ) type BitSet []bool func (bs BitSet) and(other BitSet) { for i := range bs { if bs[i] && other[i] { bs[i] = true } else { bs[i] = false } } } func (bs BitSet) or(other BitSet) { for i := range bs { if bs[i] || other[i] { bs[i] = true } else { bs[i] = false } } } func iff(cond bool, s1, s2 string) string { if cond { return s1 } return s2 } func newPuzzle(data [2]string) { rowData := strings.Fields(data[0]) colData := strings.Fields(data[1]) rows := getCandidates(rowData, len(colData)) cols := getCandidates(colData, len(rowData)) for { numChanged := reduceMutual(cols, rows) if numChanged == -1 { fmt.Println("No solution") return } if numChanged == 0 { break } } for _, row := range rows { for i := 0; i < len(cols); i++ { fmt.Printf(iff(row[0][i], "# ", ". ")) } fmt.Println() } fmt.Println() } // collect all possible solutions for the given clues func getCandidates(data []string, le int) [][]BitSet { var result [][]BitSet for _, s := range data { var lst []BitSet a := []byte(s) sumBytes := 0 for _, b := range a { sumBytes += int(b - 'A' + 1) } prep := make([]string, len(a)) for i, b := range a { prep[i] = strings.Repeat("1", int(b-'A'+1)) } for _, r := range genSequence(prep, le-sumBytes+1) { bits := []byte(r[1:]) bitset := make(BitSet, len(bits)) for i, b := range bits { bitset[i] = b == '1' } lst = append(lst, bitset) } result = append(result, lst) } return result } func genSequence(ones []string, numZeros int) []string { le := len(ones) if le == 0 { return []string{strings.Repeat("0", numZeros)} } var result []string for x := 1; x < numZeros-le+2; x++ { skipOne := ones[1:] for _, tail := range genSequence(skipOne, numZeros-x) { result = append(result, strings.Repeat("0", x)+ones[0]+tail) } } return result } /* If all the candidates for a row have a value in common for a certain cell, then it's the only possible outcome, and all the candidates from the corresponding column need to have that value for that cell too. The ones that don't, are removed. The same for all columns. It goes back and forth, until no more candidates can be removed or a list is empty (failure). */ func reduceMutual(cols, rows [][]BitSet) int { countRemoved1 := reduce(cols, rows) if countRemoved1 == -1 { return -1 } countRemoved2 := reduce(rows, cols) if countRemoved2 == -1 { return -1 } return countRemoved1 + countRemoved2 } func reduce(a, b [][]BitSet) int { countRemoved := 0 for i := 0; i < len(a); i++ { commonOn := make(BitSet, len(b)) for j := 0; j < len(b); j++ { commonOn[j] = true } commonOff := make(BitSet, len(b)) // determine which values all candidates of a[i] have in common for _, candidate := range a[i] { commonOn.and(candidate) commonOff.or(candidate) } // remove from b[j] all candidates that don't share the forced values for j := 0; j < len(b); j++ { fi, fj := i, j for k := len(b[j]) - 1; k >= 0; k-- { cnd := b[j][k] if (commonOn[fj] && !cnd[fi]) || (!commonOff[fj] && cnd[fi]) { lb := len(b[j]) copy(b[j][k:], b[j][k+1:]) b[j][lb-1] = nil b[j] = b[j][:lb-1] countRemoved++ } } if len(b[j]) == 0 { return -1 } } } return countRemoved } func main() { p1 := [2]string{"C BA CB BB F AE F A B", "AB CA AE GA E C D C"} p2 := [2]string{ "F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA", } p3 := [2]string{ "CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " + "BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " + "AAAAD BDG CEF CBDB BBB FC", } p4 := [2]string{ "E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " + "ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM", } for _, puzzleData := range [][2]string{p1, p2, p3, p4} { newPuzzle(puzzleData) } }
Numbers with equal rises and falls
Go from Wren
When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right). ;Definition: Given the decimal digits of the number are written as a series d: :* A ''rise'' is an index i such that d(i) < d(i+1) :* A ''fall'' is an index i such that d(i) > d(i+1) ;Examples: :* The number '''726,169''' has '''3''' rises and '''2''' falls, so it isn't in the sequence. :* The number '''83,548''' has '''2''' rises and '''2''' falls, so it is in the sequence. ;Task: :* Print the first '''200''' numbers in the sequence :* Show that the '''10 millionth''' (10,000,000th) number in the sequence is '''41,909,002''' ;See also: * OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls". ;Related tasks: * Esthetic numbers
package main import "fmt" func risesEqualsFalls(n int) bool { if n < 10 { return true } rises := 0 falls := 0 prev := -1 for n > 0 { d := n % 10 if prev >= 0 { if d < prev { rises = rises + 1 } else if d > prev { falls = falls + 1 } } prev = d n /= 10 } return rises == falls } func main() { fmt.Println("The first 200 numbers in the sequence are:") count := 0 n := 1 for { if risesEqualsFalls(n) { count++ if count <= 200 { fmt.Printf("%3d ", n) if count%20 == 0 { fmt.Println() } } if count == 1e7 { fmt.Println("\nThe 10 millionth number in the sequence is ", n) break } } n++ } }
Numeric error propagation
Go
If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; then if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, then sf can be calculated as follows: :;Addition/Subtraction :* If f = a +- c, or f = c +- a then '''sf = sa''' :* If f = a +- b then '''sf2 = sa2 + sb2''' :;Multiplication/Division :* If f = ca or f = ac then '''sf = |csa|''' :* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)''' :;Exponentiation :* If f = ac then '''sf = |fc(sa / a)|''' Caution: ::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue. ;Task details: # Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations. # Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 # Print and display both '''d''' and its error. ;References: * A Guide to Error Propagation B. Keeney, 2005. * Propagation of uncertainty Wikipedia. ;Related task: * [[Quaternion type]]
package main import ( "fmt" "math" ) // "uncertain number type" // a little optimization is to represent the error term with its square. // this saves some taking of square roots in various places. type unc struct { n float64 // the number s float64 // *square* of one sigma error term } // constructor, nice to have so it can handle squaring of error term func newUnc(n, s float64) *unc { return &unc{n, s * s} } // error term accessor method, nice to have so it can handle recovering // (non-squared) error term from internal (squared) representation func (z *unc) errorTerm() float64 { return math.Sqrt(z.s) } // Arithmetic methods are modeled on the Go big number package. // The basic scheme is to pass all operands as method arguments, compute // the result into the method receiver, and then return the receiver as // the result of the method. This has an advantage of letting the programer // determine allocation and use of temporary objects, reducing garbage; // and has the convenience and efficiency of allowing operations to be chained. // addition/subtraction func (z *unc) addC(a *unc, c float64) *unc { *z = *a z.n += c return z } func (z *unc) subC(a *unc, c float64) *unc { *z = *a z.n -= c return z } func (z *unc) addU(a, b *unc) *unc { z.n = a.n + b.n z.s = a.s + b.s return z } func (z *unc) subU(a, b *unc) *unc { z.n = a.n - b.n z.s = a.s + b.s return z } // multiplication/division func (z *unc) mulC(a *unc, c float64) *unc { z.n = a.n * c z.s = a.s * c * c return z } func (z *unc) divC(a *unc, c float64) *unc { z.n = a.n / c z.s = a.s / (c * c) return z } func (z *unc) mulU(a, b *unc) *unc { prod := a.n * b.n z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } func (z *unc) divU(a, b *unc) *unc { quot := a.n / b.n z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n)) return z } // exponentiation func (z *unc) expC(a *unc, c float64) *unc { f := math.Pow(a.n, c) g := f * c / a.n z.n = f z.s = a.s * g * g return z } func main() { x1 := newUnc(100, 1.1) x2 := newUnc(200, 2.2) y1 := newUnc(50, 1.2) y2 := newUnc(100, 2.3) var d, d2 unc d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5) fmt.Println("d: ", d.n) fmt.Println("error:", d.errorTerm()) }
Numerical and alphabetical suffixes
Go
This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be: ::* an alphabetic (named) multiplier which could be abbreviated ::* metric multiplier(s) which can be specified multiple times ::* "binary" multiplier(s) which can be specified multiple times ::* explanation marks ('''!''') which indicate a factorial or multifactorial The (decimal) numbers can be expressed generally as: {+-} {digits} {'''.'''} {digits} ------ or ------ {+-} {digits} {'''.'''} {digits} {'''E''' or '''e'''} {+-} {digits} where: ::* numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability) ::* this task will only be dealing with decimal numbers, both in the ''mantissa'' and ''exponent'' ::* +- indicates an optional plus or minus sign ('''+''' or '''-''') ::* digits are the decimal digits ('''0''' --> '''9''') ::* the digits can have comma(s) interjected to separate the ''periods'' (thousands) such as: '''12,467,000''' ::* '''.''' is the decimal point, sometimes also called a ''dot'' ::* '''e''' or '''E''' denotes the use of decimal exponentiation (a number multiplied by raising ten to some power) This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task. The use of the word ''periods'' (thousands) is not meant to confuse, that word (as used above) is what the '''comma''' separates; the groups of decimal digits are called ''periods'', and in almost all cases, are groups of three decimal digits. If an '''e''' or '''E''' is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it. Also, there must be some digits expressed in all cases, not just a sign and/or decimal point. Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved. I.E.: '''+7''' '''007''' '''7.00''' '''7E-0''' '''7E000''' '''70e-1''' could all be expressed as '''7''' All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity. ;Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used): '''PAIRs''' multiply the number by '''2''' (as in pairs of shoes or pants) '''SCOres''' multiply the number by '''20''' (as '''3score''' would be '''60''') '''DOZens''' multiply the number by '''12''' '''GRoss''' multiply the number by '''144''' (twelve dozen) '''GREATGRoss''' multiply the number by '''1,728''' (a dozen gross) '''GOOGOLs''' multiply the number by '''10^100''' (ten raised to the 100>th power) Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas) ;Metric suffixes to be supported (whether or not they're officially sanctioned): '''K''' multiply the number by '''10^3''' kilo (1,000) '''M''' multiply the number by '''10^6''' mega (1,000,000) '''G''' multiply the number by '''10^9''' giga (1,000,000,000) '''T''' multiply the number by '''10^12''' tera (1,000,000,000,000) '''P''' multiply the number by '''10^15''' peta (1,000,000,000,000,000) '''E''' multiply the number by '''10^18''' exa (1,000,000,000,000,000,000) '''Z''' multiply the number by '''10^21''' zetta (1,000,000,000,000,000,000,000) '''Y''' multiply the number by '''10^24''' yotta (1,000,000,000,000,000,000,000,000) '''X''' multiply the number by '''10^27''' xenta (1,000,000,000,000,000,000,000,000,000) '''W''' multiply the number by '''10^30''' wekta (1,000,000,000,000,000,000,000,000,000,000) '''V''' multiply the number by '''10^33''' vendeka (1,000,000,000,000,000,000,000,000,000,000,000) '''U''' multiply the number by '''10^36''' udekta (1,000,000,000,000,000,000,000,000,000,000,000,000) ;Binary suffixes to be supported (whether or not they're officially sanctioned): '''Ki''' multiply the number by '''2^10''' kibi (1,024) '''Mi''' multiply the number by '''2^20''' mebi (1,048,576) '''Gi''' multiply the number by '''2^30''' gibi (1,073,741,824) '''Ti''' multiply the number by '''2^40''' tebi (1,099,571,627,776) '''Pi''' multiply the number by '''2^50''' pebi (1,125,899,906,884,629) '''Ei''' multiply the number by '''2^60''' exbi (1,152,921,504,606,846,976) '''Zi''' multiply the number by '''2^70''' zeb1 (1,180,591,620,717,411,303,424) '''Yi''' multiply the number by '''2^80''' yobi (1,208,925,819,614,629,174,706,176) '''Xi''' multiply the number by '''2^90''' xebi (1,237,940,039,285,380,274,899,124,224) '''Wi''' multiply the number by '''2^100''' webi (1,267,650,600,228,229,401,496,703,205,376) '''Vi''' multiply the number by '''2^110''' vebi (1,298,074,214,633,706,907,132,624,082,305,024) '''Ui''' multiply the number by '''2^120''' uebi (1,329,227,995,784,915,872,903,807,060,280,344,576) All of the metric and binary suffixes can be expressed in lowercase, uppercase, ''or'' mixed case. All of the metric and binary suffixes can be ''stacked'' (expressed multiple times), and also be intermixed: I.E.: '''123k''' '''123K''' '''123GKi''' '''12.3GiGG''' '''12.3e-7T''' '''.78E100e''' ;Factorial suffixes to be supported: '''!''' compute the (regular) factorial product: '''5!''' is '''5''' x '''4''' x '''3''' x '''2''' x '''1''' = '''120''' '''!!''' compute the double factorial product: '''8!''' is '''8''' x '''6''' x '''4''' x '''2''' = '''384''' '''!!!''' compute the triple factorial product: '''8!''' is '''8''' x '''5''' x '''2''' = '''80''' '''!!!!''' compute the quadruple factorial product: '''8!''' is '''8''' x '''4''' = '''32''' '''!!!!!''' compute the quintuple factorial product: '''8!''' is '''8''' x '''3''' = '''24''' *** the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) *** Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein. Multifactorials aren't to be confused with ''super-factorials'' where '''(4!)!''' would be '''(24)!'''. ;Task: ::* Using the test cases (below), show the "expanded" numbers here, on this page. ::* For each list, show the input on one line, and also show the output on one line. ::* When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is. ::* For each result (list) displayed on one line, separate each number with two blanks. ::* Add commas to the output numbers were appropriate. ;Test cases: 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre 1,567 +1.567k 0.1567e-2m 25.123kK 25.123m 2.5123e-00002G 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei -.25123e-34Vikki 2e-77gooGols 9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!! where the last number for the factorials has nine factorial symbols ('''!''') after the '''9''' ;Related tasks: * [[Multifactorial]] (which has a clearer and more succinct definition of multifactorials.) * [[Factorial]]
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) type minmult struct { min int mult float64 } var abbrevs = map[string]minmult{ "PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12}, "GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100}, } var metric = map[string]float64{ "K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18, "Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36, } var binary = map[string]float64{ "Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60), "Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120), } func b(e float64) float64 { return math.Pow(2, e) } func googol() *big.Float { g1 := new(big.Float).SetPrec(500) g1.SetInt64(10000000000) g := new(big.Float) g.Set(g1) for i := 2; i <= 10; i++ { g.Mul(g, g1) } return g } func fact(num string, d int) int { prod := 1 n, _ := strconv.Atoi(num) for i := n; i > 0; i -= d { prod *= i } return prod } func parse(number string) *big.Float { bf := new(big.Float).SetPrec(500) t1 := new(big.Float).SetPrec(500) t2 := new(big.Float).SetPrec(500) // find index of last digit var i int for i = len(number) - 1; i >= 0; i-- { if '0' <= number[i] && number[i] <= '9' { break } } num := number[:i+1] num = strings.Replace(num, ",", "", -1) // get rid of any commas suf := strings.ToUpper(number[i+1:]) if suf == "" { bf.SetString(num) return bf } if suf[0] == '!' { prod := fact(num, len(suf)) bf.SetInt64(int64(prod)) return bf } for k, v := range abbrevs { kk := strings.ToUpper(k) if strings.HasPrefix(kk, suf) && len(suf) >= v.min { t1.SetString(num) if k != "GOOGOLs" { t2.SetFloat64(v.mult) } else { t2 = googol() // for greater accuracy } bf.Mul(t1, t2) return bf } } bf.SetString(num) for k, v := range metric { for j := 0; j < len(suf); j++ { if k == suf[j:j+1] { if j < len(suf)-1 && suf[j+1] == 'I' { t1.SetFloat64(binary[k+"i"]) bf.Mul(bf, t1) j++ } else { t1.SetFloat64(v) bf.Mul(bf, t1) } } } } return bf } func commatize(s string) string { if len(s) == 0 { return "" } neg := s[0] == '-' if neg { s = s[1:] } frac := "" if ix := strings.Index(s, "."); ix >= 0 { frac = s[ix:] s = s[:ix] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { return s + frac } return "-" + s + frac } func process(numbers []string) { fmt.Print("numbers = ") for _, number := range numbers { fmt.Printf("%s ", number) } fmt.Print("\nresults = ") for _, number := range numbers { res := parse(number) t := res.Text('g', 50) fmt.Printf("%s ", commatize(t)) } fmt.Println("\n") } func main() { numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"} process(numbers) numbers = []string{"1,567", "+1.567k", "0.1567e-2m"} process(numbers) numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"} process(numbers) numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"} process(numbers) numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"} process(numbers) numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"} process(numbers) }
Odd word problem
Go
Write a program that solves the odd word problem with the restrictions given below. ;Description: You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: * the words (sequence of consecutive letters) are delimited by one and only one punctuation, * the stream will begin with a word, * the words will be at least one letter long, and * a full stop (a period, [.]) appears after, and only after, the last word. ;Example: A stream with six words: :: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: :: what,si,the;gninaem,of:efil. while observing the following restrictions: # Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; # You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; # You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. ;Test cases: Work on both the "life" example given above, and also the text: :: we,are;not,in,kansas;any,more.
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } func owp(dst io.Writer, src io.Reader) { byte_in := func () byte { bs := make([]byte, 1) src.Read(bs) return bs[0] } byte_out := func (b byte) { dst.Write([]byte{b}) } odd := func() byte { for { b := byte_in() if unicode.IsPunct(int(b)) { return b } defer byte_out(b) } panic("impossible") } for { for { b := byte_in() byte_out(b) if b == '.' { return } if unicode.IsPunct(rune(b)) { break } } b := odd() byte_out(b) if b == '.' { return } } }
Odd word problem
Go from Tcl
Write a program that solves the odd word problem with the restrictions given below. ;Description: You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: * the words (sequence of consecutive letters) are delimited by one and only one punctuation, * the stream will begin with a word, * the words will be at least one letter long, and * a full stop (a period, [.]) appears after, and only after, the last word. ;Example: A stream with six words: :: what,is,the;meaning,of:life. The task is to reverse the letters in every other word while leaving punctuations intact, producing: :: what,si,the;gninaem,of:efil. while observing the following restrictions: # Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use; # You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal; # You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters. ;Test cases: Work on both the "life" example given above, and also the text: :: we,are;not,in,kansas;any,more.
package main import ( "bytes" "fmt" "io" "os" "unicode" ) func main() { owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life.")) fmt.Println() owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more.")) fmt.Println() } type Coroutine struct { out <-chan Coroutine in chan<- byte } func owp(dst io.Writer, src io.Reader) { byte_in := func () (byte, error) { bs := make([]byte, 1) _, err := src.Read(bs) return bs[0], err } byte_out := func (b byte) { dst.Write([]byte{b}) } var f, r Coroutine f = func () Coroutine { out := make(chan Coroutine) in := make(chan byte) var fwd func (byte) byte fwd = func (c byte) (z byte) { if unicode.IsLetter(rune(c)) { byte_out(c) out <- f z = fwd(<- in) } else { z = c } return } go func () { for { x, ok := <- in if !ok { break } byte_out(fwd(x)) out <- r } } () return Coroutine{ out, in } } () r = func () Coroutine { out := make(chan Coroutine) in := make(chan byte) var rev func (byte) byte rev = func (c byte) (z byte) { if unicode.IsLetter(rune(c)) { out <- r z = rev(<- in) byte_out(c) } else { z = c } return } go func () { for { x, ok := <- in if !ok { break } byte_out(rev(x)) out <- f } } () return Coroutine{ out, in } } () for coro := f; ; coro = <- coro.out { c, err := byte_in() if err != nil { break } coro.in <- c } close(f.in) close(r.in) }
Old Russian measure of length
Go from Kotlin
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''. ;Also see: :* Old Russian measure of length
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000, } scanner := bufio.NewScanner(os.Stdin) for { for i, u := range units { fmt.Printf("%2d %s\n", i+1, u) } fmt.Println() var unit int var err error for { fmt.Print("Please choose a unit 1 to 13 : ") scanner.Scan() unit, err = strconv.Atoi(scanner.Text()) if err == nil && unit >= 1 && unit <= 13 { break } } unit-- var value float64 for { fmt.Print("Now enter a value in that unit : ") scanner.Scan() value, err = strconv.ParseFloat(scanner.Text(), 32) if err == nil && value >= 0 { break } } fmt.Println("\nThe equivalent in the remaining units is:\n") for i, u := range units { if i == unit { continue } fmt.Printf(" %10s : %g\n", u, float32(value)*convs[unit]/convs[i]) } fmt.Println() yn := "" for yn != "y" && yn != "n" { fmt.Print("Do another one y/n : ") scanner.Scan() yn = strings.ToLower(scanner.Text()) } if yn == "n" { return } } }
Old lady swallowed a fly
Go
Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
package main import "fmt" var name, lyric, animals = 0, 1, [][]string{ {"fly", "I don't know why she swallowed a fly. Perhaps she'll die."}, {"spider", "That wiggled and jiggled and tickled inside her."}, {"bird", "How absurd, to swallow a bird."}, {"cat", "Imagine that, she swallowed a cat."}, {"dog", "What a hog, to swallow a dog."}, {"goat", "She just opened her throat and swallowed that goat."}, {"cow", "I don't know how she swallowed that cow."}, {"horse", "She's dead, of course."}, } func main() { for i, animal := range animals { fmt.Printf("There was an old lady who swallowed a %s,\n", animal[name]) if i > 0 { fmt.Println(animal[lyric]) } // Swallowing the last animal signals her death, cutting the // lyrics short. if i+1 == len(animals) { break } for ; i > 0; i-- { fmt.Printf("She swallowed the %s to catch the %s,\n", animals[i][name], animals[i-1][name]) } fmt.Println(animals[0][lyric] + "\n") } }
One-time pad
Go from Kotlin
One-time pad, for encrypting and decrypting messages. To keep it simple, we will be using letters only. ;Sub-Tasks: * '''Generate''' the data for a One-time pad (user needs to specify a filename and length) : The important part is to get "true random" numbers, e.g. from /dev/random * '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] ) : For this step, much of [[Vigenere cipher]] could be reused,with the key to be read from the file containing the One-time pad. * optional: '''management''' of One-time pads: list, mark as used, delete, etc. : Somehow, the users needs to keep track which pad to use for which partner. To support the management of pad-files: * Such files have a file-extension ".1tp" * Lines starting with "#" may contain arbitary meta-data (i.e. comments) * Lines starting with "-" count as "used" * Whitespace within the otp-data is ignored For example, here is the data from Wikipedia: # Example data - Wikipedia - 2014-11-13 -ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ -HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE ;See also * one time pad encryption in Python * snapfractalpop - One-Time-Pad Command-Line-Utility (C). * Crypt-OTP-2.00 on CPAN (Perl)
package main import ( "bufio" "crypto/rand" "fmt" "io/ioutil" "log" "math/big" "os" "strconv" "strings" "unicode" ) const ( charsPerLine = 48 chunkSize = 6 cols = 8 demo = true // would normally be set to false ) type fileType int const ( otp fileType = iota enc dec ) var scnr = bufio.NewScanner(os.Stdin) func check(err error) { if err != nil { log.Fatal(err) } } func toAlpha(s string) string { var filtered []rune for _, r := range s { if unicode.IsUpper(r) { filtered = append(filtered, r) } } return string(filtered) } func isOtpRelated(s string) bool { return strings.HasSuffix(s, ".1tp") || strings.HasSuffix(s, "1tp_cpy") || strings.HasSuffix(s, ".1tp_enc") || strings.HasSuffix(s, "1tp_dec") } func makePad(nLines int) string { nChars := nLines * charsPerLine bytes := make([]byte, nChars) /* generate random upper case letters */ max := big.NewInt(26) for i := 0; i < nChars; i++ { n, err := rand.Int(rand.Reader, max) check(err) bytes[i] = byte(65 + n.Uint64()) } return inChunks(string(bytes), nLines, otp) } func vigenere(text, key string, encrypt bool) string { bytes := make([]byte, len(text)) var ci byte for i, c := range text { if encrypt { ci = (byte(c) + key[i] - 130) % 26 } else { ci = (byte(c) + 26 - key[i]) % 26 } bytes[i] = ci + 65 } temp := len(bytes) % charsPerLine if temp > 0 { // pad with random characters so each line is a full one max := big.NewInt(26) for i := temp; i < charsPerLine; i++ { n, err := rand.Int(rand.Reader, max) check(err) bytes = append(bytes, byte(65+n.Uint64())) } } ft := enc if !encrypt { ft = dec } return inChunks(string(bytes), len(bytes)/charsPerLine, ft) } func inChunks(s string, nLines int, ft fileType) string { nChunks := len(s) / chunkSize remainder := len(s) % chunkSize chunks := make([]string, nChunks) for i := 0; i < nChunks; i++ { chunks[i] = s[i*chunkSize : (i+1)*chunkSize] } if remainder > 0 { chunks = append(chunks, s[nChunks*chunkSize:]) } var sb strings.Builder for i := 0; i < nLines; i++ { j := i * cols sb.WriteString(" " + strings.Join(chunks[j:j+cols], " ") + "\n") } ss := " file\n" + sb.String() switch ft { case otp: return "# OTP" + ss case enc: return "# Encrypted" + ss default: // case dec: return "# Decrypted" + ss } } func menu() int { fmt.Println(` 1. Create one time pad file. 2. Delete one time pad file. 3. List one time pad files. 4. Encrypt plain text. 5. Decrypt cipher text. 6. Quit program. `) choice := 0 for choice < 1 || choice > 6 { fmt.Print("Your choice (1 to 6) : ") scnr.Scan() choice, _ = strconv.Atoi(scnr.Text()) check(scnr.Err()) } return choice } func main() { for { choice := menu() fmt.Println() switch choice { case 1: // Create OTP fmt.Println("Note that encrypted lines always contain 48 characters.\n") fmt.Print("OTP file name to create (without extension) : ") scnr.Scan() fileName := scnr.Text() + ".1tp" nLines := 0 for nLines < 1 || nLines > 1000 { fmt.Print("Number of lines in OTP (max 1000) : ") scnr.Scan() nLines, _ = strconv.Atoi(scnr.Text()) } check(scnr.Err()) key := makePad(nLines) file, err := os.Create(fileName) check(err) _, err = file.WriteString(key) check(err) file.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", fileName) if demo { // a copy of the OTP file would normally be on a different machine fileName2 := fileName + "_cpy" // copy for decryption file, err := os.Create(fileName2) check(err) _, err = file.WriteString(key) check(err) file.Close() fmt.Printf("'%s' has been created in the current directory.\n", fileName2) fmt.Println("\nThe contents of these files are :\n") fmt.Println(key) } case 2: // Delete OTP fmt.Println("Note that this will also delete ALL associated files.\n") fmt.Print("OTP file name to delete (without extension) : ") scnr.Scan() toDelete1 := scnr.Text() + ".1tp" check(scnr.Err()) toDelete2 := toDelete1 + "_cpy" toDelete3 := toDelete1 + "_enc" toDelete4 := toDelete1 + "_dec" allToDelete := []string{toDelete1, toDelete2, toDelete3, toDelete4} deleted := 0 fmt.Println() for _, name := range allToDelete { if _, err := os.Stat(name); !os.IsNotExist(err) { err = os.Remove(name) check(err) deleted++ fmt.Printf("'%s' has been deleted from the current directory.\n", name) } } if deleted == 0 { fmt.Println("There are no files to delete.") } case 3: // List OTPs fmt.Println("The OTP (and related) files in the current directory are:\n") files, err := ioutil.ReadDir(".") // already sorted by file name check(err) for _, fi := range files { name := fi.Name() if !fi.IsDir() && isOtpRelated(name) { fmt.Println(name) } } case 4: // Encrypt fmt.Print("OTP file name to use (without extension) : ") scnr.Scan() keyFile := scnr.Text() + ".1tp" if _, err := os.Stat(keyFile); !os.IsNotExist(err) { file, err := os.Open(keyFile) check(err) bytes, err := ioutil.ReadAll(file) check(err) file.Close() lines := strings.Split(string(bytes), "\n") le := len(lines) first := le for i := 0; i < le; i++ { if strings.HasPrefix(lines[i], " ") { first = i break } } if first == le { fmt.Println("\nThat file has no unused lines.") continue } lines2 := lines[first:] // get rid of comments and used lines fmt.Println("Text to encrypt :-\n") scnr.Scan() text := toAlpha(strings.ToUpper(scnr.Text())) check(scnr.Err()) tl := len(text) nLines := tl / charsPerLine if tl%charsPerLine > 0 { nLines++ } if len(lines2) >= nLines { key := toAlpha(strings.Join(lines2[0:nLines], "")) encrypted := vigenere(text, key, true) encFile := keyFile + "_enc" file2, err := os.Create(encFile) check(err) _, err = file2.WriteString(encrypted) check(err) file2.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", encFile) for i := first; i < first+nLines; i++ { lines[i] = "-" + lines[i][1:] } file3, err := os.Create(keyFile) check(err) _, err = file3.WriteString(strings.Join(lines, "\n")) check(err) file3.Close() if demo { fmt.Println("\nThe contents of the encrypted file are :\n") fmt.Println(encrypted) } } else { fmt.Println("Not enough lines left in that file to do encryption.") } } else { fmt.Println("\nThat file does not exist.") } case 5: // Decrypt fmt.Print("OTP file name to use (without extension) : ") scnr.Scan() keyFile := scnr.Text() + ".1tp_cpy" check(scnr.Err()) if _, err := os.Stat(keyFile); !os.IsNotExist(err) { file, err := os.Open(keyFile) check(err) bytes, err := ioutil.ReadAll(file) check(err) file.Close() keyLines := strings.Split(string(bytes), "\n") le := len(keyLines) first := le for i := 0; i < le; i++ { if strings.HasPrefix(keyLines[i], " ") { first = i break } } if first == le { fmt.Println("\nThat file has no unused lines.") continue } keyLines2 := keyLines[first:] // get rid of comments and used lines encFile := keyFile[0:len(keyFile)-3] + "enc" if _, err := os.Stat(encFile); !os.IsNotExist(err) { file2, err := os.Open(encFile) check(err) bytes, err := ioutil.ReadAll(file2) check(err) file2.Close() encLines := strings.Split(string(bytes), "\n")[1:] // exclude comment line nLines := len(encLines) if len(keyLines2) >= nLines { encrypted := toAlpha(strings.Join(encLines, "")) key := toAlpha(strings.Join(keyLines2[0:nLines], "")) decrypted := vigenere(encrypted, key, false) decFile := keyFile[0:len(keyFile)-3] + "dec" file3, err := os.Create(decFile) check(err) _, err = file3.WriteString(decrypted) check(err) file3.Close() fmt.Printf("\n'%s' has been created in the current directory.\n", decFile) for i := first; i < first+nLines; i++ { keyLines[i] = "-" + keyLines[i][1:] } file4, err := os.Create(keyFile) check(err) _, err = file4.WriteString(strings.Join(keyLines, "\n")) check(err) file4.Close() if demo { fmt.Println("\nThe contents of the decrypted file are :\n") fmt.Println(decrypted) } } } else { fmt.Println("Not enough lines left in that file to do decryption.") } } else { fmt.Println("\nThat file does not exist.") } case 6: // Quit program return } } }
One of n lines in a file
Go
A method of choosing a line randomly from a file: ::* Without reading the file more than once ::* When substantial parts of the file cannot be held in memory ::* Without knowing how many lines are in the file Is to: ::* keep the first line of the file as a possible choice, then ::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. ::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. ::* ... ::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N ::* Return the computed possible choice when no further lines exist in the file. ;Task: # Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run. # Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times. # Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
package main import ( "bufio" "fmt" "io" "math/rand" "time" ) // choseLineRandomly implements the method described in the task. // input is a an io.Reader, which could be an os.File, for example. // Or, to implement a simulation, it could be anything else that implements // io.Reader. The method as described suggests saving and returning // lines, but the rest of the task requires line numbers. This function // thus returns both. func choseLineRandomly(r io.Reader) (s string, ln int, err error) { br := bufio.NewReader(r) s, err = br.ReadString('\n') if err != nil { return } ln = 1 lnLast := 1. var sLast string for { // note bufio.ReadString used here. This effectively defines a // line of the file as zero or more bytes followed by a newline. sLast, err = br.ReadString('\n') if err == io.EOF { return s, ln, nil // normal return } if err != nil { break } lnLast++ if rand.Float64() < 1/lnLast { s = sLast ln = int(lnLast) } } return // error return } // oneOfN function required for task item 1. Specified to take a number // n, the number of lines in a file, but the method (above) specified to // to be used does not need n, but rather the file itself. This function // thus takes both, ignoring n and passing the file to choseLineRandomly. func oneOfN(n int, file io.Reader) int { _, ln, err := choseLineRandomly(file) if err != nil { panic(err) } return ln } // simulated file reader for task item 2 type simReader int func (r *simReader) Read(b []byte) (int, error) { if *r <= 0 { return 0, io.EOF } b[0] = '\n' *r-- return 1, nil } func main() { // task item 2 simulation consists of accumulating frequency statistic // on 1,000,000 calls of oneOfN on simulated file. n := 10 freq := make([]int, n) rand.Seed(time.Now().UnixNano()) for times := 0; times < 1e6; times++ { sr := simReader(n) freq[oneOfN(n, &sr)-1]++ } // task item 3. show frequencies. fmt.Println(freq) }
OpenWebNet password
Go from Python
Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist '''Note:''' Factory default password is '12345'. Changing it is highly recommended ! conversation goes as follows - *#*1## - *99*0## - *#603356072## at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent - *#25280520## - *#*1##
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd } start = false } switch c { case '1': num1 = (num2 & 0xFFFFFF80) >> 7 num2 = num2 << 25 case '2': num1 = (num2 & 0xFFFFFFF0) >> 4 num2 = num2 << 28 case '3': num1 = (num2 & 0xFFFFFFF8) >> 3 num2 = num2 << 29 case '4': num1 = num2 << 1 num2 = num2 >> 31 case '5': num1 = num2 << 5 num2 = num2 >> 27 case '6': num1 = num2 << 12 num2 = num2 >> 20 case '7': num3 := num2 & 0x0000FF00 num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16) num1 = num3 | num4 num2 = (num2 & 0xFF000000) >> 8 case '8': num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24) num2 = (num2 & 0x00FF0000) >> 8 case '9': num1 = ^num2 default: num1 = num2 } num1 &= 0xFFFFFFFF num2 &= 0xFFFFFFFF if c != '0' && c != '9' { num1 |= num2 } num2 = num1 } return num1 } func testPasswordCalc(password, nonce string, expected uint32) { res := ownCalcPass(password, nonce) m := fmt.Sprintf("%s %s %-10d %-10d", password, nonce, res, expected) if res == expected { fmt.Println("PASS", m) } else { fmt.Println("FAIL", m) } } func main() { testPasswordCalc("12345", "603356072", 25280520) testPasswordCalc("12345", "410501656", 119537670) testPasswordCalc("12345", "630292165", 4269684735) }
Operator precedence
Go
Operators in C and C++}} ;Task: Provide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. State whether arguments are passed by value or by reference.
{| class="wikitable" ! Precedence ! Operators |- | Highest | Unary operators: +, -, !, ^, *, &, <- |- | 5 | *, /, %, <<, >>, &, &^ |- | 4 | +, -, <nowiki>|</nowiki>, ^ |- | 3 | ==, !=, <, <=, >, >= |- | 2 | && |- | 1 | <nowiki>||</nowiki> |} Binary operators of the same precedence associate from left to right. Associativity has no meaning for unary operators. Syntactic elements not in the list are not considered operators in Go; if they present ambiguity in order of evaluation, the ambiguity is resolved by other rules specific to those elements.
Padovan n-step number sequences
Go from Wren
As the [[Fibonacci sequence]] expands to the [[Fibonacci n-step number sequences]]; We similarly expand the [[Padovan sequence]] to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2 For n == N: start: First N terms of R(N-1, x) Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N)) For this task we similarly define terms of the first 2..n-step Padovan sequences as: For n == 2: start: 1, 1, 1 Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2 For n == N: start: First N + 1 terms of R(N-1, x) Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1)) The initial values of the sequences are: :: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Padovan n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Values !! OEIS Entry |- | 2 || 1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ... || A134816: 'Padovan's spiral numbers' |- | 3 || 1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ... || A000930: 'Narayana's cows sequence' |- | 4 || 1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ... || A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter' |- | 5 || 1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ... || A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's' |- | 6 || 1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ... || |- | 7 || 1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ... || A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)' |- | 8 || 1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ... || |- |} ;Task: # Write a function to generate the first t terms, of the first 2..max_n Padovan n-step number sequences as defined above. # Use this to print and show here at least the first t=15 values of the first 2..8 n-step sequences. (The OEIS column in the table above should be omitted).
package main import "fmt" func padovanN(n, t int) []int { if n < 2 || t < 3 { ones := make([]int, t) for i := 0; i < t; i++ { ones[i] = 1 } return ones } p := padovanN(n-1, t) for i := n + 1; i < t; i++ { p[i] = 0 for j := i - 2; j >= i-n-1; j-- { p[i] += p[j] } } return p } func main() { t := 15 fmt.Println("First", t, "terms of the Padovan n-step number sequences:") for n := 2; n <= 8; n++ { fmt.Printf("%d: %3d\n", n, padovanN(n, t)) } }
Padovan sequence
Go from Wren
The Fibonacci sequence in several ways. Some are given in the table below, and the referenced video shows some of the geometric similarities. ::{| class="wikitable" ! Comment !! Padovan !! Fibonacci |- | || || |- | Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci |- | || || |- | Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1 |- | Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2) |- | || || |- | First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34 |- | || || |- | Ratio of successive terms... || Plastic ratio, p || Golden ratio, g |- | || 1.324717957244746025960908854... || 1.6180339887498948482... |- | Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2 |- | Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1 |- | || || |- | Spirally tiling the plane using. || Equilateral triangles || Squares |- | || || |- | Constants for ... || s= 1.0453567932525329623 || a=5**0.5 |- | ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5) |- | || || |- | L-System Variables. || A,B,C || A,B |- | L-System Start/Axiom. || A || A |- | L-System Rules. || A->B,B->C,C->AB || A->B,B->AB |} ;Task: * Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation. * Write a function/method/subroutine to compute successive members of the Padovan series using the floor function. * Show the first twenty terms of the sequence. * Confirm that the recurrence and floor based functions give the same results for 64 terms, * Write a function/method/... using the L-system to generate successive strings. * Show the first 10 strings produced from the L-system * Confirm that the length of the first 32 strings produced is the Padovan sequence. Show output here, on this page. ;Ref: * The Plastic Ratio - Numberphile video.
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat) p, _ = p.SetString("1.324717957244746025960908854") s, _ = s.SetString("1.0453567932525329623") f := make([]int, n) pow := new(big.Rat).SetInt64(1) u = u.SetFrac64(1, 2) t.Quo(pow, p) t.Quo(t, s) t.Add(t, u) v, _ := t.Float64() f[0] = int(math.Floor(v)) for i := 1; i < n; i++ { t.Quo(pow, s) t.Add(t, u) v, _ = t.Float64() f[i] = int(math.Floor(v)) pow.Mul(pow, p) } return f } type LSystem struct { rules map[string]string init, current string } func step(lsys *LSystem) string { var sb strings.Builder if lsys.current == "" { lsys.current = lsys.init } else { for _, c := range lsys.current { sb.WriteString(lsys.rules[string(c)]) } lsys.current = sb.String() } return lsys.current } func padovanLSys(n int) []string { rules := map[string]string{"A": "B", "B": "C", "C": "AB"} lsys := &LSystem{rules, "A", ""} p := make([]string, n) for i := 0; i < n; i++ { p[i] = step(lsys) } return p } // assumes lists are same length func areSame(l1, l2 []int) bool { for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { fmt.Println("First 20 members of the Padovan sequence:") fmt.Println(padovanRecur(20)) recur := padovanRecur(64) floor := padovanFloor(64) same := areSame(recur, floor) s := "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and floor based functions", s, "the same results for 64 terms.") p := padovanLSys(32) lsyst := make([]int, 32) for i := 0; i < 32; i++ { lsyst[i] = len(p[i]) } fmt.Println("\nFirst 10 members of the Padovan L-System:") fmt.Println(p[:10]) fmt.Println("\nand their lengths:") fmt.Println(lsyst[:10]) same = areSame(recur[:32], lsyst) s = "give" if !same { s = "do not give" } fmt.Println("\nThe recurrence and L-system based functions", s, "the same results for 32 terms.")
Palindrome dates
Go
Today ('''2020-02-02''', at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the '''yyyy-mm-dd''' format but, unusually, also for countries which use the '''dd-mm-yyyy''' format. ;Task Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the '''yyyy-mm-dd''' format.
package main import ( "fmt" "time" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { const ( layout = "20060102" layout2 = "2006-01-02" ) fmt.Println("The next 15 palindromic dates in yyyymmdd format after 20200202 are:") date := time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC) count := 0 for count < 15 { date = date.AddDate(0, 0, 1) s := date.Format(layout) r := reverse(s) if r == s { fmt.Println(date.Format(layout2)) count++ } } }
Palindromic gapful numbers
Go
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''1037''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''1037'''. A palindromic number is (for this task, a positive integer expressed in base ten), when the number is reversed, is the same as the original number. ;Task: :* Show (nine sets) the first '''20''' palindromic gapful numbers that ''end'' with: :::* the digit '''1''' :::* the digit '''2''' :::* the digit '''3''' :::* the digit '''4''' :::* the digit '''5''' :::* the digit '''6''' :::* the digit '''7''' :::* the digit '''8''' :::* the digit '''9''' :* Show (nine sets, like above) of palindromic gapful numbers: :::* the last '''15''' palindromic gapful numbers (out of '''100''') :::* the last '''10''' palindromic gapful numbers (out of '''1,000''') {optional} For other ways of expressing the (above) requirements, see the ''discussion'' page. ;Note: All palindromic gapful numbers are divisible by eleven. ;Related tasks: :* palindrome detection. :* gapful numbers. ;Also see: :* The OEIS entry: A108343 gapful numbers.
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) 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 ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
Pancake numbers
Go from Phix
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. [[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). ;References # Bill Gates and the pancake problem # A058986
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) = %2d ", n, pancake(n)) } fmt.Println() } }
Pancake numbers
Go from Wren
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. [[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)? Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). ;References # Bill Gates and the pancake problem # A058986
package main import ( "fmt" "strconv" "strings" "time" ) type assoc map[string]int // Converts a string of the form "[1 2]" into a slice of ints: {1, 2} func asSlice(s string) []int { split := strings.Split(s[1:len(s)-1], " ") le := len(split) res := make([]int, le) for i := 0; i < le; i++ { res[i], _ = strconv.Atoi(split[i]) } return res } // Merges two assocs into one. If the same key is present in both assocs // its value will be the one in the second assoc. func merge(m1, m2 assoc) assoc { m3 := make(assoc) for k, v := range m1 { m3[k] = v } for k, v := range m2 { m3[k] = v } return m3 } // Finds the maximum value in 'dict' and returns the first key // it finds (iteration order is undefined) with that value. func findMax(dict assoc) string { max := -1 maxKey := "" for k, v := range dict { if v > max { max = v maxKey = k } } return maxKey } // Creates a new slice of ints by reversing an existing one. func reverse(s []int) []int { le := len(s) rev := make([]int, le) for i := 0; i < le; i++ { rev[i] = s[le-1-i] } return rev } func pancake(n int) (string, int) { numStacks := 1 gs := make([]int, n) for i := 0; i < n; i++ { gs[i] = i + 1 } goalStack := fmt.Sprintf("%v", gs) stacks := assoc{goalStack: 0} newStacks := assoc{goalStack: 0} for i := 1; i <= 1000; i++ { nextStacks := assoc{} for key := range newStacks { arr := asSlice(key) for pos := 2; pos <= n; pos++ { t := append(reverse(arr[0:pos]), arr[pos:len(arr)]...) newStack := fmt.Sprintf("%v", t) if _, ok := stacks[newStack]; !ok { nextStacks[newStack] = i } } } newStacks = nextStacks stacks = merge(stacks, newStacks) perms := len(stacks) if perms == numStacks { return findMax(stacks), i - 1 } numStacks = perms } return "", 0 } func main() { start := time.Now() fmt.Println("The maximum number of flips to sort a given number of elements is:") for i := 1; i <= 10; i++ { example, steps := pancake(i) fmt.Printf("pancake(%2d) = %-2d example: %s\n", i, steps, example) } fmt.Printf("\nTook %s\n", time.Since(start)) }
Pangram checker
Go
A pangram is a sentence that contains all the letters of the English alphabet at least once. For example: ''The quick brown fox jumps over the lazy dog''. ;Task: Write a function or method to check a sentence to see if it is a pangram (or not) and show its use. ;Related tasks: :* determine if a string has all the same characters :* determine if a string has all unique characters
package main import "fmt" func main() { for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt.Println("No: ", s) } } } func pangram(s string) bool { var missing uint32 = (1 << 26) - 1 for _, c := range s { var index uint32 if 'a' <= c && c <= 'z' { index = uint32(c - 'a') } else if 'A' <= c && c <= 'Z' { index = uint32(c - 'A') } else { continue } missing &^= 1 << index if missing == 0 { return true } } return false }
Paraffins
Go from C
This organic chemistry task is essentially to implement a tree enumeration algorithm. ;Task: Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). Paraffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the "backbone" structure, with adding hydrogen atoms linking the remaining unused bonds. In a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2 But for all '''n''' >= 4 there are several distinct molecules ("isomers") with the same formula but different structures. The number of isomers rises rather rapidly when '''n''' increases. In counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D "out of the paper" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule. ;Example: With '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations: :::* a straight chain: (CH3)(CH2)(CH2)(CH3) :::* a branched chain: (CH3)(CH(CH3))(CH3) Due to bond rotations, it doesn't matter which direction the branch points in. The phenomenon of "stereo-isomerism" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task. The input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). The output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17). The sequence of those results is visible in the OEIS entry: ::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. The sequence is (the index starts from zero, and represents the number of carbon atoms): 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359, 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245, 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763, 10660307791, 27711253769, ... ;Extra credit: Show the paraffins in some way. A flat 1D representation, with arrays or lists is enough, for instance: *Main> all_paraffins 1 [CCP H H H H] *Main> all_paraffins 2 [BCP (C H H H) (C H H H)] *Main> all_paraffins 3 [CCP H H (C H H H) (C H H H)] *Main> all_paraffins 4 [BCP (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 5 [CCP H H (C H H (C H H H)) (C H H (C H H H)), CCP H (C H H H) (C H H H) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H H)] *Main> all_paraffins 6 [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))), BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)), BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)), CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)), CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))] Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary): methane ethane propane isobutane H H H H H H H H H | | | | | | | | | H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H | | | | | | | | | H H H H H H H | H | H - C - H | H ;Links: * A paper that explains the problem and its solution in a functional language: http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf * A Haskell implementation: https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs * A Scheme implementation: http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm * A Fortress implementation: (this site has been closed) http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d: %d\n", n, &unrooted[n]) } }
Parse an IP Address
Go
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: ::: {| border="5" cellspacing="0" cellpadding=2 |- |127.0.0.1 |The "localhost" IPv4 address |- |127.0.0.1:80 |The "localhost" IPv4 address, with a specified port (80) |- |::1 |The "localhost" IPv6 address |- |[::1]:80 |The "localhost" IPv6 address, with a specified port (80) |- |2605:2700:0:3::4713:93e3 |Rosetta Code's primary server's public IPv6 address |- |[2605:2700:0:3::4713:93e3]:80 |Rosetta Code's primary server's public IPv6 address, with a specified port (80) |} ;Task: Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. In languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified. ;Example: '''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal) in the ipv4 address space. '''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the address number '''FFFF7F000001''' (281472812449793 decimal). '''::1''' has address number '''1''' and serves the same purpose in the ipv6 address space that '''127.0.0.1''' serves in the ipv4 address space.
package main import ( "encoding/hex" "fmt" "io" "net" "os" "strconv" "strings" "text/tabwriter" ) // parseIPPort parses an IP with an optional port, returning an IP and a port (or nil // if no port was present in the given address). func parseIPPort(address string) (net.IP, *uint64, error) { ip := net.ParseIP(address) if ip != nil { return ip, nil, nil } host, portStr, err := net.SplitHostPort(address) if err != nil { return nil, nil, fmt.Errorf("splithostport failed: %w", err) } port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { return nil, nil, fmt.Errorf("failed to parse port: %w", err) } ip = net.ParseIP(host) if ip == nil { return nil, nil, fmt.Errorf("failed to parse ip address") } return ip, &port, nil } func ipVersion(ip net.IP) int { if ip.To4() == nil { return 6 } return 4 } func main() { testCases := []string{ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:443", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", } w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) writeTSV := func(w io.Writer, args ...interface{}) { fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...) fmt.Fprintf(w, "\n") } writeTSV(w, "Input", "Address", "Space", "Port") for _, addr := range testCases { ip, port, err := parseIPPort(addr) if err != nil { panic(err) } portStr := "n/a" if port != nil { portStr = fmt.Sprint(*port) } ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip)) writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr) } w.Flush() }
Parsing/RPN calculator algorithm
Go
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''. * Assume an input of a correct, space separated, string of tokens of an RPN expression * Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: 3 4 2 * 1 5 - 2 3 ^ ^ / + * Print or display the output here ;Notes: * '''^''' means exponentiation in the expression above. * '''/''' means division. ;See also: * [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression. * Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task). * [[Parsing/RPN to infix conversion]]. * [[Arithmetic evaluation]].
package main import ( "fmt" "math" "strconv" "strings" ) var input = "3 4 2 * 1 5 - 2 3 ^ ^ / +" func main() { fmt.Printf("For postfix %q\n", input) fmt.Println("\nToken Action Stack") var stack []float64 for _, tok := range strings.Fields(input) { action := "Apply op to top of stack" switch tok { case "+": stack[len(stack)-2] += stack[len(stack)-1] stack = stack[:len(stack)-1] case "-": stack[len(stack)-2] -= stack[len(stack)-1] stack = stack[:len(stack)-1] case "*": stack[len(stack)-2] *= stack[len(stack)-1] stack = stack[:len(stack)-1] case "/": stack[len(stack)-2] /= stack[len(stack)-1] stack = stack[:len(stack)-1] case "^": stack[len(stack)-2] = math.Pow(stack[len(stack)-2], stack[len(stack)-1]) stack = stack[:len(stack)-1] default: action = "Push num onto top of stack" f, _ := strconv.ParseFloat(tok, 64) stack = append(stack, f) } fmt.Printf("%3s %-26s %v\n", tok, action, stack) } fmt.Println("\nThe final value is", stack[0]) }
Parsing/RPN to infix conversion
Go
Create a program that takes an infix notation. * Assume an input of a correct, space separated, string of tokens * Generate a space separated output string representing the same expression in infix notation * Show how the major datastructure of your algorithm changes with each new token parsed. * Test with the following input RPN strings then print and display the output here. :::::{| class="wikitable" ! RPN input !! sample output |- || align="center" | 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 |- || align="center" | 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 ) |} * Operator precedence and operator associativity is given in this table: ::::::::{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;See also: * [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression. * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * Postfix to infix from the RubyQuiz site.
package main import ( "fmt" "strings" ) var tests = []string{ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^", } var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } const nPrec = 9 func main() { for _, t := range tests { parseRPN(t) } } func parseRPN(e string) { fmt.Println("\npostfix:", e) type sf struct { prec int expr string } var stack []sf for _, tok := range strings.Fields(e) { fmt.Println("token:", tok) if op, isOp := opa[tok]; isOp { rhs := &stack[len(stack)-1] stack = stack[:len(stack)-1] lhs := &stack[len(stack)-1] if lhs.prec < op.prec || (lhs.prec == op.prec && op.rAssoc) { lhs.expr = "(" + lhs.expr + ")" } lhs.expr += " " + tok + " " if rhs.prec < op.prec || (rhs.prec == op.prec && !op.rAssoc) { lhs.expr += "(" + rhs.expr + ")" } else { lhs.expr += rhs.expr } lhs.prec = op.prec } else { stack = append(stack, sf{nPrec, tok}) } for _, f := range stack { fmt.Printf(" %d %q\n", f.prec, f.expr) } } fmt.Println("infix:", stack[0].expr) }
Parsing/Shunting-yard algorithm
Go
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. * Assume an input of a correct, space separated, string of tokens representing an infix expression * Generate a space separated output string representing the RPN * Test with the input string: :::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 * print and display the output here. * Operator precedence is given in this table: :{| class="wikitable" ! operator !! associativity !! operation |- || align="center" | ^ || 4 || right || exponentiation |- || align="center" | * || 3 || left || multiplication |- || align="center" | / || 3 || left || division |- || align="center" | + || 2 || left || addition |- || align="center" | - || 2 || left || subtraction |} ;Extra credit Add extra text explaining the actions and an optional comment for the action on receipt of each token. ;Note The handling of functions and arguments is not required. ;See also: * [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression. * [[Parsing/RPN to infix conversion]].
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string // holds operators and left parenthesis for _, tok := range strings.Fields(e) { switch tok { case "(": stack = append(stack, tok) // push "(" to stack case ")": var op string for { // pop item ("(" or operator) from stack op, stack = stack[len(stack)-1], stack[:len(stack)-1] if op == "(" { break // discard "(" } rpn += " " + op // add operator to result } default: if o1, isOp := opa[tok]; isOp { // token is an operator for len(stack) > 0 { // consider top item on stack op := stack[len(stack)-1] if o2, isOp := opa[op]; !isOp || o1.prec > o2.prec || o1.prec == o2.prec && o1.rAssoc { break } // top item is an operator that needs to come off stack = stack[:len(stack)-1] // pop it rpn += " " + op // add it to result } // push operator (the new one) to stack stack = append(stack, tok) } else { // token is an operand if rpn > "" { rpn += " " } rpn += tok // add operand to result } } } // drain stack to result for len(stack) > 0 { rpn += " " + stack[len(stack)-1] stack = stack[:len(stack)-1] } return }
Pascal's triangle/Puzzle
Go
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). ;Task: Write a program to find a solution to this puzzle.
package main import "fmt" // representation of an expression in x, y, and z type expr struct { x, y, z float64 // coefficients c float64 // constant term } // add two expressions func addExpr(a, b expr) expr { return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c} } // subtract two expressions func subExpr(a, b expr) expr { return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c} } // multiply expression by a constant func mulExpr(a expr, c float64) expr { return expr{a.x * c, a.y * c, a.z * c, a.c * c} } // given a row of expressions, produce the next row up, by the given // sum relation between blocks func addRow(l []expr) []expr { if len(l) == 0 { panic("wrong") } r := make([]expr, len(l)-1) for i := range r { r[i] = addExpr(l[i], l[i+1]) } return r } // given expression b in a variable, and expression a, // take b == 0 and substitute to remove that variable from a. func substX(a, b expr) expr { if b.x == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.x/b.x)) } func substY(a, b expr) expr { if b.y == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.y/b.y)) } func substZ(a, b expr) expr { if b.z == 0 { panic("wrong") } return subExpr(a, mulExpr(b, a.z/b.z)) } // given an expression in a single variable, return value of that variable func solveX(a expr) float64 { if a.x == 0 || a.y != 0 || a.z != 0 { panic("wrong") } return -a.c / a.x } func solveY(a expr) float64 { if a.x != 0 || a.y == 0 || a.z != 0 { panic("wrong") } return -a.c / a.y } func solveZ(a expr) float64 { if a.x != 0 || a.y != 0 || a.z == 0 { panic("wrong") } return -a.c / a.z } func main() { // representation of given information for bottom row r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}} fmt.Println("bottom row:", r5) // given definition of brick sum relation r4 := addRow(r5) fmt.Println("next row up:", r4) r3 := addRow(r4) fmt.Println("middle row:", r3) // given relation y = x + z xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1}) fmt.Println("xyz relation:", xyz) // remove z from third cell using xyz relation r3[2] = substZ(r3[2], xyz) fmt.Println("middle row after substituting for z:", r3) // given cell = 40, b := expr{c: 40} // this gives an xy relation xy := subExpr(r3[0], b) fmt.Println("xy relation:", xy) // substitute 40 for cell r3[0] = b // remove x from third cell using xy relation r3[2] = substX(r3[2], xy) fmt.Println("middle row after substituting for x:", r3) // continue applying brick sum relation to get top cell r2 := addRow(r3) fmt.Println("next row up:", r2) r1 := addRow(r2) fmt.Println("top row:", r1) // given top cell = 151, we have an equation in y y := subExpr(r1[0], expr{c: 151}) fmt.Println("y relation:", y) // using xy relation, we get an equation in x x := substY(xy, y) fmt.Println("x relation:", x) // using xyz relation, we get an equation in z z := substX(substY(xyz, y), x) fmt.Println("z relation:", z) // show final answers fmt.Println("x =", solveX(x)) fmt.Println("y =", solveY(y)) fmt.Println("z =", solveZ(z)) }
Pascal matrix generation
Go from Kotlin
A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr. Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. A Pascal upper-triangular matrix that is populated with jCi: [[1, 1, 1, 1, 1], [0, 1, 2, 3, 4], [0, 0, 1, 3, 6], [0, 0, 0, 1, 4], [0, 0, 0, 0, 1]] A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix): [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 2, 1, 0, 0], [1, 3, 3, 1, 0], [1, 4, 6, 4, 1]] A Pascal symmetric matrix that is populated with i+jCi: [[1, 1, 1, 1, 1], [1, 2, 3, 4, 5], [1, 3, 6, 10, 15], [1, 4, 10, 20, 35], [1, 5, 15, 35, 70]] ;Task: Write functions capable of generating each of the three forms of n-by-n matrices. Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows). ;Note: The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
package main import ( "fmt" "strings" ) func binomial(n, k int) int { if n < k { return 0 } if n == 0 || k == 0 { return 1 } num := 1 for i := k + 1; i <= n; i++ { num *= i } den := 1 for i := 2; i <= n-k; i++ { den *= i } return num / den } func pascalUpperTriangular(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(j, i) } } return m } func pascalLowerTriangular(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(i, j) } } return m } func pascalSymmetric(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(i+j, i) } } return m } func printMatrix(title string, m [][]int) { n := len(m) fmt.Println(title) fmt.Print("[") for i := 0; i < n; i++ { if i > 0 { fmt.Print(" ") } mi := strings.Replace(fmt.Sprint(m[i]), " ", ", ", -1) fmt.Print(mi) if i < n-1 { fmt.Println(",") } else { fmt.Println("]\n") } } } func main() { printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5)) printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5)) printMatrix("Pascal symmetric matrix", pascalSymmetric(5)) }
Password generator
Go
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a --> z upper-case letters: A --> Z digits: 0 --> 9 other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above character list excludes white-space, backslash and grave) The generated password(s) must include ''at least one'' (of each of the four groups): lower-case letter, upper-case letter, digit (numeral), and one "other" character. The user must be able to specify the password length and the number of passwords to generate. The passwords should be displayed or written to a file, one per line. The randomness should be from a system source or library. The program should implement a help option or button which should describe the program and options when invoked. You may also allow the user to specify a seed value, and give the option of excluding visually similar characters. For example: Il1 O0 5S 2Z where the characters are: ::::* capital eye, lowercase ell, the digit one ::::* capital oh, the digit zero ::::* the digit five, capital ess ::::* the digit two, capital zee
package main import ( "crypto/rand" "math/big" "strings" "flag" "math" "fmt" ) var lowercase = "abcdefghijklmnopqrstuvwxyz" var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" var numbers = "0123456789" var signs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" var similar = "Il1O05S2Z" func check(e error){ if e != nil { panic(e) } } func randstr(length int, alphastr string) string{ alphabet := []byte(alphastr) pass := make([]byte,length) for i := 0; i < length; i++ { bign, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphabet)))) check(err) n := bign.Int64() pass[i] = alphabet[n] } return string(pass) } func verify(pass string,checkUpper bool,checkLower bool, checkNumber bool, checkSign bool) bool{ isValid := true if(checkUpper){ isValid = isValid && strings.ContainsAny(pass,uppercase) } if(checkLower){ isValid = isValid && strings.ContainsAny(pass,lowercase) } if(checkNumber){ isValid = isValid && strings.ContainsAny(pass,numbers) } if(checkSign){ isValid = isValid && strings.ContainsAny(pass,signs) } return isValid } func main() { passCount := flag.Int("pc", 6, "Number of passwords") passLength := flag.Int("pl", 10, "Passwordlength") useUpper := flag.Bool("upper", true, "Enables or disables uppercase letters") useLower := flag.Bool("lower", true, "Enables or disables lowercase letters") useSign := flag.Bool("sign", true, "Enables or disables signs") useNumbers := flag.Bool("number", true, "Enables or disables numbers") useSimilar := flag.Bool("similar", true,"Enables or disables visually similar characters") flag.Parse() passAlphabet := "" if *useUpper { passAlphabet += uppercase } if *useLower { passAlphabet += lowercase } if *useSign { passAlphabet += signs } if *useNumbers { passAlphabet += numbers } if !*useSimilar { for _, r := range similar{ passAlphabet = strings.Replace(passAlphabet,string(r),"", 1) } } fmt.Printf("Generating passwords with an average entropy of %.1f bits \n", math.Log2(float64(len(passAlphabet))) * float64(*passLength)) for i := 0; i < *passCount;i++{ passFound := false pass := "" for(!passFound){ pass = randstr(*passLength,passAlphabet) passFound = verify(pass,*useUpper,*useLower,*useNumbers,*useSign) } fmt.Println(pass) } }
Pathological floating point problems
Go
Most programmers are familiar with the inexactness of floating point calculations in a binary processor. The classic example being: 0.1 + 0.2 = 0.30000000000000004 In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding. There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision. This task's purpose is to show how your language deals with such classes of problems. '''A sequence that seems to converge to a wrong limit.''' Consider the sequence: :::::: v1 = 2 :::::: v2 = -4 :::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) As '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''. ;Task 1: Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places. n = 3 18.5 n = 4 9.378378 n = 5 7.801153 n = 6 7.154414 n = 7 6.806785 n = 8 6.5926328 n = 20 6.0435521101892689 n = 30 6.006786093031205758530554 n = 50 6.0001758466271871889456140207471954695237 n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266 ;Task 2: '''The Chaotic Bank Society''' is offering a new investment account to their customers. You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms. After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. So ... ::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges. ::* after 2 years your balance will be doubled and $1 removed. ::* after 3 years your balance will be tripled and $1 removed. ::* ... ::* after 10 years, multiplied by 10 and $1 removed, and so on. What will your balance be after 25 years? Starting balance: $e-1 Balance = (Balance * year) - 1 for 25 years Balance after 25 years: $0.0399387296732302 ;Task 3, extra credit: '''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988. :::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) :::::: compute f(a,b) where a=77617.0 and b=33096.0 :::::: f(77617.0, 33096.0) = -0.827396059946821 Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty. ;See also; * Floating-Point Arithmetic Section 1.3.2 Difficult problems.
package main import ( "fmt" "math/big" ) func main() { sequence() bank() rump() } func sequence() { // exact computations using big.Rat var v, v1 big.Rat v1.SetInt64(2) v.SetInt64(-4) n := 2 c111 := big.NewRat(111, 1) c1130 := big.NewRat(1130, 1) c3000 := big.NewRat(3000, 1) var t2, t3 big.Rat r := func() (vn big.Rat) { vn.Add(vn.Sub(c111, t2.Quo(c1130, &v)), t3.Quo(c3000, t3.Mul(&v, &v1))) return } fmt.Println(" n sequence value") for _, x := range []int{3, 4, 5, 6, 7, 8, 20, 30, 50, 100} { for ; n < x; n++ { v1, v = v, r() } f, _ := v.Float64() fmt.Printf("%3d %19.16f\n", n, f) } } func bank() { // balance as integer multiples of e and whole dollars using big.Int var balance struct{ e, d big.Int } // initial balance balance.e.SetInt64(1) balance.d.SetInt64(-1) // compute balance over 25 years var m, one big.Int one.SetInt64(1) for y := 1; y <= 25; y++ { m.SetInt64(int64(y)) balance.e.Mul(&m, &balance.e) balance.d.Mul(&m, &balance.d) balance.d.Sub(&balance.d, &one) } // sum account components using big.Float var e, ef, df, b big.Float e.SetPrec(100).SetString("2.71828182845904523536028747135") ef.SetInt(&balance.e) df.SetInt(&balance.d) b.Add(b.Mul(&e, &ef), &df) fmt.Printf("Bank balance after 25 years: $%.2f\n", &b) } func rump() { a, b := 77617., 33096. fmt.Printf("Rump f(%g, %g): %g\n", a, b, f(a, b)) } func f(a, b float64) float64 { // computations done with big.Float with enough precision to give // a correct answer. fp := func(x float64) *big.Float { return big.NewFloat(x).SetPrec(128) } a1 := fp(a) b1 := fp(b) a2 := new(big.Float).Mul(a1, a1) b2 := new(big.Float).Mul(b1, b1) b4 := new(big.Float).Mul(b2, b2) b6 := new(big.Float).Mul(b2, b4) b8 := new(big.Float).Mul(b4, b4) two := fp(2) t1 := fp(333.75) t1.Mul(t1, b6) t21 := fp(11) t21.Mul(t21.Mul(t21, a2), b2) t23 := fp(121) t23.Mul(t23, b4) t2 := new(big.Float).Sub(t21, b6) t2.Mul(a2, t2.Sub(t2.Sub(t2, t23), two)) t3 := fp(5.5) t3.Mul(t3, b8) t4 := new(big.Float).Mul(two, b1) t4.Quo(a1, t4) s := new(big.Float).Add(t1, t2) f64, _ := s.Add(s.Add(s, t3), t4).Float64() return f64 }
Peaceful chess queen armies
Go
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour. \ | / = = = = / | \ / | \ | The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''. ;Task: # Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion). # Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board. # Display here results for the m=4, n=5 case. ;References: * Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62. * A250000 OEIS
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *[]position) bool { if m == 0 { return true } placingBlack := true for i := 0; i < n; i++ { inner: for j := 0; j < n; j++ { pos := position{i, j} for _, queen := range *pBlackQueens { if queen == pos || !placingBlack && isAttacking(queen, pos) { continue inner } } for _, queen := range *pWhiteQueens { if queen == pos || placingBlack && isAttacking(queen, pos) { continue inner } } if placingBlack { *pBlackQueens = append(*pBlackQueens, pos) placingBlack = false } else { *pWhiteQueens = append(*pWhiteQueens, pos) if place(m-1, n, pBlackQueens, pWhiteQueens) { return true } *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] *pWhiteQueens = (*pWhiteQueens)[0 : len(*pWhiteQueens)-1] placingBlack = true } } } if !placingBlack { *pBlackQueens = (*pBlackQueens)[0 : len(*pBlackQueens)-1] } return false } func isAttacking(queen, pos position) bool { if queen.i == pos.i { return true } if queen.j == pos.j { return true } if iabs(queen.i-pos.i) == iabs(queen.j-pos.j) { return true } return false } func printBoard(n int, blackQueens, whiteQueens []position) { board := make([]int, n*n) for _, queen := range blackQueens { board[queen.i*n+queen.j] = black } for _, queen := range whiteQueens { board[queen.i*n+queen.j] = white } for i, b := range board { if i != 0 && i%n == 0 { fmt.Println() } switch b { case black: fmt.Printf("%c ", bqueen) case white: fmt.Printf("%c ", wqueen) case empty: if i%2 == 0 { fmt.Printf("%c ", bbullet) } else { fmt.Printf("%c ", wbullet) } } } fmt.Println("\n") } func main() { nms := [][2]int{ {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, } for _, nm := range nms { n, m := nm[0], nm[1] fmt.Printf("%d black and %d white queens on a %d x %d board:\n", m, m, n, n) var blackQueens, whiteQueens []position if place(m, n, &blackQueens, &whiteQueens) { printBoard(n, blackQueens, whiteQueens) } else { fmt.Println("No solution exists.\n") } } }
Pentomino tiling
Go from Java
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I I L N Y FF I L NN PP TTT V W X YY ZZ FF I L N PP T U U V WW XXX Y Z F I LL N P T UUU VVV WW X Y ZZ A Pentomino tiling is an example of an exact cover problem and can take on many forms. A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered by the 12 pentomino shapes, without overlaps, with every shape only used once. The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable. ;Task Create an 8 by 8 tiling and print the result. ;Example F I I I I I L N F F F L L L L N W F - X Z Z N N W W X X X Z N V T W W X - Z Z V T T T P P V V V T Y - P P U U U Y Y Y Y P U - U ;Related tasks * Free polyominoes enumeration
package main import ( "fmt" "math/rand" "time" ) var F = [][]int{ {1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0}, {1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1}, {1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1}, } var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}} var L = [][]int{ {1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0}, } var N = [][]int{ {0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1}, {0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3}, {1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1}, } var P = [][]int{ {0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1}, {1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2}, {1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0}, } var T = [][]int{ {0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0}, {1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0}, } var U = [][]int{ {0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1}, {0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1}, } var V = [][]int{ {1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0}, {1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2}, } var W = [][]int{ {1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1}, } var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}} var Y = [][]int{ {1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2}, {1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0}, } var Z = [][]int{ {0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2}, {0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2}, } var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z} var symbols = []byte("FILNPTUVWXYZ-") const ( nRows = 8 nCols = 8 blank = 12 ) var grid [nRows][nCols]int var placed [12]bool func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool { for i := 0; i < len(o); i += 2 { x := c + o[i+1] y := r + o[i] if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 { return false } } grid[r][c] = shapeIndex for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = shapeIndex } return true } func removeOrientation(o []int, r, c int) { grid[r][c] = -1 for i := 0; i < len(o); i += 2 { grid[r+o[i]][c+o[i+1]] = -1 } } func solve(pos, numPlaced int) bool { if numPlaced == len(shapes) { return true } row := pos / nCols col := pos % nCols if grid[row][col] != -1 { return solve(pos+1, numPlaced) } for i := range shapes { if !placed[i] { for _, orientation := range shapes[i] { if !tryPlaceOrientation(orientation, row, col, i) { continue } placed[i] = true if solve(pos+1, numPlaced+1) { return true } removeOrientation(orientation, row, col) placed[i] = false } } } return false } func shuffleShapes() { rand.Shuffle(len(shapes), func(i, j int) { shapes[i], shapes[j] = shapes[j], shapes[i] symbols[i], symbols[j] = symbols[j], symbols[i] }) } func printResult() { for _, r := range grid { for _, i := range r { fmt.Printf("%c ", symbols[i]) } fmt.Println() } } func main() { rand.Seed(time.Now().UnixNano()) shuffleShapes() for r := 0; r < nRows; r++ { for i := range grid[r] { grid[r][i] = -1 } } for i := 0; i < 4; i++ { var randRow, randCol int for { randRow = rand.Intn(nRows) randCol = rand.Intn(nCols) if grid[randRow][randCol] != blank { break } } grid[randRow][randCol] = blank } if solve(0, 0) { printResult() } else { fmt.Println("No solution") } }
Perfect shuffle
Go
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: ::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles: ::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right" |- | ''original:'' || 1 2 3 4 5 6 7 8 |- | ''after 1st shuffle:'' || 1 5 2 6 3 7 4 8 |- | ''after 2nd shuffle:'' || 1 3 5 7 2 4 6 8 |- | ''after 3rd shuffle:'' || 1 2 3 4 5 6 7 8 |} '''''The Task''''' # Write a function that can perform a perfect shuffle on an even-sized list of values. # Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below. #* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck. #* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases. '''''Test Cases''''' ::::: {| class="wikitable" |- ! input ''(deck size)'' !! output ''(number of shuffles required)'' |- | 8 || 3 |- | 24 || 11 |- | 52 || 8 |- | 100 || 30 |- | 1020 || 1018 |- | 1024 || 10 |- | 10000 || 300 |}
package main import "fmt" type Deck struct { Cards []int length int } func NewDeck(deckSize int) (res *Deck){ if deckSize % 2 != 0{ panic("Deck size must be even") } res = new(Deck) res.Cards = make([]int, deckSize) res.length = deckSize for i,_ := range res.Cards{ res.Cards[i] = i } return } func (d *Deck)shuffleDeck(){ tmp := make([]int,d.length) for i := 0;i <d.length/2;i++ { tmp[i*2] = d.Cards[i] tmp[i*2+1] = d.Cards[d.length / 2 + i] } d.Cards = tmp } func (d *Deck) isEqualTo(c Deck) (res bool) { if d.length != c.length { panic("Decks aren't equally sized") } res = true for i, v := range d.Cards{ if v != c.Cards[i] { res = false } } return } func main(){ for _,v := range []int{8,24,52,100,1020,1024,10000} { fmt.Printf("Cards count: %d, shuffles required: %d\n",v,ShufflesRequired(v)) } } func ShufflesRequired(deckSize int)(res int){ deck := NewDeck(deckSize) Ref := *deck deck.shuffleDeck() res++ for ;!deck.isEqualTo(Ref);deck.shuffleDeck(){ res++ } return }
Perfect totient numbers
Go
Generate and show here, the first twenty Perfect totient numbers. ;Related task: ::* [[Totient function]] ;Also see: ::* the OEIS entry for perfect totient numbers. ::* mrob list of the first 54
package main import "fmt" func gcd(n, k int) int { if n < k || k < 1 { panic("Need n >= k and k >= 1") } s := 1 for n&1 == 0 && k&1 == 0 { n >>= 1 k >>= 1 s <<= 1 } t := n if n&1 != 0 { t = -k } for t != 0 { for t&1 == 0 { t >>= 1 } if t > 0 { n = t } else { k = -t } t = n - k } return n * s } func totient(n int) int { tot := 0 for k := 1; k <= n; k++ { if gcd(n, k) == 1 { tot++ } } return tot } func main() { var perfect []int for n := 1; len(perfect) < 20; n += 2 { tot := n sum := 0 for tot != 1 { tot = totient(tot) sum += tot } if sum == n { perfect = append(perfect, n) } } fmt.Println("The first 20 perfect totient numbers are:") fmt.Println(perfect) }
Periodic table
Go from Wren
Display the row and column in the periodic table of the given atomic number. ;The periodic table: Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | | | |1 H He | | | |2 Li Be B C N O F Ne | | | |3 Na Mg Al Si P S Cl Ar | | | |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | | | |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | | | |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | | | |7 Fr Ra deg Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | |__________________________________________________________________________| | | | | |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | | | |9 Aktinoidideg Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | |__________________________________________________________________________| ;Example test cases; * 1 -> 1 1 * 2 -> 1 18 * 29 -> 4 11 * 42 -> 5 6 * 57 -> 8 4 * 58 -> 8 5 * 72 -> 6 4 * 89 -> 9 4 ;Details; The representation of the periodic table may be represented in various way. The one presented in this challenge does have the following property : Lantanides and Aktinoides are all in a dedicated row, hence there is no element that is placed at 6, 3 nor 7, 3. You may take a look at the atomic number repartitions here. The atomic number is at least 1, at most 118. ;See also: * the periodic table * This task was an idea from CompSciFact * The periodic table in ascii that was used as template
package main import ( "fmt" "log" ) var limits = [][2]int{ {3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118}, } func periodicTable(n int) (int, int) { if n < 1 || n > 118 { log.Fatal("Atomic number is out of range.") } if n == 1 { return 1, 1 } if n == 2 { return 1, 18 } if n >= 57 && n <= 71 { return 8, n - 53 } if n >= 89 && n <= 103 { return 9, n - 85 } var row, start, end int for i := 0; i < len(limits); i++ { limit := limits[i] if n >= limit[0] && n <= limit[1] { row, start, end = i+2, limit[0], limit[1] break } } if n < start+2 || row == 4 || row == 5 { return row, n - start + 1 } return row, n - end + 18 } func main() { for _, n := range []int{1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113} { row, col := periodicTable(n) fmt.Printf("Atomic number %3d -> %d, %-2d\n", n, row, col) } }
Perlin noise
Go
The '''computer graphics, most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a pseudo-random mapping of \R^d into \R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4. Either by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012. ''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fade(x) v := fade(y) w := fade(z) A := p[X] + Y AA := p[A] + Z AB := p[A+1] + Z B := p[X+1] + Y BA := p[B] + Z BB := p[B+1] + Z return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x-1, y, z)), lerp(u, grad(p[AB], x, y-1, z), grad(p[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(p[AA+1], x, y, z-1), grad(p[BA+1], x-1, y, z-1)), lerp(u, grad(p[AB+1], x, y-1, z-1), grad(p[BB+1], x-1, y-1, z-1)))) } func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { // Go doesn't have a ternary. Ternaries can be translated directly // with if statements, but chains of if statements are often better // expressed with switch statements. switch hash & 15 { case 0, 12: return x + y case 1, 14: return y - x case 2: return x - y case 3: return -x - y case 4: return x + z case 5: return z - x case 6: return x - z case 7: return -x - z case 8: return y + z case 9, 13: return z - y case 10: return y - z } // case 11, 16: return -y - z } var permutation = []int{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, } var p = append(permutation, permutation...)
Permutations/Derangements
Go
A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. There are various ways to calculate !''n''. ;Task: # Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). # Generate ''and show'' all the derangements of 4 integers using the above routine. # Create a function that calculates the subfactorial of ''n'', !''n''. # Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive. ;Optional stretch goal: * Calculate !''20'' ;Related tasks: * [[Anagrams/Deranged anagrams]] * [[Best shuffle]] * [[Left_factorials]]
package main import ( "fmt" "math/big" ) // task 1: function returns list of derangements of n integers func dList(n int) (r [][]int) { a := make([]int, n) for i := range a { a[i] = i } // recursive closure permutes a var recurse func(last int) recurse = func(last int) { if last == 0 { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged. for j, v := range a { if j == v { return // no, ignore it } } // yes, save a copy r = append(r, append([]int{}, a...)) return } for i := last; i >= 0; i-- { a[i], a[last] = a[last], a[i] recurse(last - 1) a[i], a[last] = a[last], a[i] } } recurse(n - 1) return } // task 3: function computes subfactorial of n func subFact(n int) *big.Int { if n == 0 { return big.NewInt(1) } else if n == 1 { return big.NewInt(0) } d0 := big.NewInt(1) d1 := big.NewInt(0) f := new(big.Int) for i, n64 := int64(1), int64(n); i < n64; i++ { d0, d1 = d1, d0.Mul(f.SetInt64(i), d0.Add(d0, d1)) } return d1 } func main() { // task 2: fmt.Println("Derangements of 4 integers") for _, d := range dList(4) { fmt.Println(d) } // task 4: fmt.Println("\nNumber of derangements") fmt.Println("N Counted Calculated") for n := 0; n <= 9; n++ { fmt.Printf("%d %8d %11s\n", n, len(dList(n)), subFact(n).String()) } // stretch (sic) fmt.Println("\n!20 =", subFact(20)) }
Permutations/Rank of a permutation
Go
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1). For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank: PERMUTATION RANK (0, 1, 2, 3) -> 0 (0, 1, 3, 2) -> 1 (0, 2, 1, 3) -> 2 (0, 2, 3, 1) -> 3 (0, 3, 1, 2) -> 4 (0, 3, 2, 1) -> 5 (1, 0, 2, 3) -> 6 (1, 0, 3, 2) -> 7 (1, 2, 0, 3) -> 8 (1, 2, 3, 0) -> 9 (1, 3, 0, 2) -> 10 (1, 3, 2, 0) -> 11 (2, 0, 1, 3) -> 12 (2, 0, 3, 1) -> 13 (2, 1, 0, 3) -> 14 (2, 1, 3, 0) -> 15 (2, 3, 0, 1) -> 16 (2, 3, 1, 0) -> 17 (3, 0, 1, 2) -> 18 (3, 0, 2, 1) -> 19 (3, 1, 0, 2) -> 20 (3, 1, 2, 0) -> 21 (3, 2, 0, 1) -> 22 (3, 2, 1, 0) -> 23 Algorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above). One use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them. A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items. ;Task: # Create a function to generate a permutation from a rank. # Create the inverse function that given the permutation generates its rank. # Show that for n=3 the two functions are indeed inverses of each other. # Compute and show here 4 random, individual, samples of permutations of 12 objects. ;Stretch goal: * State how reasonable it would be to use your program to address the limits of the Stack Overflow question. ;References: # Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here). # Ranks on the DevData site. # Another answer on Stack Overflow to a different question that explains its algorithm in detail. ;Related tasks: #[[Factorial_base_numbers_indexing_permutations_of_a_collection]]
package main import ( "fmt" "math/rand" ) // returns permutation q of n items, using Myrvold-Ruskey rank. func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } // returns identity permutation of n items. func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } return p } // returns Myrvold-Ruskey rank of permutation p func MRRank(p []int) (r int) { p = append([]int{}, p...) inv := inverse(p) for i := len(p) - 1; i > 0; i-- { s := p[i] p[inv[i]] = s inv[s] = inv[i] } for i := 1; i < len(p); i++ { r = r*(i+1) + p[i] } return } // returns inverse of a permutation. func inverse(p []int) []int { r := make([]int, len(p)) for i, x := range p { r[x] = i } return r } // returns n! func fact(n int) (f int) { for f = n; n > 2; { n-- f *= n } return } func main() { n := 3 fmt.Println("permutations of", n, "items") f := fact(n) for i := 0; i < f; i++ { p := MRPerm(i, n) fmt.Println(i, p, MRRank(p)) } n = 12 fmt.Println("permutations of", n, "items") f = fact(n) m := map[int]bool{} for len(m) < 4 { r := rand.Intn(f) if m[r] { continue } m[r] = true fmt.Println(r, MRPerm(r, n)) } }
Permutations by swapping
Go
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation ''here''. Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind. Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement. ;References: * Steinhaus-Johnson-Trotter algorithm * Johnson-Trotter Algorithm Listing All Permutations * Heap's algorithm * Tintinnalogia ;Related tasks: * [[Matrix arithmetic] * [[Gray code]]
package permute // Iter takes a slice p and returns an iterator function. The iterator // permutes p in place and returns the sign. After all permutations have // been generated, the iterator returns 0 and p is left in its initial order. func Iter(p []int) func() int { f := pf(len(p)) return func() int { return f(p) } } // Recursive function used by perm, returns a chain of closures that // implement a loopless recursive SJT. func pf(n int) func([]int) int { sign := 1 switch n { case 0, 1: return func([]int) (s int) { s = sign sign = 0 return } default: p0 := pf(n - 1) i := n var d int return func(p []int) int { switch { case sign == 0: case i == n: i-- sign = p0(p[:i]) d = -1 case i == 0: i++ sign *= p0(p[1:]) d = 1 if sign == 0 { p[0], p[1] = p[1], p[0] } default: p[i], p[i-1] = p[i-1], p[i] sign = -sign i += d } return sign } } }
Phrase reversals
Go
Given a string of space separated words containing the following phrase: rosetta code phrase reversal :# Reverse the characters of the string. :# Reverse the characters of each individual word in the string, maintaining original word order within the string. :# Reverse the order of each word of the string, maintaining the order of characters in each word. Show your output here.
package main import ( "fmt" "strings" ) const phrase = "rosetta code phrase reversal" func revStr(s string) string { rs := make([]rune, len(s)) i := len(s) for _, r := range s { i-- rs[i] = r } return string(rs[i:]) } func main() { fmt.Println("Reversed: ", revStr(phrase)) ws := strings.Fields(phrase) for i, w := range ws { ws[i] = revStr(w) } fmt.Println("Words reversed: ", strings.Join(ws, " ")) ws = strings.Fields(phrase) last := len(ws) - 1 for i, w := range ws[:len(ws)/2] { ws[i], ws[last-i] = ws[last-i], w } fmt.Println("Word order reversed:", strings.Join(ws, " ")) }
Pig the dice game
Go
The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach '''100''' points or more. Play is taken in turns. On each person's turn that person has the option of either: :# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. :# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player. ;Task: Create a program to score for, and simulate dice throws for, a two-person game. ;Related task: * [[Pig the dice game/Player]]
package main import ( "fmt" "math/rand" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) //Set seed to current time playerScores := [...]int{0, 0} turn := 0 currentScore := 0 for { player := turn % len(playerScores) fmt.Printf("Player %v [%v, %v], (H)old, (R)oll or (Q)uit: ", player, playerScores[player], currentScore) var answer string fmt.Scanf("%v", &answer) switch strings.ToLower(answer) { case "h": //Hold playerScores[player] += currentScore fmt.Printf(" Player %v now has a score of %v.\n\n", player, playerScores[player]) if playerScores[player] >= 100 { fmt.Printf(" Player %v wins!!!\n", player) return } currentScore = 0 turn += 1 case "r": //Roll roll := rand.Intn(6) + 1 if roll == 1 { fmt.Printf(" Rolled a 1. Bust!\n\n") currentScore = 0 turn += 1 } else { fmt.Printf(" Rolled a %v.\n", roll) currentScore += roll } case "q": //Quit return default: //Incorrent input fmt.Print(" Please enter one of the given inputs.\n") } } fmt.Printf("Player %v wins!!!\n", (turn-1)%len(playerScores)) }
Pig the dice game/Player
Go
Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy. * State here the play strategies involved. * Show play during a game here. As a stretch goal: * Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger. ;Game Rules: The game of Pig is a multiplayer game played with a single six-sided die. The object of the game is to reach 100 points or more. Play is taken in turns. On each person's turn that person has the option of either # '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player. # '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player. ;References * Pig (dice) * The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.
package pig import ( "fmt" "math/rand" "time" ) type ( PlayerID int MessageID int StrategyID int PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } ) const ( // Status messages gameOver = iota piggedOut rolls pointSpending holds turn gameOverSummary // Players player1 = PlayerID(0) player2 = PlayerID(1) noPlayer = PlayerID(-1) // Max score maxScore = 100 // Strategies scoreChaseStrat = iota rollCountStrat ) // Returns "s" if n != 1 func pluralS(n int) string { if n != 1 { return "s" } return "" } // Creates an intializes a new PigGameData structure, returns a *PigGameData func New() *PigGameData { return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false} } // Create a status message for a given message ID func (pg *PigGameData) statusMessage(id MessageID) string { var msg string switch id { case gameOver: msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount) case piggedOut: msg = fmt.Sprintf(" Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount)) case rolls: msg = fmt.Sprintf(" Rolls %d", pg.lastRoll) case pointSpending: msg = fmt.Sprintf(" %d point%s pending", pg.turnScore, pluralS(pg.turnScore)) case holds: msg = fmt.Sprintf(" Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer)) case turn: msg = fmt.Sprintf("Player %d's turn:", pg.player+1) case gameOverSummary: msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2)) } return msg } // Print a status message, if pg.Verbose is true func (pg *PigGameData) PrintStatus(id MessageID) { if pg.verbose { fmt.Println(pg.statusMessage(id)) } } // Play a given strategy func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) { if pg.GameOver() { pg.PrintStatus(gameOver) return false } if pg.turnCount == 0 { pg.player = player2 pg.NextPlayer() } pg.lastRoll = rand.Intn(6) + 1 pg.PrintStatus(rolls) pg.turnRollCount++ if pg.lastRoll == 1 { pg.PrintStatus(piggedOut) pg.NextPlayer() } else { pg.turnScore += pg.lastRoll pg.PrintStatus(pointSpending) success := false switch id { case scoreChaseStrat: success = pg.scoreChaseStrategy() case rollCountStrat: success = pg.rollCountStrategy() } if success { pg.Hold() pg.NextPlayer() } } return true } // Get the score for a given player func (pg *PigGameData) PlayerScore(id PlayerID) int { if id == noPlayer { return pg.scores[pg.player] } return pg.scores[id] } // Check if the game is over func (pg *PigGameData) GameOver() bool { return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore } // Returns the Player ID if there is a winner, or -1 func (pg *PigGameData) Winner() PlayerID { for index, score := range pg.scores { if score >= maxScore { return PlayerID(index) } } return noPlayer } // Get the ID of the other player func (pg *PigGameData) otherPlayer() PlayerID { // 0 becomes 1, 1 becomes 0 return 1 - pg.player } func (pg *PigGameData) Hold() { pg.scores[pg.player] += pg.turnScore pg.PrintStatus(holds) pg.turnRollCount, pg.turnScore = 0, 0 } func (pg *PigGameData) NextPlayer() { pg.turnCount++ pg.turnRollCount, pg.turnScore = 0, 0 pg.player = pg.otherPlayer() pg.PrintStatus(turn) } func (pg *PigGameData) rollCountStrategy() bool { return pg.turnRollCount >= 3 } func (pg *PigGameData) scoreChaseStrategy() bool { myScore := pg.PlayerScore(pg.player) otherScore := pg.PlayerScore(pg.otherPlayer()) myPendingScore := pg.turnScore + myScore return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5 } // Run the simulation func main() { // Seed the random number generator rand.Seed(time.Now().UnixNano()) // Start a new game pg := New() pg.verbose = true strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat} // Play until game over for !pg.GameOver() { pg.Play(strategies[pg.player]) } pg.PrintStatus(gameOverSummary) }
Plasma effect
Go
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. ;Task Create a plasma effect. ;See also * Computer Graphics Tutorial (lodev.org) * Plasma (bidouille.org)
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 100 const delay = 4 // 40ms w, h := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, w, h) palette := make([]color.Color, nframes+1) palette[0] = color.White for i := 1; i <= nframes; i++ { r, g, b := hsb2rgb(float64(i)/nframes, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } for f := 1; f <= nframes; f++ { img := image.NewPaletted(rect, palette) setBackgroundColor(img, w, h, 0) // white background for y := 0; y < h; y++ { for x := 0; x < w; x++ { fx, fy := float64(x), float64(y) value := math.Sin(fx / 16) value += math.Sin(fy / 8) value += math.Sin((fx + fy) / 16) value += math.Sin(math.Sqrt(fx*fx+fy*fy) / 8) value += 4 // shift range from [-4, 4] to [0, 8] value /= 8 // bring range down to [0, 1] _, rem := math.Modf(value + float64(f)/float64(nframes)) ci := uint8(nframes*rem) + 1 img.SetColorIndex(x, y, ci) } } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("plasma.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
Playfair cipher
Go from Kotlin
Implement a Playfair cipher for encryption and decryption. The user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet. The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces. ;Output example: HI DE TH EG OL DI NT HE TR EX ES TU MP
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { // Build table. var used [26]bool // all elements false if p.pfo == noQ { used[16] = true // Q used } else { used[9] = true // J used } alphabet := strings.ToUpper(p.keyword) + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for i, j, k := 0, 0, 0; k < len(alphabet); k++ { c := alphabet[k] if c < 'A' || c > 'Z' { continue } d := int(c - 65) if !used[d] { p.table[i][j] = c used[d] = true j++ if j == 5 { i++ if i == 5 { break // table has been filled } j = 0 } } } } func (p *playfair) getCleanText(plainText string) string { // Ensure everything is upper case. plainText = strings.ToUpper(plainText) // Get rid of any non-letters and insert X between duplicate letters. var cleanText strings.Builder // Safe to assume null byte won't be present in plainText. prevByte := byte('\000') for i := 0; i < len(plainText); i++ { nextByte := plainText[i] // It appears that Q should be omitted altogether if NO_Q option is specified; // we assume so anyway. if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) { continue } // If iEqualsJ option specified, replace J with I. if nextByte == 'J' && p.pfo == iEqualsJ { nextByte = 'I' } if nextByte != prevByte { cleanText.WriteByte(nextByte) } else { cleanText.WriteByte('X') cleanText.WriteByte(nextByte) } prevByte = nextByte } l := cleanText.Len() if l%2 == 1 { // Dangling letter at end so add another letter to complete digram. if cleanText.String()[l-1] != 'X' { cleanText.WriteByte('X') } else { cleanText.WriteByte('Z') } } return cleanText.String() } func (p *playfair) findByte(c byte) (int, int) { for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if p.table[i][j] == c { return i, j } } } return -1, -1 } func (p *playfair) encode(plainText string) string { cleanText := p.getCleanText(plainText) var cipherText strings.Builder l := len(cleanText) for i := 0; i < l; i += 2 { row1, col1 := p.findByte(cleanText[i]) row2, col2 := p.findByte(cleanText[i+1]) switch { case row1 == row2: cipherText.WriteByte(p.table[row1][(col1+1)%5]) cipherText.WriteByte(p.table[row2][(col2+1)%5]) case col1 == col2: cipherText.WriteByte(p.table[(row1+1)%5][col1]) cipherText.WriteByte(p.table[(row2+1)%5][col2]) default: cipherText.WriteByte(p.table[row1][col2]) cipherText.WriteByte(p.table[row2][col1]) } if i < l-1 { cipherText.WriteByte(' ') } } return cipherText.String() } func (p *playfair) decode(cipherText string) string { var decodedText strings.Builder l := len(cipherText) // cipherText will include spaces so we need to skip them. for i := 0; i < l; i += 3 { row1, col1 := p.findByte(cipherText[i]) row2, col2 := p.findByte(cipherText[i+1]) switch { case row1 == row2: temp := 4 if col1 > 0 { temp = col1 - 1 } decodedText.WriteByte(p.table[row1][temp]) temp = 4 if col2 > 0 { temp = col2 - 1 } decodedText.WriteByte(p.table[row2][temp]) case col1 == col2: temp := 4 if row1 > 0 { temp = row1 - 1 } decodedText.WriteByte(p.table[temp][col1]) temp = 4 if row2 > 0 { temp = row2 - 1 } decodedText.WriteByte(p.table[temp][col2]) default: decodedText.WriteByte(p.table[row1][col2]) decodedText.WriteByte(p.table[row2][col1]) } if i < l-1 { decodedText.WriteByte(' ') } } return decodedText.String() } func (p *playfair) printTable() { fmt.Println("The table to be used is :\n") for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { fmt.Printf("%c ", p.table[i][j]) } fmt.Println() } } func main() { scanner := bufio.NewScanner(os.Stdin) fmt.Print("Enter Playfair keyword : ") scanner.Scan() keyword := scanner.Text() var ignoreQ string for ignoreQ != "y" && ignoreQ != "n" { fmt.Print("Ignore Q when building table y/n : ") scanner.Scan() ignoreQ = strings.ToLower(scanner.Text()) } pfo := noQ if ignoreQ == "n" { pfo = iEqualsJ } var table [5][5]byte pf := &playfair{keyword, pfo, table} pf.init() pf.printTable() fmt.Print("\nEnter plain text : ") scanner.Scan() plainText := scanner.Text() if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) return } encodedText := pf.encode(plainText) fmt.Println("\nEncoded text is :", encodedText) decodedText := pf.decode(encodedText) fmt.Println("Deccoded text is :", decodedText) }
Plot coordinate pairs
Go
Plot a function represented as x, y numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}; This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
package main import ( "fmt" "log" "os/exec" ) var ( x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} ) func main() { g := exec.Command("gnuplot", "-persist") w, err := g.StdinPipe() if err != nil { log.Fatal(err) } if err = g.Start(); err != nil { log.Fatal(err) } fmt.Fprintln(w, "unset key; plot '-'") for i, xi := range x { fmt.Fprintf(w, "%d %f\n", xi, y[i]) } fmt.Fprintln(w, "e") w.Close() g.Wait() }
Poker hand analyser
Go from Kotlin
Create a program to parse a single five card poker hand and rank it according to this list of poker hands. A poker hand is specified as a space separated list of five playing cards. Each input card has two characters indicating face and suit. ;Example: ::::'''2d''' (two of diamonds). Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k''' Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or alternatively, the unicode card-suit characters: Duplicate cards are illegal. The program should analyze a single hand and produce one of the following outputs: straight-flush four-of-a-kind full-house flush straight three-of-a-kind two-pair one-pair high-card invalid ;Examples: 2 2 2 k q: three-of-a-kind 2 5 7 8 9: high-card a 2 3 4 5: straight 2 3 2 3 3: full-house 2 7 2 3 3: two-pair 2 7 7 7 7: four-of-a-kind 10 j q k a: straight-flush 4 4 k 5 10: one-pair q 10 7 6 q: invalid The programs output for the above examples should be displayed here on this page. ;Extra credit: # use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE). # allow two jokers ::* use the symbol '''joker''' ::* duplicates would be allowed (for jokers only) ::* five-of-a-kind would then be the highest hand ;More extra credit examples: joker 2 2 k q: three-of-a-kind joker 5 7 8 9: straight joker 2 3 4 5: straight joker 3 2 3 3: four-of-a-kind joker 7 2 3 3: three-of-a-kind joker 7 7 7 7: five-of-a-kind joker j q k A: straight-flush joker 4 k 5 10: one-pair joker k 7 6 4: flush joker 2 joker 4 5: straight joker Q joker A 10: straight joker Q joker A 10: straight-flush joker 2 2 joker q: four-of-a-kind ;Related tasks: * [[Playing cards]] * [[Card shuffles]] * [[Deal cards_for_FreeCell]] * [[War Card_Game]] * [[Go Fish]]
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted[i].face < sorted[j].face }) if sorted[0].face+4 == sorted[4].face { return true } if sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5 { return true } return false } func isFlush(cards []card) bool { suit := cards[0].suit for i := 1; i < 5; i++ { if cards[i].suit != suit { return false } } return true } func analyzeHand(hand string) string { temp := strings.Fields(strings.ToLower(hand)) splitSet := make(map[string]bool) var split []string for _, s := range temp { if !splitSet[s] { splitSet[s] = true split = append(split, s) } } if len(split) != 5 { return "invalid" } var cards []card for _, s := range split { if len(s) != 2 { return "invalid" } fIndex := strings.IndexByte(faces, s[0]) if fIndex == -1 { return "invalid" } sIndex := strings.IndexByte(suits, s[1]) if sIndex == -1 { return "invalid" } cards = append(cards, card{byte(fIndex + 2), s[1]}) } groups := make(map[byte][]card) for _, c := range cards { groups[c.face] = append(groups[c.face], c) } switch len(groups) { case 2: for _, group := range groups { if len(group) == 4 { return "four-of-a-kind" } } return "full-house" case 3: for _, group := range groups { if len(group) == 3 { return "three-of-a-kind" } } return "two-pair" case 4: return "one-pair" default: flush := isFlush(cards) straight := isStraight(cards) switch { case flush && straight: return "straight-flush" case flush: return "flush" case straight: return "straight" default: return "high-card" } } } func main() { hands := [...]string{ "2h 2d 2c kc qd", "2h 5h 7d 8c 9s", "ah 2d 3c 4c 5d", "2h 3h 2d 3c 3d", "2h 7h 2d 3c 3d", "2h 7h 7d 7c 7s", "th jh qh kh ah", "4h 4s ks 5d ts", "qc tc 7c 6c 4c", "ah ah 7c 6c 4c", } for _, hand := range hands { fmt.Printf("%s: %s\n", hand, analyzeHand(hand)) } }
Polyspiral
Go
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. ;Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied. If animation is not practical in your programming environment, you may show a single frame instead. ;Pseudo code set incr to 0.0 // animation loop WHILE true incr = (incr + 0.05) MOD 360 x = width / 2 y = height / 2 length = 5 angle = incr // spiral loop FOR 1 TO 150 drawline change direction by angle length = length + 3 angle = (angle + incr) MOD 360 ENDFOR
package main import ( "image" "image/color" "image/gif" "log" "math" "os" ) func drawLine(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) { var first, last int if x2 != x1 { m := float64(y2-y1) / float64(x2-x1) if x1 < x2 { first, last = x1, x2 } else { first, last = x2, x1 } for x := first; x <= last; x++ { y := int(m*float64(x-x1)+0.5) + y1 img.SetColorIndex(x, y, ci) } } else { if y1 < y2 { first, last = y1, y2 } else { first, last = y2, y1 } for y := first; y <= last; y++ { img.SetColorIndex(x1, y, ci) } } } func setBackgroundColor(img *image.Paletted, w, h int, ci uint8) { for x := 0; x < w; x++ { for y := 0; y < h; y++ { img.SetColorIndex(x, y, ci) } } } func hsb2rgb(hue, sat, bri float64) (r, g, b int) { u := int(bri*255 + 0.5) if sat == 0 { r, g, b = u, u, u } else { h := (hue - math.Floor(hue)) * 6 f := h - math.Floor(h) p := int(bri*(1-sat)*255 + 0.5) q := int(bri*(1-sat*f)*255 + 0.5) t := int(bri*(1-sat*(1-f))*255 + 0.5) switch int(h) { case 0: r, g, b = u, t, p case 1: r, g, b = q, u, p case 2: r, g, b = p, u, t case 3: r, g, b = p, q, u case 4: r, g, b = t, p, u case 5: r, g, b = u, p, q } } return } func main() { const degToRad = math.Pi / 180 const nframes = 360 const delay = 20 // 200ms width, height := 640, 640 anim := gif.GIF{LoopCount: nframes} rect := image.Rect(0, 0, width, height) palette := make([]color.Color, 151) palette[0] = color.White for i := 1; i <= 150; i++ { r, g, b := hsb2rgb(float64(i)/150, 1, 1) palette[i] = color.RGBA{uint8(r), uint8(g), uint8(b), 255} } incr := 0 for f := 1; f <= nframes; f++ { incr = (incr + 1) % 360 x1, y1 := width/2, height/2 length := 5.0 img := image.NewPaletted(rect, palette) setBackgroundColor(img, width, height, 0) // white background angle := incr for ci := uint8(1); ci <= 150; ci++ { x2 := x1 + int(math.Cos(float64(angle)*degToRad)*length) y2 := y1 - int(math.Sin(float64(angle)*degToRad)*length) drawLine(img, x1, y1, x2, y2, ci) x1, y1 = x2, y2 length += 3 angle = (angle + incr) % 360 } anim.Delay = append(anim.Delay, delay) anim.Image = append(anim.Image, img) } file, err := os.Create("polyspiral.gif") if err != nil { log.Fatal(err) } defer file.Close() if err2 := gif.EncodeAll(file, &anim); err != nil { log.Fatal(err2) } }
Population count
Go
The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer. ''Population count'' is also known as: ::::* ''pop count'' ::::* ''popcount'' ::::* ''sideways sum'' ::::* ''bit summation'' ::::* ''Hamming weight'' For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''. ''Evil numbers'' are non-negative integers that have an ''even'' population count. ''Odious numbers'' are positive integers that have an ''odd'' population count. ;Task: * write a function (or routine) to return the population count of a non-negative integer. * all computation of the lists below should start with '''0''' (zero indexed). :* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329'''). :* display the 1st thirty ''evil'' numbers. :* display the 1st thirty ''odious'' numbers. * display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified. ;See also * The On-Line Encyclopedia of Integer Sequences: A000120 population count. * The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers. * The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
package main import ( "fmt" "math/bits" ) func main() { fmt.Println("Pop counts, powers of 3:") n := uint64(1) // 3^0 for i := 0; i < 30; i++ { fmt.Printf("%d ", bits.OnesCount64(n)) n *= 3 } fmt.Println() fmt.Println("Evil numbers:") var od [30]uint64 var ne, no int for n = 0; ne+no < 60; n++ { if bits.OnesCount64(n)&1 == 0 { if ne < 30 { fmt.Printf("%d ", n) ne++ } } else { if no < 30 { od[no] = n no++ } } } fmt.Println() fmt.Println("Odious numbers:") for _, n := range od { fmt.Printf("%d ", n) } fmt.Println() }
Prime triangle
Go from Phix
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements. ;See also :* OEIS:A036440
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { if canFollow[ad-1][n-1] { if bFirst { for _, e := range arrang { fmt.Printf("%2d ", e) } fmt.Println() bFirst = false } res++ } } else { done++ for i := done - 1; i <= n-2; i += 2 { ai := arrang[i] if canFollow[ad-1][ai-1] { arrang[i], arrang[done-1] = arrang[done-1], arrang[i] res = ptrs(res, n, done) arrang[i], arrang[done-1] = arrang[done-1], arrang[i] } } } return res } func primeTriangle(n int) int { canFollow = make([][]bool, n) for i := 0; i < n; i++ { canFollow[i] = make([]bool, n) for j := 0; j < n; j++ { _, ok := pmap[i+j+2] canFollow[i][j] = ok } } bFirst = true arrang = make([]int, n) for i := 0; i < n; i++ { arrang[i] = i + 1 } return ptrs(0, n, 1) } func main() { counts := make([]int, 19) for i := 2; i <= 20; i++ { counts[i-2] = primeTriangle(i) } fmt.Println() for i := 0; i < 19; i++ { fmt.Printf("%d ", counts[i]) } fmt.Println() }
Priority queue
Go
A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order. ;Task: Create a priority queue. The queue must support at least two operations: :# Insertion. An element is added to the queue with a priority (a numeric value). :# Top item removal. Deletes the element or one of the elements with the current top priority and return it. Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc. To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data: '''Priority''' '''Task''' ---------- ---------------- 3 Clear drains 4 Feed cat 5 Make tea 1 Solve RC tasks 2 Tax return The implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
package main import ( "fmt" "container/heap" ) type Task struct { priority int name string } type TaskPQ []Task func (self TaskPQ) Len() int { return len(self) } func (self TaskPQ) Less(i, j int) bool { return self[i].priority < self[j].priority } func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) } func (self *TaskPQ) Pop() (popped interface{}) { popped = (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return } func main() { pq := &TaskPQ{{3, "Clear drains"}, {4, "Feed cat"}, {5, "Make tea"}, {1, "Solve RC tasks"}} // heapify heap.Init(pq) // enqueue heap.Push(pq, Task{2, "Tax return"}) for pq.Len() != 0 { // dequeue fmt.Println(heap.Pop(pq)) } }
Pseudo-random numbers/Combined recursive generator MRG32k3a
Go from Python
MRG32k3a Combined recursive generator (pseudo-code): /* Constants */ /* First generator */ a1 = [0, 1403580, -810728] m1 = 2**32 - 209 /* Second Generator */ a2 = [527612, 0, -1370589] m2 = 2**32 - 22853 d = m1 + 1 class MRG32k3a x1 = [0, 0, 0] /* list of three last values of gen #1 */ x2 = [0, 0, 0] /* list of three last values of gen #2 */ method seed(u64 seed_state) assert seed_state in range >0 and < d x1 = [seed_state, 0, 0] x2 = [seed_state, 0, 0] end method method next_int() x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1 x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2 x1 = [x1i, x1[0], x1[1]] /* Keep last three */ x2 = [x2i, x2[0], x2[1]] /* Keep last three */ z = (x1i - x2i) % m1 answer = (z + 1) return answer end method method next_float(): return float next_int() / d end method end class :MRG32k3a Use: random_gen = instance MRG32k3a random_gen.seed(1234567) print(random_gen.next_int()) /* 1459213977 */ print(random_gen.next_int()) /* 2827710106 */ print(random_gen.next_int()) /* 4245671317 */ print(random_gen.next_int()) /* 3877608661 */ print(random_gen.next_int()) /* 2595287583 */ ;Task * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers generated with the seed `1234567` are as shown above * Show that for an initial seed of '987654321' the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) Is as follows: 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931 * Show your output here, on this page.
package main import ( "fmt" "log" "math" ) var a1 = []int64{0, 1403580, -810728} var a2 = []int64{527612, 0, -1370589} const m1 = int64((1 << 32) - 209) const m2 = int64((1 << 32) - 22853) const d = m1 + 1 // Python style modulus func mod(x, y int64) int64 { m := x % y if m < 0 { if y < 0 { return m - y } else { return m + y } } return m } type MRG32k3a struct{ x1, x2 [3]int64 } func MRG32k3aNew() *MRG32k3a { return &MRG32k3a{} } func (mrg *MRG32k3a) seed(seedState int64) { if seedState <= 0 || seedState >= d { log.Fatalf("Argument must be in the range [0, %d].\n", d) } mrg.x1 = [3]int64{seedState, 0, 0} mrg.x2 = [3]int64{seedState, 0, 0} } func (mrg *MRG32k3a) nextInt() int64 { x1i := mod(a1[0]*mrg.x1[0]+a1[1]*mrg.x1[1]+a1[2]*mrg.x1[2], m1) x2i := mod(a2[0]*mrg.x2[0]+a2[1]*mrg.x2[1]+a2[2]*mrg.x2[2], m2) mrg.x1 = [3]int64{x1i, mrg.x1[0], mrg.x1[1]} /* keep last three */ mrg.x2 = [3]int64{x2i, mrg.x2[0], mrg.x2[1]} /* keep last three */ return mod(x1i-x2i, m1) + 1 } func (mrg *MRG32k3a) nextFloat() float64 { return float64(mrg.nextInt()) / float64(d) } func main() { randomGen := MRG32k3aNew() randomGen.seed(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Pseudo-random numbers/Middle-square method
Go
{{Wikipedia|Middle-square method|en}} ; The Method: To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number in the sequence and returned as the result. This process is then repeated to generate more numbers. ; Pseudo code: var seed = 675248 function random() var s = str(seed * seed) 'str: turn a number into string do while not len(s) = 12 s = "0" + s 'add zeroes before the string end do seed = val(mid(s, 4, 6)) 'mid: string variable, start, length 'val: turn a string into number return seed end function ; Middle-square method use: for i = 1 to 5 print random() end for ;Task: * Generate a class/set of functions that generates pseudo-random numbers (6 digits) as shown above. * Show the first five integers generated with the seed 675248 as shown above. * Show your output here, on this page.
package main import "fmt" func random(seed int) int { return seed * seed / 1e3 % 1e6 } func main() { seed := 675248 for i := 1; i <= 5; i++ { seed = random(seed) fmt.Println(seed) } }
Pseudo-random numbers/PCG32
Go from Python
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 :'''|''' Bitwise or operator ::https://en.wikipedia.org/wiki/Bitwise_operation#OR ::Bitwise comparison gives 1 if any of corresponding bits are 1 :::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111 ;PCG32 Generator (pseudo-code): PCG32 has two unsigned 64-bit integers of internal state: # '''state''': All 2**64 values may be attained. # '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime). Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state. The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:- const N<-U64 6364136223846793005 const inc<-U64 (seed_sequence << 1) | 1 state<-U64 ((inc+seed_state)*N+inc do forever xs<-U32 (((state>>18)^state)>>27) rot<-INT (state>>59) OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31)) state<-state*N+inc end do Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`. ;Task: * Generate a class/set of functions that generates pseudo-random numbers using the above. * Show that the first five integers generated with the seed 42, 54 are: 2707161783 2068313097 3122475824 2211639955 3215226955 * Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005 * Show your output here, on this page.
package main import ( "fmt" "math" ) const CONST = 6364136223846793005 type Pcg32 struct{ state, inc uint64 } func Pcg32New() *Pcg32 { return &Pcg32{0x853c49e6748fea9b, 0xda3e39cb94b95bdb} } func (pcg *Pcg32) seed(seedState, seedSequence uint64) { pcg.state = 0 pcg.inc = (seedSequence << 1) | 1 pcg.nextInt() pcg.state = pcg.state + seedState pcg.nextInt() } func (pcg *Pcg32) nextInt() uint32 { old := pcg.state pcg.state = old*CONST + pcg.inc pcgshifted := uint32(((old >> 18) ^ old) >> 27) rot := uint32(old >> 59) return (pcgshifted >> rot) | (pcgshifted << ((-rot) & 31)) } func (pcg *Pcg32) nextFloat() float64 { return float64(pcg.nextInt()) / (1 << 32) } func main() { randomGen := Pcg32New() randomGen.seed(42, 54) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321, 1) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Pseudo-random numbers/Xorshift star
Go from Python
Some definitions to help in the explanation: :Floor operation ::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions ::Greatest integer less than or equal to a real number. :Bitwise Logical shift operators (c-inspired) ::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts ::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. ::Examples are shown for 8 bit binary numbers; most significant bit to the left. :: '''<<''' Logical shift left by given number of bits. :::E.g Binary 00110101 '''<<''' 2 == Binary 11010100 :: '''>>''' Logical shift right by given number of bits. :::E.g Binary 00110101 '''>>''' 2 == Binary 00001101 :'''^''' Bitwise exclusive-or operator ::https://en.wikipedia.org/wiki/Exclusive_or ::Bitwise comparison for if bits differ :::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110 ;Xorshift_star Generator (pseudo-code): /* Let u64 denote an unsigned 64 bit integer type. */ /* Let u32 denote an unsigned 32 bit integer type. */ class Xorshift_star u64 state /* Must be seeded to non-zero initial value */ u64 const = HEX '2545F4914F6CDD1D' method seed(u64 num): state = num end method method next_int(): u64 x = state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) state = x u32 answer = ((x * const) >> 32) return answer end method method next_float(): return float next_int() / (1 << 32) end method end class :;Xorshift use: random_gen = instance Xorshift_star random_gen.seed(1234567) print(random_gen.next_int()) /* 3540625527 */ print(random_gen.next_int()) /* 2750739987 */ print(random_gen.next_int()) /* 4037983143 */ print(random_gen.next_int()) /* 1993361440 */ print(random_gen.next_int()) /* 3809424708 */ ;Task: * Generate a class/set of functions that generates pseudo-random numbers as shown above. * Show that the first five integers genrated with the seed 1234567 are as shown above * Show that for an initial seed of 987654321, the counts of 100_000 repetitions of floor(random_gen.next_float() * 5) :Is as follows: 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007 * Show your output here, on this page.
package main import ( "fmt" "math" ) const CONST = 0x2545F4914F6CDD1D type XorshiftStar struct{ state uint64 } func XorshiftStarNew(state uint64) *XorshiftStar { return &XorshiftStar{state} } func (xor *XorshiftStar) seed(state uint64) { xor.state = state } func (xor *XorshiftStar) nextInt() uint32 { x := xor.state x = x ^ (x >> 12) x = x ^ (x << 25) x = x ^ (x >> 27) xor.state = x return uint32((x * CONST) >> 32) } func (xor *XorshiftStar) nextFloat() float64 { return float64(xor.nextInt()) / (1 << 32) } func main() { randomGen := XorshiftStarNew(1234567) for i := 0; i < 5; i++ { fmt.Println(randomGen.nextInt()) } var counts [5]int randomGen.seed(987654321) for i := 0; i < 1e5; i++ { j := int(math.Floor(randomGen.nextFloat() * 5)) counts[j]++ } fmt.Println("\nThe counts for 100,000 repetitions are:") for i := 0; i < 5; i++ { fmt.Printf(" %d : %d\n", i, counts[i]) } }
Pythagoras tree
Go
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. ;Task Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). ;Related tasks * Fractal tree
package main import ( "image" "image/color" "image/draw" "image/png" "log" "os" ) const ( width, height = 800, 600 maxDepth = 11 // how far to recurse, between 1 and 20 is reasonable colFactor = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out fileName = "pythagorasTree.png" ) func main() { img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background drawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image imgFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } defer imgFile.Close() if err := png.Encode(imgFile, img); err != nil { imgFile.Close() log.Fatal(err) } } func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { if depth > maxDepth { return } dx, dy := bx-ax, ay-by x3, y3 := bx-dy, by-dx x4, y4 := ax-dy, ay-dx x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} drawLine(ax, ay, bx, by, img, col) drawLine(bx, by, x3, y3, img, col) drawLine(x3, y3, x4, y4, img, col) drawLine(x4, y4, ax, ay, img, col) drawSquares(x4, y4, x5, y5, img, depth+1) drawSquares(x5, y5, x3, y3, img, depth+1) } func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { dx := abs(x1 - x0) dy := abs(y1 - y0) var sx, sy int = -1, -1 if x0 < x1 { sx = 1 } if y0 < y1 { sy = 1 } err := dx - dy for { img.Set(x0, y0, col) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } } func abs(x int) int { if x < 0 { return -x } return x }
Pythagorean quadruples
Go from FreeBASIC
One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): :::::::: a2 + b2 + c2 = d2 An example: :::::::: 22 + 32 + 62 = 72 ::::: which is: :::::::: 4 + 9 + 36 = 49 ;Task: For positive integers up '''2,200''' (inclusive), for all values of '''a''', '''b''', '''c''', and '''d''', find (and show here) those values of '''d''' that ''can't'' be represented. Show the values of '''d''' on one line of output (optionally with a title). ;Related tasks: * [[Euler's sum of powers conjecture]]. * [[Pythagorean triples]]. ;Reference: :* the Wikipedia article: Pythagorean quadruple.
package main import "fmt" const ( N = 2200 N2 = N * N * 2 ) func main() { s := 3 var s1, s2 int var r [N + 1]bool var ab [N2 + 1]bool for a := 1; a <= N; a++ { a2 := a * a for b := a; b <= N; b++ { ab[a2 + b * b] = true } } for c := 1; c <= N; c++ { s1 = s s += 2 s2 = s for d := c + 1; d <= N; d++ { if ab[s1] { r[d] = true } s1 += s2 s2 += 2 } } for d := 1; d <= N; d++ { if !r[d] { fmt.Printf("%d ", d) } } fmt.Println() }
Pythagorean triples
Go
A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2. They are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\rm gcd}(a, b) = {\rm gcd}(a, c) = {\rm gcd}(b, c) = 1. Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\rm gcd}(a, b) = 1). Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c. ;Task: The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive. ;Extra credit: Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000? Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner. ;Related tasks: * [[Euler's sum of powers conjecture]] * [[List comprehensions]] * [[Pythagorean quadruples]]
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
Quaternion type
Go
complex numbers. A complex number has a real and complex part, sometimes written as a + bi, where a and b stand for real numbers, and i stands for the square root of minus 1. An example of a complex number might be -3 + 2i, where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. A quaternion has one real part and ''three'' imaginary parts, i, j, and k. A quaternion might be written as a + bi + cj + dk. In the quaternion numbering system: :::* ii = jj = kk = ijk = -1, or more simply, :::* ii = jj = kk = ijk = -1. The order of multiplication is important, as, in general, for two quaternions: :::: q1 and q2: q1q2 q2q1. An example of a quaternion might be 1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. So the example above would be written as (1, 2, 3, 4) ;Task: Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number r = 7. Create functions (or classes) to perform simple maths with quaternions including computing: # The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2} # The negative of a quaternion: = (-a, -b, -c, -d) # The conjugate of a quaternion: = ( a, -b, -c, -d) # Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) # Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) # Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) # Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) # Show that, for the two quaternions q1 and q2: q1q2 q2q1 If a language has built-in support for quaternions, then use it. ;C.f.: * [[Vector products]] * On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
package main import ( "fmt" "math" ) type qtn struct { r, i, j, k float64 } var ( q = &qtn{1, 2, 3, 4} q1 = &qtn{2, 3, 4, 5} q2 = &qtn{3, 4, 5, 6} r float64 = 7 ) func main() { fmt.Println("Inputs") fmt.Println("q:", q) fmt.Println("q1:", q1) fmt.Println("q2:", q2) fmt.Println("r:", r) var qr qtn fmt.Println("\nFunctions") fmt.Println("q.norm():", q.norm()) fmt.Println("neg(q):", qr.neg(q)) fmt.Println("conj(q):", qr.conj(q)) fmt.Println("addF(q, r):", qr.addF(q, r)) fmt.Println("addQ(q1, q2):", qr.addQ(q1, q2)) fmt.Println("mulF(q, r):", qr.mulF(q, r)) fmt.Println("mulQ(q1, q2):", qr.mulQ(q1, q2)) fmt.Println("mulQ(q2, q1):", qr.mulQ(q2, q1)) } func (q *qtn) String() string { return fmt.Sprintf("(%g, %g, %g, %g)", q.r, q.i, q.j, q.k) } func (q *qtn) norm() float64 { return math.Sqrt(q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k) } func (z *qtn) neg(q *qtn) *qtn { z.r, z.i, z.j, z.k = -q.r, -q.i, -q.j, -q.k return z } func (z *qtn) conj(q *qtn) *qtn { z.r, z.i, z.j, z.k = q.r, -q.i, -q.j, -q.k return z } func (z *qtn) addF(q *qtn, r float64) *qtn { z.r, z.i, z.j, z.k = q.r+r, q.i, q.j, q.k return z } func (z *qtn) addQ(q1, q2 *qtn) *qtn { z.r, z.i, z.j, z.k = q1.r+q2.r, q1.i+q2.i, q1.j+q2.j, q1.k+q2.k return z } func (z *qtn) mulF(q *qtn, r float64) *qtn { z.r, z.i, z.j, z.k = q.r*r, q.i*r, q.j*r, q.k*r return z } func (z *qtn) mulQ(q1, q2 *qtn) *qtn { z.r, z.i, z.j, z.k = q1.r*q2.r-q1.i*q2.i-q1.j*q2.j-q1.k*q2.k, q1.r*q2.i+q1.i*q2.r+q1.j*q2.k-q1.k*q2.j, q1.r*q2.j-q1.i*q2.k+q1.j*q2.r+q1.k*q2.i, q1.r*q2.k+q1.i*q2.j-q1.j*q2.i+q1.k*q2.r return z }
Quine
Go
A quine is a self-referential program that can, without any external access, output its own source. A '''quine''' (named after Willard Van Orman Quine) is also known as: ::* ''self-reproducing automata'' (1972) ::* ''self-replicating program'' or ''self-replicating computer program'' ::* ''self-reproducing program'' or ''self-reproducing computer program'' ::* ''self-copying program'' or ''self-copying computer program'' It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. ;Task: Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: * Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. ** Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. ** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. * Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. ** If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. ** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. ** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. '''Next to the Quines presented here, many other versions can be found on the Quine page.''' ;Related task: :* print itself.
package main import "fmt" func main() { a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n" fmt.Printf(a, a) }
Quoting constructs
Go
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format? This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, '''NOT''' just a link to [See the language docs]. Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
package main import ( "fmt" "os" "regexp" "strconv" ) /* Quoting constructs in Go. */ // In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune' // but the more familiar term 'character' will be used instead here. // Character literal (single quotes). // Can contain any single character including an escaped character. var ( rl1 = 'a' rl2 = '\'' // single quote can only be included in escaped form ) // Interpreted string literal (double quotes). // A sequence of characters including escaped characters. var ( is1 = "abc" is2 = "\"ab\tc\"" // double quote can only be included in escaped form ) // Raw string literal(single back quotes). // Can contain any character including a 'physical' new line but excluding back quote. // Escaped characters are interpreted literally i.e. `\n` is backslash followed by n. // Raw strings are typically used for hard-coding pieces of text perhaps // including single and/or double quotes without the need to escape them. // They are particularly useful for regular expressions. var ( rs1 = ` first" second' third" ` rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.` rs3 = `\d+` // a sequence of one or more digits in a regular expression ) func main() { fmt.Println(rl1, rl2) // prints the code point value not the character itself fmt.Println(is1, is2) fmt.Println(rs1) fmt.Println(rs2) re := regexp.MustCompile(rs3) fmt.Println(re.FindString("abcd1234efgh")) /* None of the above quoting constructs can deal directly with interpolation. This is done instead using library functions. */ // C-style using %d, %f, %s etc. within a 'printf' type function. n := 3 fmt.Printf("\nThere are %d quoting constructs in Go.\n", n) // Using a function such as fmt.Println which can take a variable // number of arguments, of any type, and print then out separated by spaces. s := "constructs" fmt.Println("There are", n, "quoting", s, "in Go.") // Using the function os.Expand which requires a mapper function to fill placeholders // denoted by ${...} within a string. mapper := func(placeholder string) string { switch placeholder { case "NUMBER": return strconv.Itoa(n) case "TYPES": return s } return "" } fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper)) }
RPG attributes generator
Go
'''RPG''' = Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: * The total of all character attributes must be at least 75. * At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. ;Task: Write a program that: # Generates 4 random, whole values between 1 and 6. # Saves the sum of the 3 largest values. # Generates a total of 6 values this way. # Displays the total, and all 6 values once finished. * The order in which each value was generated must be preserved. * The total of all 6 values must be at least 75. * At least 2 of the values must be 15 or more.
package main import ( "fmt" "math/rand" "sort" "time" ) func main() { s := rand.NewSource(time.Now().UnixNano()) r := rand.New(s) for { var values [6]int vsum := 0 for i := range values { var numbers [4]int for j := range numbers { numbers[j] = 1 + r.Intn(6) } sort.Ints(numbers[:]) nsum := 0 for _, n := range numbers[1:] { nsum += n } values[i] = nsum vsum += values[i] } if vsum < 75 { continue } vcount := 0 for _, v := range values { if v >= 15 { vcount++ } } if vcount < 2 { continue } fmt.Println("The 6 random numbers generated are:") fmt.Println(values) fmt.Println("\nTheir sum is", vsum, "and", vcount, "of them are >= 15") break } }
Ramer-Douglas-Peucker line simplification
Go
The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. ;Task: Using the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is: '''1.0'''. Display the remaining points here. ;Reference: :* the Wikipedia article: Ramer-Douglas-Peucker algorithm.
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x - x21*p.y + p2.x*p1.y - p2.y*p1.x); d > dMax { x = i + 1 dMax = d } } if dMax > ε { return append(RDP(l[:x+1], ε), RDP(l[x:], ε)[1:]...) } return []point{l[0], l[len(l)-1]} } func main() { fmt.Println(RDP([]point{{0, 0}, {1, 0.1}, {2, -0.1}, {3, 5}, {4, 6}, {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}}, 1)) }
Random Latin squares
Go
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. For the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero. ;Example n=4 randomised Latin square: 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 ;Task: # Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. # Use the function to generate ''and show here'', two randomly generated squares of size 5. ;Note: Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task. ;Related tasks: * [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]] * [[Latin Squares in reduced form]] ;Reference: * Wikipedia: Latin square * OEIS: A002860
package main import ( "fmt" "math/rand" "time" ) type matrix [][]int func shuffle(row []int, n int) { rand.Shuffle(n, func(i, j int) { row[i], row[j] = row[j], row[i] }) } func latinSquare(n int) { if n <= 0 { fmt.Println("[]\n") return } latin := make(matrix, n) for i := 0; i < n; i++ { latin[i] = make([]int, n) if i == n-1 { break } for j := 0; j < n; j++ { latin[i][j] = j } } // first row shuffle(latin[0], n) // middle row(s) for i := 1; i < n-1; i++ { shuffled := false shuffling: for !shuffled { shuffle(latin[i], n) for k := 0; k < i; k++ { for j := 0; j < n; j++ { if latin[k][j] == latin[i][j] { continue shuffling } } } shuffled = true } } // last row for j := 0; j < n; j++ { used := make([]bool, n) for i := 0; i < n-1; i++ { used[latin[i][j]] = true } for k := 0; k < n; k++ { if !used[k] { latin[n-1][j] = k break } } } printSquare(latin, n) } func printSquare(latin matrix, n int) { for i := 0; i < n; i++ { fmt.Println(latin[i]) } fmt.Println() } func main() { rand.Seed(time.Now().UnixNano()) latinSquare(5) latinSquare(5) latinSquare(10) // for good measure }
Random number generator (device)
Go
If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then: show how to obtain a random 32-bit number from that mechanism. ;Related task * [[Random_number_generator_(included)]]
package main import ( "crypto/rand" "encoding/binary" "fmt" "io" "os" ) func main() { testRandom("crypto/rand", rand.Reader) testRandom("dev/random", newDevRandom()) } func newDevRandom() (f *os.File) { var err error if f, err = os.Open("/dev/random"); err != nil { panic(err) } return } func testRandom(label string, src io.Reader) { fmt.Printf("%s:\n", label) var r int32 for i := 0; i < 10; i++ { if err := binary.Read(src, binary.LittleEndian, &r); err != nil { panic(err) } fmt.Print(r, " ") } fmt.Println() }
Random number generator (included)
Go
The task is to: : State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. : If possible, give a link to a wider explanation of the algorithm used. Note: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
Go has two random number packages in the standard library and another package in the "subrepository." # [https://golang.org/pkg/math/rand/ math/rand] in the standard library provides general purpose random number support, implementing some sort of feedback shift register. (It uses a large array commented "feeback register" and has variables named "tap" and "feed.") Comments in the code attribute the algorithm to DP Mitchell and JA Reeds. A little more insight is in [https://github.com/golang/go/issues/21835 this issue] in the Go issue tracker. # [https://golang.org/pkg/crypto/rand/ crypto/rand], also in the standard library, says it "implements a cryptographically secure pseudorandom number generator." I think though it should say that it ''accesses'' a cryptographically secure pseudorandom number generator. It uses <tt>/dev/urandom</tt> on Unix-like systems and the CryptGenRandom API on Windows. # [https://godoc.org/golang.org/x/exp/rand x/exp/rand] implements the Permuted Congruential Generator which is also described in the issue linked above.
Range consolidation
Go
Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. That range can be shown as: ::::::::: '''[b0, b1]''' :::::::: or equally as: ::::::::: '''[b1, b0]''' Given two ranges, the act of consolidation between them compares the two ranges: * If one range covers all of the other then the result is that encompassing range. * If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges. * Otherwise the act of consolidation is to return the two non-touching ranges. Given '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If '''N < 2''' then range consolidation has no strict meaning and the input can be returned. ;Example 1: : Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then : there is no common region between the ranges and the result is the same as the input. ;Example 2: : Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then : there is : an overlap '''[2.5, 1.8]''' between the ranges and : the result is the single range '''[1, 4.7]'''. : Note that order of bounds in a range is not (yet) stated. ;Example 3: : Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then : they touch at '''7.2''' and : the result is the single range '''[6.1, 8.3]'''. ;Example 4: : Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' : then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' : but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and : consolidate to produce the range '''[1, 5]'''. : This range, in turn, overlaps the other range '''[4, 8]''', and : so consolidates to the final output of the single range '''[1, 8]'''. ;Task: Let a normalized range display show the smaller bound to the left; and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the ''normalized'' result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. ;See also: * [[Set consolidation]] * [[Set of real numbers]]
package main import ( "fmt" "math" "sort" ) type Range struct{ Lower, Upper float64 } func (r Range) Norm() Range { if r.Lower > r.Upper { return Range{r.Upper, r.Lower} } return r } func (r Range) String() string { return fmt.Sprintf("[%g, %g]", r.Lower, r.Upper) } func (r1 Range) Union(r2 Range) []Range { if r1.Upper < r2.Lower { return []Range{r1, r2} } r := Range{r1.Lower, math.Max(r1.Upper, r2.Upper)} return []Range{r} } func consolidate(rs []Range) []Range { for i := range rs { rs[i] = rs[i].Norm() } le := len(rs) if le < 2 { return rs } sort.Slice(rs, func(i, j int) bool { return rs[i].Lower < rs[j].Lower }) if le == 2 { return rs[0].Union(rs[1]) } for i := 0; i < le-1; i++ { for j := i + 1; j < le; j++ { ru := rs[i].Union(rs[j]) if len(ru) == 1 { rs[i] = ru[0] copy(rs[j:], rs[j+1:]) rs = rs[:le-1] le-- i-- break } } } return rs } func main() { rss := [][]Range{ {{1.1, 2.2}}, {{6.1, 7.2}, {7.2, 8.3}}, {{4, 3}, {2, 1}}, {{4, 3}, {2, 1}, {-1, -2}, {3.9, 10}}, {{1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6}}, } for _, rs := range rss { s := fmt.Sprintf("%v", rs) fmt.Printf("%40s => ", s[1:len(s)-1]) rs2 := consolidate(rs) s = fmt.Sprintf("%v", rs2) fmt.Println(s[1 : len(s)-1]) } }
Range expansion
Go
{{:Range extraction/Format}} ;Task: Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the '''range from minus 3 to ''minus'' 1'''. ;Related task: * [[Range extraction]]
package main import ( "fmt" "strconv" "strings" ) const input = "-6,-3--1,3-5,7-11,14,15,17-20" func main() { fmt.Println("range:", input) var r []int var last int for _, part := range strings.Split(input, ",") { if i := strings.Index(part[1:], "-"); i == -1 { n, err := strconv.Atoi(part) if err != nil { fmt.Println(err) return } if len(r) > 0 { if last == n { fmt.Println("duplicate value:", n) return } else if last > n { fmt.Println("values not ordered:", last, ">", n) return } } r = append(r, n) last = n } else { n1, err := strconv.Atoi(part[:i+1]) if err != nil { fmt.Println(err) return } n2, err := strconv.Atoi(part[i+2:]) if err != nil { fmt.Println(err) return } if n2 < n1+2 { fmt.Println("invalid range:", part) return } if len(r) > 0 { if last == n1 { fmt.Println("duplicate value:", n1) return } else if last > n1 { fmt.Println("values not ordered:", last, ">", n1) return } } for i = n1; i <= n2; i++ { r = append(r, i) } last = n2 } } fmt.Println("expanded:", r) }
Range extraction
Go
{{:Range extraction/Format}} ;Task: * Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. * Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 * Show the output of your program. ;Related task: * [[Range expansion]]
package main import ( "errors" "fmt" "strconv" "strings" ) func main() { rf, err := rangeFormat([]int{ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, }) if err != nil { fmt.Println(err) return } fmt.Println("range format:", rf) } func rangeFormat(a []int) (string, error) { if len(a) == 0 { return "", nil } var parts []string for n1 := 0; ; { n2 := n1 + 1 for n2 < len(a) && a[n2] == a[n2-1]+1 { n2++ } s := strconv.Itoa(a[n1]) if n2 == n1+2 { s += "," + strconv.Itoa(a[n2-1]) } else if n2 > n1+2 { s += "-" + strconv.Itoa(a[n2-1]) } parts = append(parts, s) if n2 == len(a) { break } if a[n2] == a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence repeats value %d", a[n2])) } if a[n2] < a[n2-1] { return "", errors.New(fmt.Sprintf( "sequence not ordered: %d < %d", a[n2], a[n2-1])) } n1 = n2 } return strings.Join(parts, ","), nil }
Rate counter
Go from C
Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed. Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: * Run N seconds worth of jobs and/or Y jobs. * Report at least three distinct times. Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can. '''See also:''' [[System time]], [[Time a function]]
package main import ( "fmt" "math/rand" "time" ) // representation of time.Time is nanosecond, actual resolution system specific type rateStateS struct { lastFlush time.Time period time.Duration tickCount int } func ticRate(pRate *rateStateS) { pRate.tickCount++ now := time.Now() if now.Sub(pRate.lastFlush) >= pRate.period { // TPS Report tps := 0. if pRate.tickCount > 0 { tps = float64(pRate.tickCount) / now.Sub(pRate.lastFlush).Seconds() } fmt.Println(tps, "tics per second.") // Reset pRate.tickCount = 0 pRate.lastFlush = now } } func somethingWeDo() { time.Sleep(time.Duration(9e7 + rand.Int63n(2e7))) // sleep about .1 second. } func main() { start := time.Now() rateWatch := rateStateS{ lastFlush: start, period: 5 * time.Second, } // Loop for twenty seconds latest := start for latest.Sub(start) < 20*time.Second { somethingWeDo() ticRate(&rateWatch) latest = time.Now() } }
Read a specific line from a file
Go
Some languages have special semantics for obtaining a known line number from a file. ;Task: Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. If no special semantics are available for obtaining the required line, it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
Recaman's sequence
Go
The '''Recaman's sequence''' generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated. If the conditions ''don't'' hold then a(n) = a(n-1) + n. ;Task: # Generate and show here the first 15 members of the sequence. # Find and show here, the first duplicated number in the sequence. # '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated. ;References: * A005132, The On-Line Encyclopedia of Integer Sequences. * The Slightly Spooky Recaman Sequence, Numberphile video. * Recaman's sequence, on Wikipedia.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
Remove lines from a file
Go
Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2 Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" ) func main() { if err := removeLines("foobar.txt", 1, 2); err != nil { fmt.Println(err) } } func removeLines(fn string, start, n int) (err error) { if start < 1 { return errors.New("invalid request. line numbers start at 1.") } if n < 0 { return errors.New("invalid request. negative number to remove.") } var f *os.File if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil { return } defer func() { if cErr := f.Close(); err == nil { err = cErr } }() var b []byte if b, err = ioutil.ReadAll(f); err != nil { return } cut, ok := skip(b, start-1) if !ok { return fmt.Errorf("less than %d lines", start) } if n == 0 { return nil } tail, ok := skip(cut, n) if !ok { return fmt.Errorf("less than %d lines after line %d", n, start) } t := int64(len(b) - len(cut)) if err = f.Truncate(t); err != nil { return } if len(tail) > 0 { _, err = f.WriteAt(tail, t) } return } func skip(b []byte, n int) ([]byte, bool) { for ; n > 0; n-- { if len(b) == 0 { return nil, false } x := bytes.IndexByte(b, '\n') if x < 0 { x = len(b) } else { x++ } b = b[x:] } return b, true }
Rep-string
Go from Python
Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''. For example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string. Note that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string. ;Task: * Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). * There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice. * Use the function to indicate the repeating substring if any, in the following: 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 * Show your output on this page.
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() { for _, s := range strings.Fields(m) { if n := rep(s); n > 0 { fmt.Printf("%q %d rep-string %q\n", s, n, s[:n]) } else { fmt.Printf("%q not a rep-string\n", s) } } }
Repeat
Go
Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
Resistor mesh
Go from C
Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown, find the resistance between points '''A''' and '''B'''. ;See also: * (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits) * An article on how to calculate this and an implementation in Mathematica
package main import "fmt" const ( S = 10 ) type node struct { v float64 fixed int } func alloc2(w, h int) [][]node { a := make([][]node, h) for i := range a { a[i] = make([]node, w) } return a } func set_boundary(m [][]node) { m[1][1].fixed = 1 m[1][1].v = 1 m[6][7].fixed = -1 m[6][7].v = -1 } func calc_diff(m [][]node, d [][]node, w, h int) float64 { total := 0.0 for i := 0; i < h; i++ { for j := 0; j < w; j++ { v := 0.0 n := 0 if i != 0 { v += m[i-1][j].v n++ } if j != 0 { v += m[i][j-1].v n++ } if i+1 < h { v += m[i+1][j].v n++ } if j+1 < w { v += m[i][j+1].v n++ } v = m[i][j].v - v/float64(n) d[i][j].v = v if m[i][j].fixed == 0 { total += v * v } } } return total } func iter(m [][]node, w, h int) float64 { d := alloc2(w, h) diff := 1.0e10 cur := []float64{0, 0, 0} for diff > 1e-24 { set_boundary(m) diff = calc_diff(m, d, w, h) for i := 0; i < h; i++ { for j := 0; j < w; j++ { m[i][j].v -= d[i][j].v } } } for i := 0; i < h; i++ { for j := 0; j < w; j++ { t := 0 if i != 0 { t += 1 } if j != 0 { t += 1 } if i < h-1 { t += 1 } if j < w-1 { t += 1 } cur[m[i][j].fixed+1] += d[i][j].v * float64(t) } } return (cur[2] - cur[0]) / 2 } func main() { mesh := alloc2(S, S) fmt.Printf("R = %g\n", 2/iter(mesh, S, S)) }
Reverse words in a string
Go
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified. ;Example: Hey you, Bub! would be shown reversed as: Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. '''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.) ;Input data (ten lines within the box) line +----------------------------------------+ 1 | ---------- Ice and Fire ------------ | 2 | | <--- a blank line here. 3 | fire, in end will world the say Some | 4 | ice. in say Some | 5 | desire of tasted I've what From | 6 | fire. favor who those with hold I | 7 | | <--- a blank line here. 8 | ... elided paragraph last ... | 9 | | <--- a blank line here. 10 | Frost Robert ----------------------- | +----------------------------------------+ ;Cf. * [[Phrase reversals]]
package main import ( "fmt" "strings" ) // a number of strings var n = []string{ "---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ", "... elided paragraph last ... ", " ", "Frost Robert -----------------------", } func main() { for i, s := range n { t := strings.Fields(s) // tokenize // reverse last := len(t) - 1 for j, k := range t[:len(t)/2] { t[j], t[last-j] = t[last-j], k } n[i] = strings.Join(t, " ") } // display result for _, t := range n { fmt.Println(t) } }