messages
listlengths
2
2
[ { "role": "user", "content": "The sequence is from the natural numbers and is defined by:\n\n* `a(1) = 1`;\n* `a(2) = Start = 2`;\n* for n > 2, `a(n)` shares at least one prime factor with `a(n-1)` and is the *smallest* such natural number *not already used*.\n\nThe sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call:\n\n* The sequence described above , starting `1, 2, ...` the `EKG(2)` sequence;\n* the sequence starting `1, 3, ...` the `EKG(3)` sequence;\n* ... the sequence starting `1, N, ...` the `EKG(N)` sequence.\n\nConvergence\n\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential **state**. Two EKG generators with differing starts can converge to produce the same sequence after initial differences. \n`EKG(N1)` and `EKG(N2)` are said to to have converged at and after generation `a(c)` if `state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c))`.\n\nTask\n\n1. Calculate and show here the first 10 members of `EKG(2)`.\n2. Calculate and show here the first 10 members of `EKG(5)`.\n3. Calculate and show here the first 10 members of `EKG(7)`.\n4. Calculate and show here the first 10 members of `EKG(9)`.\n5. Calculate and show here the first 10 members of `EKG(10)`.\n6. Calculate and show here at which term `EKG(5)` and `EKG(7)` converge   (**stretch goal**).\n\nRelated Tasks\n\n1. Greatest common divisor\n2. Sieve of Eratosthenes\n3. Yellowstone sequence\n\nReference\n\n* The EKG Sequence and the Tree of Numbers. (Video)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2018.04.1\n\n```\nsub infix:<shares-divisors-with> { ($^a gcd $^b) > 1 }\n\nsub next-EKG ( *@s ) {\n return first {\n @s ∌ $_ and @s.tail shares-divisors-with $_\n }, 2..*;\n}\n\nsub EKG ( Int $start ) { 1, $start, &next-EKG … * }\n\nsub converge-at ( @ints ) {\n my @ekgs = @ints.map: &EKG;\n\n return (2 .. *).first: -> $i {\n [==] @ekgs.map( *.[$i] ) and\n [===] @ekgs.map( *.head($i).Set )\n }\n}\n\nsay \"EKG($_): \", .&EKG.head(10) for 2, 5, 7, 9, 10;\n\nfor [5, 7], [2, 5, 7, 9, 10] -> @ints {\n say \"EKGs of (@ints[]) converge at term {$_+1}\" with converge-at(@ints);\n}\n\n```\n\nOutput:\n\n```\nEKG(2): (1 2 4 6 3 9 12 8 10 5)\nEKG(5): (1 5 10 2 4 6 3 9 12 8)\nEKG(7): (1 7 14 2 4 6 3 9 12 8)\nEKG(9): (1 9 3 6 2 4 8 10 5 15)\nEKG(10): (1 10 2 4 6 3 9 12 8 14)\nEKGs of (5 7) converge at term 21\nEKGs of (2 5 7 9 10) converge at term 45\n\n```" } ]
[ { "role": "user", "content": "This task is similar to:\n\n: : * Matrix multiplication\n * Matrix transposition\n\nTask\n\nImplement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks.\n\nImplement:\n\n: : : * addition\n * subtraction\n * multiplication\n * division\n * exponentiation\n\nExtend the task if necessary to include additional basic operations, which should not require their own specialised task." }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku already implements this and other metaoperators as higher-order functions (cross, zip, reduce, triangle, etc.) that are usually accessed through a meta-operator syntactic sugar that is productive over all appropriate operators, including user-defined ones. In this case, a dwimmy element-wise operator (generically known as a \"hyper\") is indicated by surrounding the operator with double angle quotes. Hypers dwim on the pointy end with cyclic APL semantics as necessary. You can turn the quote the other way to suppress dwimmery on that end. In this case we could have used »op» instead of «op» since the short side is always on the right.\n\n```\nmy @a =\n [1,2,3],\n [4,5,6],\n [7,8,9];\n\nsub msay(@x) {\n say .map( { ($_%1) ?? $_.nude.join('/') !! $_ } ).join(' ') for @x;\n say '';\n}\n\nmsay @a «+» @a;\nmsay @a «-» @a;\nmsay @a «*» @a;\nmsay @a «/» @a;\nmsay @a «+» [1,2,3];\nmsay @a «-» [1,2,3];\nmsay @a «*» [1,2,3];\nmsay @a «/» [1,2,3];\nmsay @a «+» 2;\nmsay @a «-» 2;\nmsay @a «*» 2;\nmsay @a «/» 2;\n\n# In addition to calling the underlying higher-order functions directly, it's possible to name a function.\n\nsub infix:<M+> (\\l,\\r) { l <<+>> r }\n\nmsay @a M+ @a;\nmsay @a M+ [1,2,3];\nmsay @a M+ 2;\n\n```\n\nOutput:\n\n```\n 2 4 6\n 8 10 12\n 14 16 18\n\n 0 0 0\n 0 0 0\n 0 0 0\n\n 1 4 9\n 16 25 36\n 49 64 81\n\n 1 1 1\n 1 1 1\n 1 1 1\n\n 2 3 4\n 6 7 8\n 10 11 12\n\n 0 1 2\n 2 3 4\n 4 5 6\n\n 1 2 3\n 8 10 12\n 21 24 27\n\n 1 2 3\n 2 5/2 3\n 7/3 8/3 3\n\n 3 4 5\n 6 7 8\n 9 10 11\n\n -1 0 1\n 2 3 4\n 5 6 7\n\n 2 4 6\n 8 10 12\n 14 16 18\n\n 1/2 1 3/2\n 2 5/2 3\n 7/2 4 9/2\n\n 2 4 6\n 8 10 12\n 14 16 18\n\n 2 3 4\n 6 7 8\n 10 11 12\n\n 3 4 5\n 6 7 8\n 9 10 11\n```" } ]
[ { "role": "user", "content": "An **elementary cellular automaton** is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\nTask\n\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should *wrap*: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of one-dimensional cellular automata.\n\nRelated tasks\n\n* One-dimensional cellular automata\n\nSee also\n\n* Cellular automata (natureofcode.com)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUsing the Automaton class defined at One-dimensional\\_cellular\\_automata#Raku:\n\n```\nclass Automaton {\n has $.rule;\n has @.cells;\n has @.code = $!rule.fmt('%08b').flip.comb».Int;\n \n method gist { \"|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|\" }\n \n method succ {\n self.new: :$!rule, :@!code, :cells( \n @!code[\n 4 «*« @!cells.rotate(-1)\n  »+« 2 «*« @!cells\n  »+«  @!cells.rotate(1)\n ]\n )\n }\n}\n\nmy @padding = 0 xx 10;\n\nmy Automaton $a .= new:\n  :rule(30),\n  :cells(flat @padding, 1, @padding);\n\nsay $a++ for ^10;\n\n```\n\nOutput:\n\n```\n| # |\n| ### |\n| ## # |\n| ## #### |\n| ## # # |\n| ## #### ### |\n| ## # # # |\n| ## #### ###### |\n| ## # ### # |\n| ## #### ## # ### |\n\n```" } ]
[ { "role": "user", "content": "The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n```\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n```\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version." }, { "role": "assistant", "content": "(formerly Perl 6)\nThis version, while it is *capable* of working with infinite length cellular automata, makes the assumption that any cells which have not been explicitly examined are in a 'null' state, neither '0' or '1'. Further it makes the assumption that a null cell, on being examined, initially contains nothing (░). Otherwise it would take infinite time to calculate every row and would be exceptionally boring to watch.\n\nBased heavily on the code from the One-dimensional cellular automata task. Example uses rule 90 (Sierpinski triangle).\n\n```\nclass Automaton {\n has $.rule;\n has @.cells;\n has @.code = $!rule.fmt('%08b').flip.comb».Int;\n\n method gist { @!cells.map({+$_ ?? '▲' !! '░'}).join }\n\n method succ {\n self.new: :$!rule, :@!code, :cells(\n ' ',\n |@!code[\n 4 «*« @!cells.rotate(-1)\n  »+« 2 «*« @!cells\n  »+«  @!cells.rotate(1)\n ],\n ' '\n )\n }\n}\n\nmy Automaton $a .= new: :rule(90), :cells(flat '010'.comb);\n\n# display the first 20 rows\nsay $a++ for ^20;\n\n# then calculate the other infinite number of rows, (may take a while)\n$a++ for ^Inf;\n\n```\n\nOutput:\n\n```\n░▲░\n░▲░▲░\n░▲░░░▲░\n░▲░▲░▲░▲░\n░▲░░░░░░░▲░\n░▲░▲░░░░░▲░▲░\n░▲░░░▲░░░▲░░░▲░\n░▲░▲░▲░▲░▲░▲░▲░▲░\n░▲░░░░░░░░░░░░░░░▲░\n░▲░▲░░░░░░░░░░░░░▲░▲░\n░▲░░░▲░░░░░░░░░░░▲░░░▲░\n░▲░▲░▲░▲░░░░░░░░░▲░▲░▲░▲░\n░▲░░░░░░░▲░░░░░░░▲░░░░░░░▲░\n░▲░▲░░░░░▲░▲░░░░░▲░▲░░░░░▲░▲░\n░▲░░░▲░░░▲░░░▲░░░▲░░░▲░░░▲░░░▲░\n░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░▲░\n░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░\n░▲░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░▲░\n░▲░░░▲░░░░░░░░░░░░░░░░░░░░░░░░░░░▲░░░▲░\n░▲░▲░▲░▲░░░░░░░░░░░░░░░░░░░░░░░░░▲░▲░▲░▲░\n^C\n\n```" } ]
[ { "role": "user", "content": "Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, for a long time rule 30 was used by the Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the parent task, which you don't need to re-write here, show the ten first bytes that emerge from this recommendation. To be precise, you will start with a state of all cells but one equal to zero, and you'll follow the evolution of the particular cell whose state was initially one. Then you'll regroup those bits by packets of eight, reconstituting bytes with the first bit being the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\nReference\n\n* Cellular automata: Is Rule 30 random? (PDF)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nclass Automaton {\n has $.rule;\n has @.cells handles <AT-POS>;\n has @.code = $!rule.fmt('%08b').flip.comb».Int;\n \n method gist { \"|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|\" }\n \n method succ {\n self.new: :$!rule, :@!code, :cells( \n @!code[\n 4 «*« @!cells.rotate(-1)\n  »+« 2 «*« @!cells\n  »+«  @!cells.rotate(1)\n ]\n )\n }\n}\n\nmy Automaton $a .= new: :rule(30), :cells( flat 1, 0 xx 100 );\n\nsay :2[$a++[0] xx 8] xx 10;\n\n```\n\nOutput:\n\n```\n220 197 147 174 117 97 149 171 240 241\n```" } ]
[ { "role": "user", "content": "Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures.\n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol.\n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the **x** and **y** coordinates of any point on the curve:\n\n: : : : y\n\n 2\n =\n\n x\n\n 3\n +\n a\n x\n +\n b\n {\\displaystyle {\\displaystyle y^{2}=x^{3}+ax+b}}\n\n**a** and **b** are arbitrary parameters that define the specific curve which is used.\n\nFor this particular task, we'll use the following parameters:\n\n: : : : a=0**,**   b=7\n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it.\n\nTo do so we define an   internal composition   rule with an additive notation **+**,   such that for any three distinct points **P**, **Q** and **R** on the curve, whenever these points are aligned, we have:\n\n: : : : P + Q + R = 0\n\nHere   **0**   (zero)   is the *infinity point*,   for which the **x** and **y** values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry.\n\nWe'll also assume here that this infinity point is unique and defines the   neutral element   of the addition.\n\nThis was not the definition of the addition, but only its desired property.   For a more accurate definition, we proceed as such:\n\nGiven any three aligned points **P**, **Q** and **R**,   we define the sum   **S = P + Q**   as the point (possibly the infinity point) such that   **S**, **R**   and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points **S** and **R** can be aligned with the infinity point if and only if **S** and **R** are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n**S** is thus defined as the symmetric of **R** towards the **x** axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.\n\nYou will use the **a** and **b** parameters of secp256k1, i.e. respectively zero and seven.\n\n*Hint*:   You might need to define a \"doubling\" function, that returns **P+P** for any given point **P**.\n\n*Extra credit*:   define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns,\n \nfor any point **P** and integer **n**,   the point **P + P + ... + P**     (**n** times)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmodule EC {\n our ($A, $B) = (0, 7);\n\n our class Point {\n has ($.x, $.y);\n multi method new(\n $x, $y where $y**2 == $x**3 + $A*$x + $B\n ) { samewith :$x, :$y }\n multi method gist { \"EC Point at x=$.x, y=$.y\" }\n multi method gist(::?CLASS:U:) { 'Point at horizon' }\n }\n\n multi prefix:<->(Point $p) is export { Point.new: x => $p.x, y => -$p.y }\n multi prefix:<->(Point:U) is export { Point }\n multi infix:<->(Point $a, Point $b) is export { $a + -$b }\n\n multi infix:<+>(Point:U $, Point $p) is export { $p }\n multi infix:<+>(Point $p, Point:U) is export { $p }\n\n multi infix:<*>(Point $u, Int $n) is export { $n * $u }\n multi infix:<*>(Int $n, Point:U) is export { Point }\n multi infix:<*>(0, Point) is export { Point }\n multi infix:<*>(1, Point $p) is export { $p }\n multi infix:<*>(2, Point $p) is export {\n my $l = (3*$p.x**2 + $A) / (2 *$p.y);\n my $y = $l*($p.x - my $x = $l**2 - 2*$p.x) - $p.y;\n $p.new(:$x, :$y);\n }\n multi infix:<*>(Int $n where $n > 2, Point $p) is export {\n 2 * ($n div 2 * $p) + $n % 2 * $p;\n }\n\n multi infix:<+>(Point $p, Point $q) is export {\n if $p.x ~~ $q.x {\n return $p.y ~~ $q.y ?? 2 * $p !! Point;\n }\n else {\n my $slope = ($q.y - $p.y) / ($q.x - $p.x);\n my $y = $slope*($p.x - my $x = $slope**2 - $p.x - $q.x) - $p.y;\n return $p.new(:$x, :$y);\n }\n }\n\n}\n\nimport EC;\n\nsay my $p = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 1;\nsay my $q = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 2;\nsay my $s = $p + $q;\n\nuse Test;\nis abs(($p.x - $q.x)*(-$s.y - $q.y) - ($p.y - $q.y)*($s.x - $q.x)), 0, \"S, P and Q are aligned\";\n\n```\n\nOutput:\n\n```\nEC Point at x=1, y=2.8284271247461903\nEC Point at x=2, y=3.872983346207417\nEC Point at x=-1.9089023002066448, y=0.21008487055753378\nok 1 - S, P and Q are aligned\n```" } ]
[ { "role": "user", "content": "Elliptic curves.\n\nAn elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form\n**y²= x³ + ax + b**, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p),\ntogether with a special point 𝒪 called the point at infinity.\nThe set **E(ℤp)** consists of all points (x, y), with x, y ∈ ℤp,\nwhich satisfy the above defining equation, together with 𝒪.\n\nThere is a rule for adding two points on an elliptic curve to give a third point.\nThis addition operation and the set of points E(ℤp) form a group with identity 𝒪.\nIt is this group that is used in the construction of elliptic curve cryptosystems.\n\nThe addition rule — which can be explained geometrically — is summarized as follows:\n\n```\n1. P + 𝒪 = 𝒪 + P = P for all P ∈ E(ℤp).\n\n2. If P = (x, y) ∈ E(ℤp), then inverse -P = (x,-y), and P + (-P) = 𝒪.\n\n3. Let P = (xP, yP) and Q = (xQ, yQ), both ∈ E(ℤp), where P ≠ -Q.\n Then R = P + Q = (xR, yR), where\n\n xR = λ^2 - xP - xQ\n yR = λ·(xP - xR) - yP,\n\n with\n\n λ = (yP - yQ) / (xP - xQ) if P ≠ Q,\n (3·xP·xP + a) / 2·yP if P = Q (point doubling).\n\n```\n\nRemark: there already is a task page requesting “a simplified (without modular arithmetic)\nversion of the elliptic curve arithmetic”.\nHere we do add modulo operations. If also the domain is changed from reals to rationals,\nthe elliptic curves are no longer continuous but break up into a finite number of distinct points.\nIn that form we use them to implement ECDSA:\n\nElliptic curve digital signature algorithm.\n\nA digital signature is the electronic analogue of a hand-written signature\nthat convinces the recipient that a message has been sent intact by the presumed sender.\nAnyone with access to the public key of the signer may verify this signature.\nChanging even a single bit of a signed message will cause the verification procedure to fail.\n\n**ECDSA key generation.** Party A does the following: \n1. Select an elliptic curve E defined over ℤp. \n The number of points in E(ℤp) should be divisible by a large prime r. \n2. Select a base point G ∈ E(ℤp) of order r (which means that rG = 𝒪). \n3. Select a random integer s in the interval [1, r - 1]. \n4. Compute W = sG. \n The public key is (E, G, r, W), the private key is s.\n\n**ECDSA signature computation.** To sign a message m, A does the following: \n1. Compute message representative f = H(m), using a\ncryptographic hash function. \n Note that f can be greater than r but not longer (measuring bits). \n2. Select a random integer u in the interval [1, r - 1]. \n3. Compute V = uG = (xV, yV) and c ≡ xV mod r  (goto (2) if c = 0). \n4. Compute d ≡ u^-1·(f + s·c) mod r  (goto (2) if d = 0). \n The signature for the message m is the pair of integers (c, d).\n\n**ECDSA signature verification.** To verify A's signature, B should do the following: \n1. Obtain an authentic copy of A's public key (E, G, r, W). \n Verify that c and d are integers in the interval [1, r - 1]. \n2. Compute f = H(m) and h ≡ d^-1 mod r. \n3. Compute h1 ≡ f·h mod r and h2 ≡ c·h mod r. \n4. Compute h1G + h2W = (x1, y1) and c1 ≡ x1 mod r. \n Accept the signature if and only if c1 = c.\n\nTo be cryptographically useful, the parameter r should have at least 250 bits.\nThe basis for the security of elliptic curve cryptosystems\nis the intractability of the elliptic curve discrete logarithm problem (ECDLP) in a group of this size:\ngiven two points G, W ∈ E(ℤp), where W lies in the subgroup of order r generated by G,\ndetermine an integer k such that W = kG and 0 ≤ k < r.\n\nTask.\n\nThe task is to write a **toy version** of the ECDSA, quasi the equal of a real-world\nimplementation, but utilizing parameters that fit into standard arithmetic types.\nTo keep things simple there's no need for key export or a hash function (just a sample\nhash value and a way to tamper with it). The program should be lenient where possible\n(for example: if it accepts a composite modulus N it will either function as expected,\nor demonstrate the principle of elliptic curve factorization)\n— but strict where required (a point G that is not on E will always cause failure). \nToy ECDSA is of course completely useless for its cryptographic purpose.\nIf this bothers you, please add a multiple-precision version.\n\nReference.\n\nElliptic curves are in the IEEE Std 1363-2000 (Standard Specifications for Public-Key Cryptography), see:\n\n7. Primitives based on the elliptic curve discrete logarithm problem (p. 27ff.)\n\n7.1 The EC setting \n7.1.2 EC domain parameters \n7.1.3 EC key pairs\n\n7.2 Primitives \n7.2.7 ECSP-DSA (p. 35) \n7.2.8 ECVP-DSA (p. 36)\n\nAnnex A. Number-theoretic background \nA.9 Elliptic curves: overview (p. 115) \nA.10 Elliptic curves: algorithms (p. 121)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmodule EC {\n use FiniteField;\n\n our class Point {\n has ($.x, $.y);\n submethod TWEAK { fail unless $!y**2 == $!x**3 + $*a*$!x + $*b }\n multi method gist(::?CLASS:U:) { \"Point at Horizon\" }\n multi method new($x, $y) { samewith :$x, :$y }\n }\n multi infix:<==>(Point:D $A, Point:D $B) is export { $A.x == $B.x and $A.y == $B.y }\n\n multi prefix:<->(Point $P) returns Point is export { Point.new: $P.x, -$P.y }\n multi infix:<+>(Point $A, Point:U) is export { $A }\n multi infix:<+>(Point:U, Point $B) is export { $B }\n multi infix:<+>(Point:D $A, Point:D $B) returns Point is export {\n my $λ;\n if $A.x == $B.x and $A.y == -$B.y { return Point }\n elsif $A == $B {\n return Point if $A.y == 0;\n $λ = (3*$A.x² + $*a) / (2*$A.y);\n }\n else { $λ = ($A.y - $B.y) / ($A.x - $B.x); }\n\n given $λ**2 - $A.x - $B.x {\n return Point.new: $_, $λ*($A.x - $_) - $A.y;\n }\n }\n multi infix:<*>(0, Point ) is export { Point }\n multi infix:<*>(1, Point $p) is export { $p }\n multi infix:<*>(2, Point:D $p) is export { $p + $p }\n multi infix:<*>(Int $n, Point $p) is export { 2*(($n div 2)*$p) + ($n mod 2)*$p }\n}\n\nimport EC;\n\nmodule ECDSA {\n use Digest::SHA256::Native;\n our class Signature {\n has UInt ($.c, $.d);\n multi method new(Str $message, UInt :$private-key) {\n my $z = :16(sha256-hex $message) % $*n;\n loop (my $k = my $s = my $r = 0; $r == 0; ) {\n loop ( $r = $s = 0 ; $r == 0 ; ) {\n $r = (( $k = (1..^$*n).roll ) * $*G).x % $*n;\n }\n {\n use FiniteField; my $*modulus = $*n;\n $s = ($z + $r*$private-key) / $k;\n }\n }\n samewith c => $r, d => $s;\n }\n multi method verify(Str $message, EC::Point :$public-key) {\n my $z = :16(sha256-hex $message) % $*n;\n my ($u1, $u2);\n {\n use FiniteField;\n my $*modulus = $*n;\n my $w = 1/$!d;\n ($u1, $u2) = $z*$w, $!c*$w;\n }\n my $p = ($u1 * $*G) + ($u2 * $public-key);\n die unless ($p.x mod $*n) == ($!c mod $*n);\n }\n }\n}\n\nmy ($*a, $*b) = 355, 671;\nmy $*modulus = my $*p = 1073741789;\n\nmy $*G = EC::Point.new: 13693, 10088;\nmy $*n = 1073807281;\n\ndie \"G is not of order n\" if $*n*$*G;\n\nmy $private-key = ^$*n .pick;\nmy $public-key = $private-key*$*G; \n\nmy $message = \"Show me the monKey\";\nmy $signature = ECDSA::Signature.new: $message, :$private-key;\n\nprintf \"The curve E is  : 𝑦² = 𝑥³ + %s 𝑥 + %s (mod %s)\\n\", $*a, $*b, $*p;\nprintf \"with generator G at  : (%s, %s)\\n\", $*G.x, $*G.y;\nprintf \"G's order is  : %d\\n\", $*n;\nprintf \"The private key is  : %d\\n\", $private-key;\nprintf \"The public key is at  : (%s, %s)\\n\", $public-key.x, $public-key.y;\nprintf \"The message is  : %s\\n\", $message;\nprintf \"The signature is  : (%s, %s)\\n\", $signature.c, $signature.d;\n\n{\n use Test;\n\n lives-ok {\n $signature.verify: $message, :$public-key;\n }, \"good signature for <$message>\";\n\n my $altered = $message.subst(/monKey/, \"money\");\n dies-ok {\n $signature.verify: $altered, :$public-key\n }, \"wrong signature for <$altered>\";\n}\n\n```\n\nOutput:\n\n```\nThe curve E is  : 𝑦² = 𝑥³ + 355 𝑥 + 671 (mod 1073741789)\nwith generator G at  : (13693, 10088)\nG's order is  : 1073807281\nThe private key is  : 405586338\nThe public key is at  : (457744420, 236326628)\nThe message is  : Show me the monKey\nThe signature is  : (839907635, 23728690)\nok 1 - good signature for <Show me the monKey>\nok 2 - wrong signature for <Show me the money>\n```" } ]
[ { "role": "user", "content": "An   *emirp*   (**prime** spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime.\n\n(This rules out palindromic primes.)\n\nTask\n: : * show the first   twenty   emirps\n * show all emirps between   7,700   and   8,000\n * show the   10,000th   emirp\n\nIn each list, the numbers should be in order.\n\nInvoke the (same) program once per task requirement, this will show what limit is used as the upper bound for calculating surplus (regular) primes.\n\nThe specific method of how to determine if a range or if specific values are to be shown will be left to the programmer.\n\nSee also\n\n* Wikipedia, Emirp.\n* The Prime Pages, emirp.\n* Wolfram MathWorld™, Emirp.\n* The On‑Line Encyclopedia of Integer Sequences, emirps (A6567)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\nFor better performance, build the lazy list using module `Math::Primesieve`, not the built-in, then display results based on parameters passed in. The default is to display an array slice starting and stopping at the given indices. Alternately, ask for all values between two endpoints.\n\n```\nuse Math::Primesieve;\n\nsub prime-hash (Int $max) {\n my $sieve = Math::Primesieve.new;\n my @primes = $sieve.primes($max);\n @primes.Set;\n}\n\nsub MAIN ($start, $stop = Nil, $display = <slice>) {\n my $end = $stop // $start;\n my %primes = prime-hash(100*$end);\n my @emirps = lazy gather for 1 .. * -> $n {\n take $n if %primes{$n} and %primes{$n.flip} and $n != $n.flip\n }\n\n given $display {\n when 'slice' { return @emirps[$start-1 .. $end-1] };\n when 'values' {\n my @values = gather for @emirps {\n .take if $start < $_ < $end;\n last if $_> $end\n }\n return @values\n }\n }\n}\n\n```\n\nOutput:\n\nRun with passed parameters: 1 20\n\n('slice' is the default. you *could* pass it in, but it isn't necessary.)\n\n```\n13 17 31 37 71 73 79 97 107 113 149 157 167 179 199 311 337 347 359 389\n```\n\nRun with passed parameters: 7700 8000 values\n\n```\n7717 7757 7817 7841 7867 7879 7901 7927 7949 7951 7963\n```\n\nRun with passed parameter: 10000\n\n```\n948349\n```" } ]
[ { "role": "user", "content": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories.\nWith Unix or Windows systems, every directory contains an entry for “`.`” and almost every directory contains “`..`” (except for a root directory); an empty directory contains no other entries." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub dir-is-empty ($d) { not dir $d }\n\n```\n\nThe dir function returns a lazy list of filenames, excluding \".\" and \"..\" automatically. Any boolean context (in this case the not function) will do just enough work on the lazy list to determine whether there are any elements, so we don't have to count the directory entries, or even read them all into memory, if there are more than one buffer's worth." } ]
[ { "role": "user", "content": "Task\n\nCreate the simplest possible program that is still considered \"correct.\"" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe empty program is valid and does nothing but return a successful exit code:\n\nIt is also possible to just specify that the program is written in Raku:\n\n```\nuse v6;\n```\n\nor even:\n\n```\nv6;\n```" } ]
[ { "role": "user", "content": "Languages may have features for dealing specifically with empty strings\n(those containing no characters).\n\nTask\n: : * Demonstrate how to assign an empty string to a variable.\n * Demonstrate how to check that a string is empty.\n * Demonstrate how to check that a string is not empty.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $s = '';\nsay 'String is empty' unless $s;\nsay 'String is not empty' if $s;\n```\n\nUnlike in Perl 5, only empty strings test as false - the string \"0\" tests as true now." } ]
[ { "role": "user", "content": "Task\n\nDemonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created." }, { "role": "assistant", "content": "(formerly Perl 6)\nYou can create constants in Raku with `constant`:\n\n```\nconstant $pi = 3.14159;\nconstant $msg = \"Hello World\";\n\nconstant @arr = (1, 2, 3, 4, 5);\n\n```\n\nImmutability is abstract enough that you can define an infinite constant lazily:\n\n```\nconstant fibonacci = 0, 1, *+* ... *;\n\n```\n\nVariables are considered mutable by default, but may be marked as readonly after initialization:\n\n```\nmy $pi := 3 + rand;\n\n```\n\nUnlike variables, formal parameters are considered readonly by default even if bound to a mutable container.\n\n```\nsub sum (Num $x, Num $y) {\n\t$x += $y; # ERROR\n}\n\n# Explicitly ask for pass-by-reference semantics\nsub addto (Num $x is rw, Num $y) {\n $x += $y; # ok, propagated back to caller\n}\n\n# Explicitly ask for pass-by-value semantics\nsub sum (Num $x is copy, Num $y) {\n $x += $y; # ok, but NOT propagated back to caller\n $x;\n}\n\n```\n\nA number of built-in types are considered immutable value types, including:\n\n```\nStr String (finite sequence of Unicode characters)\nInt Integer (allows Inf/NaN, arbitrary precision, etc.)\nNum Number (approximate Real, generally via floating point)\nRat Rational (exact Real, limited denominator)\nFatRat Rational (unlimited precision in both parts)\nComplex Complex number\nBool Boolean\nException Exception\nBlock Executable objects that have lexical scopes\nSeq A list of values (can be generated lazily)\nRange A pair of Ordered endpoints\nSet Unordered collection of values that allows no duplicates\nBag Unordered collection of values that allows duplicates\nEnum An immutable Pair\nMap A mapping of Enums with no duplicate keys\nSignature Function parameters (left-hand side of a binding)\nCapture Function call arguments (right-hand side of a binding)\nBlob An undifferentiated mass of ints, an immutable Buf\nInstant A point on the continuous atomic timeline\nDuration The difference between two Instants\n```\n\nThese values, though objects, can't mutate; they may only be \"changed\" by modifying a mutable container holding one of them to hold a different value instead. (In the abstract, that is. In the interests of efficiency, a string or list implementation would be allowed to cheat as long as it doesn't get caught cheating.) Some of these types have corresponding \"unboxed\" native representations, where the container itself must carry the type information since the value can't. In this case, it's still the container that might be\nconsidered mutable as an lvalue location, not the value stored in that location.\n\nBy default, object attributes are not modifiable from outside a class, though this is usually viewed more as encapsulation than as mutability control." } ]
[ { "role": "user", "content": "The Engel expansion of a positive real number x is the unique non-decreasing sequence of positive integers ***{ a1, a2, a3 ... }*** such that\n\n```\n x = 1 / a1 + 1 / a1a2 + 1 / a1a2a3 ...\n\n```\n\nIn other words, each term is the reciprocal of the cumulative product of the expansion and *x* is the sum of those terms.\n\nRational numbers have a finite Engel expansion, while irrational numbers have an infinite Engel expansion.\n\nTiny amounts of imprecision can cause wild variation from actual values as the (reciprocal) terms grow smaller. It can be quite challenging to maintain precision in later terms.\n\nTask\n\n* Write routines (functions, procedures, whatever it may be called in your language) to convert a rational number to an Engel expansion representation and from an Engle expansion to a rational number.\n* Demonstrate converting some rational numbers to an Engel expansion and back.\n\nTest it with at least the following rational approximations of:\n\n* 𝜋 - 3.14159265358979\n* 𝑒 - 2.71828182845904\n* √2 - 1.414213562373095\n\nStretch\n\n* If your language supports high precision rational numbers, do the same with at least:\n\n* 𝜋 - 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211\n* 𝑒 - 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743\n* √2 - 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558\n\nThere almost definitely *will* be some imprecision in the later terms. Feel free to limit the display of the expansion to the first 30 terms.\n\nSee also\n\n* Wikipedia: Engel expansion * OEIS:A006784 - Engel expansion of Pi * OEIS:A028310 - Engel expansion of 𝑒 * OEIS:A028254 - Engel expansion of sqrt(2)" }, { "role": "assistant", "content": "```\nsub to-engel ($rat is copy) { do while $rat { my $a = ceiling 1 / $rat; $rat = $rat × $a - 1; $a } }\n\nsub from-engel (@expanded) { sum [\\×] @expanded.map: { FatRat.new: 1, $_ } }\n\nfor # low precision 𝜋, 𝑒, √2 and 1.5 to a power\n 3.14159265358979, 2.71828182845904, 1.414213562373095, 1.5 ** 5,\n\n # high precision 𝜋, 𝑒, and √2 and 1.5 to a power\n 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211.FatRat,\n\n 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743.FatRat,\n\n 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558.FatRat,\n\n 1.5 ** 8\n -> $rat {\n say \"Rational number: $rat\";\n my @expanded = $rat.&to-engel;\n put \"Engel expansion: \" ~ @expanded.head(30);\n say \" Converted back: \" ~ @expanded.&from-engel;\n put '';\n}\n\n```\n\nOutput:\n\n```\nRational number: 3.14159265358979\nEngel expansion: 1 1 1 8 8 17 19 300 1991 2768 4442 4830 10560 37132 107315 244141 651042 1953125\n Converted back: 3.14159265358979\n\nRational number: 2.71828182845904\nEngel expansion: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 82 144 321 2289 9041 21083 474060 887785 976563 1953125\n Converted back: 2.71828182845904\n\nRational number: 1.414213562373095\nEngel expansion: 1 3 5 5 16 18 78 102 120 144 260 968 18531 46065 63005 65105 78125\n Converted back: 1.414213562373095\n\nRational number: 7.59375\nEngel expansion: 1 1 1 1 1 1 1 2 6 8\n Converted back: 7.59375\n\nRational number: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211\nEngel expansion: 1 1 1 8 8 17 19 300 1991 2492 7236 10586 34588 63403 70637 1236467 5417668 5515697 5633167 7458122 9637848 9805775 41840855 58408380 213130873 424342175 2366457522 4109464489 21846713216 27803071890\n Converted back: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211\n\nRational number: 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743\nEngel expansion: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n Converted back: 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516642743\n\nRational number: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558\nEngel expansion: 1 3 5 5 16 18 78 102 120 144 251 363 1402 31169 88630 184655 259252 298770 4196070 38538874 616984563 1975413035 5345718057 27843871197 54516286513 334398528974 445879679626 495957494386 2450869042061 2629541150527\n Converted back: 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927558\n\nRational number: 25.628906\nEngel expansion: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 4 32\n Converted back: 25.628906\n```" } ]
[ { "role": "user", "content": "Certain numbers, when spelled out in their English cardinal representation, are anagrams of other numbers.\n\nSome are very obvious: **sixty-seven <=> seventy-six**\n\nOthers are a little more subtle: **one hundred twelve <=> two hundred eleven**\n\nTask\n\n* Find and display the first thirty numbers that are a member of English cardinal anagrams, starting from **zero**.\n* Find and display the **count** of English cardinal anagrams from **zero** to **one thousand**.\n* Find and display the **largest group(s)** of English cardinal anagrams from **zero** to **one thousand**.\n\nStretch\n\n* Find and display the **count** of English cardinal anagrams from **zero** to **ten thousand**, restricted to numbers within those bounds. *(Ignore anagrams of numbers outside those bounds. **E.G. 1010 <=> 10001**)*\n* Find and display the **largest group(s)** of English cardinal anagrams from **zero** to **ten thousand**.\n\nSee also\n\n* OEIS::A169936 - Numbers whose name in English is an anagram of the name of another number * Related task: Number names" }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\nuse List::Allmax;\n\nfor 1_000, 10_000 {\n my %eca; # English cardinal anagrams\n (^$_).map: { %eca{.&cardinal.comb.sort.join}.push: $_ }\n\n once say \"\\nFirst 30 English cardinal anagrams:\\n \" ~\n (sort flat %eca.grep(+*.value > 1)».value.map: *.flat)[^30]\\\n .batch(10)».fmt(\"%3d\").join: \"\\n \";\n\n say \"\\nCount of English cardinal anagrams up to {.&comma}: \" ~\n +%eca.grep(+*.value > 1)».value.map: *.flat;\n\n say \"\\nLargest group(s) of English cardinal anagrams up to {.&comma}:\\n [\" ~\n %eca.&all-max( :by(+*.value) )».value.sort.join(\"]\\n [\") ~ ']'\n}\n\n```\n\nOutput:\n\n```\nFirst 30 English cardinal anagrams:\n 67 69 76 79 96 97 102 103 104 105\n 106 107 108 109 112 122 123 124 125 126\n 127 128 129 132 133 134 135 136 137 138\n\nCount of English cardinal anagrams up to 1,000: 317\n\nLargest group(s) of English cardinal anagrams up to 1,000:\n [679 697 769 796 967 976]\n\nCount of English cardinal anagrams up to 10,000: 2534\n\nLargest group(s) of English cardinal anagrams up to 10,000:\n [1679 1697 1769 1796 1967 1976 6179 6197 6791 6971 7169 7196 7691 7961 9167 9176 9671 9761]\n [2679 2697 2769 2796 2967 2976 6279 6297 6792 6972 7269 7296 7692 7962 9267 9276 9672 9762]\n [3679 3697 3769 3796 3967 3976 6379 6397 6793 6973 7369 7396 7693 7963 9367 9376 9673 9763]\n [4679 4697 4769 4796 4967 4976 6479 6497 6794 6974 7469 7496 7694 7964 9467 9476 9674 9764]\n [5679 5697 5769 5796 5967 5976 6579 6597 6795 6975 7569 7596 7695 7965 9567 9576 9675 9765]\n [6798 6879 6897 6978 7698 7869 7896 7968 8679 8697 8769 8796 8967 8976 9678 9768 9867 9876]\n```" } ]
[ { "role": "user", "content": "Task\n\nCalculate the Shannon entropy   H   of a given input string.\n\nGiven the discrete random variable \n\nX\n{\\displaystyle {\\displaystyle X}}\n that is a string of \n\nN\n{\\displaystyle {\\displaystyle N}}\n \"symbols\" (total characters) consisting of \n\nn\n{\\displaystyle {\\displaystyle n}}\n different characters (n=2 for binary), the Shannon entropy of X in **bits/symbol** is :\n\n: H\n\n 2\n (\n X\n )\n =\n −\n\n ∑\n\n i\n =\n 1\n\n n\n\n c\n o\n u\n n\n\n t\n\n i\n N\n\n log\n\n 2\n ⁡\n\n (\n\n c\n o\n u\n n\n\n t\n\n i\n N\n )\n {\\displaystyle {\\displaystyle H\\_{2}(X)=-\\sum \\_{i=1}^{n}{\\frac {count\\_{i}}{N}}\\log \\_{2}\\left({\\frac {count\\_{i}}{N}}\\right)}}\n\nwhere \n\nc\no\nu\nn\n\nt\n\ni\n{\\displaystyle {\\displaystyle count\\_{i}}}\n is the count of character \n\nn\n\ni\n{\\displaystyle {\\displaystyle n\\_{i}}}\n.\n\nFor this task, use X=\"1223334444\" as an example. The result should be 1.84644... bits/symbol. This assumes X was a random variable, which may not be the case, or it may depend on the observer.\n\nThis coding problem calculates the \"specific\" or \"intensive\" entropy that finds its parallel in physics with \"specific entropy\" S0 which is entropy per kg or per mole, not like physical entropy S and therefore not the \"information\" content of a file. It comes from Boltzmann's H-theorem where \n\nS\n=\n\nk\n\nB\nN\nH\n{\\displaystyle {\\displaystyle S=k\\_{B}NH}}\n where N=number of molecules. Boltzmann's H is the same equation as Shannon's H, and it gives the specific entropy H on a \"per molecule\" basis.\n\nThe \"total\", \"absolute\", or \"extensive\" information entropy is\n\n: S\n =\n\n H\n\n 2\n N\n {\\displaystyle {\\displaystyle S=H\\_{2}N}}\n bits\n\nThis is not the entropy being coded here, but it is the closest to physical entropy and a measure of the information content of a string. But it does not look for any patterns that might be available for compression, so it is a very restricted, basic, and certain measure of \"information\". Every binary file with an equal number of 1's and 0's will have S=N bits. All hex files with equal symbol frequencies will have \n\nS\n=\nN\n\nlog\n\n2\n⁡\n(\n16\n)\n{\\displaystyle {\\displaystyle S=N\\log \\_{2}(16)}}\n bits of entropy. The total entropy in bits of the example above is S= 10\\*18.4644 = 18.4644 bits.\n\nThe H function does not look for any patterns in data or check if X was a random variable. For example, X=000000111111 gives the same calculated entropy in all senses as Y=010011100101. For most purposes it is usually more relevant to divide the gzip length by the length of the original data to get an informal measure of how much \"order\" was in the data.\n\nTwo other \"entropies\" are useful:\n\nNormalized specific entropy:\n\n: H\n\n n\n =\n\n H\n\n 2\n ∗\n log\n ⁡\n (\n 2\n )\n\n log\n ⁡\n (\n n\n )\n {\\displaystyle {\\displaystyle H\\_{n}={\\frac {H\\_{2}\\*\\log(2)}{\\log(n)}}}}\n\nwhich varies from 0 to 1 and it has units of \"entropy/symbol\" or just 1/symbol. For this example, Hn<\\sub>= 0.923.\n\nNormalized total (extensive) entropy:\n\n: S\n\n n\n =\n\n H\n\n 2\n N\n ∗\n log\n ⁡\n (\n 2\n )\n\n log\n ⁡\n (\n n\n )\n {\\displaystyle {\\displaystyle S\\_{n}={\\frac {H\\_{2}N\\*\\log(2)}{\\log(n)}}}}\n\nwhich varies from 0 to N and does not have units. It is simply the \"entropy\", but it needs to be called \"total normalized extensive entropy\" so that it is not confused with Shannon's (specific) entropy or physical entropy. For this example, Sn<\\sub>= 9.23.\n\nShannon himself is the reason his \"entropy/symbol\" H function is very confusingly called \"entropy\". That's like calling a function that returns a speed a \"meter\". See section 1.7 of his classic A Mathematical Theory of Communication and search on \"per symbol\" and \"units\" to see he always stated his entropy H has units of \"bits/symbol\" or \"entropy/symbol\" or \"information/symbol\". So it is legitimate to say entropy NH is \"information\".\n\nIn keeping with Landauer's limit, the physics entropy generated from erasing N bits is \n\nS\n=\n\nH\n\n2\nN\n\nk\n\nB\nln\n⁡\n(\n2\n)\n{\\displaystyle {\\displaystyle S=H\\_{2}Nk\\_{B}\\ln(2)}}\n if the bit storage device is perfectly efficient. This can be solved for H2\\*N to (arguably) get the number of bits of information that a physical entropy represents.\n\nRelated tasks\n: * Fibonacci\\_word\n * Entropy/Narcissist" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-09-09\n\n```\nsub entropy(@a) {\n [+] map -> \\p { p * -log p }, bag(@a).values »/» +@a;\n}\n\nsay log(2) R/ entropy '1223334444'.comb;\n\n```\n\nOutput:\n\n```\n1.84643934467102\n```\n\nIn case we would like to add this function to Raku's core, here is one way it could be done:\n\n```\nuse MONKEY-TYPING;\naugment class Bag {\n method entropy {\n\t[+] map -> \\p { - p * log p },\n\tself.values »/» +self;\n }\n}\n\nsay '1223334444'.comb.Bag.entropy / log 2;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a computer program that computes and shows its own   entropy.\n\nRelated Tasks\n: * Fibonacci\\_word\n * Entropy" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.05\n\n```\nsay log(2) R/ [+] map -> \\p { p * -log p }, $_.comb.Bag.values >>/>> +$_\n given slurp($*PROGRAM-NAME).comb\n\n```\n\nResult should be in the neighborhood of 4.9\n\nOutput:\n\n```\n4.89351613053006\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate an enumeration of constants with and without explicit values." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.01\n\n```\nenum Fruit <Apple Banana Cherry>; # Numbered 0 through 2.\n\nenum ClassicalElement (\n Earth => 5,\n 'Air', # gets the value 6\n 'Fire', # gets the value 7\n Water => 10,\n);\n```" } ]
[ { "role": "user", "content": "Task\n\nShow how to get one of your process's environment variables.\n\nThe available variables vary by system;   some of the common ones available on Unix include:\n\n: : : * PATH\n * HOME\n * USER" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #24 \"Seoul\"\n\nThe `%*ENV` hash maps environment variables to their values:\n\n```\nsay %*ENV<HOME>;\n\n```" } ]
[ { "role": "user", "content": "Suppose we have a sequence of prime sums, where each term **Pn** is the sum of the first **n** primes.\n\n```\nP = (2), (2 + 3), (2 + 3 + 5), (2 + 3 + 5 + 7), (2 + 3 + 5 + 7 + 11), ...\n\n```\n\n```\nP = 2, 5, 10, 17, 28, etc.\n\n```\n\nFurther; suppose we have a sequence of composite sums, where each term **Cm** is the sum of the first **m** composites.\n\n```\nC = (4), (4 + 6), (4 + 6 + 8), (4 + 6 + 8 + 9), (4 + 6 + 8 + 9 + 10), ...\n\n```\n\n```\nC = 4, 10, 18, 27, 37, etc.\n\n```\n\nNotice that the third term of **P**; **P3** (**10**) is equal to the second term of **C**; **C2** (**10**);\n\nTask\n\n* Find and display the indices (**n**, **m**) and value of at least the first 6 terms of the sequence of numbers that are both the sum of the first **n** primes and the first **m** composites.\n\nSee also\n\n* OEIS:A007504 - Sum of the first n primes * OEIS:A053767 - Sum of first n composite numbers * OEIS:A294174 - Numbers that can be expressed both as the sum of first primes and as the sum of first composites" }, { "role": "assistant", "content": "Let it run until I got bored and killed it. Time is total accumulated seconds since program start.\n\n```\nuse Lingua::EN::Numbers:ver<2.8.2+>;\n\nmy $prime-sum = [\\+] (2..*).grep: *.is-prime;\nmy $composite-sum = [\\+] (2..*).grep: !*.is-prime;\n\nmy $c-index = 0;\n\nfor ^∞ -> $p-index {\n next if $prime-sum[$p-index] < $composite-sum[$c-index];\n printf( \"%20s - %11s prime sum, %12s composite sum %5.2f seconds\\n\",\n $prime-sum[$p-index].&comma, ordinal-digit($p-index + 1, :u, :c),\n ordinal-digit($c-index + 1, :u, :c), now - INIT now )\n and next if $prime-sum[$p-index] == $composite-sum[$c-index];\n ++$c-index;\n redo;\n};\n\n```\n\nOutput:\n\n```\n 10 - 3ʳᵈ prime sum, 2ⁿᵈ composite sum 0.01 seconds\n 1,988 - 33ʳᵈ prime sum, 51ˢᵗ composite sum 0.01 seconds\n 14,697 - 80ᵗʰ prime sum, 147ᵗʰ composite sum 0.02 seconds\n 83,292 - 175ᵗʰ prime sum, 361ˢᵗ composite sum 0.03 seconds\n 1,503,397 - 660ᵗʰ prime sum, 1,582ⁿᵈ composite sum 0.04 seconds\n 18,859,052 - 2,143ʳᵈ prime sum, 5,699ᵗʰ composite sum 0.08 seconds\n 93,952,013 - 4,556ᵗʰ prime sum, 12,821ˢᵗ composite sum 0.14 seconds\n 89,171,409,882 - 118,785ᵗʰ prime sum, 403,341ˢᵗ composite sum 4.23 seconds\n 9,646,383,703,961 - 1,131,142ⁿᵈ prime sum, 4,229,425ᵗʰ composite sum 76.23 seconds\n 209,456,854,921,713 - 5,012,372ⁿᵈ prime sum, 19,786,181ˢᵗ composite sum 968.26 seconds\n^C\n```" } ]
[ { "role": "user", "content": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.\n\nFor example, in a sequence   \n\nA\n{\\displaystyle {\\displaystyle A}}\n:\n\n: : : : : A\n\n 0\n =\n −\n 7\n {\\displaystyle {\\displaystyle A\\_{0}=-7}}\n : A\n\n 1\n =\n 1\n {\\displaystyle {\\displaystyle A\\_{1}=1}}\n : A\n\n 2\n =\n 5\n {\\displaystyle {\\displaystyle A\\_{2}=5}}\n : A\n\n 3\n =\n 2\n {\\displaystyle {\\displaystyle A\\_{3}=2}}\n : A\n\n 4\n =\n −\n 4\n {\\displaystyle {\\displaystyle A\\_{4}=-4}}\n : A\n\n 5\n =\n 3\n {\\displaystyle {\\displaystyle A\\_{5}=3}}\n : A\n\n 6\n =\n 0\n {\\displaystyle {\\displaystyle A\\_{6}=0}}\n\n3   is an equilibrium index, because:\n\n: : : : : A\n\n 0\n +\n\n A\n\n 1\n +\n\n A\n\n 2\n =\n\n A\n\n 4\n +\n\n A\n\n 5\n +\n\n A\n\n 6\n {\\displaystyle {\\displaystyle A\\_{0}+A\\_{1}+A\\_{2}=A\\_{4}+A\\_{5}+A\\_{6}}}\n\n6   is also an equilibrium index, because:\n\n: : : : : A\n\n 0\n +\n\n A\n\n 1\n +\n\n A\n\n 2\n +\n\n A\n\n 3\n +\n\n A\n\n 4\n +\n\n A\n\n 5\n =\n 0\n {\\displaystyle {\\displaystyle A\\_{0}+A\\_{1}+A\\_{2}+A\\_{3}+A\\_{4}+A\\_{5}=0}}\n\n(sum of zero elements is zero)\n\n7   is not an equilibrium index, because it is not a valid index of sequence \n\nA\n{\\displaystyle {\\displaystyle A}}\n.\n\nTask;\n\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub equilibrium_index(@list) {\n my ($left,$right) = 0, [+] @list;\n\n gather for @list.kv -> $i, $x {\n $right -= $x;\n take $i if $left == $right;\n $left += $x;\n }\n}\n\nmy @list = -7, 1, 5, 2, -4, 3, 0;\n.say for equilibrium_index(@list).grep(/\\d/);\n\n```\n\nAnd here's an FP solution that manages to remain O(n):\n\n```\nsub equilibrium_index(@list) {\n my @a = [\\+] @list;\n my @b = reverse [\\+] reverse @list;\n ^@list Zxx (@a »==« @b); \n}\n\n```\n\nThe [\\+] is a reduction that returns a list of partial results. The »==« is a vectorized equality comparison; it returns a vector of true and false. The Zxx is a zip with the list replication operator, so we return only the elements of the left list where the right list is true (which is taken to mean 1 here). And the ^@list is just shorthand for 0 ..^ @list. We could just as easily have used @list.keys there.\n\n### Single-pass solution\n\nThe task can be restated in a way that removes the \"right side\" from the calculation.\n\nC is the current element, \nL is the sum of elements left of C, \nR is the sum of elements right of C, \nS is the sum of the entire list.\n\nBy definition, L + C + R == S for any choice of C, and L == R for any C that is an equilibrium point. \nTherefore (by substituting L for R), L + C + L == S at all equilibrium points. \nRestated, 2L + C == S.\n\n```\n# Original example, with expanded calculations:\n 0 1 2 3 4 5 6 # Index\n -7 1 5 2 -4 3 0 # C (Value at index)\n 0 -7 -6 -1 1 -3 0 # L (Sum of left)\n -7 -13 -7 0 -2 -3 0 # 2L+C\n\n```\n\nIf we build a hash as we walk the list, with 2L+C as hash keys, and arrays of C-indexes as hash values, we get:\n\n```\n{\n -7 => [ 0, 2 ],\n -13 => [ 1 ],\n 0 => [ 3, 6 ],\n -2 => [ 4 ],\n -3 => [ 5 ],\n}\n\n```\n\nAfter we have finished walking the list, we will have the sum (S), which we look up in the hash. Here S=0, so the equilibrium points are 3 and 6.\n\nNote: In the code below, it is more convenient to calculate 2L+C \\*after\\* L has already been incremented by C; the calculation is simply 2L-C, because each L has an extra C in it. 2(L-C)+C == 2L-C.\n\n```\nsub eq_index ( *@list ) {\n my $sum = 0;\n\n my %h = @list.keys.classify: {\n $sum += @list[$_];\n $sum * 2 - @list[$_];\n };\n\n return %h{$sum} // [];\n}\n\nsay eq_index < -7 1 5 2 -4 3 0 >; # 3 6\nsay eq_index < 2 4 6 >; # (no eq point)\nsay eq_index < 2 9 2 >; # 1\nsay eq_index < 1 -1 1 -1 1 -1 1 >; # 0 1 2 3 4 5 6\n\n```\n\nThe .classify method creates a hash, with its code block's return value as key. Each hash value is an Array of all the inputs that returned that key.\n\nWe could have used .pairs instead of .keys to save the cost of @list lookups, but that would change each %h value to an Array of Pairs, which would complicate the return line." } ]
[ { "role": "user", "content": "A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.\n\nThe task is first to display the first 200 primes allocated to their category, then assign the first million primes to their category, displaying the smallest prime, the largest prime, and the count of primes allocated to each category." }, { "role": "assistant", "content": "```\nuse Prime::Factor;\nuse Lingua::EN::Numbers;\nuse Math::Primesieve;\nmy $sieve = Math::Primesieve.new;\n\nmy %cat = 2 => 1, 3 => 1;\n\nsub Erdös-Selfridge ($n) {\n my @factors = prime-factors $n + 1;\n my $category = max %cat{ @factors };\n unless %cat{ @factors[*-1] } {\n $category max= ( 1 + max %cat{ prime-factors 1 + @factors[*-1] } );\n %cat{ @factors[*-1] } = $category;\n }\n $category\n}\n\nmy $upto = 200;\n\nsay \"First { cardinal $upto } primes; Erdös-Selfridge categorized:\";\n.say for sort $sieve.n-primes($upto).categorize: &Erdös-Selfridge;\n\n$upto = 1_000_000;\n\nsay \"\\nSummary of first { cardinal $upto } primes; Erdös-Selfridge categorized:\";\nprintf \"Category %2d: first: %9s last: %10s count: %s\\n\", ++$, |(.[0], .[*-1], .elems).map: &comma\nfor $sieve.n-primes($upto).categorize( &Erdös-Selfridge ).sort(+*.key)».value;\n\n```\n\nOutput:\n\n```\nFirst two hundred primes; Erdös-Selfridge categorized:\n1 => [2 3 5 7 11 17 23 31 47 53 71 107 127 191 383 431 647 863 971 1151]\n2 => [13 19 29 41 43 59 61 67 79 83 89 97 101 109 131 137 139 149 167 179 197 199 211 223 229 239 241 251 263 269 271 281 283 293 307 317 349 359 367 373 419 433 439 449 461 479 499 503 509 557 563 577 587 593 599 619 641 643 659 709 719 743 751 761 769 809 827 839 881 919 929 953 967 991 1019 1033 1049 1069 1087 1103 1187 1223]\n3 => [37 103 113 151 157 163 173 181 193 227 233 257 277 311 331 337 347 353 379 389 397 401 409 421 457 463 467 487 491 521 523 541 547 569 571 601 607 613 631 653 683 701 727 733 773 787 797 811 821 829 853 857 859 877 883 911 937 947 983 997 1009 1013 1031 1039 1051 1061 1063 1091 1097 1117 1123 1153 1163 1171 1181 1193 1217]\n4 => [73 313 443 617 661 673 677 691 739 757 823 887 907 941 977 1093 1109 1129 1201 1213]\n5 => [1021]\n\nSummary of first one million primes; Erdös-Selfridge categorized:\nCategory 1: first: 2 last: 10,616,831 count: 46\nCategory 2: first: 13 last: 15,482,669 count: 10,497\nCategory 3: first: 37 last: 15,485,863 count: 201,987\nCategory 4: first: 73 last: 15,485,849 count: 413,891\nCategory 5: first: 1,021 last: 15,485,837 count: 263,109\nCategory 6: first: 2,917 last: 15,485,857 count: 87,560\nCategory 7: first: 15,013 last: 15,484,631 count: 19,389\nCategory 8: first: 49,681 last: 15,485,621 count: 3,129\nCategory 9: first: 532,801 last: 15,472,811 count: 363\nCategory 10: first: 1,065,601 last: 15,472,321 count: 28\nCategory 11: first: 8,524,807 last: 8,524,807 count: 1\n```" } ]
[ { "role": "user", "content": "Definition\n\nAn Erdős–Nicolas number is a positive integer which is not perfect but is equal to the sum of its first **k** divisors (arranged in ascending order and including one) for some value of **k** greater than one.\n\nExamples\n\n24 is an Erdős–Nicolas number because the sum of its first 6 divisors (1, 2, 3, 4, 6 and 8) is equal to 24 and it is not perfect because 12 is also a divisor.\n\n6 is not an Erdős–Nicolas number because it is perfect (1 + 2 + 3 = 6).\n\n48 is not an Erdős–Nicolas number because its divisors are: 1, 2, 3, 4, 6, 8, 12, 16, 24 and 48. The first seven of these add up to 36, but the first eight add up to 52 which is more than 48.\n\nTask\n\nFind and show here the first 8 Erdős–Nicolas numbers and the number of divisors needed (i.e. the value of 'k') to satisfy the definition.\n\nStretch\n\nDo the same for any further Erdős–Nicolas numbers which you have the patience for.\n\nNote\n\nAs all known Erdős–Nicolas numbers are even you may assume this to be generally true in order to quicken up the search. However, it is not obvious (to me at least) why this should necessarily be the case.\n\nReference\n\n* OEIS:A194472 - Erdős–Nicolas numbers" }, { "role": "assistant", "content": "```\nuse Prime::Factor;\n\nsub is-Erdős-Nicolas ($n) {\n my @divisors = $n.&proper-divisors: :s;\n ((@divisors.sum > $n) && (my $key = ([\\+] @divisors).first: $n, :k)) ?? 1 + $key !! False\n}\n\nmy $count;\n\n(1..*).hyper(:2000batch).map( * × 2 ).map: {\n if my $key = .&is-Erdős-Nicolas {\n printf \"%8d == sum of its first %3d divisors\\n\", $_, $key;\n exit if ++$count >= 8;\n }\n}\n\n```\n\nOutput:\n\n```\n 24 == sum of its first 6 divisors\n 2016 == sum of its first 31 divisors\n 8190 == sum of its first 43 divisors\n 42336 == sum of its first 66 divisors\n 45864 == sum of its first 66 divisors\n 392448 == sum of its first 68 divisors\n 714240 == sum of its first 113 divisors\n 1571328 == sum of its first 115 divisors\n```" } ]
[ { "role": "user", "content": "Definitions\n\nIn mathematics, **Erdős primes** are prime numbers such that all p-k! for 1<=k!<p are composite.\n\nTask\n\nWrite a program to determine (and show here) all **Erdős primes** less than **2500**.\n\nOptionally, show the **number** of Erdős primes.\n\nStretch goal\n\nShow that the 7,875th Erdős prime is 999,721 (the highest below 1,000,000)\n\nAlso see\n: * the OEIS entry:   A064152 Erdos primes." }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\n\nmy @factorial = 1, |[\\*] 1..*;\nmy @Erdős = ^Inf .grep: { .is-prime and none($_ «-« @factorial[^(@factorial.first: * > $_, :k)]).is-prime }\n\nput 'Erdős primes < 2500:';\nput @Erdős[^(@Erdős.first: * > 2500, :k)]».&comma;\nput \"\\nThe 7,875th Erdős prime is: \" ~ @Erdős[7874].&comma;\n\n```\n\nOutput:\n\n```\nErdős primes < 2500:\n2 101 211 367 409 419 461 557 673 709 769 937 967 1,009 1,201 1,259 1,709 1,831 1,889 2,141 2,221 2,309 2,351 2,411 2,437\n\nThe 7,875th Erdős prime is: 999,721\n```\n\nAlternately, using fewer hard coded values:\n\n```\nuse Lingua::EN::Numbers;\nuse List::Divvy;\n\nmy @factorial = 1, |[\\*] 1..*;\nmy @Erdős = ^∞ .grep: { .is-prime and none($_ «-« @factorial.&upto: $_).is-prime }\n\nput \"Erdős primes < 2500:\\n\" ~ @Erdős.&before(2500)».&comma.batch(8)».fmt(\"%5s\").join: \"\\n\";\nput \"\\nThe largest Erdős prime less than {comma 1e6.Int} is {comma .[*-1]} in {.&ordinal-digit} position.\"\n given @Erdős.&before(1e6);\n\n```\n\nOutput:\n\n```\nErdős primes < 2500:\n 2 101 211 367 409 419 461 557\n 673 709 769 937 967 1,009 1,201 1,259\n1,709 1,831 1,889 2,141 2,221 2,309 2,351 2,411\n2,437\n\nThe largest Erdős prime less than 1,000,000 is 999,721 in 7875th position.\n```" } ]
[ { "role": "user", "content": "Description\n\nA positive integer **k** is said to be an Erdős–Woods number if it has the following property: there exists a positive integer **a** such that in the sequence (a, a + 1, …, a + k) of consecutive integers, each of the elements has a non-trivial common factor with one of the endpoints. In other words, **k** is an Erdős–Woods number if there exists a positive integer **a** such that for each integer **i** between 0 and k, at least one of the greatest common divisors gcd(a, a + i) or gcd(a + i, a + k) is greater than 1.\n\nIt can be shown that there are infinitely many such numbers. Moreover, if **k** is an E-W number for some integer **a**, then one can find an infinite number of other **a'**s using the formula **a(jq + 1)** where:\n\n* **q** is the product of all odd prime factors of **a + k**; and\n* **j** is any positive integer.\n\nExample\n\n16 is an E-W number (and also the first) for which the smallest value of **a** is 2184. This is because in the sequence 2184 to 2200 inclusive, the prime factors of the endpoints are:\n\n* 2³ x 3 x 7 x 13 = 2184\n* 2³ x 5² x 11 = 2200\n\nand, if you check all the numbers between them, you will find that they all have a prime factor in common with at least one of the endpoints (2189 is divisible by 11, 2191 by 7, 2197 by 13 and the rest by either 2, 3, or 5).\n\nTask\n\nCompute and show here the first **20** E-W numbers together with their corresponding smallest value of **a**. If your language doesn't support arbitrary precision arithmetic, just compute and show as many as you can.\n\nExtra credit\n\nDo the same for the **next 20** E-W numbers.\n\nNote\n\nAlthough all the E-W numbers relevant to this task are even, odd examples do exist the first one being **k** = 903.\n\nReferences\n\n* OEIS sequence A059756: Erdős–Woods numbers.\n* OEIS sequence A059757: Smallest values of a for a given E-W number k.\n* Planet Math: Erdős–Woods numbers." }, { "role": "assistant", "content": "**Translation of**: Wren\n\n**Translation of**: Julia\n\n```\n# 20220308 Raku programming solution\n\nsub ew (\\n) {\n\n my @primes = (^n).grep: *.is-prime; \n\n # rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation#Raku\n my @divs = (^n).map: -> \\p { ([o] map { p%%$_.Int + 2 * * }, @primes)(0) }\n\n my @partitions = [ 0, 0, 2**@primes.elems - 1 ] , ;\n\n sub ort(\\x) { (@divs[x] +| @divs[n -x]).base(2).flip.index(1) } \n\n for ((n^...1).sort: *.&ort).reverse {\n my \\newPartitions = @ = (); \n my (\\factors,\\otherFactors) = @divs[$_, n-$_];\n\n for @partitions -> \\p {\n my (\\setA, \\setB, \\rPrimes) = p[0..2];\n\n if (factors +& setA) or (otherFactors +& setB) {\n newPartitions.push: p and next \n } \n for (factors +& rPrimes).base(2).flip.comb.kv -> \\k,\\v {\n if (v == 1) {\n my \\w = 1 +< k; \n newPartitions.push: [ setA +^ w, setB, rPrimes +^ w ]\n }\n }\n for (otherFactors +& rPrimes).base(2).flip.comb.kv -> \\k,\\v {\n if (v == 1) {\n my \\w = 1 +< k; \n newPartitions.push: [ setA, setB +^ w, rPrimes +^ w ]\n }\n }\n }\n @partitions = newPartitions\n }\n\n my \\result = $ = -1;\n for @partitions -> \\p {\n my ($px,$py,$x,$y) = p[0],p[1],1,1;\n for @primes -> $p {\n $px % 2 and $x *= $p;\n $py % 2 and $y *= $p;\n ($px,$py) >>div=>> 2\n }\n my \\newresult = ((n * expmod($x, -1, $y)) % $y) * $x - n;\n result = result == -1 ?? newresult !! min(result, newresult)\n }\n return result \n}\n\nsay \"The first 20 Erdős–Woods numbers and their minimum interval start values are:\";\nfor (16..116) { if (my $ew = ew $_) > 0 { printf \"%3d -> %d\\n\",$_,$ew } } ;\n\n```\n\nOutput:\n\nSame as Wren example." } ]
[ { "role": "user", "content": "An **esthetic number** is a positive integer where every adjacent digit differs from its neighbour by 1.\n\nE.G.\n\n: * **12** is an esthetic number. One and two differ by 1.\n\n: * **5654** is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n: * **890** is **not** an esthetic number. Nine and zero differ by 9.\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers *are* included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\nTask\n\n: * Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n: * Use that routine to find esthetic numbers in bases **2** through **16** and display, here on this page, the esthectic numbers from index **(base × 4)** through index **(base × 6)**, inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n: * Find and display, here on this page, the **base 10** esthetic numbers with a magnitude between **1000** and **9999**.\n\n: * Stretch: Find and display, here on this page, the **base 10** esthetic numbers with a magnitude between **1.0e8** and **1.3e8**.\n\nRelated task\n\n* numbers with equal rises and falls\n\nSee also\n: * OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 * Numbers Aplenty - Esthetic numbers * Geeks for Geeks - Stepping numbers" }, { "role": "assistant", "content": "**Works with**: Rakudo version 2020.02\n\n```\nuse Lingua::EN::Numbers;\n\nsub esthetic($base = 10) {\n my @s = ^$base .map: -> \\s {\n ((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1)\n }\n\n flat [ (1 .. $base - 1)».base($base) ],\n { [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } … *\n}\n\nfor 2 .. 16 -> $b {\n put \"\\n{(4 × $b).&ordinal-digit} through {(6 × $b).&ordinal-digit} esthetic numbers in base $b\";\n put esthetic($b)[(4 × $b - 1) .. (6 × $b - 1)]».fmt('%3s').batch(16).join: \"\\n\"\n}\n\nmy @e10 = esthetic;\nput \"\\nBase 10 esthetic numbers between 1,000 and 9,999:\";\nput @e10.&between(1000, 9999).batch(20).join: \"\\n\";\n\nput \"\\nBase 10 esthetic numbers between {1e8.Int.&comma} and {1.3e8.Int.&comma}:\";\nput @e10.&between(1e8.Int, 1.3e8.Int).batch(9).join: \"\\n\";\n\nsub between (@array, Int $lo, Int $hi) {\n my $top = @array.first: * > $hi, :k;\n @array[^$top].grep: * > $lo\n}\n\n```\n\nOutput:\n\n```\n8th through 12th esthetic numbers in base 2\n10101010 101010101 1010101010 10101010101 101010101010\n\n12th through 18th esthetic numbers in base 3\n1210 1212 2101 2121 10101 10121 12101\n\n16th through 24th esthetic numbers in base 4\n323 1010 1012 1210 1212 1232 2101 2121 2123\n\n20th through 30th esthetic numbers in base 5\n323 343 432 434 1010 1012 1210 1212 1232 1234 2101\n\n24th through 36th esthetic numbers in base 6\n343 345 432 434 454 543 545 1010 1012 1210 1212 1232 1234\n\n28th through 42nd esthetic numbers in base 7\n345 432 434 454 456 543 545 565 654 656 1010 1012 1210 1212 1232\n\n32nd through 48th esthetic numbers in base 8\n432 434 454 456 543 545 565 567 654 656 676 765 767 1010 1012 1210\n1212\n\n36th through 54th esthetic numbers in base 9\n434 454 456 543 545 565 567 654 656 676 678 765 767 787 876 878\n1010 1012 1210\n\n40th through 60th esthetic numbers in base 10\n454 456 543 545 565 567 654 656 676 678 765 767 787 789 876 878\n898 987 989 1010 1012\n\n44th through 66th esthetic numbers in base 11\n456 543 545 565 567 654 656 676 678 765 767 787 789 876 878 898\n89A 987 989 9A9 A98 A9A 1010\n\n48th through 72nd esthetic numbers in base 12\n543 545 565 567 654 656 676 678 765 767 787 789 876 878 898 89A\n987 989 9A9 9AB A98 A9A ABA BA9 BAB\n\n52nd through 78th esthetic numbers in base 13\n545 565 567 654 656 676 678 765 767 787 789 876 878 898 89A 987\n989 9A9 9AB A98 A9A ABA ABC BA9 BAB BCB CBA\n\n56th through 84th esthetic numbers in base 14\n565 567 654 656 676 678 765 767 787 789 876 878 898 89A 987 989\n9A9 9AB A98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC\n\n60th through 90th esthetic numbers in base 15\n567 654 656 676 678 765 767 787 789 876 878 898 89A 987 989 9A9\n9AB A98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC CDE DCB DCD\n\n64th through 96th esthetic numbers in base 16\n654 656 676 678 765 767 787 789 876 878 898 89A 987 989 9A9 9AB\nA98 A9A ABA ABC BA9 BAB BCB BCD CBA CBC CDC CDE DCB DCD DED DEF\nEDC\n\nBase 10 esthetic numbers between 1,000 and 9,999:\n1010 1012 1210 1212 1232 1234 2101 2121 2123 2321 2323 2343 2345 3210 3212 3232 3234 3432 3434 3454\n3456 4321 4323 4343 4345 4543 4545 4565 4567 5432 5434 5454 5456 5654 5656 5676 5678 6543 6545 6565\n6567 6765 6767 6787 6789 7654 7656 7676 7678 7876 7878 7898 8765 8767 8787 8789 8987 8989 9876 9878\n9898\n\nBase 10 esthetic numbers between 100,000,000 and 130,000,000:\n101010101 101010121 101010123 101012101 101012121 101012123 101012321 101012323 101012343\n101012345 101210101 101210121 101210123 101212101 101212121 101212123 101212321 101212323\n101212343 101212345 101232101 101232121 101232123 101232321 101232323 101232343 101232345\n101234321 101234323 101234343 101234345 101234543 101234545 101234565 101234567 121010101\n121010121 121010123 121012101 121012121 121012123 121012321 121012323 121012343 121012345\n121210101 121210121 121210123 121212101 121212121 121212123 121212321 121212323 121212343\n121212345 121232101 121232121 121232123 121232321 121232323 121232343 121232345 121234321\n121234323 121234343 121234345 121234543 121234545 121234565 121234567 123210101 123210121\n123210123 123212101 123212121 123212123 123212321 123212323 123212343 123212345 123232101\n123232121 123232123 123232321 123232323 123232343 123232345 123234321 123234323 123234343\n123234345 123234543 123234545 123234565 123234567 123432101 123432121 123432123 123432321\n123432323 123432343 123432345 123434321 123434323 123434343 123434345 123434543 123434545\n123434565 123434567 123454321 123454323 123454343 123454345 123454543 123454545 123454565\n123454567 123456543 123456545 123456565 123456567 123456765 123456767 123456787 123456789\n```" } ]
[ { "role": "user", "content": "Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.\n\n**Method:**\n\n1. Take two numbers to be multiplied and write them down at the top of two columns.\n2. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1.\n3. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1.\n4. Examine the table produced and discard any row where the value in the left column is even.\n5. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together\n\n**For example:**   17 × 34\n\n```\n 17 34\n\n```\n\nHalving the first column:\n\n```\n 17 34\n 8\n 4\n 2\n 1\n\n```\n\nDoubling the second column:\n\n```\n 17 34\n 8 68\n 4 136 \n 2 272\n 1 544\n\n```\n\nStrike-out rows whose first cell is even:\n\n```\n 17 34\n 8 68 \n 4 136 \n 2 272 \n 1 544\n\n```\n\nSum the remaining numbers in the right-hand column:\n\n```\n 17 34\n 8 -- \n 4 --- \n 2 --- \n 1 544\n ====\n 578\n\n```\n\nSo 17 multiplied by 34, by the Ethiopian method is 578.\n\nTask\n\nThe task is to **define three named functions**/methods/procedures/subroutines:\n\n1. one to **halve an integer**,\n2. one to **double an integer**, and\n3. one to **state if an integer is even**.\n\nUse these functions to **create a function that does Ethiopian multiplication**.\n\nRelated tasks\n\n* Egyptian division\n\nReferences\n\n* Ethiopian multiplication explained (BBC Video clip)\n* A Night Of Numbers - Go Forth And Multiply (Video)\n* Russian Peasant Multiplication\n* Programming Praxis: Russian Peasant Multiplication" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub halve (Int $n is rw) { $n div= 2 }\nsub double (Int $n is rw) { $n *= 2 }\nsub even (Int $n --> Bool) { $n %% 2 }\n\nsub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {\n my Int $r = 0;\n while $a {\n\teven $a or $r += $b;\n\thalve $a;\n\tdouble $b;\n }\n return $r;\n}\n\nsay ethiopic-mult(17,34);\n```\n\nOutput:\n\n```\n578\n\n```\n\nMore succinctly using implicit typing, primed lambdas, and an infinite loop:\n\n```\nsub ethiopic-mult {\n my &halve = * div= 2;\n my &double = * *= 2;\n my &even = * %% 2;\n\n my ($a,$b) = @_;\n my $r;\n loop {\n even $a or $r += $b;\n halve $a or return $r;\n double $b;\n }\n}\n\nsay ethiopic-mult(17,34);\n```\n\nMore succinctly still, using a pure functional approach (reductions, mappings, lazy infinite sequences):\n\n```\nsub halve { $^n div 2 }\nsub double { $^n * 2 }\nsub even { $^n %% 2 }\n\nsub ethiopic-mult ($a, $b) {\n [+] ($b, &double ... *)\n Z*\n ($a, &halve ... 0).map: { not even $^n }\n}\n\nsay ethiopic-mult(17,34);\n```\n\n(same output)" } ]
[ { "role": "user", "content": "Definition\n\nThe Euclid–Mullin sequence is an infinite sequence of distinct prime numbers, in which each element is the least prime factor of one plus the product of all earlier elements.\n\nThe first element is usually assumed to be 2. So the second element is : (2) + 1 = 3 and the third element is : (2 x 3) + 1 = 7 as this is prime.\n\nAlthough intermingled with smaller elements, the sequence can produce very large elements quite quickly and only the first 51 have been computed at the time of writing.\n\nTask\n\nCompute and show here the first **16** elements of the sequence or, if your language does not support arbitrary precision arithmetic, as many as you can.\n\nStretch goal\n\nCompute the next **11** elements of the sequence.\n\nReference\n\nOEIS sequence A000945" }, { "role": "assistant", "content": "```\nuse Prime::Factor;\n\nmy @Euclid-Mullin = 2, { state $i = 1; (1 + [×] @Euclid-Mullin[^$i++]).&prime-factors.min } … *;\n\nput 'First sixteen: ', @Euclid-Mullin[^16];\n\n```\n\nOutput:\n\n```\nFirst sixteen: 2 3 7 43 13 53 5 6221671 38709183810571 139 2801 11 17 5471 52662739 23003\n```" } ]
[ { "role": "user", "content": "The **Euclidean rhythm** was proposed by Godfried Toussaint in 2004 and is described in a 2005 paper \"The Euclidean Algorithm Generates Traditional Musical Rhythms\".[1] It generates many forms of rhythm in music around the world. The program takes 2 integers *(m, n)* and outputs a binary string with *m* ones and *(n-m)* zeros.\n\nAs an example, here is how it runs on (5, 13):\n\n* Write 5 ones followed by (13-5) zeros, into 13 groups of 1-digit each:\n + 1 1 1 1 1 | 0 0 0 0 0 0 0 0\n* Repeatedly append substitute the second group into the first group:\n + 1 1 1 1 1 | 0 0 0 0 0 0 0 0\n + 10 10 10 10 10 | 0 0 0\n + 100 100 100 10 10 |\n* If the first group consists of elements of the same form, then output. Otherwise, divide the first group into two groups of the two forms, and repeat the process:\n + 100 100 100 10 10 |\n + 100 100 100 | 10 10\n + 10010 10010 100 |\n* At this point, we can continue the algorithm until only one form remains, but notice that one of the groups has only one element [100], so the algorithm can actually terminate right here and output the concatenation 1001010010100." }, { "role": "assistant", "content": "**Translation of**: Perl\n\n```\n# 20240208 Raku programming solution\n\nsay sub ($k is copy, $n is copy) {\n my @s = [ [1] xx $k ].append: [0] xx ($n - $k); \n my $z = my $d = $n - $k;\n ($k, $n) = ($d, $k).minmax.bounds;\n\n while $z > 0 || $k > 1 {\n ^$k .map: { @s[$_].append: @s.splice(*-1) } \n ($z, $d) = ($z, $n) X- $k;\n ($k, $n) = ($d, $k).minmax.bounds;\n }\n return [~] @s>>.List.flat;\n}(5, 13);\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page.\n\nThe ODE has to be provided in the following form:\n\n: : : d\n y\n (\n t\n )\n\n d\n t\n =\n f\n (\n t\n ,\n y\n (\n t\n )\n )\n {\\displaystyle {\\displaystyle {\\frac {dy(t)}{dt}}=f(t,y(t))}}\n\nwith an initial value\n\n: : : y\n (\n\n t\n\n 0\n )\n =\n\n y\n\n 0\n {\\displaystyle {\\displaystyle y(t\\_{0})=y\\_{0}}}\n\nTo get a numeric solution, we replace the derivative on the   LHS   with a finite difference approximation:\n\n: : : d\n y\n (\n t\n )\n\n d\n t\n ≈\n\n y\n (\n t\n +\n h\n )\n −\n y\n (\n t\n )\n h\n {\\displaystyle {\\displaystyle {\\frac {dy(t)}{dt}}\\approx {\\frac {y(t+h)-y(t)}{h}}}}\n\nthen solve for \n\ny\n(\nt\n+\nh\n)\n{\\displaystyle {\\displaystyle y(t+h)}}\n:\n\n: : : y\n (\n t\n +\n h\n )\n ≈\n y\n (\n t\n )\n +\n h\n\n d\n y\n (\n t\n )\n\n d\n t\n {\\displaystyle {\\displaystyle y(t+h)\\approx y(t)+h\\,{\\frac {dy(t)}{dt}}}}\n\nwhich is the same as\n\n: : : y\n (\n t\n +\n h\n )\n ≈\n y\n (\n t\n )\n +\n h\n\n f\n (\n t\n ,\n y\n (\n t\n )\n )\n {\\displaystyle {\\displaystyle y(t+h)\\approx y(t)+h\\,f(t,y(t))}}\n\nThe iterative solution rule is then:\n\n: : : y\n\n n\n +\n 1\n =\n\n y\n\n n\n +\n h\n\n f\n (\n\n t\n\n n\n ,\n\n y\n\n n\n )\n {\\displaystyle {\\displaystyle y\\_{n+1}=y\\_{n}+h\\,f(t\\_{n},y\\_{n})}}\n\nwhere   \n\nh\n{\\displaystyle {\\displaystyle h}}\n   is the step size, the most relevant parameter for accuracy of the solution.   A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.\n\n**Example: Newton's Cooling Law**\n\nNewton's cooling law describes how an object of initial temperature   \n\nT\n(\n\nt\n\n0\n)\n=\n\nT\n\n0\n{\\displaystyle {\\displaystyle T(t\\_{0})=T\\_{0}}}\n   cools down in an environment of temperature   \n\nT\n\nR\n{\\displaystyle {\\displaystyle T\\_{R}}}\n:\n\n: : : d\n T\n (\n t\n )\n\n d\n t\n =\n −\n k\n\n Δ\n T\n {\\displaystyle {\\displaystyle {\\frac {dT(t)}{dt}}=-k\\,\\Delta T}}\n\nor\n\n: : : d\n T\n (\n t\n )\n\n d\n t\n =\n −\n k\n\n (\n T\n (\n t\n )\n −\n\n T\n\n R\n )\n {\\displaystyle {\\displaystyle {\\frac {dT(t)}{dt}}=-k\\,(T(t)-T\\_{R})}}\n\nIt says that the cooling rate   \n\nd\nT\n(\nt\n)\n\nd\nt\n{\\displaystyle {\\displaystyle {\\frac {dT(t)}{dt}}}}\n   of the object is proportional to the current temperature difference   \n\nΔ\nT\n=\n(\nT\n(\nt\n)\n−\n\nT\n\nR\n)\n{\\displaystyle {\\displaystyle \\Delta T=(T(t)-T\\_{R})}}\n   to the surrounding environment.\n\nThe analytical solution, which we will compare to the numerical approximation, is\n\n: : : T\n (\n t\n )\n =\n\n T\n\n R\n +\n (\n\n T\n\n 0\n −\n\n T\n\n R\n )\n\n\n e\n\n −\n k\n t\n {\\displaystyle {\\displaystyle T(t)=T\\_{R}+(T\\_{0}-T\\_{R})\\;e^{-kt}}}\n\nTask\n\nImplement a routine of Euler's method and then to use it to solve the given example of Newton's cooling law with it for three different step sizes of:\n\n: : : * 2 s\n * 5 s       and\n * 10 s\n\nand to compare with the analytical solution.\n\nInitial values\n: : : * initial temperature   \n\n T\n\n 0\n {\\displaystyle {\\displaystyle T\\_{0}}}\n   shall be   100 °C\n * room temperature   \n\n T\n\n R\n {\\displaystyle {\\displaystyle T\\_{R}}}\n   shall be   20 °C\n * cooling constant     \n\n k\n {\\displaystyle {\\displaystyle k}}\n     shall be   0.07\n * time interval to calculate shall be from   0 s   ──►   100 s\n\nA reference solution (Common Lisp) can be seen below.   We see that bigger step sizes lead to reduced approximation accuracy." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub euler ( &f, $y0, $a, $b, $h ) {\n my $y = $y0;\n my @t_y;\n for $a, * + $h ... * > $b -> $t {\n @t_y[$t] = $y;\n $y += $h × f( $t, $y );\n }\n @t_y\n}\n\nconstant COOLING_RATE = 0.07;\nconstant AMBIENT_TEMP = 20;\nconstant INITIAL_TEMP = 100;\nconstant INITIAL_TIME = 0;\nconstant FINAL_TIME = 100;\n\nsub f ( $time, $temp ) {\n -COOLING_RATE × ( $temp - AMBIENT_TEMP )\n}\n\nmy @e;\n@e[$_] = euler( &f, INITIAL_TEMP, INITIAL_TIME, FINAL_TIME, $_ ) for 2, 5, 10;\n\nsay 'Time Analytic Step2 Step5 Step10 Err2 Err5 Err10';\n\nfor INITIAL_TIME, * + 10 ... * >= FINAL_TIME -> $t {\n\n my $exact = AMBIENT_TEMP + (INITIAL_TEMP - AMBIENT_TEMP)\n × (-COOLING_RATE × $t).exp;\n\n my $err = sub { @^a.map: { 100 × ($_ - $exact).abs / $exact } }\n\n my ( $a, $b, $c ) = map { @e[$_][$t] }, 2, 5, 10;\n\n say $t.fmt('%4d '), ( $exact, $a, $b, $c )».fmt(' %7.3f'),\n $err([$a, $b, $c])».fmt(' %7.3f%%');\n}\n\n```\n\nOutput:\n\n```\nTime Analytic Step2 Step5 Step10 Err2 Err5 Err10\n 0 100.000 100.000 100.000 100.000 0.000% 0.000% 0.000%\n 10 59.727 57.634 53.800 44.000 3.504% 9.923% 26.331%\n 20 39.728 37.704 34.281 27.200 5.094% 13.711% 31.534%\n 30 29.797 28.328 26.034 22.160 4.927% 12.629% 25.629%\n 40 24.865 23.918 22.549 20.648 3.808% 9.313% 16.959%\n 50 22.416 21.843 21.077 20.194 2.555% 5.972% 9.910%\n 60 21.200 20.867 20.455 20.058 1.569% 3.512% 5.384%\n 70 20.596 20.408 20.192 20.017 0.912% 1.959% 2.808%\n 80 20.296 20.192 20.081 20.005 0.512% 1.057% 1.432%\n 90 20.147 20.090 20.034 20.002 0.281% 0.559% 0.721%\n 100 20.073 20.042 20.014 20.000 0.152% 0.291% 0.361%\n```" } ]
[ { "role": "user", "content": "Task.\n\nCompute the Euler constant 0.5772...\n\nDiscovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these.\n\nDenoted gamma (*γ*), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ from the logarithmic function (its approximating integral): lim n → ∞ (1 + 1/2 + 1/3 + … + 1/n − log(n)).\n\nThe definition of *γ* converges too slowly to be numerically useful, but in 1735 Euler himself applied his recently discovered summation formula to compute ‘the notable number’ accurate to 15 places. For a single-precision implementation this is still the most economic algorithm.\n\nIn 1961, the young Donald Knuth used Euler's method to evaluate *γ* to 1271 places. Knuth found that the computation of the Bernoulli numbers required in the Euler-Maclaurin formula was the most time-consuming part of the procedure.\n\nThe next year Dura Sweeney computed 3566 places, using a formula based on the expansion of the exponential integral which didn't need Bernoulli numbers. It's a bit-hungry method though: *2d* digits of working precision obtain *d* correct places only.\n\nThis was remedied in 1988 by David Bailey; meanwhile Richard Brent and Ed McMillan had published an even more efficient algorithm based on Bessel function identities and found 30100 places in 20 hours time.\n\nNowadays the old records have far been exceeded: over 6·1011 decimal places are already known. These massive computations suggest that *γ* is neither rational nor algebraic, but this is yet to be proven.\n\nReferences.\n\n[1]\nGourdon and Sebah, The Euler constant *γ*. (for all formulas)\n\n[2]\nEuler's original journal article translated from the latin (p. 9)" }, { "role": "assistant", "content": "```\n# 20211124 Raku programming solution \n\nsub gamma (\\N where N > 1) { # Vacca series https://w.wiki/4ybp\n # convert terms to FatRat for arbitrary precision\n return (1/2 - 1/3) + [+] (2..N).race.map: -> \\n {\n\n my ($power, $sign, $term) = 2**n, -1;\n\n for ($power..^2*$power) { $term += ($sign = -$sign) / $_ }\n\n n*$term\n }\n}\n\nsay gamma 23 ;\n\n```\n\nOutput:\n\n```\n0.5772149198434515\n\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Euler's\\_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn mathematics, *Euler's identity* is the equality:\n\n```\n ei\n \n \n \n \n \n π\n \n \n \n \n {\\displaystyle {\\displaystyle \\pi }}\n \n + 1 = 0\n\n```\n\nwhere\n\n```\n e is Euler's number, the base of natural logarithms,\n i is the imaginary unit, which satisfies i2 = −1, and\n \n \n \n \n \n \n π\n \n \n \n \n {\\displaystyle {\\displaystyle \\pi }}\n \n is pi, the ratio of the circumference of a circle to its diameter.\n\n```\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n```\n The number 0.\n The number 1.\n The number \n \n \n \n \n \n π\n \n \n \n \n {\\displaystyle {\\displaystyle \\pi }}\n \n (\n \n \n \n \n \n π\n \n \n \n \n {\\displaystyle {\\displaystyle \\pi }}\n \n = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number i, the imaginary unit of the complex numbers.\n\n```\n\nTask\n\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.\n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.\n\nIf that is the case, or there is some other limitation, show\nthat ei\n\nπ\n{\\displaystyle {\\displaystyle \\pi }} + 1 is *approximately* equal to zero and\nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show\nthat ei\n\nπ\n{\\displaystyle {\\displaystyle \\pi }} + 1 is *exactly* equal to zero for bonus kudos points." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nImplementing an \"invisible times\" operator (Unicode character (U+2062)) to more closely emulate the layout. Alas, Raku does not do symbolic calculations at this time and is limited to IEEE 754 floating point for transcendental and irrational number calculations.\n\ne, i and π are all available as built-in constants in Raku.\n\n```\nsub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };\n\nsay 'e**i⁢π + 1 ≅ 0 : ', e**i⁢π + 1 ≅ 0;\nsay 'Error: ', e**i⁢π + 1;\n\n```\n\nOutput:\n\n```\ne**i⁢π + 1 ≅ 0 : True\nError: 0+1.2246467991473532e-16i\n```" } ]
[ { "role": "user", "content": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n: At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of \n\nx\n\n0\n\n5\n+\n\nx\n\n1\n\n5\n+\n\nx\n\n2\n\n5\n+\n\nx\n\n3\n\n5\n=\n\ny\n\n5\n{\\displaystyle {\\displaystyle x\\_{0}^{5}+x\\_{1}^{5}+x\\_{2}^{5}+x\\_{3}^{5}=y^{5}}}\n where all \n\nx\n\ni\n{\\displaystyle {\\displaystyle x\\_{i}}}\n and \n\ny\n{\\displaystyle {\\displaystyle y}}\n are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n\n* Pythagorean quadruples.\n* Pythagorean triples." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n```\nconstant MAX = 250;\n\nmy %po5{Int};\nmy %sum2{Int};\n\nfor 1..MAX -> \\i {\n %po5{i⁵} = i;\n for 1..MAX -> \\j {\n %sum2{i⁵ + j⁵} = i, j;\n }\n}\n\n%po5.keys.sort.race.map: -> \\p {\n for %sum2.keys.sort -> \\s {\n if p > s and %sum2{p - s} {\n say ((sort |%sum2{s},|%sum2{p - s}) X~ '⁵').join(' + '), \" = %po5{p}\", \"⁵\" and exit\n }\n }\n}\n\n```\n\nOutput:\n\n```\n27⁵ + 84⁵ + 110⁵ + 133⁵ = 144⁵\n```" } ]
[ { "role": "user", "content": "This programming task, is to calculate ANY binomial coefficient.\n\nHowever, it has to be able to output   \n\n(\n\n5\n3\n\n)\n{\\displaystyle {\\displaystyle {\\binom {5}{3}}}}\n,   which is   **10**.\n\nThis formula is recommended:\n\n: : (\n\n n\n k\n\n )\n =\n\n n\n !\n\n (\n n\n −\n k\n )\n !\n k\n !\n =\n\n n\n (\n n\n −\n 1\n )\n (\n n\n −\n 2\n )\n …\n (\n n\n −\n k\n +\n 1\n )\n\n k\n (\n k\n −\n 1\n )\n (\n k\n −\n 2\n )\n …\n 1\n {\\displaystyle {\\displaystyle {\\binom {n}{k}}={\\frac {n!}{(n-k)!k!}}={\\frac {n(n-1)(n-2)\\ldots (n-k+1)}{k(k-1)(k-2)\\ldots 1}}}}\n\n**See Also:**\n\n* Combinations and permutations\n* Pascal's triangle\n\n: : : : The number of samples of size k from n objects.\n \n \n With   combinations and permutations   generation tasks.\n\n | | Order Unimportant | Order Important |\n | --- | --- | --- |\n | Without replacement | ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\\displaystyle {\\displaystyle {\\binom {n}{k}}=^{n}\\operatorname {C} \\_{k}={\\frac {n(n-1)\\ldots (n-k+1)}{k(k-1)\\dots 1}}}} | n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\\displaystyle {\\displaystyle ^{n}\\operatorname {P} \\_{k}=n\\cdot (n-1)\\cdot (n-2)\\cdots (n-k+1)}} |\n | Task: Combinations | Task: Permutations |\n | With replacement | ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\\displaystyle {\\displaystyle {\\binom {n+k-1}{k}}=^{n+k-1}\\operatorname {C} \\_{k}={(n+k-1)! \\over (n-1)!k!}}} | n k {\\displaystyle {\\displaystyle n^{k}}} |\n | Task: Combinations with repetitions | Task: Permutations with repetitions |" }, { "role": "assistant", "content": "(formerly Perl 6)\nFor a start, you can get the length of the corresponding list of combinations:\n\n```\nsay combinations(5, 3).elems;\n\n```\n\nOutput:\n\n```\n10\n```\n\nThis method is efficient, as Raku will not actually compute each element of the list, since it actually uses an iterator with a defined count-only method. Such method performs computations in a way similar to the following infix operator:\n\n```\nsub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. $^p }\nsay 5 choose 3;\n```\n\nA possible optimization would use a symmetry property of the binomial coefficient:\n\n```\nsub infix:<choose> { [*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p) }\n```\n\nOne drawback of this method is that it returns a Rat, not an Int. So we actually may want to enforce the conversion:\n\n```\nsub infix:<choose> { ([*] ($^n ... 0) Z/ 1 .. min($n - $^p, $p)).Int }\n```\n\nAnd *this* is exactly what the count-only method does." } ]
[ { "role": "user", "content": "In 1742, Goldbach and Euler corresponded about what is now known as the Goldbach Conjecture: that all even integers greater than 2 can be written as the sum of two primes.\n \nIn 2000, Henry Dubner proposed a stronger conjecture: that every even integer greater than 4208 can be written as the sum of two twin primes.\n \n \nAt the time the Goldbach conjecture was made, 1 was considered a prime number - this is not so now. So, the Goldbach conjecture was originally that all even natural numbers could be written as the sum of two primes.\n\nTask\n\n* Find and display the positive even integers that cannot be expressed as the sum of two twin primes, up to a limit of 5,000.\n\n: : E.g.: The first 3 twin primes are 3, 5 and 7, so 6 (3+3), 8 (5+3) and 10 (5+5 or 7+3) can be formed but 2 and 4 cannot.\n\n* Show the numbers that cannot be formed by summing two twin primes when 1 is treated as a prime (and so a twin prime).\n\nNote\n\n* For the purposes of this task, twin prime refers to a prime that is 2 more or less than another prime, not the pair of primes.\n\nStretch\n\n* Verify that there no more such numbers up to 10,000 or more, as you like (note it has been verified up to at least 10^9).\n\nSee also\n\n* Wikipedia: Dubner's conjecture * Wikipedia: Goldbach's conjecture * OEIS:A007534 - Even numbers that are not the sum of a pair of twin primes. * Twin primes" }, { "role": "assistant", "content": "```\nmy $threshold = 10000;\n\nmy @twins = unique flat (3..$threshold).grep(&is-prime).map: { $_, $_+2 if ($_+2).is-prime };\nmy @sums;\n\nmap {++@sums[$_]}, (@twins X+ @twins);\ndisplay 'Non twin prime sums:', @sums;\n\nmap {++@sums[$_]}, flat 2, (1 X+ @twins);\ndisplay \"\\nNon twin prime sums (including 1):\", @sums;\n\nsub display ($msg, @p) {\n put \"$msg\\n\" ~ @p[^$threshold].kv.map(-> $k, $v { $k if ($k %% 2) && !$v })\\\n .skip(1).batch(10)».fmt(\"%4d\").join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\nNon twin prime sums:\n 2 4 94 96 98 400 402 404 514 516\n 518 784 786 788 904 906 908 1114 1116 1118\n1144 1146 1148 1264 1266 1268 1354 1356 1358 3244\n3246 3248 4204 4206 4208\n\nNon twin prime sums (including 1):\n 94 96 98 400 402 404 514 516 518 784\n 786 788 904 906 908 1114 1116 1118 1144 1146\n1148 1264 1266 1268 1354 1356 1358 3244 3246 3248\n4204 4206 4208\n```" } ]
[ { "role": "user", "content": "Task\n\nTest whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, *i bitwise-and 1* equals 0 iff *i* is even, or equals 1 iff *i* is odd.\n* Divide *i* by 2. The remainder equals 0 iff *i* is even. The remainder equals +1 or -1 iff *i* is odd.\n* Use modular congruences:\n + *i* ≡ 0 (mod 2) iff *i* is even.\n + *i* ≡ 1 (mod 2) iff *i* is odd." }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku doesn't have a built-in for this, but with subsets it's easy to define a predicate for it.\n\n```\nsubset Even of Int where * %% 2;\nsubset Odd of Int where * % 2;\n\nsay 1 ~~ Even; # false\nsay 1 ~~ Odd; # true\nsay 1.5 ~~ Odd # false ( 1.5 is not an Int )\n```" } ]
[ { "role": "user", "content": "**Event** is a synchronization object. An event has two states *signaled* and *reset*. A task may await for the event to enter the desired state, usually the *signaled* state. It is released once the state is entered. Releasing waiting tasks is called *event notification*. Programmatically controlled events can be set by a task into one of its states.\n\nIn concurrent programming event also refers to a notification that some state has been reached through an asynchronous activity. The source of the event can be:\n\n* *internal*, from another task, programmatically;\n* *external*, from the hardware, such as user input, timer, etc. Signaling an event from the hardware is accomplished by means of hardware interrupts.\n\nEvent is a low-level synchronization mechanism. It neither identify the state that caused it signaled, nor the source of, nor who is the subject of notification. Events augmented by data and/or publisher-subscriber schemes are often referred as **messages**, **signals** etc.\n\nIn the context of general programming **event-driven architecture** refers to a design that deploy events in order to synchronize tasks with the asynchronous activities they must be aware of. The opposite approach is **polling** sometimes called **busy waiting**, when the synchronization is achieved by an explicit periodic querying the state of the activity. As the name suggests busy waiting consumes system resources even when the external activity does not change its state.\n\nEvent-driven architectures are widely used in GUI design and SCADA systems. They are flexible and have relatively short response times. At the same time event-driven architectures suffer to the problems related to their unpredictability. They face race condition, deadlocking, live locks and priority inversion. For this reason real-time systems tend to polling schemes, trading performance for predictability in the worst case scenario.\n\n# Variants of events\n\n## Manual-reset event\n\nThis event changes its state by an explicit request of a task. I.e. once signaled it remains in this state until it will be explicitly reset.\n\n## Pulse event\n\nA pulse event when signaled releases all tasks awaiting it and then is automatically reset.\n\n# Sample implementations / APIs\n\nShow how a manual-reset event can be implemented in the language or else use an API to a library that provides events. Write a program that waits 1s and then signals the event to a task waiting for the event." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Go\n\n```\nnote now, \" program start\";\nmy $event = Channel.new;\n\nmy $todo = start {\n note now, \" task start\";\n $event.receive;\n note now, \" event reset by task\";\n}\n\nnote now, \" program sleeping\";\nsleep 1;\nnote now, \" program signaling event\";\n$event.send(0);\nawait $todo;\n\n```\n\nOutput:\n\n```\nInstant:1403880984.089974 program start\nInstant:1403880984.095400 program sleeping\nInstant:1403880984.095491 task start\nInstant:1403880985.099381 program signaling event\nInstant:1403880985.109395 event reset by task\n```\n\nSee also Handle\\_a\\_signal#Raku for an example of using Supplies to do reactive programming based on events (Unix signals in this case)." } ]
[ { "role": "user", "content": "Starting with:\n\n* The `target` string: `\"METHINKS IT IS LIKE A WEASEL\"`.\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the `parent`).\n* A `fitness` function that computes the ‘closeness’ of its argument to the target string.\n* A `mutate` function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the `parent` is not yet the `target`:\n\n: * copy the `parent` C times, each time allowing some random probability that another character might be substituted using `mutate`.\n * Assess the `fitness` of the parent and all the copies to the `target` and make the most fit string the new `parent`, discarding the others.\n * repeat until the parent converges, (hopefully), to the target.\n\nSee also\n\n* Wikipedia entry:   Weasel algorithm.\n* Wikipedia entry:   Evolutionary algorithm.\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n\n* While the `parent` is not yet the `target`:\n\n: * copy the `parent` C times, each time allowing some random probability that another character might be substituted using `mutate`.\n\nNote that some of the the solutions given retain characters in the mutated string that are *correct* in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n```\n(:* repeat until the parent converges, (hopefully), to the target.\n\n```\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by *not* being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n```\nCreate a new string based on the TOS, changing randomly any characters which\ndon't already match the target:\n\n```\n\n*NOTE:* this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2022-07-09\n\n```\nconstant target = \"METHINKS IT IS LIKE A WEASEL\";\nconstant @alphabet = flat 'A'..'Z',' ';\nconstant C = 10;\n\nsub mutate(Str $string, Real $mutate-chance where 0 ≤ * < 1) {\n $string.subst: /<?{ rand < $mutate-chance }> . /, @alphabet.pick, :global\n}\nsub fitness(Str $string) { [+] $string.comb Zeq target.comb }\n\nprintf \"\\r%6d: '%s'\", $++, $_ for\n @alphabet.roll(target.chars).join,\n { max :by(&fitness), mutate($_, .001) xx C } ... target;\nprint \"\\n\";\n\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven 5 lists of ints:\n \nlist[1] = [9,3,3,3,2,1,7,8,5]\n \nlist[2] = [5,2,9,3,3,7,8,4,1]\n \nlist[3] = [1,4,3,6,7,3,8,3,2]\n \nlist[4] = [1,2,3,4,5,6,7,8,9]\n \nlist[5] = [4,6,8,7,2,3,3,3,1]\n \n \nFor each list, print 'true' if the list contains exactly three '3's that form a consecutive subsequence, otherwise print 'false'.\nThat is, print false unless there is exactly one run of three '3's and there is no other occurrence of a '3'." }, { "role": "assistant", "content": "Generalized\n\n```\nfor 1 .. 4 -> $n {\n\n say \"\\nExactly $n {$n}s, and they are consecutive:\";\n\n say .gist, ' ', lc (.Bag{$n} == $n) && ( so .rotor($n=>-($n - 1)).grep: *.all == $n ) for\n [9,3,3,3,2,1,7,8,5],\n [5,2,9,3,3,7,8,4,1],\n [1,4,3,6,7,3,8,3,2],\n [1,2,3,4,5,6,7,8,9],\n [4,6,8,7,2,3,3,3,1],\n [3,3,3,1,2,4,5,1,3],\n [0,3,3,3,3,7,2,2,6],\n [3,3,3,3,3,4,4,4,4]\n}\n\n```\n\nOutput:\n\n```\nExactly 1 1s, and they are consecutive:\n[9 3 3 3 2 1 7 8 5] true\n[5 2 9 3 3 7 8 4 1] true\n[1 4 3 6 7 3 8 3 2] true\n[1 2 3 4 5 6 7 8 9] true\n[4 6 8 7 2 3 3 3 1] true\n[3 3 3 1 2 4 5 1 3] false\n[0 3 3 3 3 7 2 2 6] false\n[3 3 3 3 3 4 4 4 4] false\n\nExactly 2 2s, and they are consecutive:\n[9 3 3 3 2 1 7 8 5] false\n[5 2 9 3 3 7 8 4 1] false\n[1 4 3 6 7 3 8 3 2] false\n[1 2 3 4 5 6 7 8 9] false\n[4 6 8 7 2 3 3 3 1] false\n[3 3 3 1 2 4 5 1 3] false\n[0 3 3 3 3 7 2 2 6] true\n[3 3 3 3 3 4 4 4 4] false\n\nExactly 3 3s, and they are consecutive:\n[9 3 3 3 2 1 7 8 5] true\n[5 2 9 3 3 7 8 4 1] false\n[1 4 3 6 7 3 8 3 2] false\n[1 2 3 4 5 6 7 8 9] false\n[4 6 8 7 2 3 3 3 1] true\n[3 3 3 1 2 4 5 1 3] false\n[0 3 3 3 3 7 2 2 6] false\n[3 3 3 3 3 4 4 4 4] false\n\nExactly 4 4s, and they are consecutive:\n[9 3 3 3 2 1 7 8 5] false\n[5 2 9 3 3 7 8 4 1] false\n[1 4 3 6 7 3 8 3 2] false\n[1 2 3 4 5 6 7 8 9] false\n[4 6 8 7 2 3 3 3 1] false\n[3 3 3 1 2 4 5 1 3] false\n[0 3 3 3 3 7 2 2 6] false\n[3 3 3 3 3 4 4 4 4] true\n```" } ]
[ { "role": "user", "content": "This task is to give an example of an exception handling routine\nand to \"throw\" a new exception.\n\nRelated task\n\n* Exceptions Through Nested Calls" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-09-10\n\nThe Raku equivalent to Perl 5's eval {...} is try {...}. A try block by default has a CATCH block that handles all fatal exceptions by ignoring them. If you define a CATCH block within the try, it replaces the default CATCH. It also makes the try keyword redundant, because any block can function as a try block if you put a CATCH block within it. The inside of a CATCH functions as a switch statement on the current exception.\n\n```\ntry {\n die \"Help I'm dieing!\";\n CATCH {\n when X::AdHoc { note .Str.uc; say \"Cough, Cough, Aiee!!\" }\n default { note \"Unexpected exception, $_!\" }\n }\n}\n\nsay \"Yay. I'm alive.\";\n\ndie \"I'm dead.\";\n\nsay \"Arrgh.\";\n\nCATCH {\n default { note \"No you're not.\"; say $_.Str; }\n}\n```\n\n```\nHELP I'M DIEING!\nCough, Cough, Aiee!!\nYay. I'm alive.\nNo you're not.\nI'm dead.\n\n```\n\nRake comes with phasers, that are called when certain conditions in the life of a program, routine or block are met. CATCH is one of them and works nicely together with LEAVE that is called even if an exception would force the current block to be left immediately. It's a nice place to put your cleanup code.\n\n```\nsub f(){\n ENTER { note '1) f has been entered' }\n LEAVE { note '2) f has been left' }\n say '3) here be dragons';\n die '4) that happend to be deadly';\n}\n\nf();\nsay '5) am I alive?';\n\nCATCH {\n when X::AdHoc { note q{6) no, I'm dead}; }\n}\n```\n\n```\n1) f has been entered\n3) here be dragons\n6) no, I'm dead\n2) f has been left\n```" } ]
[ { "role": "user", "content": "Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.\n\n: 1. Create two user-defined exceptions,   **U0**   and   **U1**.\n 2. Have function   **foo**   call function   **bar**   twice.\n 3. Have function   **bar**   call function   **baz**.\n 4. Arrange for function   **baz**   to raise, or throw exception   **U0**   on its first call, then exception   **U1**   on its second.\n 5. Function   **foo**   should catch only exception   **U0**,   not   **U1**.\n\nShow/describe what happens when the program is run." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub foo() {\n for 0..1 -> $i {\n bar $i;\n CATCH {\n when /U0/ { say \"Function foo caught exception U0\" }\n }\n }\n}\n\nsub bar($i) { baz $i }\n\nsub baz($i) { die \"U$i\" }\n\nfoo;\n\n```\n\nOutput:\n\n```\nFunction foo caught exception U0\nU1\n in sub baz at catch:12\n in sub bar at catch:10\n in sub foo at catch:4\n in block at catch:14\n```" } ]
[ { "role": "user", "content": "The general idea behind an executable library is to create a library\nthat when used as a library does one thing;\nbut has the ability to be run directly via command line.\nThus the API comes with a CLI in the very same source code file.\n\n**Task detail**\n\n* Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.\n\n* The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:\n\n: : 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n : 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.\n\n* Create a second executable to calculate the following:\n + Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.\n\n* Explain any extra setup/run steps needed to complete the task.\n\n**Notes:**\n\n* It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed *not* to be present in the runtime environment.\n* Interpreters are present in the runtime environment." }, { "role": "assistant", "content": "(formerly Perl 6)\nThe library can be written as a module:\n\n```\nmodule Hailstone {\n our sub hailstone($n) is export {\n\t$n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1\n }\n}\n\nsub MAIN {\n say \"hailstone(27) = {.[^4]} [...] {.[*-4 .. *-1]}\" given Hailstone::hailstone 27;\n}\n\n```\n\nIt can be run with:\n\n```\n$ raku Hailstone.rakumod\n\n```\n\nOutput:\n\n```\nhailstone(27) = 27 82 41 124 [...] 8 4 2 1\n```\n\nIt can then be used with a program such as:\n\n```\nuse Hailstone;\nmy %score;\n(1 .. 100_000).race.map: { %score{hailstone($_).elems}++ };\nsay \"Most common length is {.key}, occurring {.value} times.\" given max :by(*.value), %score;\n\n```\n\nCalled with a command line as:\n\n```\n$ RAKULIB=. raku test-hailstone.raku\n```\n\nThe environment variable RAKULIB might be necessary if the file Hailstone.rakumod is not in the standard library path for Raku." } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Markov\\_algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nTask\n\nCreate an interpreter for a Markov Algorithm.\n\nRules have the syntax:\n\n```\n<ruleset> ::= ((<comment> | <rule>) <newline>+)*\n<comment> ::= # {<any character>}\n<rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement>\n<whitespace> ::= (<tab> | <space>) [<whitespace>]\n\n```\n\nThere is one rule per line.\n\nIf there is a   **.**   (period)   present before the   **<replacement>**,   then this is a terminating rule in which case the interpreter must halt execution.\n\nA ruleset consists of a sequence of rules, with optional comments.\n\nRulesets\n\nUse the following tests on entries:\n\nRuleset 1\n\n```\n# This rules file is extracted from Wikipedia:\n# http://en.wikipedia.org/wiki/Markov_Algorithm\nA -> apple\nB -> bag\nS -> shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule\n\n```\n\nSample text of:\n\n: `I bought a B of As from T S.`\n\nShould generate the output:\n\n: `I bought a bag of apples from my brother.`\n\nRuleset 2\n\nA test of the terminating rule\n\n```\n# Slightly modified from the rules on Wikipedia\nA -> apple\nB -> bag\nS -> .shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule\n```\n\nSample text of:\n\n: `I bought a B of As from T S.`\n\nShould generate:\n\n: `I bought a bag of apples from T shop.`\n\nRuleset 3\n\nThis tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.\n\n```\n# BNF Syntax testing rules\nA -> apple\nWWWW -> with\nBgage -> ->.*\nB -> bag\n->.* -> money\nW -> WW\nS -> .shop\nT -> the\nthe shop -> my brother\na never used -> .terminating rule\n\n```\n\nSample text of:\n\n: `I bought a B of As W my Bgage from T S.`\n\nShould generate:\n\n: `I bought a bag of apples with my money from T shop.`\n\nRuleset 4\n\nThis tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.)\n\n```\n### Unary Multiplication Engine, for testing Markov Algorithm implementations\n### By Donal Fellows.\n# Unary addition engine\n_+1 -> _1+\n1+1 -> 11+\n# Pass for converting from the splitting of multiplication into ordinary\n# addition\n1! -> !1\n,! -> !+\n_! -> _\n# Unary multiplication by duplicating left side, right side times\n1*1 -> x,@y\n1x -> xX\nX, -> 1,1\nX1 -> 1X\n_x -> _X\n,x -> ,X\ny1 -> 1y\ny_ -> _\n# Next phase of applying\n1@1 -> x,@y\n1@_ -> @_\n,@_ -> !_\n++ -> +\n# Termination cleanup for addition\n_1 -> 1\n1+_ -> 1\n_+_ -> \n\n```\n\nSample text of:\n\n: `_1111*11111_`\n\nshould generate the output:\n\n: `11111111111111111111`\n\nRuleset 5\n\nA simple Turing machine,\nimplementing a three-state busy beaver.\n\nThe tape consists of **0**s and **1**s,   the states are **A**, **B**, **C** and **H** (for **H**alt), and the head position is indicated by writing the state letter before the character where the head is.\nAll parts of the initial tape the machine operates on have to be given in the input.\n\nBesides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.\n\n```\n# Turing machine: three-state busy beaver\n#\n# state A, symbol 0 => write 1, move right, new state B\nA0 -> 1B\n# state A, symbol 1 => write 1, move left, new state C\n0A1 -> C01\n1A1 -> C11\n# state B, symbol 0 => write 1, move left, new state A\n0B0 -> A01\n1B0 -> A11\n# state B, symbol 1 => write 1, move right, new state B\nB1 -> 1B\n# state C, symbol 0 => write 1, move left, new state B\n0C0 -> B01\n1C0 -> B11\n# state C, symbol 1 => write 1, move left, halt\n0C1 -> H01\n1C1 -> H11\n\n```\n\nThis ruleset should turn\n\n: `000000A000000`\n\ninto\n\n: `00011H1111000`" }, { "role": "assistant", "content": "(formerly Perl 6)\nRun this without arguments and it will scan the cwd for rules.\\* files and their corresponding test.\\*.\n\nRun it with two filenames or one filename and some text to run a rulefile on the file contents or the given text.\n\nAdd --verbose to see the replacements step-by-step.\n\n```\ngrammar Markov {\n token TOP {\n ^ [^^ [<rule> | <comment>] $$ [\\n|$]]* $\n { make $<rule>>>.ast }\n }\n token comment {\n <before ^^> '#' \\N*\n { make Nil }\n }\n token ws {\n [' '|\\t]*\n }\n rule rule {\n <before ^^>$<pattern>=[\\N+?] '->'\n $<terminal>=[\\.]?$<replacement>=[\\N*]\n { make {:pattern($<pattern>.Str),\n  :replacement($<replacement>.Str),\n  :terminal($<terminal>.Str eq \".\")} }\n }\n}\n \nsub run(:$ruleset, :$start_value, :$verbose?) {\n my $value = $start_value;\n my @rules = Markov.parse($ruleset).ast.list;\n loop {\n my $beginning = $value;\n for @rules {\n my $prev = $value;\n $value = $value.subst(.<pattern>, .<replacement>);\n say $value if $verbose && $value ne $prev;\n return $value if .<terminal>;\n last if $value ne $prev;\n }\n last if $value eq $beginning;\n }\n return $value;\n}\n \nmulti sub MAIN(Bool :$verbose?) {\n my @rulefiles = dir.grep(/rules.+/).sort;\n for @rulefiles -> $rulefile {\n my $testfile = $rulefile.subst(\"rules\", \"test\");\n my $start_value = (try slurp($testfile).trim-trailing)\n // prompt(\"please give a start value: \");\n \n my $ruleset = slurp($rulefile);\n say $start_value;\n say run(:$ruleset, :$start_value, :$verbose);\n say '';\n }\n}\n \nmulti sub MAIN(Str $rulefile where *.IO.f, Str $input where *.IO.f, Bool :$verbose?) {\n my $ruleset = slurp($rulefile);\n my $start_value = slurp($input).trim-trailing;\n say \"starting with: $start_value\";\n say run(:$ruleset, :$start_value, :$verbose);\n}\n \nmulti sub MAIN(Str $rulefile where *.IO.f, *@pieces, Bool :$verbose?) {\n my $ruleset = slurp($rulefile);\n my $start_value = @pieces.join(\" \");\n say \"starting with: $start_value\";\n say run(:$ruleset, :$start_value, :$verbose);\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nRun either the   **ls**   system command   (**dir**   on Windows),   or the   **pause**   system command.\n\nRelated task\n\n* Get system command output" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nrun \"ls\" orelse .die; # output to stdout\n\nmy @ls = qx/ls/; # output to variable\n\nmy $cmd = 'ls';\n@ls = qqx/$cmd/; # same thing with interpolation\n```" } ]
[ { "role": "user", "content": "RCBF is a set of Brainf\\*\\*\\* compilers and interpreters written for Rosetta Code in a variety of languages.\n\nBelow are links to each of the versions of RCBF.\n\nAn implementation need only properly implement the following instructions:\n\n| Command | Description |\n| --- | --- |\n| `>` | Move the pointer to the right |\n| `<` | Move the pointer to the left |\n| `+` | Increment the memory cell under the pointer |\n| `-` | Decrement the memory cell under the pointer |\n| `.` | Output the character signified by the cell at the pointer |\n| `,` | Input a character and store it in the cell at the pointer |\n| `[` | Jump past the matching `]` if the cell under the pointer is 0 |\n| `]` | Jump back to the matching `[` if the cell under the pointer is nonzero |\n\nAny cell size is allowed,   EOF   (End-O-File)   support is optional, as is whether you have bounded or unbounded memory." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nSee Execute\\_Brain\\*\\*\\*\\*/Raku." } ]
[ { "role": "user", "content": "Task\n\nCreate a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs \"2+2\" and \"7\\*8\" found there.\n\n: * The virtual machine \"bytecode\" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.\n * For output, it is sufficient to have the implementation of the `STP` opcode return the accumulator to your actual language, and then use your standard printing routines to output it.\n\nBonus Points\n: Run all 5 sample programs at the aforementioned website and output their results." }, { "role": "assistant", "content": "Didn't bother implementing an assembler or disassembler.\n\n```\nmy (@mem, $ip, $acc); # memory, instruction pointer, accumulator\n\nsub load (@program) {\n die \"memory exceeded\" if +@program > 32;\n $ip = 0;\n $acc = 0;\n @mem = @program »%» 256;\n}\n\nsub execute (*@program) {\n load @program;\n loop {\n my $reg = @mem[$ip];\n quietly my ($inst, $data) = $reg +> 5 +& 7, $reg +& 31;\n given $inst {\n when 0 { #`{ NOP } }\n when 1 { #`{ LDA } $acc = @mem[$data] }\n when 2 { #`{ STA } @mem[$data] = $acc }\n when 3 { #`{ ADD } $acc += @mem[$data] }\n when 4 { #`{ SUB } $acc -= @mem[$data] }\n when 5 { #`{ BRZ } $ip = $data - 1 unless $acc }\n when 6 { #`{ JMP } $ip = $data - 1 }\n when 7 { #`{ STP } last }\n default { die 'Invalid instruction' }\n }\n ++$ip;\n last if $ip == 32;\n }\n $acc\n}\n\nsay \"2 + 2 = \" ~ execute 35,100,224,2,2;\nsay \"7 x 8 = \" ~ execute 44,106,76,43,141,75,168,192,44,224,8,7,0,1;\nsay \"Fibonacci: \" ~\nexecute 46,79,109,78,47,77,48,145,171,80,192,46,224,1,1,0,8,1;\nsay \"Linked list: \" ~\nexecute 45,111,69,112,71,0,78,0,171,79,192,46,\n224,32,0,28,1,0,0,0,6,0,2,26,5,20,3,30,1,22,4,24;\nsay \"Prisoners dilemma: \" ~\nexecute 0,0,224,0,35,157,178,35,93,174,33,127,65,194,\n32,127,64,194,35,93,33,126,99,65,32,126,99,64,194,0,1,3;\n\n```\n\nOutput:\n\n```\n2 + 2 = 4\n7 x 8 = 56\nFibonacci: 55\nLinked list: 6\nPrisoners dilemma: 0\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement a **CopyPasta Language** interpreter or compiler. These are the commands used by CopyPasta Language:\n\n| Command | Description |\n| --- | --- |\n| `Copy` | Copy the text of the following line to the clipboard |\n| `CopyFile` | Copy the text of the file cited in the following line to the clipboard or in the case where the next line is TheF\\*ckingCode copies the code to the clipboard |\n| `Duplicate` | Duplicate the text in the clipboard as many times as the following line specifies |\n| `Pasta!` | Display the clipboard and stop the program |" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub CopyPasta ($code) {\n my @code = $code.split(\"\\n\")>>.trim.grep: *.so;\n return \"Program never ends!\" unless grep { $_ eq 'Pasta!' }, @code;\n\n my @cb;\n my $PC = 0;\n loop {\n given @code[$PC] {\n when 'Copy' { @cb.push: @code[++$PC] }\n when 'CopyFile' { $PC++; @cb.push: @code[$PC] eq 'TheF*ckingCode' ?? @code !! slurp @code[$PC] }\n when 'Duplicate' { @cb = (flat @cb) xx @code[++$PC] }\n when 'Pasta!' { return @cb }\n default { return \"Does not compute: @code[$PC]\" }\n }\n $PC++;\n }\n}\n\nspurt 'pasta.txt', \"I'm the pasta.txt file.\";\n\n(say $_ for .&CopyPasta; say '')\n for\n \"Copy \\nRosetta Code\\n\\tDuplicate\\n2\\n\\nPasta!\\nLa Vista\",\n \"CopyFile\\npasta.txt\\nDuplicate\\n1\\nPasta!\",\n \"Copy\\nInvalid\\n Duplicate\\n1\\n\\nGoto\\n3\\nPasta!\",\n \"CopyFile\\nTheF*ckingCode\\nDuplicate\\n2\\nPasta!\",\n \"Copy\\nRosetta Code\\nDuplicate\\n2\\n\\nPasta\";\n\nunlink 'pasta.txt';\n\n```\n\nOutput:\n\n```\nRosetta Code\nRosetta Code\n\nI'm the pasta.txt file.\n\nDoes not compute: Goto\n\nCopyFile TheF*ckingCode Duplicate 2 Pasta!\nCopyFile TheF*ckingCode Duplicate 2 Pasta!\n\nProgram never ends!\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement a   **HQ9+**   interpreter or compiler." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-09-10\n\nThe spec is kind of vague about how to do error handling... and whether white space is significant... and how the accumulator should be accessed... and pretty much everything else too.\n\n```\nclass HQ9Interpreter {\n has @!code;\n has $!accumulator;\n has $!pointer;\n \n method run ($code) {\n @!code = $code.comb;\n $!accumulator = 0;\n $!pointer = 0;\n while $!pointer < @!code {\n given @!code[$!pointer].lc {\n when 'h' { say 'Hello world!' }\n when 'q' { say @!code }\n when '9' { bob(99) }\n when '+' { $!accumulator++ }\n default { note \"Syntax error: Unknown command \\\"{@!code[$!pointer]}\\\"\" }\n }\n\t $!pointer++;\n }\n }\n sub bob ($beer is copy) {\n sub what { \"{$beer??$beer!!'No more'} bottle{$beer-1??'s'!!''} of beer\" };\n sub where { 'on the wall' };\n sub drink { $beer--; \"Take one down, pass it around,\" }\n while $beer {\n .say for \"&what() &where(),\", \"&what()!\",\n \"&drink()\", \"&what() &where()!\", ''\n }\n }\n}\n\n# Feed it a command string:\n\nmy $hq9 = HQ9Interpreter.new;\n$hq9.run(\"hHq+++Qq\");\nsay '';\n$hq9.run(\"Jhq.k+hQ\");\n\n```\n\nOutput:\n\n```\nHello world!\nHello world!\nhHq+++Qq\nhHq+++Qq\nhHq+++Qq\n\nSyntax error: Unknown command \"J\"\nHello world!\nJhq.k+hQ\nSyntax error: Unknown command \".\"\nSyntax error: Unknown command \"k\"\nHello world!\nJhq.k+hQ\n\n```\n\nOr start a REPL (Read Execute Print Loop) and interact at the command line:\n\n```\nmy $hq9 = HQ9Interpreter.new;\nwhile 1 {\n my $in = prompt('HQ9+>').chomp;\n last unless $in.chars;\n $hq9.run($in)\n}\n\n```" } ]
[ { "role": "user", "content": "**RCSNUSP** is a set of SNUSP compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCSNUSP.\n\nAn implementation need only properly implement the Core SNUSP instructions ('$', '\\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.02\n\nImplementation of modular SNUSP.\n\n```\nclass SNUSP {\n\n has @!inst-pointer;\n has @!call-stack;\n has @!direction;\n has @!memory;\n has $!mem-pointer;\n\n method run ($code) {\n init();\n my @code = pad( |$code.lines );\n for @code.kv -> $r, @l {\n my $index = @l.grep( /'$'/, :k );\n if $index {\n @!inst-pointer = $r, $index;\n last\n }\n }\n\n loop {\n my $instruction = @code[@!inst-pointer[0]; @!inst-pointer[1]];\n given $instruction {\n when '>' { $!mem-pointer++ }\n when '<' { $!mem-pointer-- }\n when '+' { @!memory[$!mem-pointer]++ }\n when '-' { @!memory[$!mem-pointer]-- }\n when '.' { print @!memory[$!mem-pointer].chr }\n when ',' { @!memory[$!mem-pointer] = $*IN.getc.ord }\n when '/' { @!direction = @!direction.reverse «*» -1 }\n when '\\\\' { @!direction = @!direction.reverse }\n when '!' { nexti() }\n when '?' { nexti() unless @!memory[$!mem-pointer] }\n when '@' { @!call-stack.push: @!inst-pointer.Array }\n when '#' {\n last unless +@!call-stack;\n @!inst-pointer = |@!call-stack.pop;\n nexti();\n }\n }\n nexti();\n last if @!inst-pointer[0] > +@code or\n @!inst-pointer[1] > +@code[0];\n }\n\n sub init () {\n @!inst-pointer = 0, 0;\n @!direction = 0, 1;\n $!mem-pointer = 0;\n @!memory = ()\n }\n\n sub nexti () { @!inst-pointer Z+= @!direction }\n\n sub pad ( *@lines ) {\n my $max = max @lines».chars;\n my @pad = @lines.map: $max - *.chars;\n map -> $i { flat @lines[$i].comb, ' ' xx @pad[$i] }, ^@lines;\n }\n }\n}\n\n# TESTING\nmy $hw = q:to/END/;\n /++++!/===========?\\>++.>+.+++++++..+++\\\n \\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n $+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n \\==-<<<<+>+++/ /=.>.+>.--------.-/\n END\n\nmy $snusp = SNUSP.new;\n$snusp.run($hw)\n\n```\n\nOutput:\n\n```\nHello World!\n```" } ]
[ { "role": "user", "content": "Some integers (greater than 1), have the property that the digital sum of that integer raised to some integer power greater than 1, is equal to the original integer.\n\nE.G.\n\n: | | |\n | --- | --- |\n | **92 == 81** | **8 + 1 == 9** |\n\nSome integers have this property using more than one exponent.\n\n: | | |\n | --- | --- |\n | **183 == 5832** | **5 + 8 + 3 + 2 == 18** |\n | **186 == 34012224** | **3 + 4 + 0 + 1 + 2 + 2 + 2 + 4 == 18** |\n | **187 == 612220032** | **6 + 1 + 2 + 2 + 2 + 0 + 0 + 3 + 2 == 18** |\n\n*Note: **every** integer has an exponential digital sum equal to the original integer when using an exponent of 1. And, 0 and 1 raised to any power will have a digital sum of 0 and 1 respectively.*\n\nTask\n\n* Find and show the first twenty integers (with their exponents), that satisfy this condition.\n* Find and show at least the first ten integers with their exponents, that satisfy this condition in three or more ways." }, { "role": "assistant", "content": "Implement a lazy generator. Made some assumptions about search limits. May be poor assumptions, but haven't been able to find any counterexamples. (Edit: and some were bad.)\n\n```\nmy @expsum = lazy (2..*).hyper.map( -> $Int {\n my atomicint $miss = 0;\n (2..$Int).map( -> $exp {\n if (my $sum = ($Int ** $exp).comb.sum) > $Int { last if ++⚛$miss > 20 }\n $sum == $Int ?? \"$Int^$exp\" !! Empty;\n }) || Empty;\n});\n\nsay \"First twenty-five integers that are equal to the digital sum of that integer raised to some power:\";\nput .join(', ') for @expsum[^25];\nsay \"\\nFirst thirty that satisfy that condition in three or more ways:\";\nput .join(', ') for @expsum.grep({.elems≥3})[^30];\n\n```\n\nOutput:\n\n```\nFirst twenty-five integers that are equal to the digital sum of that integer raised to some power:\n7^4\n8^3\n9^2\n17^3\n18^3, 18^6, 18^7\n20^13\n22^4\n25^4\n26^3\n27^3, 27^7\n28^4, 28^5\n31^7\n34^7\n35^5\n36^4, 36^5\n40^13\n43^7\n45^6\n46^5, 46^8\n53^7\n54^6, 54^8, 54^9\n58^7\n63^8\n64^6\n68^7\n\nFirst thirty that satisfy that condition in three or more ways:\n18^3, 18^6, 18^7\n54^6, 54^8, 54^9\n90^19, 90^20, 90^21, 90^22, 90^28\n107^11, 107^13, 107^15\n181^16, 181^18, 181^19, 181^20\n360^45, 360^46, 360^49, 360^51\n370^48, 370^54, 370^57, 370^59\n388^32, 388^35, 388^36\n523^39, 523^42, 523^44, 523^45\n603^44, 603^47, 603^54\n667^48, 667^54, 667^58\n793^57, 793^60, 793^64\n1062^72, 1062^77, 1062^81\n1134^78, 1134^80, 1134^82, 1134^86\n1359^92, 1359^98, 1359^102\n1827^121, 1827^126, 1827^131\n1828^123, 1828^127, 1828^132\n2116^140, 2116^143, 2116^147\n2330^213, 2330^215, 2330^229\n2430^217, 2430^222, 2430^223, 2430^229, 2430^230\n2557^161, 2557^166, 2557^174\n2610^228, 2610^244, 2610^246\n2656^170, 2656^172, 2656^176\n2700^406, 2700^414, 2700^420, 2700^427\n2871^177, 2871^189, 2871^190\n2934^191, 2934^193, 2934^195\n3077^187, 3077^193, 3077^199\n3222^189, 3222^202, 3222^210\n3231^203, 3231^207, 3231^209\n3448^215, 3448^221, 3448^227\n```" } ]
[ { "role": "user", "content": "Most programming languages have a built-in implementation of exponentiation.\n\nTask\n\nRe-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition).\n\nIf the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants.\n\nRelated tasks\n\n* Exponentiation order\n* arbitrary-precision integers (included)\n* Exponentiation with infix operators in (or operating on) the base" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2023.09\n\n```\nproto pow (Real, Int --> Real) {*}\nmulti pow (0, 0) { fail '0**0 is undefined' }\nmulti pow ($base, UInt $exp) { [*] $base xx $exp }\nmulti pow ($base, $exp) { 1 / samewith $base, -$exp }\n\nmulti infix:<**> (Real $a, Int $b) { pow $a, $b }\n\n# Testing\n\nsay pow .75, -5;\nsay .75 ** -5;\n\n```" } ]
[ { "role": "user", "content": "This task will demonstrate the order of exponentiation   (**xy**)   when there are multiple exponents.\n\n(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of `**`, `^`, `↑` or some such for exponentiation.)\n\nTask requirements\n\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n\n: : : : * 5\\*\\*3\\*\\*2\n * (5\\*\\*3)\\*\\*2\n * 5\\*\\*(3\\*\\*2)\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well.\n\nSee also\n\n* MathWorld entry:   exponentiation\n\nRelated tasks\n\n* exponentiation operator\n* arbitrary-precision integers (included)\n* Exponentiation with infix operators in (or operating on) the base" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.08\n\nNote that the reduction forms automatically go right-to-left because the base operator is right-associative. Most other operators are left-associative and would automatically reduce left-to-right instead.\n\n```\nuse MONKEY-SEE-NO-EVAL;\nsub demo($x) { say \" $x\\t───► \", EVAL $x }\n\ndemo '5**3**2'; # show ** is right associative\ndemo '(5**3)**2';\ndemo '5**(3**2)';\n\ndemo '[**] 5,3,2'; # reduction form, show only final result\ndemo '[\\**] 5,3,2'; # triangle reduction, show growing results\n\n# Unicode postfix exponents are supported as well:\n\ndemo '(5³)²';\ndemo '5³²';\n\n```\n\nOutput:\n\n```\n 5**3**2\t───► 1953125\n (5**3)**2\t───► 15625\n 5**(3**2)\t───► 1953125\n [**] 5,3,2\t───► 1953125\n [\\**] 5,3,2\t───► 2 9 1953125\n (5³)²\t───► 15625\n 5³²\t───► 23283064365386962890625\n\n```\n\nThe Unicode exponent form without parentheses ends up raising to the 32nd power. Nor are you even allowed to parenthesize it the other way: 5(³²) would be a syntax error. Despite all that, for programs that do a lot of squaring or cubing, the postfix forms can enhance both readability and concision." } ]
[ { "role": "user", "content": "(Many programming languages,   especially those with extended─precision integer arithmetic,   usually\nsupport one of `**`, `^`, `↑` or some such for exponentiation.)\n\nSome languages treat/honor infix operators when performing exponentiation   (raising\nnumbers to some power by the language's exponentiation operator,   if the computer\nprogramming language has one).\n\nOther programming languages may make use of the   **POW**   or some other BIF\n  (**B**uilt─**I**n **F**function),   or some other library service.\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\nThis task will deal with the case where there is some form of an   *infix operator*   operating\nin   (or operating on)   the base.\n\nExample\n\nA negative five raised to the 3rd power could be specified as:\n\n```\n -5 ** 3 or as\n -(5) ** 3 or as\n (-5) ** 3 or as something else\n\n```\n\n(Not all computer programming languages have an exponential operator and/or support these syntax expression(s).\n\nTask\n: * compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.\n * Raise the following numbers   (integer or real):\n\n : : * -5     and\n * +5\n\n * to the following powers:\n\n : : * 2nd     and\n * 3rd\n\n * using the following expressions   (if applicable in your language):\n\n : : * -x\\*\\*p\n * -(x)\\*\\*p\n * (-x)\\*\\*p\n * -(x\\*\\*p)\n\n * Show here (on this page) the four (or more) types of symbolic expressions for each number and power.\n\nTry to present the results in the same format/manner as the other programming entries to make any differences apparent.\n\nThe variables may be of any type(s) that is/are applicable in your language.\n\nRelated tasks\n\n* Exponentiation order\n* Exponentiation operator\n* Arbitrary-precision integers (included)\n* Parsing/RPN to infix conversion\n* Operator precedence\n\nReferences\n\n* Wikipedia: Order of operations in Programming languages" }, { "role": "assistant", "content": "In Raku by default, infix exponentiation binds tighter than unary negation. It is trivial however to define your own infix operators with whatever precedence level meets the needs of your program.\n\nA slight departure from the task specs. Use `1 + {expression}` rather than just `{expression}` to better demonstrate the relative precedence levels. Where `{expression}` is one of:\n\n* `-x{exponential operator}p`\n* `-(x){exponential operator}p`\n* `((-x){exponential operator}p)`\n* `-(x{exponential operator}p)`\n\nAlso add a different grouping: `(1 + -x){exponential operator}p`\n\n```\nsub infix:<↑> is looser(&prefix:<->) { $^a ** $^b }\nsub infix:<∧> is looser(&infix:<->) { $^a ** $^b }\n\nfor\n ('Default precedence: infix exponentiation is tighter (higher) precedence than unary negation.',\n '1 + -$x**$p', {1 + -$^a**$^b}, '1 + (-$x)**$p', {1 + (-$^a)**$^b}, '1 + (-($x)**$p)', {1 + (-($^a)**$^b)},\n '(1 + -$x)**$p', {(1 + -$^a)**$^b}, '1 + -($x**$p)', {1 + -($^a**$^b)}),\n\n (\"\\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.\",\n '1 + -$x↑$p ', {1 + -$^a↑$^b}, '1 + (-$x)↑$p ', {1 + (-$^a)↑$^b}, '1 + (-($x)↑$p) ', {1 + (-($^a)↑$^b)},\n '(1 + -$x)↑$p ', {(1 + -$^a)↑$^b}, '1 + -($x↑$p) ', {1 + -($^a↑$^b)}),\n\n (\"\\nEven more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.\",\n '1 + -$x∧$p ', {1 + -$^a∧$^b}, '1 + (-$x)∧$p ', {1 + (-$^a)∧$^b}, '1 + (-($x)∧$p) ', {1 + (-($^a)∧$^b)},\n '(1 + -$x)∧$p ', {(1 + -$^a)∧$^b}, '1 + -($x∧$p) ', {1 + -($^a∧$^b)})\n-> $case {\n my ($title, @operations) = $case<>;\n say $title;\n for -5, 5 X 2, 3 -> ($x, $p) {\n printf \"x = %2d p = %d\", $x, $p;\n for @operations -> $label, &code { print \" │ $label = \" ~ $x.&code($p).fmt('%4d') }\n say ''\n }\n}\n\n```\n\nOutput:\n\n```\nDefault precedence: infix exponentiation is tighter (higher) precedence than unary negation.\nx = -5 p = 2 │ 1 + -$x**$p = -24 │ 1 + (-$x)**$p = 26 │ 1 + (-($x)**$p) = -24 │ (1 + -$x)**$p = 36 │ 1 + -($x**$p) = -24\nx = -5 p = 3 │ 1 + -$x**$p = 126 │ 1 + (-$x)**$p = 126 │ 1 + (-($x)**$p) = 126 │ (1 + -$x)**$p = 216 │ 1 + -($x**$p) = 126\nx = 5 p = 2 │ 1 + -$x**$p = -24 │ 1 + (-$x)**$p = 26 │ 1 + (-($x)**$p) = -24 │ (1 + -$x)**$p = 16 │ 1 + -($x**$p) = -24\nx = 5 p = 3 │ 1 + -$x**$p = -124 │ 1 + (-$x)**$p = -124 │ 1 + (-($x)**$p) = -124 │ (1 + -$x)**$p = -64 │ 1 + -($x**$p) = -124\n\nEasily modified: custom loose infix exponentiation is looser (lower) precedence than unary negation.\nx = -5 p = 2 │ 1 + -$x↑$p = 26 │ 1 + (-$x)↑$p = 26 │ 1 + (-($x)↑$p) = 26 │ (1 + -$x)↑$p = 36 │ 1 + -($x↑$p) = -24\nx = -5 p = 3 │ 1 + -$x↑$p = 126 │ 1 + (-$x)↑$p = 126 │ 1 + (-($x)↑$p) = 126 │ (1 + -$x)↑$p = 216 │ 1 + -($x↑$p) = 126\nx = 5 p = 2 │ 1 + -$x↑$p = 26 │ 1 + (-$x)↑$p = 26 │ 1 + (-($x)↑$p) = 26 │ (1 + -$x)↑$p = 16 │ 1 + -($x↑$p) = -24\nx = 5 p = 3 │ 1 + -$x↑$p = -124 │ 1 + (-$x)↑$p = -124 │ 1 + (-($x)↑$p) = -124 │ (1 + -$x)↑$p = -64 │ 1 + -($x↑$p) = -124\n\nEven more so: custom looser infix exponentiation is looser (lower) precedence than infix subtraction.\nx = -5 p = 2 │ 1 + -$x∧$p = 36 │ 1 + (-$x)∧$p = 36 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 36 │ 1 + -($x∧$p) = -24\nx = -5 p = 3 │ 1 + -$x∧$p = 216 │ 1 + (-$x)∧$p = 216 │ 1 + (-($x)∧$p) = 126 │ (1 + -$x)∧$p = 216 │ 1 + -($x∧$p) = 126\nx = 5 p = 2 │ 1 + -$x∧$p = 16 │ 1 + (-$x)∧$p = 16 │ 1 + (-($x)∧$p) = 26 │ (1 + -$x)∧$p = 16 │ 1 + -($x∧$p) = -24\nx = 5 p = 3 │ 1 + -$x∧$p = -64 │ 1 + (-$x)∧$p = -64 │ 1 + (-($x)∧$p) = -124 │ (1 + -$x)∧$p = -64 │ 1 + -($x∧$p) = -124\n```" } ]
[ { "role": "user", "content": "Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on *two* conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n```\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\n```\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword **if2**. It is similar to **if**, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n```\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\n```\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement." }, { "role": "assistant", "content": "(formerly Perl 6)\nWriting the conditional blocks is no problem, since there's no distinction between built-in closures and user-defined. The if2 is currently just a function call, which requires a comma after the second condition; eventually we will be able to drop that in user-defined code, but none of our implementations can define parse actions in the statement\\_control category quite yet. (That syntax is special insofar as it's the only place Raku allows two terms in a row.) So currently it requires the comma until the implementations catch up with the spec on that subject.\n\nThis solution is hygienic in both lexical and dynamic variables; the only caveat is that the user's program must avoid the dynamic variable being used by the implementation of conditional, $\\*IF2. This does not seem like a great hardship. (The conditionals will also nest correctly since that's how dynamic variables behave.)\n\n```\nmy &if2 = -> \\a, \\b, &x { my @*IF2 = ?a,?b; x }\n\nmy &if-both = -> &x { x if @*IF2 eq (True,True) }\nmy &if-first = -> &x { x if @*IF2 eq (True,False) }\nmy &if-second = -> &x { x if @*IF2 eq (False,True) }\nmy &if-neither = -> &x { x if @*IF2 eq (False,False)}\n\nsub test ($a,$b) {\n $_ = \"G\"; # Demo correct scoping of topic.\n my $got = \"o\"; # Demo correct scoping of lexicals.\n my $*got = \"t\"; # Demo correct scoping of dynamics.\n\n if2 $a, $b, {\n if-both { say \"$_$got$*got both\" }\n if-first { say \"$_$got$*got first\" }\n if-second { say \"$_$got$*got second\" }\n if-neither { say \"$_$got$*got neither\" }\n }\n}\n\nsay test |$_ for 1,0 X 1,0;\n\n```\n\nOutput:\n\n```\nGot both\nGot first\nGot second\nGot neither\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.\n\nThe routine should demonstrably rely on either:\n\n1. Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code.\n2. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below.\n3. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated.\n\nThe routine should be used to:\n\n* Show the first twenty primes.\n* Show the primes between 100 and 150.\n* Show the *number* of primes between 7,700 and 8,000.\n* Show the 10,000th prime.\n\nShow output on this page.\n\n**Note:** You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks).\n\n**Note 2:** If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation).\n\n**Note 3:**The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency).\n\nReference\n\n* Prime Numbers. Website with large count of primes." }, { "role": "assistant", "content": "(formerly Perl 6)\nBuild a lazy infinite list of primes using the Raku builtin is-prime method. ( A lazy list will not bother to calculate the values until they are actually used. ) That is the first line. If you choose to calculate the entire list, it is fairly certain that you will run out of process / system memory before you finish... (patience too probably) but there aren't really any other constraints. The is-prime builtin uses a Miller-Rabin primality test with 100 iterations, so while it is not 100% absolutely guaranteed that every number it flags as prime actually is, the chances that it is wrong are about 4-100. Much less than the chance that a cosmic ray will cause an error in your computers CPU. Everything after the first line is just display code for the various task requirements.\n\n```\nmy @primes = lazy gather for 1 .. * { .take if .is-prime }\n\nsay \"The first twenty primes:\\n \", \"[{@primes[^20].fmt(\"%d\", ', ')}]\";\nsay \"The primes between 100 and 150:\\n \", \"[{@primes.&between(100, 150).fmt(\"%d\", ', ')}]\";\nsay \"The number of primes between 7,700 and 8,000:\\n \", +@primes.&between(7700, 8000);\nsay \"The 10,000th prime:\\n \", @primes[9999];\n\nsub between (@p, $l, $u) {\n gather for @p { .take if $l < $_ < $u; last if $_ >= $u }\n}\n\n```\n\nOutput:\n\n```\nThe first twenty primes:\n [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\nThe primes between 100 and 150:\n [101, 103, 107, 109, 113, 127, 131, 137, 139, 149]\nThe number of primes between 7,700 and 8,000:\n 30\nThe 10,000th prime:\n 104729\n```" } ]
[ { "role": "user", "content": "Sort a huge file too large to fit into memory.\n\nThe algorithm consists in reading a large file to be sorted in chunks of data small enough to fit in main memory, sort each of the chunks, write them out to a temporary file, and finally combined the smaller subfiles into a single larger file.\n\nFor more info see: https://en.wikipedia.org/wiki/External\\_sorting\n\nThe sorting algorithm can be any popular sort, like quicksort.\n\nFor simplicity one can assume that the file consists of fixed length integers and that the sort function is less-than (<)." }, { "role": "assistant", "content": "(formerly Perl 6)\nBorrowing from Stream\\_Merge here. Temporary files are automatically deleted when program is done, so no explicit clean-up required.\n\n```\nuse File::Temp;\n\nsub merge_streams ( @streams ) {\n my @s = @streams.map({ hash( STREAM => $_, HEAD => .get ) }).grep({ .<HEAD>.defined });\n\n return gather while @s {\n my $h = @s.min: +*.<HEAD>;\n take $h<HEAD>;\n $h<HEAD> := $h<STREAM>.get\n orelse @s .= grep( { $_ !=== $h } );\n }\n}\n\nsub store (@values) {\n my ($filename,$filehandle) = tempfile(:prefix('external-sort.'));\n $filehandle.say: join \"\\n\", @values.sort: +*;\n $filename\n}\n\n# we're going to pretend that this is a long stream of input from stdin...\nmy (@chunk,@files);\nfor (<43 2 45 32 15 4 3 -9 45 66 0 42 78 123 -11 76 55 87 -2 64 92 34>) {\n @chunk.push: $_;\n @files.push: store(@chunk) and @chunk = () if @chunk.elems == 4; # limit of records per merge file\n}\[email protected]: store(@chunk) if @chunk;\n\nsay join ' ', merge_streams @files».&open;\n\n```\n\nOutput:\n\n```\n-11 -9 -2 0 2 3 4 15 32 34 42 43 45 45 55 64 66 76 78 87 92 123\n```" } ]
[ { "role": "user", "content": "Definition\n\n**n**   is an   *extra prime*   if   **n**   is prime and its decimal digits and sum of digits are also primes.\n\nTask\n\nShow the extra primes under   **10,000**.\n\nReference\n\nOEIS:A062088 - Primes with every digit a prime and the sum of the digits a prime.\n\nRelated tasks\n\n* Numbers with prime digits whose sum is 13\n* Smarandache prime-digital sequence\n* Category:Prime Numbers" }, { "role": "assistant", "content": "For the time being, (Doctor?), I'm going to assume that the task is really \"Sequence of primes with every digit a prime and the sum of the digits a prime\". Outputting my own take on a reasonable display of results, compact and easily doable but exercising it a bit.\n\n```\nmy @ppp = lazy flat 2, 3, 5, 7, 23, grep { .is-prime && .comb.sum.is-prime },\n flat (2..*).map: { flat ([X~] (2, 3, 5, 7) xx $_) X~ (3, 7) };\n\nput 'Terms < 10,000: '.fmt('%34s'), @ppp[^(@ppp.first: * > 1e4, :k)];\nput '991st through 1000th: '.fmt('%34s'), @ppp[990 .. 999];\nput 'Crossing 10th order of magnitude: ', @ppp[9055..9060];\n\n```\n\nOutput:\n\n```\n Terms < 10,000: 2 3 5 7 23 223 227 337 353 373 557 577 733 757 773 2333 2357 2377 2557 2753 2777 3253 3257 3323 3527 3727 5233 5237 5273 5323 5527 7237 7253 7523 7723 7727\n 991st through 1000th: 25337353 25353227 25353373 25353577 25355227 25355333 25355377 25357333 25357357 25357757\nCrossing 10th order of magnitude: 777777227 777777577 777777773 2222222377 2222222573 2222225273\n```" } ]
[ { "role": "user", "content": "Filename extensions are a rudimentary but commonly used way of identifying files types.\n\nTask\n\nWrite a function or program that\n\n* takes one string argument representing the path/URL to a file\n* returns the filename extension according to the below specification, or an empty string if the filename has no extension.\n\nIf your programming language  (or standard library)  has built-in functionality for extracting a filename extension,\n \nshow how it would be used and how exactly its behavior differs from this specification.\n\nSpecification\n\nFor the purposes of this task, a filename extension:\n\n* occurs at the very end of the filename\n* consists of a period, followed solely by one or more ASCII letters or digits (A-Z, a-z, 0-9)\n\nTest cases\n\n: : : : | Input | Output | Comment |\n | --- | --- | --- |\n | `http://example.com/download.tar.gz` | `.gz` | |\n | `CharacterModel.3DS` | `.3DS` | |\n | `.desktop` | `.desktop` | |\n | `document` | | *empty string* |\n | `document.txt_backup` | | *empty string, because `_` is not a letter or number* |\n | `/etc/pam.d/login` | | *empty string, as the period is in the parent directory name rather than the filename* |\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe built-in `IO::Path` class has an `.extension` method:\n\n```\nsay $path.IO.extension;\n\n```\n\nContrary to this task's specification, it\n\n* doesn't include the dot in the output\n* doesn't restrict the extension to letters and numbers.\n\nHere's a custom implementation which does satisfy the task requirements:\n\n```\nsub extension (Str $path --> Str) {\n $path.match(/:i ['.' <[a..z0..9]>+]? $ /).Str\n}\n\n# Testing:\n\nprintf \"%-35s %-11s %-12s\\n\", $_, extension($_).perl, $_.IO.extension.perl\nfor <\n http://example.com/download.tar.gz\n CharacterModel.3DS\n .desktop\n document\n document.txt_backup\n /etc/pam.d/login\n>;\n\n```\n\nOutput:\n\n```\nhttp://example.com/download.tar.gz \".gz\" \"gz\" \nCharacterModel.3DS \".3DS\" \"3DS\" \n.desktop \".desktop\" \"desktop\" \ndocument \"\" \"\" \ndocument.txt_backup \"\" \"txt_backup\"\n/etc/pam.d/login \"\" \"\"\n\n```" } ]
[ { "role": "user", "content": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.\n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables.\n\nIf your language can directly enter these extreme floating point values then show it.\n\nSee also\n\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\nRelated tasks\n\n* Infinity\n* Detect division by zero\n* Literals/Floating point" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nFloating point limits are to a large extent implementation dependent, but currently both Raku backends (MoarVM, JVM) running on a 64 bit OS have an infinity threshold of just under 1.8e308.\n\n```\nprint qq:to 'END'\npositive infinity: {1.8e308}\nnegative infinity: {-1.8e308}\nnegative zero: {0e0 * -1}\nnot a number: {0 * 1e309}\n+Inf + 2.0 = {Inf + 2}\n+Inf - 10.1 = {Inf - 10.1}\n0 * +Inf = {0 * Inf}\n+Inf + -Inf = {Inf + -Inf}\n+Inf == -Inf = {+Inf == -Inf}\n(-Inf+0i)**.5 = {(-Inf+0i)**.5}\nNaN + 1.0 = {NaN + 1.0}\nNaN + NaN = {NaN + NaN}\nNaN == NaN = {NaN == NaN}\n0.0 == -0.0 = {0e0 == -0e0}\nEND\n\n```\n\n`0e0` is used to have floating point number.\nSimply using `0.0` makes rational number that doesn't recognize `-0`.\n`qq:to` is heredoc syntax, where `qq` means\nthat variables and closures (between braces) are interpolated.\n\nOutput:\n\n```\npositive infinity: Inf\nnegative infinity: -Inf\nnegative zero: -0\nnot a number: NaN\n+Inf + 2.0 = Inf\n+Inf - 10.1 = Inf\n0 * +Inf = NaN\n+Inf + -Inf = NaN\n+Inf == -Inf = False\n(-Inf+0i)**.5 = Inf+Inf\\i\nNaN + 1.0 = NaN\nNaN + NaN = NaN\nNaN == NaN = False\n0.0 == -0.0 = True\n```" } ]
[ { "role": "user", "content": "Definition\n\nWrite down the first prime number, add the next prime number and if it is prime, add it to the series and so on. These primes are called **extreme primes**.\n\nTask\n\nFind and display the first **30 extreme primes** on this page.\n\nStretch\n\nFind and display the **1,000th**, **2,000th**, **3,000th**, **4,000th** and **5,000th** extreme primes and for each one show the prime number **p** up to and including which primes need to be summed to obtain it.\n\nRelated (and near duplicate) tasks\n\n* Prime numbers p for which the sum of primes less than or equal to p is prime\n* Summarize primes\n\nReference\n\nOEIS sequence A013918" }, { "role": "assistant", "content": "So we're just gonna keep doing the same task over and over with slightly different names?\n\nPrimes equal to the sum of the first k primes for some k.\n\n```\nuse Lingua::EN::Numbers;\n\nsay $_».&comma».fmt(\"%7s\").batch(10).join: \"\\n\" for\n(([\\+] (^∞).grep: &is-prime).grep: &is-prime)[^30,999,1999,2999,3999,4999];\n\n```\n\nOutput:\n\n```\n 2 5 17 41 197 281 7,699 8,893 22,039 24,133\n 25,237 28,697 32,353 37,561 38,921 43,201 44,683 55,837 61,027 66,463\n 70,241 86,453 102,001 109,147 116,533 119,069 121,631 129,419 132,059 263,171\n1,657,620,079\n9,744,982,591\n24,984,473,177\n49,394,034,691\n82,195,983,953\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "A mesh defining a surface has uniquely numbered vertices, and named,\nsimple-polygonal faces described usually by an ordered list of edge numbers\ngoing around the face,\n\nFor example:\nExternal image of two faces \nRough textual version without edges:\n\n```\n\n\n 1 \n 17\n 7 A\n B\n\n 11 \n 23\n\n\n```\n\n* A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or\n\nany of all the rotations of those ordered vertices.\n\n```\n 1 \n \n 7 A\n \n\n 11\n```\n\n* B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any\n\nof their rotations.\n\n```\n1 \n 17\n\n B\n\n 11 \n 23\n```\n\nLet's call the above the **perimeter format** as it traces around the perimeter.\n\nA second format\n\nA separate algorithm returns polygonal faces consisting of a face name and an unordered\nset of edge definitions for each face.\n\n* A single edge is described by the vertex numbers at its two ends, always in\n\nascending order.\n\n* All edges for the face are given, but in an undefined order.\n\nFor example face A could be described by the edges (1, 11), (7, 11), and (1, 7)\n(The order of each vertex number in an edge is ascending, but the order in\nwhich the edges are stated is arbitrary).\n\nSimilarly face B could be described by the edges (11, 23), (1, 17), (17, 23),\nand (1, 11) in arbitrary order of the edges.\n\nLet's call this second format the **edge format**.\n\nTask\n\n**1.** Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same:\n\n```\n Q: (8, 1, 3)\n R: (1, 3, 8)\n\n U: (18, 8, 14, 10, 12, 17, 19)\n V: (8, 14, 10, 12, 17, 19, 18)\n\n```\n\n**2.** Write a routine and use it to transform the following faces from edge to perimeter format.\n\n```\n E: {(1, 11), (7, 11), (1, 7)}\n F: {(11, 23), (1, 17), (17, 23), (1, 11)}\n G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}\n H: {(1, 3), (9, 11), (3, 11), (1, 11)}\n\n```\n\nShow your output here." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\n```\nsub check-equivalence ($a, $b) { so $a.Bag eqv $b.Bag }\n\nsub edge-to-periphery (@a is copy) {\n return Nil unless @a.List.Bag.values.all == 2;\n my @b = @a.shift.flat;\n while @a > 1 {\n for @a.kv -> $k, $v {\n if $v[0] == @b.tail {\n @b.push: $v[1];\n @a.splice($k,1);\n last\n }\n elsif $v[1] == @b.tail {\n @b.push: $v[0];\n @a.splice($k,1);\n last\n }\n }\n }\n @b\n}\n\nsay 'Perimeter format equality checks:';\n\nfor (8, 1, 3), (1, 3, 8),\n (18, 8, 14, 10, 12, 17, 19), (8, 14, 10, 12, 17, 19, 18)\n -> $a, $b {\n say \"({$a.join: ', '}) equivalent to ({$b.join: ', '})? \",\n check-equivalence($a, $b)\n}\n\nsay \"\\nEdge to perimeter format translations:\";\n\nfor ((1, 11), (7, 11), (1, 7)),\n ((11, 23), (1, 17), (17, 23), (1, 11)),\n ((8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)),\n ((1, 3), (9, 11), (3, 11), (1, 11))\n {\n .gist.print;\n say \" ==> ({.&edge-to-periphery || 'Invalid edge format'})\";\n}\n\n```\n\nOutput:\n\n```\nPerimeter format equality checks:\n(8, 1, 3) equivalent to (1, 3, 8)? True\n(18, 8, 14, 10, 12, 17, 19) equivalent to (8, 14, 10, 12, 17, 19, 18)? True\n\nEdge to perimeter format translations:\n((1 11) (7 11) (1 7)) ==> (1 11 7)\n((11 23) (1 17) (17 23) (1 11)) ==> (11 23 17 1)\n((8 14) (17 19) (10 12) (10 14) (12 17) (8 18) (18 19)) ==> (8 14 10 12 17 19 18)\n((1 3) (9 11) (3 11) (1 11)) ==> (Invalid edge format)\n```" } ]
[ { "role": "user", "content": "Consider the list of factors (divisors) of an integer, such as 12. The factors of 12 are [1, 2, 3, 4, 6, 12]. Consider all sorted sequences of the factors of n such that each succeeding number in such a sequence is a multiple of its predecessor. So, for 6,\nwe have the factors (divisors) [1, 2, 3, 6]. The 3 unique lists of sequential multiples starting with 1 and ending with 6 that can be derived from these factors are [1, 6], [1, 2, 6], and [1, 3, 6].\n\nAnother way to see these sequences is as an set of all the ordered factorizations of a number taken so that their product is that number (excluding 1 from the sequence). So, for 6, we would have [6], [2, 3], and [3, 2]. In this description of the sequences, we are looking at the numbers needed to multiply by, in order to generate the next element in the sequences previously listed in our first definition of the sequence type, as we described it in the preceding paragraph, above.\n\nFor example, for the factorization of 6, if the first type of sequence is [1, 6], this is generated by [6] since 1 \\* 6 = 6. Similarly, the first type of sequence [1, 2, 6] is generated by the second type of sequence [2, 3] because 1 \\* 2 = 2 and 2 \\* 3 = 6. Similarly, [1, 3, 6] is generated by [3, 2] because 1 \\* 3 = 3 and 3 \\* 2 = 6.\n\nIf we count the number of such sorted sequences of multiples, or ordered factorizations, and using that count find all integers `n` for which the count of such sequences equals `n`, we have re-created the sequence of the \"factor-perfect\" numbers (OEIS 163272).\n\nBy some convention, on its OEIS page, the factor-perfect number sequence starts with 0 rather than 1. As might be expected\nwith a sequence involving factorization and combinations, finding factor-perfect numbers becomes\nmore demanding on CPU time as the numbers become large.\n\nTask\n\n* Show all 48 ordered sequences for each of the two methods for n = 48, which is the first non-trivial factor-perfect number.\n\nAccording to the paper listed below by P. Erdos, the number of these sequences is\n\n: F\n (\n n\n )\n =\n\n ∑\n\n k\n F\n (\n\n\n n\n\n a\n\n k\n )\n +\n 1\n {\\displaystyle F(n)=\\sum \\_{k}F({\\frac {n}{a\\_{k}}})+1}\n\nwhere a is a list of the factors of n, including n, but excluding 1. F(n) is here the same as a function for calculating the number of different factorizations according to the second definition above except that F(1)=0 (where the number of factorizations of 1 must be 1 for it to be included in the sequence of factor-perfect numbers).\n\n* Write a program to calculate and show the first 7 numbers of the factor-perfect numbers.\n\nStretch task\n\n* Calculate and show more of the subsequent numbers in the sequence.\n\nsee also\n\n```\nOEIS A163272 (Numbers k such that k = A074206(k), the number of ordered factorizations of k)\nOEIS A074206 (Kalmár's [Kalmar's] problem: number of ordered factorizations of n.)\nOn the maximal order of numbers in the “factorisatio numerorum” problem (Klazar/Luca)\nOn Some Asymptotic Formulas in The Theory of The \"Factorisatio Numerorum\" (P. Erdos)\n\n```" }, { "role": "assistant", "content": "**Translation of**: Wren\n\n```\n# 20221029 Raku programming solution\n\nsub propdiv (\\x) {\n my @l = 1 if x > 1;\n for (2 .. x.sqrt.floor) -> \\d {\n unless x % d { @l.push: d; my \\y = x div d; @l.push: y if y != d }\n }\n @l\n}\n\nsub moreMultiples (@toSeq, @fromSeq) {\n my @oneMores = gather for @fromSeq -> \\j {\n take @toSeq.clone.push(j) if j > @toSeq[*-1] and j %% @toSeq[*-1]\n }\n return () unless @oneMores.Bool;\n for 0..^@oneMores {\n @oneMores.append: moreMultiples @oneMores[$_], @fromSeq\n }\n @oneMores\n}\n\nsub erdosFactorCount (\\n) {\n state %cache;\n my ($sum,@divs) = 0, |(propdiv n)[1..*];\n for @divs -> \\d {\n unless %cache{my \\t = n div d}:exists { %cache{t} = erdosFactorCount(t) }\n $sum += %cache{t}\n }\n ++$sum\n}\n\nmy @listing = moreMultiples [1], propdiv(48);\ngiven @listing { $_.map: *.push: 48; $_.push: [1,48] }\nsay @listing.elems,\" sequences using first definition:\";\nfor @listing.rotor(4) -> \\line { line.map: { printf \"%-20s\", $_ } ; say() }\n\nmy @listing2 = gather for (0..^+@listing) -> \\j {\n my @seq = |@listing[j];\n @seq.append: 48 if @seq[*-1] != 48;\n take (1..^@seq).map: { @seq[$_] div @seq[$_-1] }\n}\nsay \"\\n{@listing2.elems} sequences using second definition:\";\nfor @listing2.rotor(4) -> \\line { line.map: { printf \"%-20s\", $_ } ; say() }\n\nsay \"\\nOEIS A163272:\";\nmy ($n,@fpns) = 4, 0,1;\nwhile (@fpns < 7) { @fpns.push($n) if erdosFactorCount($n) == $n; $n += 4 }\nsay ~@fpns;\n\n```\n\nOutput:\n\n```\n48 sequences using first definition:\n1 2 48 1 24 48 1 3 48 1 16 48 \n1 4 48 1 12 48 1 6 48 1 8 48 \n1 2 24 48 1 2 16 48 1 2 4 48 1 2 12 48 \n1 2 6 48 1 2 8 48 1 2 4 24 48 1 2 4 16 48 \n1 2 4 12 48 1 2 4 8 48 1 2 4 12 24 48 1 2 4 8 24 48 \n1 2 4 8 16 48 1 2 12 24 48 1 2 6 24 48 1 2 6 12 48 \n1 2 6 12 24 48 1 2 8 24 48 1 2 8 16 48 1 3 24 48 \n1 3 12 48 1 3 6 48 1 3 12 24 48 1 3 6 24 48 \n1 3 6 12 48 1 3 6 12 24 48 1 4 24 48 1 4 16 48 \n1 4 12 48 1 4 8 48 1 4 12 24 48 1 4 8 24 48 \n1 4 8 16 48 1 12 24 48 1 6 24 48 1 6 12 48 \n1 6 12 24 48 1 8 24 48 1 8 16 48 1 48 \n\n48 sequences using second definition:\n2 24 24 2 3 16 16 3 \n4 12 12 4 6 8 8 6 \n2 12 2 2 8 3 2 2 12 2 6 4 \n2 3 8 2 4 6 2 2 6 2 2 2 4 3 \n2 2 3 4 2 2 2 6 2 2 3 2 2 2 2 2 3 2 \n2 2 2 2 3 2 6 2 2 2 3 4 2 2 3 2 4 \n2 3 2 2 2 2 4 3 2 2 4 2 3 3 8 2 \n3 4 4 3 2 8 3 4 2 2 3 2 4 2 \n3 2 2 4 3 2 2 2 2 4 6 2 4 4 3 \n4 3 4 4 2 6 4 3 2 2 4 2 3 2 \n4 2 2 3 12 2 2 6 4 2 6 2 4 \n6 2 2 2 8 3 2 8 2 3 48 \n\nOEIS A163272:\n0 1 48 1280 2496 28672 29808\n```" } ]
[ { "role": "user", "content": "Definitions\n: * The factorial of   **0**   (zero)   is defined as being   1   (unity).\n * The   **Factorial Function**   of a positive integer,   *n*,   is defined as the product of the sequence:\n\n```\n n,   n-1,   n-2,   ...   1 \n\n```\n\nTask\n\nWrite a function to return the factorial of a number.\n\nSolutions can be iterative or recursive.\n\nSupport for trapping negative   *n*   errors is optional.\n\nRelated task\n\n* Primorial numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### via User-defined Postfix Operator\n\n[\\*] is a reduction operator that multiplies all the following values together. Note that we don't need to start at 1, since the degenerate case of [\\*]() correctly returns 1, and multiplying by 1 to start off with is silly in any case.\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub postfix:<!> (Int $n) { [*] 2..$n }\nsay 5!;\n```\n\nOutput:\n\n```\n120\n```\n\n### via Memoized Constant Sequence\n\nThis approach is much more efficient for repeated use, since it automatically caches. [\\\\*] is the so-called triangular version of [\\*]. It returns the intermediate results as a list. Note that Raku allows you to define constants lazily, which is rather helpful when your constant is of infinite size...\n\n**Works with**: Rakudo version 2015.12\n\n```\nconstant fact = 1, |[\\*] 1..*;\nsay fact[5]\n```\n\nOutput:\n\n```\n120\n```" } ]
[ { "role": "user", "content": "You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers.\nThe first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0\nObserve that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2.\n\nI want to produce a 1 to 1 mapping between these numbers and permutations:-\n\n```\n 0.0.0 -> 0123\n 0.0.1 -> 0132\n 0.1.0 -> 0213\n 0.1.1 -> 0231\n 0.2.0 -> 0312\n 0.2.1 -> 0321\n 1.0.0 -> 1023\n 1.0.1 -> 1032\n 1.1.0 -> 1203\n 1.1.1 -> 1230\n 1.2.0 -> 1302\n 1.2.1 -> 1320\n 2.0.0 -> 2013\n 2.0.1 -> 2031\n 2.1.0 -> 2103\n 2.1.1 -> 2130\n 2.2.0 -> 2301\n 2.2.1 -> 2310\n 3.0.0 -> 3012\n 3.0.1 -> 3021\n 3.1.0 -> 3102\n 3.1.1 -> 3120\n 3.2.0 -> 3201\n 3.2.1 -> 3210\n\n```\n\nThe following psudo-code will do this:\nStarting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number.\n\nIf g is greater than zero, rotate the elements from m to m+g in Ω (see example)\nIncrement m and repeat the first step using the next most significant digit until the factorial base number is exhausted.\nFor example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element.\n\nStep 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3\nStep 2: m=1 g=0; No action.\nStep 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1\n\nLet me work 2.0.1 and 0123\n\n```\n step 1 n=0 g=2 Ω=2013\n step 2 n=1 g=0 so no action\n step 3 n=2 g=1 Ω=2031\n\n```\n\nThe task:\n\n```\n First use your function to recreate the above table.\n Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with\n methods in rc's permutations task.\n Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier:\n 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\n 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\n use your function to crate the corresponding permutation of the following shoe of cards:\n A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣\n Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\nUsing my interpretation of the task instructions as shown on the discussion page.\n\n```\nsub postfix:<!> (Int $n) { (flat 1, [\\*] 1..*)[$n] }\n\nmulti base (Int $n is copy, 'F', $length? is copy) {\n constant @fact = [\\*] 1 .. *;\n my $i = $length // @fact.first: * > $n, :k;\n my $f;\n [ @fact[^$i].reverse.map: { ($n, $f) = $n.polymod($_); $f } ]\n}\n\nsub fpermute (@a is copy, *@f) { (^@f).map: { @a[$_ .. $_ + @f[$_]].=rotate(-1) }; @a }\n\nput \"Part 1: Generate table\";\nput $_.&base('F', 3).join('.') ~ ' -> ' ~ [0,1,2,3].&fpermute($_.&base('F', 3)).join for ^24;\n\nput \"\\nPart 2: Compare 11! to 11! \" ~ '¯\\_(ツ)_/¯';\n# This is kind of a weird request. Since we don't actually need to _generate_\n# the permutations, only _count_ them: compare count of 11! vs count of 11!\nput \"11! === 11! : {11! === 11!}\";\n\nput \"\\nPart 3: Generate the given task shuffles\";\nmy \\Ω = <A♠ K♠ Q♠ J♠ 10♠ 9♠ 8♠ 7♠ 6♠ 5♠ 4♠ 3♠ 2♠ A♥ K♥ Q♥ J♥ 10♥ 9♥ 8♥ 7♥ 6♥ 5♥ 4♥ 3♥ 2♥\n A♦ K♦ Q♦ J♦ 10♦ 9♦ 8♦ 7♦ 6♦ 5♦ 4♦ 3♦ 2♦ A♣ K♣ Q♣ J♣ 10♣ 9♣ 8♣ 7♣ 6♣ 5♣ 4♣ 3♣ 2♣\n>;\n\nmy @books = <\n 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\n 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\n>;\n\nput \"Original deck:\";\nput Ω.join;\n\nput \"\\n$_\\n\" ~ Ω[(^Ω).&fpermute($_.split: '.')].join for @books;\n\nput \"\\nPart 4: Generate a random shuffle\";\nmy @shoe = (+Ω … 2).map: { (^$_).pick };\nput @shoe.join('.');\nput Ω[(^Ω).&fpermute(@shoe)].join;\n\nput \"\\nSeems to me it would be easier to just say: Ω.pick(*).join\";\nput Ω.pick(*).join;\n\n```\n\nOutput:\n\n```\nPart 1: Generate table\n0.0.0 -> 0123\n0.0.1 -> 0132\n0.1.0 -> 0213\n0.1.1 -> 0231\n0.2.0 -> 0312\n0.2.1 -> 0321\n1.0.0 -> 1023\n1.0.1 -> 1032\n1.1.0 -> 1203\n1.1.1 -> 1230\n1.2.0 -> 1302\n1.2.1 -> 1320\n2.0.0 -> 2013\n2.0.1 -> 2031\n2.1.0 -> 2103\n2.1.1 -> 2130\n2.2.0 -> 2301\n2.2.1 -> 2310\n3.0.0 -> 3012\n3.0.1 -> 3021\n3.1.0 -> 3102\n3.1.1 -> 3120\n3.2.0 -> 3201\n3.2.1 -> 3210\n\nPart 2: Compare 11! to 11! ¯\\_(ツ)_/¯\n11! === 11! : True\n\nPart 3: Generate the given task shuffles\nOriginal deck:\nA♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣\n\n39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0\nA♣3♣7♠4♣10♦8♦Q♠K♥2♠10♠4♦7♣J♣5♥10♥10♣K♣2♣3♥5♦J♠6♠Q♣5♠K♠A♦3♦Q♥8♣6♦9♠8♠4♠9♥A♠6♥5♣2♦7♥8♥9♣6♣7♦A♥J♦Q♦9♦2♥3♠J♥4♥K♦\n\n51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1\n2♣5♣J♥4♥J♠A♠5♥A♣6♦Q♠9♣3♦Q♥J♣10♥K♣10♣5♦7♥10♦3♠8♥10♠7♠6♥5♠K♥4♦A♥4♣2♥9♦Q♣8♣7♦6♣3♥6♠7♣2♦J♦9♥A♦Q♦8♦4♠K♦K♠3♣2♠8♠9♠\n\nPart 4: Generate a random shuffle\n47.9.46.16.28.8.36.27.29.1.9.27.1.16.21.22.28.34.30.8.19.27.18.22.3.25.15.20.12.14.8.9.11.1.4.0.3.5.4.2.2.10.8.1.6.1.2.4.1.2.1\n6♣5♠5♣10♥10♦6♠K♣9♦6♦K♠2♠5♦Q♠5♥Q♦8♦J♣2♣8♣A♥K♦9♣A♦2♦9♠4♣3♥A♣7♥2♥Q♥9♥4♥J♠4♠A♠3♠8♥J♥7♠K♥3♣10♣8♠Q♣6♥7♦7♣J♦3♦4♦10♠\n\nSeems to me it would be easier to just say: Ω.pick(*).join\n5♦3♠8♦10♦2♥7♠7♦Q♦A♠5♣8♣Q♠4♠2♦K♦5♠Q♥7♣10♠2♠K♠J♣9♣3♣4♥3♥4♦3♦Q♣2♣4♣J♦9♠A♣J♠10♣6♣9♦6♠10♥6♥9♥J♥7♥K♥A♦8♠A♥5♥8♥K♣6♦\n```" } ]
[ { "role": "user", "content": "Definition\n\nA factorial prime is a prime number that is one less or one more than a factorial.\n\nIn other words a non-negative integer **n** corresponds to a factorial prime if either **n**! - 1 or **n**! + 1 is prime.\n\nExamples\n\n4 corresponds to the factorial prime 4! - 1 = 23.\n\n5 doesn't correspond to a factorial prime because neither 5! - 1 = 119 (7 x 17) nor 5! + 1 = 121 (11 x 11) are prime.\n\nTask\n\nFind and show here the first 10 factorial primes. As well as the prime itself show the factorial number **n** to which it corresponds and whether 1 is to be added or subtracted.\n\nAs 0! (by convention) and 1! are both 1, ignore the former and start counting from 1!.\n\nStretch\n\nIf your language supports arbitrary sized integers, do the same for at least the next 19 factorial primes.\n\nAs it can take a long time to demonstrate that a large number (above say 2^64) is definitely prime, you may instead use a function which shows that a number is probably prime to a reasonable degree of certainty. Most 'big integer' libraries have such a function.\n\nIf a number has more than 40 digits, do not show the full number. Show instead the first 20 and the last 20 digits and how many digits in total the number has.\n\nReference\n\n* OEIS:A088054 - Factorial primes\n\nRelated task\n\n* Sequence of primorial primes" }, { "role": "assistant", "content": "```\nsub postfix:<!> ($n) { constant @F = (1, 1, |[\\*] 2..*); @F[$n] }\nsub abr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '..' ~ .substr(*-20) ~ \" ({.chars} digits)\" }\n\nmy $limit;\n\nfor 1..* {\n my \\f = .!;\n ++$limit and printf \"%2d: %3d! - 1 = %s\\n\", $limit, $_, abr f -1 if (f -1).is-prime;\n ++$limit and printf \"%2d: %3d! + 1 = %s\\n\", $limit, $_, abr f +1 if (f +1).is-prime;\n exit if $limit >= 30\n}\n\n```\n\nOutput:\n\n```\n 1: 1! + 1 = 2\n 2: 2! + 1 = 3\n 3: 3! - 1 = 5\n 4: 3! + 1 = 7\n 5: 4! - 1 = 23\n 6: 6! - 1 = 719\n 7: 7! - 1 = 5039\n 8: 11! + 1 = 39916801\n 9: 12! - 1 = 479001599\n10: 14! - 1 = 87178291199\n11: 27! + 1 = 10888869450418352160768000001\n12: 30! - 1 = 265252859812191058636308479999999\n13: 32! - 1 = 263130836933693530167218012159999999\n14: 33! - 1 = 8683317618811886495518194401279999999\n15: 37! + 1 = 13763753091226345046..79581580902400000001 (44 digits)\n16: 38! - 1 = 52302261746660111176..24100074291199999999 (45 digits)\n17: 41! + 1 = 33452526613163807108..40751665152000000001 (50 digits)\n18: 73! + 1 = 44701154615126843408..03680000000000000001 (106 digits)\n19: 77! + 1 = 14518309202828586963..48000000000000000001 (114 digits)\n20: 94! - 1 = 10873661566567430802..99999999999999999999 (147 digits)\n21: 116! + 1 = 33931086844518982011..00000000000000000001 (191 digits)\n22: 154! + 1 = 30897696138473508879..00000000000000000001 (272 digits)\n23: 166! - 1 = 90036917057784373664..99999999999999999999 (298 digits)\n24: 320! + 1 = 21161033472192524829..00000000000000000001 (665 digits)\n25: 324! - 1 = 22889974601791023211..99999999999999999999 (675 digits)\n26: 340! + 1 = 51008644721037110809..00000000000000000001 (715 digits)\n27: 379! - 1 = 24840307460964707050..99999999999999999999 (815 digits)\n28: 399! + 1 = 16008630711655973815..00000000000000000001 (867 digits)\n29: 427! + 1 = 29063471769607348411..00000000000000000001 (940 digits)\n30: 469! - 1 = 67718096668149510900..99999999999999999999 (1051 digits)\n```" } ]
[ { "role": "user", "content": "Definition\n\nA factorion is a natural number that equals the sum of the factorials of its digits.\n\nExample\n\n**145**   is a factorion in base **10** because:\n\n**```\n 1! + 4! + 5! = 1 + 24 + 120 = 145 \n\n```**\n\nIt can be shown (see talk page) that no factorion in base **10** can exceed   **1,499,999**.\n\nTask\n\nWrite a program in your language to demonstrate, by calculating and printing out the factorions, that:\n\n: * There are   **3**   factorions in base   **9**\n * There are   **4**   factorions in base **10**\n * There are   **5**   factorions in base **11**\n * There are   **2**   factorions in base **12**     (up to the same upper bound as for base **10**)\n\nSee also\n: * **Wikipedia article**\n * **OEIS:A014080 - Factorions in base 10**\n * **OEIS:A193163 - Factorions in base n**" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n```\nconstant @factorial = 1, |[\\*] 1..*;\n\nconstant $limit = 1500000;\n\nconstant $bases = 9 .. 12;\n\nmy @result;\n\n$bases.map: -> $base {\n\n @result[$base] = \"\\nFactorions in base $base:\\n1 2\";\n\n sink (1 .. $limit div $base).map: -> $i {\n my $product = $i * $base;\n my $partial;\n\n for $i.polymod($base xx *) {\n $partial += @factorial[$_];\n last if $partial > $product\n }\n\n next if $partial > $product;\n\n my $sum;\n\n for ^$base {\n last if ($sum = $partial + @factorial[$_]) > $product + $_;\n @result[$base] ~= \" $sum\" and last if $sum == $product + $_\n }\n }\n}\n\n.say for @result[$bases];\n\n```\n\nOutput:\n\n```\nFactorions in base 9:\n1 2 41282\n\nFactorions in base 10:\n1 2 145 40585\n\nFactorions in base 11:\n1 2 26 48 40472\n\nFactorions in base 12:\n1 2\n```" } ]
[ { "role": "user", "content": "Given a finite alphabet, we can lexicographically order all strings in the alphabet. If two strings have different lengths, then pad the shorter string on the right with the smallest letter. For example, we have 01 > 001, but 01 = 010. As we see, this order is a total preorder, but not a total order, since it identifies different strings.\n\nA Lyndon word is a non-empty string that is *strictly* lower in lexicographic order than all its circular rotations. In particular, if a string is equal to a circular rotation, then it is not a Lyndon word. For example, since 0101 = 0101 (rotation by 2), it is not a Lyndon word.\n\nThe first Lyndon words on the binary alphabet {0, 1} are:\n\n: 0, 1, 01, 001, 011, 0001, 0011, 0111, 00001, 00011, 00101, 00111, 01011, 01111, ...\n\nSome basic properties:\n\n* The only Lyndon word that ends with 0 is 0.\n* **Proof.** If s0 is a Lyndon word, and s is not empty, then s0 < 0s. If s contains 1 somewhere, then s0 > 0s. Therefore s has only 0. But then s0 = 0s, contradiction.\n* The lexicographic order *is* a total order on the Lyndon words.\n* **Proof.** For, the only way for two different strings s, s' to have the same lexicographic ordering is for one of them to pad to the other. We can assume that s00...0 = s'. If that is so, then s00...0 is a Lyndon word that ends with 0, so it is just 0, and so s is a Lyndon word that is also empty, contradiction.\n\nThe Chen–Fox–Lyndon theorem states that any string is uniquely factorizable into a sequence of Lyndon words non-decreasing in lexicographic order. Duval's algorithm computes this in O(length of input) time and and O(1) space.[1] See [2] for a description of Duval's algorithm." }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\n# 20240213 Raku programming solution\n\nsub chenfoxlyndonfactorization(Str $s) {\n my ($n, $i, @factorization) = $s.chars, 1;\n while $i <= $n {\n my ($j, $k) = $i X+ (1, 0);\n while $j <= $n && substr($s, $k-1, 1) <= substr($s, $j-1, 1) {\n substr($s, $k-1, 1) < substr($s, $j++ -1, 1) ?? ( $k = $i ) !! $k++;\n }\n while $i <= $k {\n @factorization.push: substr($s, $i-1, $j-$k);\n $i += $j - $k\n }\n }\n die unless $s eq [~] @factorization;\n return @factorization\n}\n\nmy $m = \"0\";\nfor ^7 { $m ~= $m.trans('0' => '1', '1' => '0') }\nsay chenfoxlyndonfactorization($m);\n\n```\n\nOutput:\n\nSame as Julia example.\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "A Mersenne number is a number in the form of 2P-1.\n\nIf P is prime, the Mersenne number may be a Mersenne prime\n(if P is not prime, the Mersenne number is also not prime).\n\nIn the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.\n\nThere are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).\nSome languages already have built-in implementations of this exponent-and-mod operation (called *modPow* or similar).\n\nThe following is how to implement this *modPow* yourself:\n\nFor example, let's compute 223 mod 47.\nConvert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.\nRemove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.\nUse the result of the modulo from the last step as the initial value of square in the next step:\n\n```\n remove optional \n square top bit multiply by 2 mod 47\n ──────────── ─────── ───────────── ────── \n 1*1 = 1 1 0111 1*2 = 2 2\n 2*2 = 4 0 111 no 4\n 4*4 = 16 1 11 16*2 = 32 32\n 32*32 = 1024 1 1 1024*2 = 2048 27\n 27*27 = 729 1 729*2 = 1458 1\n\n```\n\nSince 223 mod 47 = 1, 47 is a factor of 2P-1.\n(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)\nSince we've shown that 47 is a factor, 223-1 is not prime.\nFurther properties of Mersenne numbers allow us to refine the process even more.\nAny factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.\nFinally any potential factor q must be prime.\nAs in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).\n\nThese primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.\n\nTask\n\nUsing the above method find a factor of 2929-1 (aka M929)\n\nRelated tasks\n\n* count in factors\n* prime decomposition\n* factors of an integer\n* Sieve of Eratosthenes\n* primality by trial division\n* trial factoring of a Mersenne number\n* partition an integer X into N primes\n* sequence of primes by Trial Division\n\nSee also\n\n* Computers in 1948: 2127 - 1 \n       (Note:   This video is no longer available because the YouTube account associated with this video has been terminated.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub mtest($bits, $p) {\n my @bits = $bits.base(2).comb;\n loop (my $sq = 1; @bits; $sq %= $p) {\n $sq ×= $sq;\n $sq += $sq if 1 == @bits.shift;\n }\n $sq == 1;\n}\n\nfor flat 2 .. 60, 929 -> $m {\n next unless is-prime($m);\n my $f = 0;\n my $x = 2**$m - 1;\n my $q;\n for 1..* -> $k {\n $q = 2 × $k × $m + 1;\n next unless $q % 8 == 1|7 or is-prime($q);\n last if $q × $q > $x or $f = mtest($m, $q);\n }\n\n say $f ?? \"M$m = $x\\n\\t= $q × { $x div $q }\"\n  !! \"M$m = $x is prime\";\n}\n\n```\n\nOutput:\n\n```\nM2 = 3 is prime\nM3 = 7 is prime\nM5 = 31 is prime\nM7 = 127 is prime\nM11 = 2047\n\t= 23 × 89\nM13 = 8191 is prime\nM17 = 131071 is prime\nM19 = 524287 is prime\nM23 = 8388607\n\t= 47 × 178481\nM29 = 536870911\n\t= 233 × 2304167\nM31 = 2147483647 is prime\nM37 = 137438953471\n\t= 223 × 616318177\nM41 = 2199023255551\n\t= 13367 × 164511353\nM43 = 8796093022207\n\t= 431 × 20408568497\nM47 = 140737488355327\n\t= 2351 × 59862819377\nM53 = 9007199254740991\n\t= 6361 × 1416003655831\nM59 = 576460752303423487\n\t= 179951 × 3203431780337\nM929 = 4538015467766671944574165338592225830478699345884382504442663144885072806275648112625635725391102144133907238129251016389326737199538896813326509341743147661691195191795226666084858428449394948944821764472508048114220424520501343042471615418544488778723282182172070046459244838911\n\t= 13007 × 348890248924938259750454781163390930305120269538278042934009621348894657205785201247454118966026150852149399410259938217062100192168747352450719561908445272675574320888385228421992652298715687625495638077382028762529439880103124705348782610789919949159935587158612289264184273\n```" } ]
[ { "role": "user", "content": "Task\n\nCompute the   factors   of a positive integer.\n\nThese factors are the positive integers by which the number being factored can be divided to yield a positive integer result.\n\n(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases).\n\nNote that every prime number has two factors:   **1**   and itself.\n\nRelated tasks\n\n* count in factors\n* prime decomposition\n* Sieve of Eratosthenes\n* primality by trial division\n* factors of a Mersenne number\n* trial factoring of a Mersenne number\n* partition an integer X into N primes\n* sequence of primes by Trial Division\n* sequence: smallest number greater than previous term with exactly n divisors" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n### Brute-force\n\nNaive, brute-force, and slow, but ok for small numbers.\n\n```\nsub factors (Int $n) { (1..$n).grep($n %% *) }\n```\n\n### Optimized\n\nIf you don't want to roll your own.\n\n```\nuse Prime::Factor;\n\nput divisors :s, 2⁹⁹ + 1;\n\nsay (now - INIT now).round(.001) ~' seconds';\n```\n\nOutput:\n\n```\n1 3 9 19 27 57 67 171 201 513 603 683 1273 1809 2049 3819 5347 6147 11457 12977 16041 18441 20857 34371 38931 45761 48123 62571 101593 116793 137283 144369 187713 304779 350379 358249 396283 411849 563139 869459 914337 1074747 1188849 1235547 1397419 2608377 2743011 3224241 3566547 3652001 4192257 6806731 7825131 9672723 10699641 10956003 12576771 14245331 20420193 23475393 26550961 32868009 37730313 42735993 61260579 69388019 79652883 98604027 111522379 128207979 183781737 208164057 238958649 244684067 270661289 334567137 384623937 624492171 716875947 734052201 811983867 954437177 1003701411 1873476513 2118925201 2202156603 2435951601 2863311531 3011104233 4648997273 6356775603 6606469809 7307854803 7471999393 8589934593 13946991819 18134306363 19070326809 22415998179 25769803779 41840975457 54402919089 57210980427 67247994537 76169784857 125522926371 141967988467 163208757267 201743983611 228509354571 425903965401 489626271801 685528063713 1277711896203 1447225912283 2056584191139 3833135688609 4341677736849 5103375585419 13025033210547 15310126756257 39075099631641 45930380268771 96964136122961 137791140806313 242099935645987 290892408368883 726299806937961 872677225106649 2178899420813883 2618031675319947 4599898777273753 6536698262441649 13799696331821259 16220695688281129 41399088995463777 48662087064843387 124197266986391331 145986261194530161 165354256046209121 308193218077341451 437958783583590483 496062768138627363 924579654232024353 1294508355899092489 1488188304415882089 2773738962696073059 3141730864877973299 3883525067697277467 4464564913247646267 5049478357768350859 8321216888088219177 9425192594633919897 11078735155096011107 11650575203091832401 15148435073305052577 24595658762082757291 28275577783901759691 33236205465288033321 34951725609275497203 45445305219915157731 73786976286248271873 84826733351705279073 86732059845239196763 95940088797598666321 99708616395864099963 136335915659745473193 210495967946824211033 221360928858744815619 260196179535717590289 287820266392795998963 299125849187592299889 338315049970479507553 631487903840472633099 664082786576234446857 780588538607152770867 863460799178387996889 884149207079080169987 1014945149911438522659 1647909137059544738497 1894463711521417899297 2341765615821458312601 2590382397535163990667 2652447621237240509961 3044835449734315567977 3448793718355783636697 4943727411178634215491 5683391134564253697891 6427985949439110643507 7957342863711721529883 9134506349202946703931 10346381155067350910091 14831182233535902646473 16798834934502523229753 19283957848317331930521 23872028591135164589649 26999560778987372043073 31039143465202052730273 44493546700607707939419 50396504803507569689259 57851873544951995791563 59237996874298371389129 65527080648759889097243 80998682336962116129219 93117430395606158190819 151189514410522709067777 173555620634855987374689 177713990622895114167387 196581241946279667291729 231069179129837503658699 242996047010886348387657 453568543231568127203331 512991654800760068818387 533141971868685342502161 589743725838839001875187 693207537389512510976097 728988141032659045162971 1125521940611669056393451 1538974964402280206455161 1599425915606056027506483 1769231177516517005625561 1808970572192153926885891 2079622612168537532928291 3376565821835007169180353 4390314403466912569515281 4616924893206840619365483 5426911716576461780657673 6238867836505612598784873 10129697465505021507541059 13170943210400737708545843 13850774679620521858096449 16280735149729385341973019 18440700012048375105418859 30389092396515064522623177 34370440871650924610831929 39512829631202213125637529 48842205449188156025919057 55322100036145125316256577 103111322614952773832495787 118538488893606639376912587 165966300108435375948769731 309333967844858321497487361 350373300228919127002958321 497898900325306127846309193 928001903534574964492462083 1051119900686757381008874963 1235526900807241132063063553 3153359702060272143026624889 3706580702421723396189190659 9460079106180816429079874667 11119742107265170188567571977 23475011115337581509198207507 33359226321795510565702715931 70425033346012744527594622521 211275100038038233582783867563 633825300114114700748351602689\n0.046 seconds\n```" } ]
[ { "role": "user", "content": "The Thue-Morse sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n\n: *\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"*\n\nSharing fairly between two or more\n\nUse this method:\n\n: *When counting base **b**, the digit sum modulo **b** is the Thue-Morse sequence of fairer sharing between **b** people.*\n\nTask\n\nCounting from zero;   using a function/method/routine to express an integer count in base **b**,\n \nsum the digits modulo **b** to produce the next member of the Thue-Morse fairshare series for **b** people.\n\nShow the first 25 terms of the fairshare sequence:\n\n: * For two people:\n * For three people\n * For five people\n * For eleven people\n\nRelated tasks\n: * Non-decimal radices/Convert\n * Thue-Morse\n\nSee also\n: * A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.01\n\nAdd an extension showing the relative fairness correlation of this selection algorithm. An absolutely fair algorithm would have a correlation of 1 for each person (no person has an advantage or disadvantage due to an algorithmic artefact.) This algorithm is fair, and gets better the more iterations are done.\n\nA lower correlation factor corresponds to an advantage, higher to a disadvantage, the closer to 1 it is, the fairer the algorithm. Absolute best possible advantage correlation is 0. Absolute worst is 2.\n\n```\nsub fairshare (\\b) { ^∞ .hyper.map: { .polymod( b xx * ).sum % b } }\n\n.say for <2 3 5 11>.map: { .fmt('%2d:') ~ .&fairshare[^25]».fmt('%2d').join: ', ' }\n\nsay \"\\nRelative fairness of this method. Scaled fairness correlation. The closer to 1.0 each person\nis, the more fair the selection algorithm is. Gets better with more iterations.\";\n\nfor <2 3 5 11 39> -> $people {\n print \"\\n$people people: \\n\";\n for $people * 1, $people * 10, $people * 1000 -> $iterations {\n my @fairness;\n fairshare($people)[^$iterations].kv.map: { @fairness[$^v % $people] += $^k }\n my $scale = @fairness.sum / @fairness;\n my @range = @fairness.map( { $_ / $scale } );\n printf \"After round %4d: Best advantage: %-10.8g - Worst disadvantage: %-10.8g - Spread between best and worst: %-10.8g\\n\",\n $iterations/$people, @range.min, @range.max, @range.max - @range.min;\n }\n}\n\n```\n\n```\n 2: 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0\n 3: 0, 1, 2, 1, 2, 0, 2, 0, 1, 1, 2, 0, 2, 0, 1, 0, 1, 2, 2, 0, 1, 0, 1, 2, 1\n 5: 0, 1, 2, 3, 4, 1, 2, 3, 4, 0, 2, 3, 4, 0, 1, 3, 4, 0, 1, 2, 4, 0, 1, 2, 3\n11: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 2, 3, 4\n\nRelative fairness of this method. Scaled fairness correlation. The closer to 1.0 each person\nis, the more fair the selection algorithm is. Gets better with more iterations.\n\n2 people: \nAfter round 1: Best advantage: 0 - Worst disadvantage: 2 - Spread between best and worst: 2 \nAfter round 10: Best advantage: 1 - Worst disadvantage: 1 - Spread between best and worst: 0 \nAfter round 1000: Best advantage: 1 - Worst disadvantage: 1 - Spread between best and worst: 0 \n\n3 people: \nAfter round 1: Best advantage: 0 - Worst disadvantage: 2 - Spread between best and worst: 2 \nAfter round 10: Best advantage: 0.99310345 - Worst disadvantage: 1.0068966 - Spread between best and worst: 0.013793103\nAfter round 1000: Best advantage: 0.99999933 - Worst disadvantage: 1.0000007 - Spread between best and worst: 1.3337779e-06\n\n5 people: \nAfter round 1: Best advantage: 0 - Worst disadvantage: 2 - Spread between best and worst: 2 \nAfter round 10: Best advantage: 1 - Worst disadvantage: 1 - Spread between best and worst: 0 \nAfter round 1000: Best advantage: 1 - Worst disadvantage: 1 - Spread between best and worst: 0 \n\n11 people: \nAfter round 1: Best advantage: 0 - Worst disadvantage: 2 - Spread between best and worst: 2 \nAfter round 10: Best advantage: 0.99082569 - Worst disadvantage: 1.0091743 - Spread between best and worst: 0.018348624\nAfter round 1000: Best advantage: 0.99999909 - Worst disadvantage: 1.0000009 - Spread between best and worst: 1.8183471e-06\n\n39 people: \nAfter round 1: Best advantage: 0 - Worst disadvantage: 2 - Spread between best and worst: 2 \nAfter round 10: Best advantage: 0.92544987 - Worst disadvantage: 1.0745501 - Spread between best and worst: 0.14910026\nAfter round 1000: Best advantage: 0.99999103 - Worst disadvantage: 1.000009 - Spread between best and worst: 1.7949178e-05\n```" } ]
[ { "role": "user", "content": "The   Farey sequence   ***F*n**   of order   **n**   is the sequence of completely reduced fractions between   **0**   and   **1**   which, when in lowest terms, have denominators less than or equal to   **n**,   arranged in order of increasing size.\n\nThe   *Farey sequence*   is sometimes incorrectly called a   *Farey series*.\n\nEach Farey sequence:\n\n: : : * starts with the value   **0**   (zero),   denoted by the fraction     \n\n 0\n 1\n {\\displaystyle {\\displaystyle {\\frac {0}{1}}}}\n * ends with the value   **1**   (unity),   denoted by the fraction   \n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\frac {1}{1}}}}\n .\n\nThe Farey sequences of orders   **1**   to   **5**   are:\n\n: : : : F\n\n 1\n =\n\n\n 0\n 1\n ,\n\n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\bf {\\it {F}}}\\_{1}={\\frac {0}{1}},{\\frac {1}{1}}}}\n: : : : F\n\n 2\n =\n\n\n 0\n 1\n ,\n\n\n 1\n 2\n ,\n\n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\bf {\\it {F}}}\\_{2}={\\frac {0}{1}},{\\frac {1}{2}},{\\frac {1}{1}}}}\n: : : : F\n\n 3\n =\n\n\n 0\n 1\n ,\n\n\n 1\n 3\n ,\n\n\n 1\n 2\n ,\n\n\n 2\n 3\n ,\n\n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\bf {\\it {F}}}\\_{3}={\\frac {0}{1}},{\\frac {1}{3}},{\\frac {1}{2}},{\\frac {2}{3}},{\\frac {1}{1}}}}\n: : : : F\n\n 4\n =\n\n\n 0\n 1\n ,\n\n\n 1\n 4\n ,\n\n\n 1\n 3\n ,\n\n\n 1\n 2\n ,\n\n\n 2\n 3\n ,\n\n\n 3\n 4\n ,\n\n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\bf {\\it {F}}}\\_{4}={\\frac {0}{1}},{\\frac {1}{4}},{\\frac {1}{3}},{\\frac {1}{2}},{\\frac {2}{3}},{\\frac {3}{4}},{\\frac {1}{1}}}}\n: : : : F\n\n 5\n =\n\n\n 0\n 1\n ,\n\n\n 1\n 5\n ,\n\n\n 1\n 4\n ,\n\n\n 1\n 3\n ,\n\n\n 2\n 5\n ,\n\n\n 1\n 2\n ,\n\n\n 3\n 5\n ,\n\n\n 2\n 3\n ,\n\n\n 3\n 4\n ,\n\n\n 4\n 5\n ,\n\n\n 1\n 1\n {\\displaystyle {\\displaystyle {\\bf {\\it {F}}}\\_{5}={\\frac {0}{1}},{\\frac {1}{5}},{\\frac {1}{4}},{\\frac {1}{3}},{\\frac {2}{5}},{\\frac {1}{2}},{\\frac {3}{5}},{\\frac {2}{3}},{\\frac {3}{4}},{\\frac {4}{5}},{\\frac {1}{1}}}}\n\nTask\n\n* Compute and show the Farey sequence for orders   **1**   through   **11**   (inclusive).\n* Compute and display the   *number*   of fractions in the Farey sequence for order   **100**   through   **1,000**   (inclusive)   by hundreds.\n* Show the fractions as   **n/d**   (using the solidus [or slash] to separate the numerator from the denominator).\n\nThe length   (the number of fractions)   of a Farey sequence asymptotically approaches:\n\n: : : : : : : : : : : 3 × n2   ÷   \n\n π\n {\\displaystyle {\\displaystyle \\pi }}\n 2\n\nSee also\n\n* OEIS sequence   A006842 numerators of Farey series of order 1, 2, ···\n* OEIS sequence   A006843 denominators of Farey series of order 1, 2, ···\n* OEIS sequence   A005728 number of fractions in Farey series of order n\n* MathWorld entry   Farey sequence\n* Wikipedia   entry   Farey sequence" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.10\n\n```\nsub farey ($order) {\n my @l = 0/1, 1/1;\n (2..$order).map: { push @l, |(1..$^d).map: { $_/$d } }\n unique @l\n}\n\nsay \"Farey sequence order \";\n.say for (1..11).hyper(:1batch).map: { \"$_: \", .&farey.sort.map: *.nude.join('/') };\n.say for (100, 200 ... 1000).race(:1batch).map: { \"Farey sequence order $_ has \" ~ [.&farey].elems ~ ' elements.' }\n\n```\n\nOutput:\n\n```\nFarey sequence order \n1: 0/1 1/1\n2: 0/1 1/2 1/1\n3: 0/1 1/3 1/2 2/3 1/1\n4: 0/1 1/4 1/3 1/2 2/3 3/4 1/1\n5: 0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1\n6: 0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 5/6 1/1\n7: 0/1 1/7 1/6 1/5 1/4 2/7 1/3 2/5 3/7 1/2 4/7 3/5 2/3 5/7 3/4 4/5 5/6 6/7 1/1\n8: 0/1 1/8 1/7 1/6 1/5 1/4 2/7 1/3 3/8 2/5 3/7 1/2 4/7 3/5 5/8 2/3 5/7 3/4 4/5 5/6 6/7 7/8 1/1\n9: 0/1 1/9 1/8 1/7 1/6 1/5 2/9 1/4 2/7 1/3 3/8 2/5 3/7 4/9 1/2 5/9 4/7 3/5 5/8 2/3 5/7 3/4 7/9 4/5 5/6 6/7 7/8 8/9 1/1\n10: 0/1 1/10 1/9 1/8 1/7 1/6 1/5 2/9 1/4 2/7 3/10 1/3 3/8 2/5 3/7 4/9 1/2 5/9 4/7 3/5 5/8 2/3 7/10 5/7 3/4 7/9 4/5 5/6 6/7 7/8 8/9 9/10 1/1\n11: 0/1 1/11 1/10 1/9 1/8 1/7 1/6 2/11 1/5 2/9 1/4 3/11 2/7 3/10 1/3 4/11 3/8 2/5 3/7 4/9 5/11 1/2 6/11 5/9 4/7 3/5 5/8 7/11 2/3 7/10 5/7 8/11 3/4 7/9 4/5 9/11 5/6 6/7 7/8 8/9 9/10 10/11 1/1\nFarey sequence order 100 has 3045 elements.\nFarey sequence order 200 has 12233 elements.\nFarey sequence order 300 has 27399 elements.\nFarey sequence order 400 has 48679 elements.\nFarey sequence order 500 has 76117 elements.\nFarey sequence order 600 has 109501 elements.\nFarey sequence order 700 has 149019 elements.\nFarey sequence order 800 has 194751 elements.\nFarey sequence order 900 has 246327 elements.\nFarey sequence order 1000 has 304193 elements.\n```" } ]
[ { "role": "user", "content": "Task\n\nCalculate the   FFT   (Fast Fourier Transform)   of an input sequence.\n\nThe most general case allows for complex numbers at the input\nand results in a sequence of equal length, again of complex numbers.\nIf you need to restrict yourself to real numbers, the output should\nbe the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result.\n\nThe classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.\nFurther optimizations are possible but not required." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo 2022-07\n\n| |\n| --- |\n| This example is **in need of improvement:** Not numerically accurate |\n\n```\nsub fft {\n return @_ if @_ == 1;\n my @evn = fft( @_[0, 2 ... *] );\n my @odd = fft( @_[1, 3 ... *] ) Z*\n map &cis, (0, -tau / @_ ... *);\n return flat @evn »+« @odd, @evn »-« @odd;\n}\n\n.say for fft <1 1 1 1 0 0 0 0>;\n\n```\n\nOutput:\n\n```\n4+0i\n1-2.414213562373095i\n0+0i\n1-0.4142135623730949i\n0+0i\n0.9999999999999999+0.4142135623730949i\n0+0i\n0.9999999999999997+2.414213562373095i\n\n```\n\nFor the fun of it, here is a purely functional version:\n\n```\nsub fft {\n @_ == 1 ?? @_ !!\n fft(@_[0,2...*]) «+«\n fft(@_[1,3...*]) «*« map &cis, (0,-τ/@_...^-τ)\n}\n\n```" } ]
[ { "role": "user", "content": "In bioinformatics, long character strings are often encoded in a format called FASTA.\n\nA FASTA file can contain several strings, each identified by a name marked by a `>` (greater than) character at the beginning of the line.\n\nTask\n\nWrite a program that reads a FASTA file such as:\n\n```\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n```\n\nOutput:\n\n```\nRosetta_Example_1: THERECANBENOSPACE\nRosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED\n\n```\n\nNote that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\ngrammar FASTA {\n\n rule TOP { <entry>+ }\n rule entry { \\> <title> <sequence> }\n token title { <.alnum>+ }\n token sequence { ( <.alnum>+ )+ % \\n { make $0.join } }\n\n}\n\nFASTA.parse: q:to /§/;\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n§\n\nfor $/<entry>[] {\n say ~.<title>, \" : \", .<sequence>.made;\n}\n\n```\n\nOutput:\n\n```\nRosetta_Example_1 : THERECANBENOSPACE\nRosetta_Example_2 : THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED\n```" } ]
[ { "role": "user", "content": "In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the *p*-th powers of the first *n* positive integers as a *(p + 1)*th-degree polynomial function of n,   the coefficients involving Bernoulli numbers.\n\nTask\n\nGenerate the first 10 closed-form expressions, starting with *p = 0*.\n\nRelated tasks\n: * Bernoulli numbers.\n * evaluate binomial coefficients.\n\nSee also\n: * The Wikipedia entry:   Faulhaber's formula.\n * The Wikipedia entry:   Bernoulli numbers.\n * The Wikipedia entry:   binomial coefficients." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04.01\n\n```\nsub bernoulli_number($n) {\n\n return 1/2 if $n == 1;\n return 0/1 if $n % 2;\n\n my @A;\n for 0..$n -> $m {\n @A[$m] = 1 / ($m + 1);\n for $m, $m-1 ... 1 -> $j {\n @A[$j - 1] = $j * (@A[$j - 1] - @A[$j]);\n }\n }\n\n return @A[0];\n}\n\nsub binomial($n, $k) {\n $k == 0 || $n == $k ?? 1 !! binomial($n-1, $k-1) + binomial($n-1, $k);\n}\n\nsub faulhaber_s_formula($p) {\n\n my @formula = gather for 0..$p -> $j {\n take '('\n ~ join('/', (binomial($p+1, $j) * bernoulli_number($j)).Rat.nude)\n ~ \")*n^{$p+1 - $j}\";\n }\n\n my $formula = join(' + ', @formula.grep({!m{'(0/1)*'}}));\n\n $formula .= subst(rx{ '(1/1)*' }, '', :g);\n $formula .= subst(rx{ '^1'» }, '', :g);\n\n \"1/{$p+1} * ($formula)\";\n}\n\nfor 0..9 -> $p {\n say \"f($p) = \", faulhaber_s_formula($p);\n}\n\n```\n\nOutput:\n\n```\nf(0) = 1/1 * (n)\nf(1) = 1/2 * (n^2 + n)\nf(2) = 1/3 * (n^3 + (3/2)*n^2 + (1/2)*n)\nf(3) = 1/4 * (n^4 + (2/1)*n^3 + n^2)\nf(4) = 1/5 * (n^5 + (5/2)*n^4 + (5/3)*n^3 + (-1/6)*n)\nf(5) = 1/6 * (n^6 + (3/1)*n^5 + (5/2)*n^4 + (-1/2)*n^2)\nf(6) = 1/7 * (n^7 + (7/2)*n^6 + (7/2)*n^5 + (-7/6)*n^3 + (1/6)*n)\nf(7) = 1/8 * (n^8 + (4/1)*n^7 + (14/3)*n^6 + (-7/3)*n^4 + (2/3)*n^2)\nf(8) = 1/9 * (n^9 + (9/2)*n^8 + (6/1)*n^7 + (-21/5)*n^5 + (2/1)*n^3 + (-3/10)*n)\nf(9) = 1/10 * (n^10 + (5/1)*n^9 + (15/2)*n^8 + (-7/1)*n^6 + (5/1)*n^4 + (-3/2)*n^2)\n\n```" } ]
[ { "role": "user", "content": "Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:\n\n: ∑\n\n k\n =\n 1\n\n n\n\n k\n\n p\n =\n\n\n 1\n\n p\n +\n 1\n\n ∑\n\n j\n =\n 0\n\n p\n\n (\n\n\n p\n +\n 1\n j\n\n )\n\n B\n\n j\n\n n\n\n p\n +\n 1\n −\n j\n {\\displaystyle {\\displaystyle \\sum \\_{k=1}^{n}k^{p}={1 \\over p+1}\\sum \\_{j=0}^{p}{p+1 \\choose j}B\\_{j}n^{p+1-j}}}\n\nwhere \n\nB\n\nn\n{\\displaystyle {\\displaystyle B\\_{n}}}\n is the nth-Bernoulli number.\n\nThe first 5 rows of Faulhaber's triangle, are:\n\n```\n 1\n 1/2 1/2\n 1/6 1/2 1/3\n 0 1/4 1/2 1/4\n-1/30 0 1/3 1/2 1/5\n\n```\n\nUsing the third row of the triangle, we have:\n\n∑\n\nk\n=\n1\n\nn\n\nk\n\n2\n=\n\n\n1\n6\nn\n+\n\n\n1\n2\n\nn\n\n2\n+\n\n\n1\n3\n\nn\n\n3\n{\\displaystyle {\\displaystyle \\sum \\_{k=1}^{n}k^{2}={1 \\over 6}n+{1 \\over 2}n^{2}+{1 \\over 3}n^{3}}}\n\nTask\n\n: * show the first 10 rows of Faulhaber's triangle.\n * using the 18th row of Faulhaber's triangle, compute the sum: \n\n ∑\n\n k\n =\n 1\n\n 1000\n\n k\n\n 17\n {\\displaystyle {\\displaystyle \\sum \\_{k=1}^{1000}k^{17}}}\n (extra credit).\n\nSee also\n\n* Bernoulli numbers\n* Evaluate binomial coefficients\n* Faulhaber's formula (Wikipedia)\n* Faulhaber's triangle (PDF)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\n**Translation of**: Sidef\n\n```\n# Helper subs\n\nsub infix:<reduce> (\\prev, \\this) { this.key => this.key * (this.value - prev.value) }\n\nsub next-bernoulli ( (:key($pm), :value(@pa)) ) {\n $pm + 1 => [ map *.value, [\\reduce] ($pm + 2 ... 1) Z=> 1 / ($pm + 2), |@pa ]\n}\n\nconstant bernoulli = (0 => [1.FatRat], &next-bernoulli ... *).map: { .value[*-1] };\n\nsub binomial (Int $n, Int $p) { combinations($n, $p).elems }\n\nsub asRat (FatRat $r) { $r ?? $r.denominator == 1 ?? $r.numerator !! $r.nude.join('/') !! 0 }\n\n\n# The task\nsub faulhaber_triangle ($p) { map { binomial($p + 1, $_) * bernoulli[$_] / ($p + 1) }, ($p ... 0) }\n\n# First 10 rows of Faulhaber's triangle:\nsay faulhaber_triangle($_)».&asRat.fmt('%5s') for ^10;\nsay '';\n\n# Extra credit:\nmy $p = 17;\nmy $n = 1000;\nsay sum faulhaber_triangle($p).kv.map: { $^value * $n**($^key + 1) }\n\n```\n\nOutput:\n\n```\n 1\n 1/2 1/2\n 1/6 1/2 1/3\n 0 1/4 1/2 1/4\n-1/30 0 1/3 1/2 1/5\n 0 -1/12 0 5/12 1/2 1/6\n 1/42 0 -1/6 0 1/2 1/2 1/7\n 0 1/12 0 -7/24 0 7/12 1/2 1/8\n-1/30 0 2/9 0 -7/15 0 2/3 1/2 1/9\n 0 -3/20 0 1/2 0 -7/10 0 3/4 1/2 1/10\n\n56056972216555580111030077961944183400198333273050000\n```" } ]
[ { "role": "user", "content": "Task\n\nCalculate the Feigenbaum constant.\n\nSee\n: * Details in the Wikipedia article:   Feigenbaum constant." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04.01\n\n**Translation of**: Ring\n\n```\nmy $a1 = 1;\nmy $a2 = 0;\nmy $d = 3.2;\n\nsay ' i d';\n\nfor 2 .. 13 -> $exp {\n my $a = $a1 + ($a1 - $a2) / $d;\n do {\n my $x = 0;\n my $y = 0;\n for ^2 ** $exp {\n $y = 1 - 2 * $y * $x;\n $x = $a - $x²;\n }\n $a -= $x / $y;\n } xx 10;\n $d = ($a1 - $a2) / ($a - $a1);\n ($a2, $a1) = ($a1, $a);\n printf \"%2d %.8f\\n\", $exp, $d;\n}\n\n```\n\nOutput:\n\n```\n i d\n 2 3.21851142\n 3 4.38567760\n 4 4.60094928\n 5 4.65513050\n 6 4.66611195\n 7 4.66854858\n 8 4.66906066\n 9 4.66917155\n10 4.66919515\n11 4.66920026\n12 4.66920098\n13 4.66920537\n```" } ]
[ { "role": "user", "content": "In mathematics, a Fermat number, *named after Pierre de Fermat who first studied them,* is a positive integer of the form **Fn = 2*2**n* + 1** where **n** is a non-negative integer.\n\nDespite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-random number generation, and are often linked to other number theoric fields.\n\nAs of this writing, (mid 2019), there are only five known prime Fermat numbers, the first five (**F0** through **F4**). Only the first twelve Fermat numbers have been completely factored, though many have been partially factored.\n\nTask\n\n: * Write a routine (function, procedure, whatever) to generate **Fermat numbers**.\n\n: * Use the routine to find and display here, on this page, the first **10 Fermat numbers** - **F0** through **F9**.\n\n: * Find and display here, on this page, the **prime factors** of as many Fermat numbers as you have patience for. (Or as many as can be found in five minutes or less of processing time). *Note: if you make it past **F11**, there may be money, and certainly will be acclaim in it for you.*\n\nSee also\n\n: * **Wikipedia - Fermat numbers**\n * **OEIS:A000215 - Fermat numbers**\n * **OEIS:A019434 - Fermat primes**" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nI gave up on factoring F₉ after about 20 minutes.\n\n**Library:** ntheory\n\n```\nuse ntheory:from<Perl5> <factor>;\n\nmy @Fermats = (^Inf).map: 2 ** 2 ** * + 1;\n\nmy $sub = '₀';\nsay \"First 10 Fermat numbers:\";\nprintf \"F%s = %s\\n\", $sub++, $_ for @Fermats[^10];\n\n$sub = '₀';\nsay \"\\nFactors of first few Fermat numbers:\";\nfor @Fermats[^9].map( {\"$_\".&factor} ) -> $f {\n printf \"Factors of F%s: %s %s\\n\", $sub++, $f.join(' '), $f.elems == 1 ?? '- prime' !! ''\n}\n\n```\n\nOutput:\n\n```\nFirst 10 Fermat numbers:\nF₀ = 3\nF₁ = 5\nF₂ = 17\nF₃ = 257\nF₄ = 65537\nF₅ = 4294967297\nF₆ = 18446744073709551617\nF₇ = 340282366920938463463374607431768211457\nF₈ = 115792089237316195423570985008687907853269984665640564039457584007913129639937\nF₉ = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084097\n\nFactors of first few Fermat numbers:\nFactors of F₀: 3 - prime\nFactors of F₁: 5 - prime\nFactors of F₂: 17 - prime\nFactors of F₃: 257 - prime\nFactors of F₄: 65537 - prime\nFactors of F₅: 641 6700417 \nFactors of F₆: 274177 67280421310721 \nFactors of F₇: 59649589127497217 5704689200685129054721 \nFactors of F₈: 1238926361552897 93461639715357977769163558199606896584051237541638188580280321\n\n```" } ]
[ { "role": "user", "content": "A Fermat pseudoprime is a positive composite integer that passes the Fermat primality test.\n\nFermat's little theorem states that if ***p*** is prime and ***a*** is coprime to ***p***, then ***ap−1 − 1*** is divisible by ***p***.\n\nFor an integer ***a*** > 1, if a composite integer ***x*** evenly divides ***ax−1 − 1***, then ***x*** is called a **Fermat pseudoprime** to base ***a***.\n\nFermat pseudoprimes to base **2** are sometimes called **Sarrus numbers** or **Poulet numbers**.\n\nFermat pseudoprimes can be found to any positive integer base. When using a base integer ***a*** = 1, this method returns *all* composite numbers.\n\nTask\n\nFor base integers ***a*** of **1** through **20**:\n\n* Find the **count** of pseudoprimes up to and including **12,000**.\n* Show the first **20** pseudoprimes.\n\nStretch\n\n* Extend the count threshold out to **25,000**, **50,000** or higher.\n\nSee also\n\n* Wikipedia: Fermat pseudoprime * OEIS:A002808 - Composite numbers * OEIS:A001567 - Fermat pseudoprimes to base 2 * OEIS:A005935 - Fermat pseudoprimes to base 3 * OEIS:A020136 - Fermat pseudoprimes to base 4 * OEIS:A005936 - Fermat pseudoprimes to base 5 * OEIS:A005937 - Fermat pseudoprimes to base 6 * OEIS:A005938 - Fermat pseudoprimes to base 7 * OEIS:A020137 - Fermat pseudoprimes to base 8 * OEIS:A020138 - Fermat pseudoprimes to base 9 * OEIS:A005939 - Fermat pseudoprimes to base 10 * OEIS:A020139 - Fermat pseudoprimes to base 11 * OEIS:A020140 - Fermat pseudoprimes to base 12 * OEIS:A020141 - Fermat pseudoprimes to base 13 * OEIS:A020142 - Fermat pseudoprimes to base 14 * OEIS:A020143 - Fermat pseudoprimes to base 15 * OEIS:A020144 - Fermat pseudoprimes to base 16 * OEIS:A020145 - Fermat pseudoprimes to base 17 * OEIS:A020146 - Fermat pseudoprimes to base 18 * OEIS:A020147 - Fermat pseudoprimes to base 19 * OEIS:A020148 - Fermat pseudoprimes to base 20\n\nRelated\n\n* Task: Modular exponentiation * Task: Super-Poulet numbers" }, { "role": "assistant", "content": "```\nuse List::Divvy;\nfor 1..20 -> $base {\n my @pseudo = lazy (2..*).hyper.grep: { !.is-prime && (1 == expmod $base, $_ - 1, $_) }\n my $threshold = 100_000;\n say $base.fmt(\"Base %2d - Up to $threshold: \") ~ (+@pseudo.&upto: $threshold).fmt('%5d')\n ~ \" First 20: \" ~ @pseudo[^20].gist\n}\n\n```\n\n```\nBase 1 - Up to 100000: 90407 First 20: (4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30 32)\nBase 2 - Up to 100000: 78 First 20: (341 561 645 1105 1387 1729 1905 2047 2465 2701 2821 3277 4033 4369 4371 4681 5461 6601 7957 8321)\nBase 3 - Up to 100000: 78 First 20: (91 121 286 671 703 949 1105 1541 1729 1891 2465 2665 2701 2821 3281 3367 3751 4961 5551 6601)\nBase 4 - Up to 100000: 153 First 20: (15 85 91 341 435 451 561 645 703 1105 1247 1271 1387 1581 1695 1729 1891 1905 2047 2071)\nBase 5 - Up to 100000: 73 First 20: (4 124 217 561 781 1541 1729 1891 2821 4123 5461 5611 5662 5731 6601 7449 7813 8029 8911 9881)\nBase 6 - Up to 100000: 104 First 20: (35 185 217 301 481 1105 1111 1261 1333 1729 2465 2701 2821 3421 3565 3589 3913 4123 4495 5713)\nBase 7 - Up to 100000: 73 First 20: (6 25 325 561 703 817 1105 1825 2101 2353 2465 3277 4525 4825 6697 8321 10225 10585 10621 11041)\nBase 8 - Up to 100000: 218 First 20: (9 21 45 63 65 105 117 133 153 231 273 341 481 511 561 585 645 651 861 949)\nBase 9 - Up to 100000: 164 First 20: (4 8 28 52 91 121 205 286 364 511 532 616 671 697 703 946 949 1036 1105 1288)\nBase 10 - Up to 100000: 90 First 20: (9 33 91 99 259 451 481 561 657 703 909 1233 1729 2409 2821 2981 3333 3367 4141 4187)\nBase 11 - Up to 100000: 89 First 20: (10 15 70 133 190 259 305 481 645 703 793 1105 1330 1729 2047 2257 2465 2821 4577 4921)\nBase 12 - Up to 100000: 127 First 20: (65 91 133 143 145 247 377 385 703 1045 1099 1105 1649 1729 1885 1891 2041 2233 2465 2701)\nBase 13 - Up to 100000: 91 First 20: (4 6 12 21 85 105 231 244 276 357 427 561 1099 1785 1891 2465 2806 3605 5028 5149)\nBase 14 - Up to 100000: 96 First 20: (15 39 65 195 481 561 781 793 841 985 1105 1111 1541 1891 2257 2465 2561 2665 2743 3277)\nBase 15 - Up to 100000: 70 First 20: (14 341 742 946 1477 1541 1687 1729 1891 1921 2821 3133 3277 4187 6541 6601 7471 8701 8911 9073)\nBase 16 - Up to 100000: 200 First 20: (15 51 85 91 255 341 435 451 561 595 645 703 1105 1247 1261 1271 1285 1387 1581 1687)\nBase 17 - Up to 100000: 83 First 20: (4 8 9 16 45 91 145 261 781 1111 1228 1305 1729 1885 2149 2821 3991 4005 4033 4187)\nBase 18 - Up to 100000: 134 First 20: (25 49 65 85 133 221 323 325 343 425 451 637 931 1105 1225 1369 1387 1649 1729 1921)\nBase 19 - Up to 100000: 121 First 20: (6 9 15 18 45 49 153 169 343 561 637 889 905 906 1035 1105 1629 1661 1849 1891)\nBase 20 - Up to 100000: 101 First 20: (21 57 133 231 399 561 671 861 889 1281 1653 1729 1891 2059 2413 2501 2761 2821 2947 3059)\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Fibonacci heap. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nTask\n\n* Implement queue operations for **Fibonacci heaps**. Where H is heap, x node with data value, k integer.\n* Operations:\n + MakeHeap() - create new empty Fibonacci heap\n + Insert(H,x) - insert new element x into heap H\n + Union(H1, H2) - union heap H1 and heap H2\n + Minimum(H) - return minimum value from heap H\n + ExtractMin(H) - (or DeleteMin(H)) - return minimum value from heap H and remove it from heap\n + DecreaseKey(H,x,k) - decrease value of element x in heap H to value k\n + Delete(H,x) - remove element x from heap H" }, { "role": "assistant", "content": "**Translation of**: Go & Kotlin\n\n```\n# 20200609 Raku programming solution\n\nsubset vEle of Any; \n\nclass Node {\n has vEle $.value is rw is default(Nil) ; \n has Node $.parent is rw ;\n has Node $.child is rw ; \n has Node $.prev is rw ; \n has Node $.next is rw ; \n has Int $.rank is rw is default(0) ; \n has Bool $.mark is rw is default(False) ; \n}\n\nmulti infix:<⪡>(vEle \\a, vEle \\b) { a le b } # custom defined 'less than'\n\nclass Heap { \n\n has Node $.root is rw ; \n\n method MakeHeap { self.root = Node.new } \n\n method Insert(vEle \\v) {\n my $x = Node.new: value => v;\n if self.root.value ~~ Nil {\n $x.next = $x;\n $x.prev = $x; \n self.root = $x\n } else {\n meld1(self.root, $x);\n self.root = $x if $x.value ⪡ self.root.value \n }\n return $x\n }\n\n method Union(Heap $h2) {\n if not self.root.defined {\n self.root = $h2.root\n } elsif $h2.root.defined { \t\t \n meld2(self.root, $h2.root);\n self.root = $h2.root if $h2.root.value ⪡ self.root.value \n }\n $h2.root = Nil;\n }\n\n method Minimum() {\n return unless self.root.defined; \n return self.root.value\n }\n\n method ExtractMin() {\n return Nil unless self.root.defined;\n my \\min = self.root.value;\n my %roots;\n\n sub add (Node \\r) {\n r.prev = r;\n r.next = r;\n loop {\n (defined my \\x = %roots{r.rank}) or last;\n %roots{r.rank}:delete;\n (r, x) = (x, r) if x.value ⪡ r.value ; \n x.parent = r ;\n x.mark = False ;\n if not r.child.defined {\n x.next = x;\n x.prev = x;\n r.child = x\n } else {\n meld1(r.child, x)\n }\n r.rank++\n }\n %roots{r.rank} = r ;\n }\n\n loop (my \\r = self.root.next ; not r ~~ self.root ; ) {\n my $n = r.next; \n add(r);\n r = $n ;\n }\n if defined (my \\c = self.root.child ) {\n c.parent = Nil;\n r = c.next;\n add(c);\n while not r ~~ c {\n my $n = r.next;\n r.parent = Nil;\n add(r);\n r = $n;\n }\n }\n \n unless %roots.defined {\n self.root = Nil;\n return min\n }\n my Node $mv = %roots{my $d = %roots.keys.first}; \n %roots{$d}:delete;\n $mv.next = $mv;\n $mv.prev = $mv;\n %roots.values.map: {\n $_.prev = $mv;\n $_.next = $mv.next;\n $mv.next.prev = $_;\n $mv.next = $_; \n $mv = $_ if $_.value ⪡ $mv.value \n }\n self.root = $mv;\n return min\n }\n\n\n method DecreaseKey(\\n, \\v) {\n die \"DecreaseKey new value greater than existing value\" if n.value ⪡ v;\n n.value = v; \n return Nil if n ~~ self.root;\n my \\p = n.parent;\n unless p.defined {\n self.root = n if v ⪡ self.root.value; \n return Nil \n }\n self.cutAndMeld(n);\n return Nil \n }\n\n method cutAndMeld(\\x) {\n self.cut(x);\n x.parent = Nil;\n meld1(self.root, x)\n }\n\n method cut(\\x) {\n my \\p = x.parent;\n return Nil unless p.defined;\n p.rank--;\n if p.rank == 0 {\n p.child = Nil\n } else {\n p.child = x.next;\n x.prev.next = x.next;\n x.next.prev = x.prev\n }\n return Nil unless p.parent.defined;\n unless p.mark {\n p.mark = True;\n return Nil\n }\n self.cutAndMeld(p)\n }\n \n method Delete(\\n) {\n my \\p = n.parent;\n if not p.defined {\n self.ExtractMin() and return if n ~~ self.root ; \n n.prev.next = n.next;\n n.next.prev = n.prev\n } else {\n self.cut(n)\n }\n my \\c = n.child;\n return Nil unless c.defined;\n loop ( c.parent = Nil, c = c.next ; c ~~ n.child ; c = c.next ) {} \n meld2(self.root, c)\n }\n\n method Vis() {\n\n if self.root.value ~~ Nil { say \"<empty>\" and return }\n\n sub f(Node $n, Str $pre) {\n loop ( my $pc = \"│ \", my $x = $n ; ; $x = $x.next) {\n if !($x.next ~~ $n) {\n print $pre, \"├─\"\n } else {\n print $pre, \"└─\";\n $pc = \" \"\n }\n if not $x.child.defined {\n say \"╴\", $x.value\n } else {\n say \"┐\", $x.value;\n f($x.child, $pre~$pc)\n }\n last if $x.next ~~ $n \n }\n }\n f(self.root, \"\")\n }\n}\n\nsub meld1(\\list, \\single) {\n list.prev.next = single;\n single.prev = list.prev;\n single.next = list;\n list.prev = single;\n}\n\nsub meld2(\\a, \\b) {\n a.prev.next = b;\n b.prev.next = a;\n ( a.prev, b.prev ) = ( b.prev, a.prev )\n}\n\nsay \"MakeHeap:\";\nmy $h = Heap.new; \n$h.MakeHeap;\n$h.Vis;\n\nsay \"\\nInsert:\";\n$h.Insert(\"cat\");\n$h.Vis;\n\nsay \"\\nUnion:\";\nmy $h2 = Heap.new; \n$h2.MakeHeap;\n$h2.Insert(\"rat\");\n$h.Union($h2);\n$h.Vis;\n\nsay \"\\nMinimum:\";\nmy \\m = $h.Minimum();\nsay m;\n\nsay \"\\nExtractMin:\";\n$h.Insert(\"bat\");\nmy $x = $h.Insert(\"meerkat\"); \nsay \"extracted: \", my $mm = $h.ExtractMin();\n$h.Vis;\n\nsay \"\\nDecreaseKey:\";\n$h.DecreaseKey($x, \"gnat\");\n$h.Vis;\n\nsay \"\\nDelete:\";\n$h.Insert(\"bobcat\");\n$h.Insert(\"bat\");\nsay \"deleting: \", $x.value;\n$h.Delete($x);\n$h.Vis;\n\n```\n\nOutput:\n\n```\nMakeHeap:\n<empty>\n\nInsert:\n└─╴cat\n\nUnion:\n├─╴cat\n└─╴rat\n\nMinimum:\ncat\n\nExtractMin:\nextracted: bat\n├─┐cat\n│ └─╴rat\n└─╴meerkat\n\nDecreaseKey:\n├─┐cat\n│ └─╴rat\n└─╴gnat\n\nDelete:\ndeleting: gnat\n├─╴bat\n├─╴bobcat\n└─┐cat\n └─╴rat\n```" } ]
[ { "role": "user", "content": "The **Fibonacci sequence** defined with matrix-exponentiation:\n\n: : : : : (\n\n 1\n\n 1\n\n\n 1\n\n 0\n )\n\n n\n =\n\n\n (\n\n F\n\n n\n +\n 1\n\n\n F\n\n n\n\n F\n\n n\n\n\n F\n\n n\n −\n 1\n )\n .\n {\\displaystyle {\\displaystyle {\\begin{pmatrix}1&1\\\\1&0\\end{pmatrix}}^{n}={\\begin{pmatrix}F\\_{n+1}&F\\_{n}\\\\F\\_{n}&F\\_{n-1}\\end{pmatrix}}.}}\n\nTask\n\nWrite a program using   *matrix exponentiation*   to generate Fibonacci(n) for   **n**   equal to:\n\n: : : * 10\n * 100\n * 1,000\n * 10,000\n * 100,000\n * 1,000,000\n * 10,000,000\n\nOnly display the first **20** decimal digits   and   the last **20** decimal digits of each Fibonacci number.\n\nExtra\n\nGenerate Fibonacci(216 ), Fibonacci(232) and Fibonacci(264) using the same method or another one.\n\nRelated tasks\n\n* Fibonacci sequence\n* Matrix-exponentiation operator" }, { "role": "assistant", "content": "(formerly Perl 6)\nFollowing the general approach of Sidef, and relying on Perl for `fibmod` function. Borrowed/adapted routines from Ramanujan's\\_constant task to allow `FatRat` calculations throughout. Does not quite meet task spec, as n^64 results not working yet.\n\n```\nuse Math::Matrix;\nuse Inline::Perl5;\nmy $p5 = Inline::Perl5.new();\n$p5.use( 'Math::AnyNum' );\n\nconstant D = 53; # set the size of FatRat calcluations\n\n# matrix exponentiation\nsub fibonacci ($n) {\n my $M = Math::Matrix.new( [[1,1],[1,0]] );\n ($M ** $n)[0][1]\n}\n\n# calculation of 𝑒\nsub postfix:<!> (Int $n) { (constant f = 1, |[\\×] 1..*)[$n] }\nsub 𝑒 (--> FatRat) { sum map { FatRat.new(1,.!) }, ^D }\n\n# calculation of π\nsub π (--> FatRat) {\n my ($a, $n, $g, $z, $pi) = 1, 1, sqrt(1/2.FatRat), 0.25;\n\n for ^5 {\n given [ ($a + $g)/2, sqrt $a × $g ] {\n $z -= (.[0] - $a)**2 × $n;\n $n += $n;\n ($a, $g) = @$_;\n $pi = ($a ** 2 / $z).substr: 0, 2 + D\n }\n }\n $pi.FatRat\n}\n\n# square-root: accepts/return FatRat\nmulti sqrt(FatRat $r --> FatRat) {\n FatRat.new: sqrt($r.nude[0] × 10**(D×2) div $r.nude[1]), 10**D\n}\n\n# square-root: accepts/return Int\nmulti sqrt(Int $n --> Int) {\n my $guess = 10**($n.chars div 2);\n my $iterator = { ( $^x + $n div ($^x) ) div 2 };\n my $endpoint = { $^x == $^y|$^z };\n min ($guess, $iterator … $endpoint)[*-1, *-2]\n}\n\n# arithmetic-geometric mean: accepts/returns FatRat\nsub AG-mean(FatRat $a is copy, FatRat $g is copy --> FatRat) {\n ($a, $g) = ($a + $g)/2, sqrt $a × $g until $a - $g < 10**-D;\n $a\n}\n\n# override built-in definitions with 'FatRat' versions\nconstant 𝑒 = &𝑒();\nconstant π = &π();\n\n# approximation of natural log, accepts any numeric, returns FatRat\nsub log-approx ($x --> FatRat) {\n constant ln2 = 2 * [+] (((1/3).FatRat**(2*$_+1))/(2*$_+1) for 0..D); # 1/3 = (2-1)/(2+1)\n π / (2 × AG-mean(1.FatRat, 2.FatRat**(2-D)/$x)) - D × ln2\n}\n\n# power function, with exponent less than zero: accepts/returns FatRat\nmulti infix:<**> (FatRat $base, FatRat $exp is copy where * < 0 --> FatRat) {\n constant ε = 10**-D;\n my ($low, $high) = 0.FatRat, 1.FatRat;\n my $mid = $high / 2;\n my $acc = my $sqr = sqrt($base);\n $exp = -$exp;\n\n while (abs($mid - $exp) > ε) {\n $sqr = sqrt($sqr);\n if ($mid <= $exp) { $low = $mid; $acc ×= $sqr }\n else { $high = $mid; $acc ×= 1/$sqr }\n $mid = ($low + $high) / 2\n }\n\n (1/$acc).substr(0, D).FatRat\n}\n\nsub binet_approx (Int $n --> FatRat) {\n constant PHI = sqrt(1.25.FatRat) + 0.5 ;\n constant IHP = -(sqrt(1.25.FatRat) - 0.5);\n $n × log-approx(PHI) - log-approx(PHI - IHP)\n}\n\nsub nth_fib_first_k_digits ($n,$k) {\n my $f = binet_approx($n);\n my $log10 = log-approx(10);\n floor( 𝑒**($f - $log10×(floor($f/$log10 + 1))) × 10**$k)\n}\n\nmy &nth_fib_last_k_digits =\n $p5.run('sub { my($n,$k) = @_; Math::AnyNum::fibmod($n, 10**$k) }');\n\n# matrix exponentiation is very inefficient, n^64 not feasible\nfor (16, 32) -> $n {\n my $f = fibonacci(2**$n);\n printf \"F(2^$n) = %s ... %s\\n\", substr($f,0,20), $f % 10**20\n}\n\n# this way is much faster, but not yet able to handle 2^64 case\nfor 16, 32 -> $n {\n my $first20 = nth_fib_first_k_digits(2**$n, 20);\n my $last20 = nth_fib_last_k_digits(2**$n, 20);\n printf \"F(2^$n) = %s ... %s\\n\", $first20, $last20\n}\n\n```\n\nOutput:\n\n```\nF(2^16) = 73199214460290552832 ... 97270190955307463227\nF(2^32) = 61999319689381859818 ... 39623735538208076347\nF(2^16) = 73199214460290552832 ... 97270190955307463227\nF(2^32) = 61999319689381859818 ... 39623735538208076347\n```" } ]
[ { "role": "user", "content": "These number series are an expansion of the ordinary Fibonacci sequence where:\n\n1. For \n\n n\n =\n 2\n {\\displaystyle {\\displaystyle n=2}}\n we have the Fibonacci sequence; with initial values \n\n [\n 1\n ,\n 1\n ]\n {\\displaystyle {\\displaystyle [1,1]}}\n and \n\n F\n\n k\n\n 2\n =\n\n F\n\n k\n −\n 1\n\n 2\n +\n\n F\n\n k\n −\n 2\n\n 2\n {\\displaystyle {\\displaystyle F\\_{k}^{2}=F\\_{k-1}^{2}+F\\_{k-2}^{2}}}\n2. For \n\n n\n =\n 3\n {\\displaystyle {\\displaystyle n=3}}\n we have the tribonacci sequence; with initial values \n\n [\n 1\n ,\n 1\n ,\n 2\n ]\n {\\displaystyle {\\displaystyle [1,1,2]}}\n and \n\n F\n\n k\n\n 3\n =\n\n F\n\n k\n −\n 1\n\n 3\n +\n\n F\n\n k\n −\n 2\n\n 3\n +\n\n F\n\n k\n −\n 3\n\n 3\n {\\displaystyle {\\displaystyle F\\_{k}^{3}=F\\_{k-1}^{3}+F\\_{k-2}^{3}+F\\_{k-3}^{3}}}\n3. For \n\n n\n =\n 4\n {\\displaystyle {\\displaystyle n=4}}\n we have the tetranacci sequence; with initial values \n\n [\n 1\n ,\n 1\n ,\n 2\n ,\n 4\n ]\n {\\displaystyle {\\displaystyle [1,1,2,4]}}\n and \n\n F\n\n k\n\n 4\n =\n\n F\n\n k\n −\n 1\n\n 4\n +\n\n F\n\n k\n −\n 2\n\n 4\n +\n\n F\n\n k\n −\n 3\n\n 4\n +\n\n F\n\n k\n −\n 4\n\n 4\n {\\displaystyle {\\displaystyle F\\_{k}^{4}=F\\_{k-1}^{4}+F\\_{k-2}^{4}+F\\_{k-3}^{4}+F\\_{k-4}^{4}}}\n \n ...\n4. For general \n\n n\n >\n 2\n {\\displaystyle {\\displaystyle n>2}}\n we have the Fibonacci \n\n n\n {\\displaystyle {\\displaystyle n}}\n -step sequence - \n\n F\n\n k\n\n n\n {\\displaystyle {\\displaystyle F\\_{k}^{n}}}\n ; with initial values of the first \n\n n\n {\\displaystyle {\\displaystyle n}}\n values of the \n\n (\n n\n −\n 1\n )\n {\\displaystyle {\\displaystyle (n-1)}}\n 'th Fibonacci \n\n n\n {\\displaystyle {\\displaystyle n}}\n -step sequence \n\n F\n\n k\n\n n\n −\n 1\n {\\displaystyle {\\displaystyle F\\_{k}^{n-1}}}\n ; and \n\n k\n {\\displaystyle {\\displaystyle k}}\n 'th value of this \n\n n\n {\\displaystyle {\\displaystyle n}}\n 'th sequence being \n\n F\n\n k\n\n n\n =\n\n ∑\n\n i\n =\n 1\n\n (\n n\n )\n\n\n F\n\n k\n −\n i\n\n (\n n\n )\n {\\displaystyle {\\displaystyle F\\_{k}^{n}=\\sum \\_{i=1}^{(n)}{F\\_{k-i}^{(n)}}}}\n\nFor small values of \n\nn\n{\\displaystyle {\\displaystyle n}}\n, Greek numeric prefixes are sometimes used to individually name each series.\n\n: : : : Fibonacci \n\n n\n {\\displaystyle {\\displaystyle n}}\n -step sequences\n\n | n {\\displaystyle {\\displaystyle n}} | Series name | Values |\n | --- | --- | --- |\n | 2 | fibonacci | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |\n | 3 | tribonacci | 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |\n | 4 | tetranacci | 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |\n | 5 | pentanacci | 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |\n | 6 | hexanacci | 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |\n | 7 | heptanacci | 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |\n | 8 | octonacci | 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |\n | 9 | nonanacci | 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |\n | 10 | decanacci | 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |\n\nAllied sequences can be generated where the initial values are changed:\n\n: **The Lucas series** sums the two preceding values like the fibonacci series for \n\n n\n =\n 2\n {\\displaystyle {\\displaystyle n=2}}\n but uses \n\n [\n 2\n ,\n 1\n ]\n {\\displaystyle {\\displaystyle [2,1]}}\n as its initial values.\n\nTask\n\n1. Write a function to generate Fibonacci \n\n n\n {\\displaystyle {\\displaystyle n}}\n -step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n2. Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\nRelated tasks\n\n* Fibonacci sequence\n* Wolfram Mathworld\n* Hofstadter Q sequence‎\n* Leonardo numbers\n\nAlso see\n\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Lazy List with Closure\n\n```\nsub nacci ( $s = 2, :@start = (1,) ) {\n my @seq = |@start, { state $n = +@start; @seq[ ($n - $s .. $n++ - 1).grep: * >= 0 ].sum } … *;\n}\n\nput \"{.fmt: '%2d'}-nacci: \", nacci($_)[^20] for 2..12 ;\n\nput \"Lucas: \", nacci(:start(2,1))[^20];\n\n```\n\nOutput:\n\n```\n 2-nacci: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765\n 3-nacci: 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 5768 10609 19513 35890 66012\n 4-nacci: 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 10671 20569 39648 76424 147312\n 5-nacci: 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 13624 26784 52656 103519 203513\n 6-nacci: 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 15109 29970 59448 117920 233904\n 7-nacci: 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 15808 31489 62725 124946 248888\n 8-nacci: 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 16128 32192 64256 128257 256005\n 9-nacci: 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 16272 32512 64960 129792 259328\n10-nacci: 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 16336 32656 65280 130496 260864\n11-nacci: 1 1 2 4 8 16 32 64 128 256 512 1024 2047 4093 8184 16364 32720 65424 130816 261568\n12-nacci: 1 1 2 4 8 16 32 64 128 256 512 1024 2048 4095 8189 16376 32748 65488 130960 261888\nLucas: 2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349\n```\n\n### Generative\n\nA slightly more straight forward way of constructing a lazy list.\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub fib ($n, @xs is copy = [1]) {\n flat gather {\n take @xs[*];\n loop {\n take my $x = [+] @xs;\n @xs.push: $x;\n @xs.shift if @xs > $n;\n }\n }\n}\n\nfor 2..10 -> $n {\n say fib($n, [1])[^20];\n}\nsay fib(2, [2,1])[^20];\n\n```" } ]
[ { "role": "user", "content": "The **Fibonacci sequence** is a sequence   Fn   of natural numbers defined recursively:\n\n```\n F0 = 0 \n F1 = 1 \n Fn = Fn-1 + Fn-2, if n>1 \n\n```\n\nTask\n\nWrite a function to generate the   nth   Fibonacci number.\n\nSolutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).\n\nThe sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:\n\n```\n Fn = Fn+2 - Fn+1, if n<0 \n\n```\n\nsupport for negative     n     in the solution is optional.\n\nRelated tasks\n\n* Fibonacci n-step number sequences‎\n* Leonardo numbers\n\nReferences\n\n* Wikipedia, Fibonacci number\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### List Generator\n\nThis constructs the fibonacci sequence as a lazy infinite list.\n\n```\nconstant @fib = 0, 1, *+* ... *;\n```\n\nIf you really need a function for it:\n\n```\nsub fib ($n) { @fib[$n] }\n```\n\nTo support negative indices:\n\n```\nconstant @neg-fib = 0, 1, *-* ... *;\nsub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }\n```\n\n### Iterative\n\n```\nsub fib (Int $n --> Int) {\n $n > 1 or return $n;\n my ($prev, $this) = 0, 1;\n ($prev, $this) = $this, $this + $prev for 1 ..^ $n;\n return $this;\n}\n```\n\n### Recursive\n\n```\nproto fib (Int $n --> Int) {*}\nmulti fib (0) { 0 }\nmulti fib (1) { 1 }\nmulti fib ($n) { fib($n - 1) + fib($n - 2) }\n```" } ]
[ { "role": "user", "content": "Fibonacci word.\n\nThe   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here:\n\n```\n Define   F_Word1   as   1\n Define   F_Word2   as   0\n Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01\n Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2\n\n```\n\nTask\n\nPerform the above steps for     n = 37.\n\nYou may display the first few but not the larger values of   n.\n \n{Doing so will get the task's author into trouble with them what be (again!).}\n\nInstead, create a table for   F\\_Words   **1**   to   **37**   which shows:\n\n: : * The number of characters in the word\n * The word's Entropy\n\nRelated tasks\n\n* Fibonacci word/fractal\n* Entropy\n* Entropy/Narcissist" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nconstant @fib-word = 1, 0, { $^b ~ $^a } ... *;\n \nsub entropy {\n -log(2) R/\n [+] map -> \\p { p * log p },\n $^string.comb.Bag.values »/» $string.chars\n}\nfor @fib-word[^37] {\n printf \"%5d\\t%10d\\t%.8e\\t%s\\n\",\n (state $n)++, .chars, .&entropy, $n > 10 ?? '' !! $_;\n}\n\n```\n\nThat works, but is terribly slow due to all the string processing and bag creation, just to count 0's and 1's. By contrast, the following prints the table up to 100 almost instantly by tracking the values to calculate entropy in parallel with the actual strings. This works in Raku because lazy lists are calculated on demand, so if we don't actually ask for the larger string forms, we don't calculate them. Which would be relatively difficult for a string containing 573147844013817084101 characters, unless you happen to have a computer with a zettabyte or so of memory sitting in your garage.\n\n```\nconstant @fib-word = '1', '0', { $^b ~ $^a } ... *;\nconstant @fib-ones = 1, 0, * + * ... *;\nconstant @fib-chrs = 1, 1, * + * ... *;\n \nmulti entropy(0) { 0 }\nmulti entropy(1) { 0 }\nmulti entropy($n) {\n my $chars = @fib-chrs[$n];\n my $ones = @fib-ones[$n];\n my $zeros = $chars - $ones;\n -log(2) R/\n [+] map -> \\p { p * log p },\n $ones / $chars, $zeros / $chars\n}\n\nfor 0..100 -> $n {\n printf \"%5d\\t%21d\\t%.15e\\t%s\\n\",\n\t $n, @fib-chrs[$n], entropy($n), $n > 9 ?? '' !! @fib-word[$n];\n}\n\n```\n\nOutput:\n\n```\n 0\t 1\t0.000000000000000e+00\t1\n 1\t 1\t0.000000000000000e+00\t0\n 2\t 2\t1.000000000000000e+00\t01\n 3\t 3\t9.182958340544895e-01\t010\n 4\t 5\t9.709505944546688e-01\t01001\n 5\t 8\t9.544340029249650e-01\t01001010\n 6\t 13\t9.612366047228759e-01\t0100101001001\n 7\t 21\t9.587118829771317e-01\t010010100100101001010\n 8\t 34\t9.596868937742167e-01\t0100101001001010010100100101001001\n 9\t 55\t9.593160320543776e-01\t0100101001001010010100100101001001010010100100101001010\n 10\t 89\t9.594579158386695e-01\t\n 11\t 144\t9.594037542210229e-01\t\n 12\t 233\t9.594244469559866e-01\t\n 13\t 377\t9.594165437404406e-01\t\n 14\t 610\t9.594195626031441e-01\t\n 15\t 987\t9.594184095152244e-01\t\n 16\t 1597\t9.594188499578099e-01\t\n 17\t 2584\t9.594186817240321e-01\t\n 18\t 4181\t9.594187459836640e-01\t\n 19\t 6765\t9.594187214386754e-01\t\n 20\t 10946\t9.594187308140276e-01\t\n 21\t 17711\t9.594187272329618e-01\t\n 22\t 28657\t9.594187286008074e-01\t\n 23\t 46368\t9.594187280783370e-01\t\n 24\t 75025\t9.594187282779029e-01\t\n 25\t 121393\t9.594187282016755e-01\t\n 26\t 196418\t9.594187282307919e-01\t\n 27\t 317811\t9.594187282196701e-01\t\n 28\t 514229\t9.594187282239183e-01\t\n 29\t 832040\t9.594187282222958e-01\t\n 30\t 1346269\t9.594187282229156e-01\t\n 31\t 2178309\t9.594187282226789e-01\t\n 32\t 3524578\t9.594187282227692e-01\t\n 33\t 5702887\t9.594187282227345e-01\t\n 34\t 9227465\t9.594187282227477e-01\t\n 35\t 14930352\t9.594187282227427e-01\t\n 36\t 24157817\t9.594187282227447e-01\t\n 37\t 39088169\t9.594187282227441e-01\t\n 38\t 63245986\t9.594187282227441e-01\t\n 39\t 102334155\t9.594187282227441e-01\t\n 40\t 165580141\t9.594187282227441e-01\t\n 41\t 267914296\t9.594187282227441e-01\t\n 42\t 433494437\t9.594187282227441e-01\t\n 43\t 701408733\t9.594187282227441e-01\t\n 44\t 1134903170\t9.594187282227441e-01\t\n 45\t 1836311903\t9.594187282227441e-01\t\n 46\t 2971215073\t9.594187282227441e-01\t\n 47\t 4807526976\t9.594187282227441e-01\t\n 48\t 7778742049\t9.594187282227441e-01\t\n 49\t 12586269025\t9.594187282227441e-01\t\n 50\t 20365011074\t9.594187282227441e-01\t\n 51\t 32951280099\t9.594187282227441e-01\t\n 52\t 53316291173\t9.594187282227441e-01\t\n 53\t 86267571272\t9.594187282227441e-01\t\n 54\t 139583862445\t9.594187282227441e-01\t\n 55\t 225851433717\t9.594187282227441e-01\t\n 56\t 365435296162\t9.594187282227441e-01\t\n 57\t 591286729879\t9.594187282227441e-01\t\n 58\t 956722026041\t9.594187282227441e-01\t\n 59\t 1548008755920\t9.594187282227441e-01\t\n 60\t 2504730781961\t9.594187282227441e-01\t\n 61\t 4052739537881\t9.594187282227441e-01\t\n 62\t 6557470319842\t9.594187282227441e-01\t\n 63\t 10610209857723\t9.594187282227441e-01\t\n 64\t 17167680177565\t9.594187282227441e-01\t\n 65\t 27777890035288\t9.594187282227441e-01\t\n 66\t 44945570212853\t9.594187282227441e-01\t\n 67\t 72723460248141\t9.594187282227441e-01\t\n 68\t 117669030460994\t9.594187282227441e-01\t\n 69\t 190392490709135\t9.594187282227441e-01\t\n 70\t 308061521170129\t9.594187282227441e-01\t\n 71\t 498454011879264\t9.594187282227441e-01\t\n 72\t 806515533049393\t9.594187282227441e-01\t\n 73\t 1304969544928657\t9.594187282227441e-01\t\n 74\t 2111485077978050\t9.594187282227441e-01\t\n 75\t 3416454622906707\t9.594187282227441e-01\t\n 76\t 5527939700884757\t9.594187282227441e-01\t\n 77\t 8944394323791464\t9.594187282227441e-01\t\n 78\t 14472334024676221\t9.594187282227441e-01\t\n 79\t 23416728348467685\t9.594187282227441e-01\t\n 80\t 37889062373143906\t9.594187282227441e-01\t\n 81\t 61305790721611591\t9.594187282227441e-01\t\n 82\t 99194853094755497\t9.594187282227441e-01\t\n 83\t 160500643816367088\t9.594187282227441e-01\t\n 84\t 259695496911122585\t9.594187282227441e-01\t\n 85\t 420196140727489673\t9.594187282227441e-01\t\n 86\t 679891637638612258\t9.594187282227441e-01\t\n 87\t 1100087778366101931\t9.594187282227441e-01\t\n 88\t 1779979416004714189\t9.594187282227441e-01\t\n 89\t 2880067194370816120\t9.594187282227441e-01\t\n 90\t 4660046610375530309\t9.594187282227441e-01\t\n 91\t 7540113804746346429\t9.594187282227441e-01\t\n 92\t 12200160415121876738\t9.594187282227441e-01\t\n 93\t 19740274219868223167\t9.594187282227441e-01\t\n 94\t 31940434634990099905\t9.594187282227441e-01\t\n 95\t 51680708854858323072\t9.594187282227441e-01\t\n 96\t 83621143489848422977\t9.594187282227441e-01\t\n 97\t135301852344706746049\t9.594187282227441e-01\t\n 98\t218922995834555169026\t9.594187282227441e-01\t\n 99\t354224848179261915075\t9.594187282227441e-01\t\n 100\t573147844013817084101\t9.594187282227441e-01\n```" } ]
[ { "role": "user", "content": "The Fibonacci word may be represented as a fractal as described here:\n \n \n(Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)\n\n: For F\\_wordm start with F\\_wordCharn=1\n: Draw a segment forward\n: If current F\\_wordChar is 0\n\n : Turn left if n is even\n : Turn right if n is odd\n: next n and iterate until end of F\\_word\n\nTask\n\nCreate and display a fractal similar to Fig 1.\n \n \n(Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nconstant @fib-word = '1', '0', { $^b ~ $^a } ... *;\n\nsub MAIN($m = 17, $scale = 3) {\n (my %world){0}{0} = 1;\n my $loc = 0+0i;\n my $dir = i;\n my $n = 1;\n\n for @fib-word[$m].comb {\n when '0' {\n step;\n if $n %% 2 { turn-left }\n else { turn-right; }\n }\n $n++;\n }\n\n braille-graphics %world;\n\n sub step {\n for ^$scale {\n $loc += $dir;\n %world{$loc.im}{$loc.re} = 1;\n }\n }\n\n sub turn-left { $dir *= i; }\n sub turn-right { $dir *= -i; }\n\n}\n\nsub braille-graphics (%a) {\n my ($ylo, $yhi, $xlo, $xhi);\n for %a.keys -> $y {\n\t$ylo min= +$y; $yhi max= +$y;\n\tfor %a{$y}.keys -> $x {\n\t $xlo min= +$x; $xhi max= +$x;\n\t}\n }\n\n for $ylo, $ylo + 4 ...^ * > $yhi -> \\y {\n\tfor $xlo, $xlo + 2 ...^ * > $xhi -> \\x {\n\t my $cell = 0x2800;\n\t $cell += 1 if %a{y + 0}{x + 0};\n\t $cell += 2 if %a{y + 1}{x + 0};\n\t $cell += 4 if %a{y + 2}{x + 0};\n\t $cell += 8 if %a{y + 0}{x + 1};\n\t $cell += 16 if %a{y + 1}{x + 1};\n\t $cell += 32 if %a{y + 2}{x + 1};\n\t $cell += 64 if %a{y + 3}{x + 0};\n\t $cell += 128 if %a{y + 3}{x + 1};\n\t print chr($cell);\n\t}\n\tprint \"\\n\";\n }\n}\n\n```\n\nOutput:\n\n```\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢈⣉⡁⠀⠀⠀⢈⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⢀⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠸⠤⡄⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⢰⠒⡆⢰⠒⠃⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⣏⣉⠀⣉⣉⠀⠀⠀⠀⣉⣉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣉⣉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠈⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣸⠉⣇⣀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⢤⠀⡤⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⡖⢲⠀⡖⠚⠀⠓⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢈⣉⡁⠀⠀⠀⢈⣉⡁⢈⣉⡇⢸⣉⡁⢈⣉⡁⠀⠀⠀⢈⣉⡁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢈⣉⡁⠀⠀⠀⢈⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠧⢤⠀⡤⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢹⣀⡏⠉⠀⠉⢹⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⡄⠀⠀⠀⢠⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⡖⠚⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⣀⣀⠀⣉⣹⠀⣏⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⣀⣀⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⠇⠀⠀⠀⠸⠤⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⢰⠒⠃⠘⠒⡆⢰⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⢰⠒⠃⠘⠒⡆⢰⠒⡆⠀⠀⠀⢰⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣉⠀⠀⠀⠀⣉⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣉⠀⠀⠀⠀⣉⣉⠀⣉⣹⠀⣏⣉⠀⣉⣉⠀⠀⠀⠀⣀⣀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⡄⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⢰⠒⠃⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⢈⣉⡇⢸⣉⡁⢀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⢈⣉⡇⢸⣉⡁⢀⣀⡀⠀⠀⠀⢀⣀⡀⢈⣉⡇⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⡖⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⡖⢲⠀⡖⠚⠀⠓⢲⠀⡖⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⠀⠀⢈⣉⡁⢈⣉⡇⢸⣉⡁⢈⣉⡁⠀⠀⠀⢀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⠀⠀⢈⣉⡁⢈⣉⡇⢸⣉⡁⢈⣉⡁⠀⠀⠀⢈⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠧⢤⠀⡤⠼⠀⠧⢤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠧⢤⠀⡤⠼⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⡖⠚⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢹⣀⡏⠉⠀⠉⢹⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠤⡄⠀⠀⠀⢠⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⠚⠀⠓⢲⠀⡖⠚⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⣀⣀⠀⣉⣹⠀⣏⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⢠⠤⠇⠸⠤⠇⠀⠀⠀⠸⠤⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⠀⠀⠀⢰⠒⡆⢰⠒⠃⠘⠒⡆⢰⠒⡆⠀⠀⠀⢰⠒⡆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⠀⠀⠀⢰⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⠉⠉⠀⠀⠀⠀⠉⠉⠀⣉⣹⠀⣏⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⢤⠀⡤⠼⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⠃⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⣇⣀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣸⠉⣇⣸⠉⠁⠈⠉⣇⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⢤⠀⡤⢤⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⢰⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠒⠃⠘⠒⡆⢰⠒⠃⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⢀⣀⡀⢈⣉⡇⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⡤⠼⠀⠧⠼⠀⠀⠀⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠧⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠓⢲⠀⡖⢲⠀⠀⠀⠀⡖⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡖⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠈⠉⠁⢈⣉⡇⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣉⡁⢈⣉⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠸⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡏⢹⣀⡏⠉⠀⠉⢹⣀⡏⢹⣀⡀⢀⣀⡏⢹⣀⡏⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⢠⠤⠇⠸⠤⡄⢠⠤⡄⠀⠀⠀⢠⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⠚⠀⠀⠀⠀⠓⠚⠀⠓⢲⠀⡖⠚⠀⠓⢲⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⣀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠤⠇⠀⠀⠀⠸⠤⠇⠸⠤⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⡆⠀⠀⠀⢰⠒⡆⢰⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣏⣉⠀⣉⣹⠀⣏⣉⠀⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⢤⠀⡤⠼⠀⠧⢤⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⠒⠃⠘⠒⠃⠀⠀⠀⠘⠒⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⣇⣸⠉⣇⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡤⠼⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠃\n```" } ]
[ { "role": "user", "content": "Filename extensions are a rudimentary but commonly used way of identifying files types.\n\nTask\n\nGiven an arbitrary filename and a list of extensions, tell whether the filename has one of those extensions.\n\nNotes:\n\n* The check should be case insensitive.\n* The extension must occur at the very end of the filename, and be immediately preceded by a dot (`.`).\n* You may assume that none of the given extensions are the empty string, and none of them contain a dot. Other than that they may be arbitrary strings.\n\n*Extra credit:*\n: Allow extensions to contain dots. This way, users of your function/program have full control over what they consider as the extension in cases like:\n\n```\n archive.tar.gz\n\n```\n\n: Please state clearly whether or not your solution does this.\n\nTest cases\n\nThe following test cases all assume this list of extensions:   `zip`, `rar`, `7z`, `gz`, `archive`, `A##`\n\n: : : : : : : : | Filename | Result |\n | --- | --- |\n | `MyData.a##` | true |\n | `MyData.tar.Gz` | true |\n | `MyData.gzip` | false |\n | `MyData.7z.backup` | false |\n | `MyData...` | false |\n | `MyData` | false |\n\nIf your solution does the extra credit requirement, add `tar.bz2` to the list of extensions, and check the following additional test cases:\n\n: : : : : : : : | Filename | Result |\n | --- | --- |\n | `MyData_v1.0.tar.bz2` | true |\n | `MyData_v1.0.bz2` | false |\n\nMotivation\n\nChecking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension *(see e.g. `FileNameExtensionFilter` in Java)*.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the Extract file extension task.\n\nRelated tasks\n\n* Extract file extension\n* String matching" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nDoes the extra credit requirement.\n\n```\nsub check-extension ($filename, *@extensions) {\n so $filename ~~ /:i '.' @extensions $/\n}\n\n# Testing:\n\nmy @extensions = <zip rar 7z gz archive A## tar.bz2>;\nmy @files= <\n MyData.a## MyData.tar.Gz MyData.gzip MyData.7z.backup MyData... MyData\n MyData_v1.0.tar.bz2 MyData_v1.0.bz2\n>;\nsay \"{$_.fmt: '%-19s'} - {check-extension $_, @extensions}\" for @files;\n\n```\n\nOutput:\n\n```\nMyData.a## - True\nMyData.tar.Gz - True\nMyData.gzip - False\nMyData.7z.backup - False\nMyData... - False\nMyData - False\nMyData_v1.0.tar.bz2 - True\nMyData_v1.0.bz2 - False\n\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a file called   \"output.txt\",   and place in it the contents of the file   \"input.txt\",   *via an intermediate variable*.\n\nIn other words, your program will demonstrate:\n\n: : 1. how to read from a file into a variable\n 2. how to write a variable's contents into a file\n\nOneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nIf it is okay to have a temporary copy of the entire file in memory:\n\n**Works with**: Rakudo version 2016.07\n\n```\nspurt \"output.txt\", slurp \"input.txt\";\n```\n\nOtherwise, copying line-by line:\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy $in = open \"input.txt\";\nmy $out = open \"output.txt\", :w;\nfor $in.lines -> $line {\n $out.say: $line;\n}\n$in.close;\n$out.close;\n```" } ]
[ { "role": "user", "content": "Task\n\nGet and set the modification time of a file." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nuse NativeCall;\n\nclass utimbuf is repr('CStruct') {\n has int $.actime;\n has int $.modtime;\n\n submethod BUILD(:$atime, :$mtime) {\n $!actime = $atime;\n $!modtime = $mtime.to-posix[0].round;\n }\n}\n\nsub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}\n\nsub MAIN (Str $file) {\n my $mtime = $file.IO.modified orelse .die;\n\n my $ubuff = utimbuf.new(:atime(time),:mtime($mtime));\n\n sysutime($file, $ubuff);\n}\n\n```\n\nSets the last access time to now,\nwhile restoring the modification time to what it was before." } ]
[ { "role": "user", "content": "Verify the size of a file called     **input.txt**     for a file in the current working directory, and another one in the file system root." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsay 'input.txt'.IO.s;\nsay '/input.txt'.IO.s;\n\n```\n\nCross-platform version of the second one:\n\n```\nsay $*SPEC.rootdir.IO.child(\"input.txt\").s;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nBeginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.\n\nMy suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.\n\nDon't forget that empty files may exist, to serve as a marker.\n\nIs your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\nBy default, process the current and all readable sub-directories, or, pass in a directory path at the command line.\n\n```\nsub MAIN($dir = '.') {\n sub log10 (Int $s) { $s ?? $s.log(10).Int !! 0 }\n my %fsize;\n my @dirs = $dir.IO;\n while @dirs {\n for @dirs.pop.dir -> $path {\n %fsize{$path.s.&log10}++ if $path.f;\n @dirs.push: $path if $path.d and $path.r\n }\n }\n my $max = %fsize.values.max;\n my $bar-size = 80;\n say \"File size distribution in bytes for directory: $dir\\n\";\n for 0 .. %fsize.keys.max {\n say sprintf( \"# Files @ %5sb %8s: \", $_ ?? \"10e{$_-1}\" !! 0, %fsize{$_} // 0 ),\n histogram( $max, %fsize{$_} // 0, $bar-size )\n }\n say %fsize.values.sum, ' total files.';\n}\n\nsub histogram ($max, $value, $width = 60) {\n my @blocks = <| ▏ ▎ ▍ ▌ ▋ ▊ ▉ █>;\n my $scaled = ($value * $width / $max).Int;\n my ($end, $bar) = $scaled.polymod(8);\n (@blocks[8] x $bar * 8) ~ (@blocks[$end] if $end) ~ \"\\n\"\n}\n\n```\n\nOutput:\n\n```\nFile size distribution in bytes for directory: /home\n\n# Files @ 0b 989: ▏\n\n# Files @ 10e0b 6655: ████████\n\n# Files @ 10e1b 31776: ████████████████████████████████████████\n\n# Files @ 10e2b 63165: ████████████████████████████████████████████████████████████████████████████████\n\n# Files @ 10e3b 19874: ████████████████████████▏\n\n# Files @ 10e4b 7730: ████████▏\n\n# Files @ 10e5b 3418: ▌\n\n# Files @ 10e6b 1378: ▏\n\n# Files @ 10e7b 199:\n\n# Files @ 10e8b 45:\n\n135229 total files.\n```" } ]
[ { "role": "user", "content": "Task\n\nSelect certain elements from an Array into a new Array in a generic way.\n\nTo demonstrate, select all even numbers from an Array.\n\nAs an option, give a second solution which filters destructively,\nby modifying the original Array rather than creating a new Array." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nmy @a = 1..6;\nmy @even = grep * %% 2, @a;\n```\n\nAlternatively:\n\n```\nmy @a = 1..6;\nmy @even = @a.grep(* %% 2);\n```\n\nDestructive:\n\n```\nmy @a = 1..6;\n@a .= grep(* %% 2);\n```" } ]
[ { "role": "user", "content": "Task\n\nFind adjacent primes under **1,000,000** whose difference **(> 36)** is a square integer." }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\nuse Math::Primesieve;\n\nmy $iterator = Math::Primesieve::iterator.new;\nmy $limit = 1e10;\nmy @squares = (1..30).map: *²;\nmy $last = 2;\nmy @gaps;\nmy @counts;\n\nloop {\n my $this = (my $p = $iterator.next) - $last;\n quietly @gaps[$this].push($last) if +@gaps[$this] < 10;\n @counts[$this]++;\n last if $p > $limit;\n $last = $p;\n}\n\nprint \"Adjacent primes up to {comma $limit.Int} with a gap value that is a perfect square:\";\nfor @gaps.pairs.grep: { (.key ∈ @squares) && .value.defined} -> $p {\n my $ten = (@counts[$p.key] > 10) ?? ', (first ten)' !! '';\n say \"\\nGap {$p.key}: {comma @counts[$p.key]} found$ten:\";\n put join \"\\n\", $p.value.batch(5)».map({\"($_, {$_+ $p.key})\"})».join(', ');\n}\n\n```\n\nOutput:\n\n```\nAdjacent primes up to 10,000,000,000 with a gap value that is a perfect square:\nGap 1: 1 found:\n(2, 3)\n\nGap 4: 27,409,998 found, (first ten):\n(7, 11), (13, 17), (19, 23), (37, 41), (43, 47)\n(67, 71), (79, 83), (97, 101), (103, 107), (109, 113)\n\nGap 16: 15,888,305 found, (first ten):\n(1831, 1847), (1933, 1949), (2113, 2129), (2221, 2237), (2251, 2267)\n(2593, 2609), (2803, 2819), (3121, 3137), (3373, 3389), (3391, 3407)\n\nGap 36: 11,593,345 found, (first ten):\n(9551, 9587), (12853, 12889), (14107, 14143), (15823, 15859), (18803, 18839)\n(22193, 22229), (22307, 22343), (22817, 22853), (24281, 24317), (27143, 27179)\n\nGap 64: 1,434,957 found, (first ten):\n(89689, 89753), (107377, 107441), (288583, 288647), (367957, 368021), (381103, 381167)\n(400759, 400823), (445363, 445427), (623107, 623171), (625699, 625763), (637003, 637067)\n\nGap 100: 268,933 found, (first ten):\n(396733, 396833), (838249, 838349), (1313467, 1313567), (1648081, 1648181), (1655707, 1655807)\n(2345989, 2346089), (2784373, 2784473), (3254959, 3255059), (3595489, 3595589), (4047157, 4047257)\n\nGap 144: 35,563 found, (first ten):\n(11981443, 11981587), (18687587, 18687731), (20024339, 20024483), (20388583, 20388727), (21782503, 21782647)\n(25507423, 25507567), (27010003, 27010147), (28716287, 28716431), (31515413, 31515557), (32817493, 32817637)\n\nGap 196: 1,254 found, (first ten):\n(70396393, 70396589), (191186251, 191186447), (208744777, 208744973), (233987851, 233988047), (288568771, 288568967)\n(319183093, 319183289), (336075937, 336076133), (339408151, 339408347), (345247753, 345247949), (362956201, 362956397)\n\nGap 256: 41 found, (first ten):\n(1872851947, 1872852203), (2362150363, 2362150619), (2394261637, 2394261893), (2880755131, 2880755387), (2891509333, 2891509589)\n(3353981623, 3353981879), (3512569873, 3512570129), (3727051753, 3727052009), (3847458487, 3847458743), (4008610423, 4008610679)\n```" } ]
[ { "role": "user", "content": "As described on the **Chess960** page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory \"book knowledge\". That task is to generate legal starting positions, and some of the solutions accept a standard Starting Position Identifier number (\"SP-ID\"), and generate the corresponding position.\n\nTask\n\nThis task is to go the other way: given a starting array of pieces (provided in any form that suits your implementation, whether string or list or array, of letters or Unicode chess symbols or enum values, etc.), derive its unique SP-ID. For example, given the starting array **QNRBBNKR** (or **♕♘♖♗♗♘♔♖** or **♛♞♜♝♝♞♚♜**), which we assume is given as seen from White's side of the board from left to right, your (sub)program should return 105; given the starting lineup of standard chess, it should return 518.\n\nYou may assume the input is a valid Chess960 position; detecting invalid input (including illegal characters or starting arrays with the bishops on the same color square or the king not between the two rooks) is optional.\n\nAlgorithm\n\nThe derivation is the inverse of the algorithm given at Wikipedia, and goes like this (we'll use the standard chess setup as an example).\n\n1. Ignoring the Queen and Bishops, find the positions of the Knights within the remaining five spaces (in the standard array they're in the second and fourth positions), and then find the index number of that combination. There's a table at the above Wikipedia article, but it's just the possible positions sorted left to right and numbered 0 to 9: 0=**NN---**, 1=**N-N--**, 2=**N--N-**, 3=**N---N**, 4=**-NN--**, etc; our pair is combination number 5. Call this number N. **N=5**\n\n2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces; number them 0..5 from left to right and call the index of the Queen's position Q. In our example, **Q=2**.\n\n3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares. It's important to note here that the board in chess is placed such that the leftmost position on the home row is on a dark square and the rightmost a light. So if we number the squares of each color 0..3 from left to right, the dark bishop in the standard position is on square 1 (**D=1**), and the light bishop is on square 2 (**L=2**).\n\n4. Then the position number is given by **4(4(6N + Q)+D)+L**, which reduces to **96N + 16Q + 4D + L**. In our example, that's 96×5 + 16×2 + 4×1 + 2 = 480 + 32 + 4 + 2 = 518.\n\nNote that an earlier iteration of this page contained an incorrect description of the algorithm which would give the same SP-ID for both of the following two positions.\n\n```\n RQNBBKRN = 601\n RNQBBKRN = 617\n\n```" }, { "role": "assistant", "content": "```\nsub c960-spid($array) {\n # standardize on letters for easier processing\n my $ascii = $array.trans('♜♞♝♛♚♖♘♗♕♔' => 'RNBQK');\n\n # error-checking\n my %Names = <Q Queen K King R Rook N Knight B Bishop>;\n return 'Illegal position: should have exactly eight pieces' unless 8 == $ascii.chars;\n return 'Illegal position: Bishops not on opposite colors.' unless 1 == sum $ascii.indices('B').map(* % 2);\n return 'Illegal position: King not between rooks.' unless $ascii ~~ /'R' .* 'K' .* 'R'/;\n for <K 1 Q 1 B 2 N 2 R 2> -> $piece, $count {\n return \"Illegal position: should have exactly $count %Names{$piece}\\(s\\)\\n\" unless $count == $ascii.indices($piece)\n }\n\n # Work backwards through the placement rules.\n # King and rooks are forced during placement, so ignore them. \n\n # 1. Figure out which knight combination was used:\n my @knights = $ascii.subst(/<[QB]>/, '', :g).indices('N');\n my $knight = combinations(5,2).kv.grep( -> $i, @c { @c eq @knights } ).flat.first;\n\n # 2. Then which queen position:\n my $queen = $ascii.subst('B', '', :g).index('Q'); \n\n # 3. Finally the two bishops:\n my @bishops = $ascii.indices('B');\n my ($dark,$light) = (@bishops.first %% 2 ?? @bishops !! @bishops.reverse) Xdiv 2;\n\n $ascii.trans('RNBQK' => '♖♘♗♕♔') ~ ' ' ~ 4 × (4 × (6 × $knight + $queen) + $dark) + $light;\n}\n\nsay .&c960-spid for <♖♘♗♕♔♗♘♖ ♛♞♜♝♝♞♚♜ RQNBBKRN RNQBBKRN QNBRBNKR>;\n\n```\n\nOutput:\n\n```\n♖♘♗♕♔♗♘♖ 518\n♕♘♖♗♗♘♔♖ 105\n♖♕♘♗♗♔♖♘ 601\n♖♘♕♗♗♔♖♘ 617\nIllegal position: Bishops not on opposite colors.\n```" } ]
[ { "role": "user", "content": "Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.\n\nTest your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:\n\n```\n '/home/user1/tmp/coverage/test'\n '/home/user1/tmp/covert/operator'\n '/home/user1/tmp/coven/members'\n\n```\n\nNote: The resultant path should be the valid directory `'/home/user1/tmp'` and not the longest common string `'/home/user1/tmp/cove'`.\n\nIf your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $sep = '/';\nmy @dirs = </home/user1/tmp/coverage/test\n /home/user1/tmp/covert/operator\n /home/user1/tmp/coven/members>;\n\nmy @comps = @dirs.map: { [ .comb(/ $sep [ <!before $sep> . ]* /) ] }; \n\nmy $prefix = '';\n\nwhile all(@comps[*]»[0]) eq @comps[0][0] {\n $prefix ~= @comps[0][0] // last;\n @comps».shift;\n}\n\nsay \"The longest common path is $prefix\";\n\n```\n\nOutput:\n\n```\nThe longest common path is /home/user1/tmp\n\n```\n\nIf you'd prefer a pure FP solution without side effects, you can use this:\n\n```\nmy $sep := '/';\nmy @dirs := </home/user1/tmp/coverage/test\n /home/user1/tmp/covert/operator\n /home/user1/tmp/coven/members>;\n\nmy @comps = @dirs.map: { [ .comb(/ $sep [ <!before $sep> . ]* /) ] };\n\nsay \"The longest common path is \",\n gather for 0..* -> $column {\n last unless all(@comps[*]»[$column]) eq @comps[0][$column];\n take @comps[0][$column] // last;\n }\n\n```\n\nOr here's another factoring, that focuses on building the result with cumulative sequences and getting the solution with `first`:\n\n```\nmy $sep = '/';\nmy @dirs = </home/user1/tmp/coverage/test\n /home/user1/tmp/covert/operator\n /home/user1/tmp/coven/members>;\n\nsub is_common_prefix { so $^prefix eq all(@dirs).substr(0, $prefix.chars) }\n\nsay ([\\~] @dirs.comb(/ $sep [ <!before $sep> . ]* /)).reverse.first: &is_common_prefix\n\n```" } ]
[ { "role": "user", "content": "In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion.\n\nTask\n\nCreate a program which, given a minimum size and a folder/directory, will find all files of at least *size* bytes with duplicate contents under the directory and output or show the sets of duplicate files in order of decreasing size.\n\nThe program may be command-line or graphical, and duplicate content may be determined by direct comparison or by calculating a hash of the data.\n\nSpecify which filesystems or operating systems your program works with if it has any filesystem- or OS-specific requirements.\n\nIdentify hard links (filenames referencing the same content) in the output if applicable for the filesystem.\n\nFor extra points, detect when whole directory sub-trees are identical, or optionally remove or link identical files." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis implementation takes a starting directory (defaults to the current directory) and has a few flags to set behaviour: --minsize, minimum file size to look at, defaults to 5 bytes; and --recurse, recurse into the directory structure, default True. It finds files of the same size, calculates hashes to compare, then reports files that hash the same.\n\n```\nuse Digest::SHA256::Native;\n\nsub MAIN( $dir = '.', :$minsize = 5, :$recurse = True ) {\n my %files;\n my @dirs = $dir.IO.absolute.IO;\n while @dirs {\n my @files = @dirs.pop;\n while @files {\n for @files.pop.dir -> $path {\n %files{ $path.s }.push: $path if $path.f and $path.s >= $minsize;\n @dirs.push: $path if $path.d and $path.r and $recurse\n }\n }\n }\n\n for %files.sort( +*.key ).grep( *.value.elems > 1)».kv -> ($size, @list) {\n my %dups;\n @list.map: { %dups{ sha256-hex( ($_.slurp :bin).decode ) }.push: $_.Str };\n for %dups.grep( *.value.elems > 1)».value -> @dups {\n say sprintf(\"%9s : \", scale $size ), @dups.join(', ');\n }\n }\n}\n\nsub scale ($bytes) {\n given $bytes {\n when $_ < 2**10 { $bytes ~ ' B' }\n when $_ < 2**20 { ($bytes / 2**10).round(.1) ~ ' KB' }\n when $_ < 2**30 { ($bytes / 2**20).round(.1) ~ ' MB' }\n default { ($bytes / 2**30).round(.1) ~ ' GB' }\n }\n}\n\n```\n\nSample output:\n\nPassing in command line switches: --minsize=0 --recurse=False /home/me/p6\n\n```\n 0 B : /home/me/p6/vor.ppm, /home/me/p6/ns.txt\n 190 B : /home/me/p6/scrub(copy).t, /home/me/p6/scrub.t\n 1.3 KB : /home/me/p6/coco.p6, /home/me/p6/coc.p6\n 80.5 KB : /home/me/p6/temp.txt, /home/me/p6/temp.html\n279.6 KB : /home/me/p6/pentaflake.svg, /home/me/p6/5nflake.svg\n```" } ]
[ { "role": "user", "content": "*Clarification: This task is asking for the position of two bits in the binary representation of a positive integer. Some parts of this task assume that this is the native representation in the language you are working in. Any part of this task which makes assumptions about native representation should be treated as a recommendation which is only relevant in some contexts. A bit is defined as the exponent in a binary polynomial -- an exponent corresponding to a power of 2 which has a non-zero multiplier in the summation sequence of powers of two which yields the desired positive integer, where the only allowed coefficients are 0 and 1.*\n\nDefine routines (or operators) **lwb** and **upb** that find the *first* and *last* set bit in a binary value. Implement using a binary search to find the location of the particular upper/lower bit.\n\nAlso: Define the reverse routines (or operators) **rlwb** and **rupb** that find host's *positive integers* least- and most-significant set bit in a binary value expressed in LSB 0 bit numbering, i.e. indexed from the extreme right bit.\n\nUse primarily **bit** operations, such as **and**, **or**, and bit shifting. Avoid additions, multiplications and especially avoid divisions.\n\nTwo implementations\n\n1. For the host word size on the host platform, implement the routine \"efficiently\" in without looping or recursion.\n2. For the extended precision/long word implement the algorithm more generally - maybe as a template, and maybe with looping - so that any *bits width* for a binary type can be accommodated.\n\nTest cases\n\n1. For the host machine word size: Use the powers of 42 up to host's the \"natural\" word size to calculate the index of the first and last set bit.\n2. For the extended precision: Use the powers of 1302 up to the host's next \"natural\" **long** host *word* size to calculate the index of the first and last set bit.\n3. Output bit indexes in LSB 0 bit numbering.\n\nAdditionally\n\nIn a particular language, there maybe (at least) two alternative approaches of calculating the required values:\n\n* Using an external library.\n* Using a built-in library.\n\nIf any of these approaches are available, then *also* note the library or built-in name.\n\nSee also\n\n* Find the log base 2 of an N-bit integer in O(lg(N)) operations\n* 80386 Instruction Set - BSF -- Bit Scan Forward" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nRaku integers are arbitrary sized, and the lsb and msb methods are built-in.\n\n```\nsub table ($base,$power) {\n my $digits = ($base ** $power).chars;\n printf \"%{$digits}s lsb msb\\n\", 'number';\n for 0..$power {\n\tmy $x = $base ** $_;\n\tprintf \"%{$digits}d %2d %2d\\n\", $x, $x.lsb, $x.msb;\n }\n}\n\ntable 42, 20;\ntable 1302, 20;\n\n```\n\nOutput:\n\n```\n number lsb msb\n 1 0 0\n 42 1 5\n 1764 2 10\n 74088 3 16\n 3111696 4 21\n 130691232 5 26\n 5489031744 6 32\n 230539333248 7 37\n 9682651996416 8 43\n 406671383849472 9 48\n 17080198121677824 10 53\n 717368321110468608 11 59\n 30129469486639681536 12 64\n 1265437718438866624512 13 70\n 53148384174432398229504 14 75\n 2232232135326160725639168 15 80\n 93753749683698750476845056 16 86\n 3937657486715347520027492352 17 91\n 165381614442044595841154678784 18 97\n 6946027806565873025328496508928 19 102\n291733167875766667063796853374976 20 107\n number lsb msb\n 1 0 0\n 1302 1 10\n 1695204 2 20\n 2207155608 3 31\n 2873716601616 4 41\n 3741579015304032 5 51\n 4871535877925849664 6 62\n 6342739713059456262528 7 72\n 8258247106403412053811456 8 82\n 10752237732537242494062515712 9 93\n 13999413527763489727269395457024 10 103\n 18227236413148063624904752885045248 11 113\n 23731861809918778839625988256328912896 12 124\n 30898884076514250049193036709740244590592 13 134\n 40230347067621553564049333796081798456950784 14 144\n 52379911882043262740392232602498501590949920768 15 155\n 68198645270420328087990686848453049071416796839936 16 165\n 88794636142087267170563874276685869890984669485596672 17 175\n 115610616256997621856074164308245002598062039670246866944 18 186\n 150525022366610903656608561929334993382676775650661420761088 19 196\n195983579121327396560904347631994161384245161897161169830936576 20 206\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven a list of integer arrays **nums** (which may be unsorted), find the smallest missing positive integer in each array in the list.\n\nA missing positive integer is any positive integer, starting from 1, which is not present in the array.\n\nExample\n\n* **nums**  =   [1,2,0], [3,4,-1,1], [7,8,9,11,12]\n* **output** =   3, 2, 1" }, { "role": "assistant", "content": "```\nsay $_, \" ==> \", (1..Inf).first( -> \\n { n ∉ $_ } ) for\n[ 1, 2, 0], [3, 4, 1, 1], [7, 8, 9, 11, 12], [1, 2, 3, 4, 5], [-6, -5, -2, -1], [5, -5], [-2], [1], []\n\n```\n\nOutput:\n\n```\n[1 2 0] ==> 3\n[3 4 1 1] ==> 2\n[7 8 9 11 12] ==> 1\n[1 2 3 4 5] ==> 6\n[-6 -5 -2 -1] ==> 1\n[5 -5] ==> 1\n[-2] ==> 1\n[1] ==> 2\n[] ==> 1\n```" } ]
[ { "role": "user", "content": "Find if a point is within a triangle.\n\nTask\n\n: : * Assume points are on a plane defined by (x, y) real number coordinates.\n\n: : * Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.\n\n: : * You may use any algorithm.\n\n: : * Bonus: explain why the algorithm you chose works.\n\nRelated tasks\n\n* Determine\\_if\\_two\\_triangles\\_overlap\n\nAlso see\n: * Discussion of several methods. [[1]]\n * Determine if a point is in a polygon [[2]]\n * Triangle based coordinate systems [[3]]\n * Wolfram entry [[4]]" }, { "role": "assistant", "content": "Reusing code from the Convex hull task and some logic from the Determine if two triangles overlap task.\n\n```\nclass Point {\n has Real $.x is rw;\n has Real $.y is rw;\n method gist { [~] '(', self.x,', ', self.y, ')' };\n}\n\nsub sign (Point $a, Point $b, Point $c) {\n ($b.x - $a.x)*($c.y - $a.y) - ($b.y - $a.y)*($c.x - $a.x);\n}\n\nsub triangle (*@points where *.elems == 6) {\n @points.batch(2).map: { Point.new(:x(.[0]),:y(.[1])) };\n}\n\nsub is-within ($point, @triangle is copy) {\n my @signs = sign($point, |(@triangle.=rotate)[0,1]) xx 3;\n so (all(@signs) >= 0) or so(all(@signs) <= 0);\n}\n\nmy @triangle = triangle((1.5, 2.4), (5.1, -3.1), (-3.8, 0.5));\n\nfor Point.new(:x(0),:y(0)),\n Point.new(:x(0),:y(1)),\n Point.new(:x(3),:y(1))\n -> $point {\n say \"Point {$point.gist} is within triangle {join ', ', @triangle».gist}: \",\n $point.&is-within: @triangle\n}\n\n```\n\nOutput:\n\n```\nPoint (0, 0) is within triangle (1.5, 2.4), (5.1, -3.1), (-3.8, 0.5): True\nPoint (0, 1) is within triangle (1.5, 2.4), (5.1, -3.1), (-3.8, 0.5): True\nPoint (3, 1) is within triangle (1.5, 2.4), (5.1, -3.1), (-3.8, 0.5): False\n```" } ]
[ { "role": "user", "content": "A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes *when understood as numbers in a particular base*. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.\n\nLet's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in *The Hitchhiker's Guide to the Galaxy*, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.\n\nLet's work base 3 by hand:\n\n0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.\n\nThe task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.\n\nRelated Tasks:\n\n* Miller-Rabin primality test" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nPretty fast for bases 3 .. 11. 12 is slow. 18 is glacial.\n\n```\nuse ntheory:from<Perl5> <is_prime>;\n\nfor 3 .. 11 -> $base {\n say \"Starting base $base...\";\n my @stems = grep { .is-prime }, ^$base;\n for 1 .. * -> $digits {\n print ' ', @stems.elems;\n my @new;\n my $place = $base ** $digits;\n for 1 ..^ $base -> $digit {\n my $left = $digit * $place;\n @new.append: (@stems »+» $left).grep: { is_prime(\"$_\") }\n }\n last unless +@new;\n @stems = @new;\n }\n say \"\\nLargest ltp in base $base = {@stems.max} or :$base\\<@stems.max.base($base)}>\\n\";\n}\n\n```\n\nOutput:\n\n```\nStarting base 3...\n 1 1 1\nLargest ltp in base 3 = 23 or :3<212>\n\nStarting base 4...\n 2 2 3 3 3 3\nLargest ltp in base 4 = 4091 or :4<333323>\n\nStarting base 5...\n 2 4 4 3 1 1\nLargest ltp in base 5 = 7817 or :5<222232>\n\nStarting base 6...\n 3 4 12 25 44 54 60 62 59 51 35 20 12 7 3 2 1\nLargest ltp in base 6 = 4836525320399 or :6<14141511414451435>\n\nStarting base 7...\n 3 6 6 4 1 1 1\nLargest ltp in base 7 = 817337 or :7<6642623>\n\nStarting base 8...\n 4 12 29 50 66 77 61 51 38 27 17 8 3 2 1\nLargest ltp in base 8 = 14005650767869 or :8<313636165537775>\n\nStarting base 9...\n 4 9 15 17 24 16 9 6 5 3\nLargest ltp in base 9 = 1676456897 or :9<4284484465>\n\nStarting base 10...\n 4 11 39 99 192 326 429 521 545 517 448 354 276 212 117 72 42 24 13 6 5 4 3 1\nLargest ltp in base 10 = 357686312646216567629137 or :10<357686312646216567629137>\n\nStarting base 11...\n 4 8 15 18 15 8 4 2 1\nLargest ltp in base 11 = 2276005673 or :11<A68822827>\n\nStarting base 12...\n 5 23 119 409 1124 2496 4733 7711 11231 14826 17341 18787 19001 17567 15169 12085 9272 6606 4451 2882 1796 1108 601 346 181 103 49 19 8 2 1 1\nLargest ltp in base 12 = 13092430647736190817303130065827539 or :12<471A34A164259BA16B324AB8A32B7817>\n\nStarting base 13...\n 5 13 20 23 17 11 7 4\nLargest ltp in base 13 = 812751503 or :13<CC4C8C65>\n\nStarting base 14...\n 6 26 101 300 678 1299 2093 3017 3751 4196 4197 3823 3206 2549 1908 1269 783 507 322 163 97 55 27 13 5 2\nLargest ltp in base 14 = 615419590422100474355767356763 or :14<D967CCD63388522619883A7D23>\n\nStarting base 15...\n 6 22 79 207 391 644 934 1177 1275 1167 1039 816 608 424 261 142 74 45 25 13 7 1\nLargest ltp in base 15 = 34068645705927662447286191 or :15<6C6C2CE2CEEEA4826E642B>\n\nStarting base 16...\n 6 31 124 337 749 1292 1973 2695 3210 3490 3335 2980 2525 1840 1278 878 556 326 174 93 50 25 9 5 1\nLargest ltp in base 16 = 1088303707153521644968345559987 or :16<DBC7FBA24FE6AEC462ABF63B3>\n\nStarting base 17...\n 6 22 43 55 74 58 41 31 23 8 1\nLargest ltp in base 17 = 13563641583101 or :17<6C66CC4CC83>\n...\n```" } ]
[ { "role": "user", "content": "Task\n\nFind the limit of recursion." }, { "role": "assistant", "content": "(formerly Perl 6)\nMaximum recursion depth is memory dependent. Values in excess of 1 million are easily achieved.\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy $x = 0;\nrecurse;\n\nsub recurse () {\n ++$x;\n say $x if $x %% 1_000_000; \n recurse;\n}\n```\n\nOutput:\n\nWhen manually terminated memory use was on the order of 4Gb:\n\n```\n1000000\n2000000\n3000000\n4000000\n5000000\n6000000\n7000000\n8000000\n9000000\n10000000\n^C\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show here on this page the minimum number of coins that can make a value of   **988.**\n\nAvailable coins are:   **1,   2,   5,   10,   20,   50,   100,**   and   **200.**\n\nThe coins that would be dispensed are:\n\n```\n four coins of 200\n one coin of 100\n one coin of 50 \n one coin of 20\n one coin of 10 \n one coin of 5 \n one coin of 2\n one coin of 1\n\n```" }, { "role": "assistant", "content": "Since unit denominations are possible, don't bother to check to see if an exact pay-out isn't possible.\n\n```\nmy @denominations = 200, 100, 50, 20, 10, 5, 2, 1;\n\nsub change (Int $n is copy where * >= 0) { gather for @denominations { take $n div $_; $n %= $_ } }\n\nfor 988, 1307, 37511, 0 -> $amount {\n say \"\\n$amount:\";\n printf \"%d × %d\\n\", |$_ for $amount.&change Z @denominations;\n}\n\n```\n\nOutput:\n\n```\n988:\n4 × 200\n1 × 100\n1 × 50\n1 × 20\n1 × 10\n1 × 5\n1 × 2\n1 × 1\n\n1307:\n6 × 200\n1 × 100\n0 × 50\n0 × 20\n0 × 10\n1 × 5\n1 × 2\n0 × 1\n\n37511:\n187 × 200\n1 × 100\n0 × 50\n0 × 20\n1 × 10\n0 × 5\n0 × 2\n1 × 1\n\n0:\n0 × 200\n0 × 100\n0 × 50\n0 × 20\n0 × 10\n0 × 5\n0 × 2\n0 × 1\n```" } ]
[ { "role": "user", "content": "Task\n\n* Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   *both*:\n\n: : : * base 2\n * base 3\n\n* Display   **0**   (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\nIt's permissible to assume the first two numbers and simply list them.\n\nSee also\n\n* Sequence A60792,   numbers that are palindromic in bases 2 and 3 on *The On-Line Encyclopedia of Integer Sequences*." }, { "role": "assistant", "content": "(formerly Perl 6)\nInstead of searching for numbers that are palindromes in one base then checking the other, generate palindromic trinary numbers directly, then check to see if they are also binary palindromes (with additional simplifying constraints as noted in other entries). Outputs the list in decimal, binary and trinary.\n\n```\nconstant palindromes = 0, 1, |gather for 1 .. * -> $p {\n my $pal = $p.base(3);\n my $n = :3($pal ~ '1' ~ $pal.flip);\n next if $n %% 2;\n my $b2 = $n.base(2);\n next if $b2.chars %% 2;\n next unless $b2 eq $b2.flip;\n take $n;\n}\n\nprintf \"%d, %s, %s\\n\", $_, .base(2), .base(3) for palindromes[^6];\n\n```\n\nOutput:\n\n```\n0, 0, 0\n1, 1, 1\n6643, 1100111110011, 100010001\n1422773, 101011011010110110101, 2200021200022\n5415589, 10100101010001010100101, 101012010210101\n90396755477, 1010100001100000100010000011000010101, 22122022220102222022122\n```" } ]