messages
listlengths 2
2
|
---|
[
{
"role": "user",
"content": "Task\n\nA particular activity of bats occurs at these times of the day:\n\n: 23:00:17, 23:40:20, 00:12:45, 00:17:19\n\nUsing the idea that there are twenty-four hours in a day,\nwhich is analogous to there being 360 degrees in a circle,\nmap times of day to and from angles;\nand using the ideas of Averages/Mean angle\ncompute and show the average time of the nocturnal activity\nto an accuracy of one second of time.\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub tod2rad($_) { [+](.comb(/\\d+/) Z* 3600,60,1) * tau / 86400 }\n \nsub rad2tod ($r) {\n my $x = $r * 86400 / tau;\n (($x xx 3 Z/ 3600,60,1) Z% 24,60,60).fmt('%02d',':');\n}\n \nsub phase ($c) { $c.polar[1] }\n \nsub mean-time (@t) { rad2tod phase [+] map { cis tod2rad $_ }, @t }\n\nmy @times = [\"23:00:17\", \"23:40:20\", \"00:12:45\", \"00:17:19\"];\n \nsay \"{ mean-time(@times) } is the mean time of @times[]\";\n\n```\n\nOutput:\n\n```\n23:47:43 is the mean time of 23:00:17 23:40:20 00:12:45 00:17:19\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program to find the median value of a vector of floating-point numbers.\n\nThe program need not handle the case where the vector is empty, but *must* handle the case where there are an even number of elements. In that case, return the average of the two middle values.\n\nThere are several approaches to this. One is to sort the elements, and then pick the element(s) in the middle.\n\nSorting would take at least O(*n* log*n*). Another approach would be to build a priority queue from the elements, and then extract half of the elements to get to the middle element(s). This would also take O(*n* log*n*). The best solution is to use the selection algorithm to find the median in O(*n*) time.\n\nSee also\n\nQuickselect\\_algorithm\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.08\n\n```\nsub median {\n my @a = sort @_;\n return (@a[(*-1) div 2] + @a[* div 2]) / 2;\n}\n\n```\n\nNotes:\n\n* The div operator does integer division. The / operator (rational number division) would work too, since the array subscript automatically coerces to Int, but using div is more explicit (i.e. clearer to readers) as well as faster, and thus recommended in cases like this.\n* The \\* inside the subscript stands for the array's length (see documentation).\n\nIn a slightly more compact way:\n\n```\nsub median { @_.sort[(*-1)/2, */2].sum / 2 }\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program to find the mode value of a collection.\n\nThe case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.\n\nIf it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03.1\n\n```\nsub mode (*@a) {\n my %counts := @a.Bag;\n my $max = %counts.values.max;\n %counts.grep(*.value == $max).map(*.key);\n}\n\n# Testing with arrays:\nsay mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];\nsay mode [1, 1, 2, 4, 4];\n\n```\n\nOutput:\n\n```\n6\n(4 1)\n\n```\n\nAlternatively, a version that uses a single method chain with no temporary variables: (Same output with same input)\n\n```\nsub mode (*@a) {\n @a.Bag # count elements\n .classify(*.value) # group elements with the same count\n .max(*.key) # get group with the highest count\n .value.map(*.key); # get elements in the group\n}\n\nsay mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];\nsay mode [1, 1, 2, 4, 4];\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCompute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).\n\nShow that \n\nA\n(\n\nx\n\n1\n,\n…\n,\n\nx\n\nn\n)\n≥\nG\n(\n\nx\n\n1\n,\n…\n,\n\nx\n\nn\n)\n≥\nH\n(\n\nx\n\n1\n,\n…\n,\n\nx\n\nn\n)\n{\\displaystyle {\\displaystyle A(x\\_{1},\\ldots ,x\\_{n})\\geq G(x\\_{1},\\ldots ,x\\_{n})\\geq H(x\\_{1},\\ldots ,x\\_{n})}}\n for this set of positive integers.\n\n* The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:\n\n: A\n (\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n )\n =\n\n x\n\n 1\n +\n ⋯\n +\n\n x\n\n n\n n\n {\\displaystyle {\\displaystyle A(x\\_{1},\\ldots ,x\\_{n})={\\frac {x\\_{1}+\\cdots +x\\_{n}}{n}}}}\n\n* The geometric mean is the \n\n n\n {\\displaystyle {\\displaystyle n}}\n th root of the product of the list:\n\n: G\n (\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n )\n =\n\n x\n\n 1\n ⋯\n\n x\n\n n\n\n n\n {\\displaystyle {\\displaystyle G(x\\_{1},\\ldots ,x\\_{n})={\\sqrt[{n}]{x\\_{1}\\cdots x\\_{n}}}}}\n\n* The harmonic mean is \n\n n\n {\\displaystyle {\\displaystyle n}}\n divided by the sum of the reciprocal of each item in the list:\n\n: H\n (\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n )\n =\n\n\n n\n\n 1\n\n x\n\n 1\n +\n ⋯\n +\n\n\n 1\n\n x\n\n n\n {\\displaystyle {\\displaystyle H(x\\_{1},\\ldots ,x\\_{n})={\\frac {n}{{\\frac {1}{x\\_{1}}}+\\cdots +{\\frac {1}{x\\_{n}}}}}}}\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub A { ([+] @_) / @_ }\nsub G { ([*] @_) ** (1 / @_) }\nsub H { @_ / [+] 1 X/ @_ }\n\nsay \"A(1,...,10) = \", A(1..10);\nsay \"G(1,...,10) = \", G(1..10);\nsay \"H(1,...,10) = \", H(1..10);\n\n```\n\nOutput:\n\n```\nA(1,...,10) = 5.5\nG(1,...,10) = 4.52872868811677\nH(1,...,10) = 3.41417152147406\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\nThe *root mean square* is also known by its initials RMS (or rms), and as the **quadratic mean**.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n: : : x\n\n\n r\n m\n s\n =\n\n x\n\n 1\n\n 2\n +\n\n x\n\n 2\n\n 2\n +\n ⋯\n +\n\n x\n\n n\n\n 2\n n\n .\n {\\displaystyle {\\displaystyle x\\_{\\mathrm {rms} }={\\sqrt {{{x\\_{1}}^{2}+{x\\_{2}}^{2}+\\cdots +{x\\_{n}}^{2}} \\over n}}.}}\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub rms(*@nums) { sqrt ([+] @nums X** 2) / @nums }\n\nsay rms 1..10;\n\n```\n\nHere's a slightly more concise version, albeit arguably less readable:\n\n```\nsub rms { sqrt @_ R/ [+] @_».² }\n\n```"
}
]
|
[
{
"role": "user",
"content": "Computing the simple moving average of a series of numbers.\n\nTask\n\nCreate a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.\n\nDescription\n\nA simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.\n\nIt can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().\n\nThe word *stateful* in the task description refers to the need for SMA() to remember certain information between calls to it:\n\n* The period, P\n* An ordered container of at least the last P numbers from each of its individual calls.\n\n*Stateful* also means that successive calls to I(), the initializer, should return separate routines that do *not* share saved state so they could be used on two independent streams of data.\n\nPseudo-code for an implementation of SMA is:\n\n```\nfunction SMA(number: N):\n stateful integer: P\n stateful list: stream\n number: average\n\n stream.append_last(N)\n if stream.length() > P:\n # Only average the last P elements of the stream\n stream.delete_first()\n if stream.length() == 0:\n average = 0\n else: \n average = sum( stream.values() ) / stream.length()\n return average\n\n```\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.08\n\n```\nsub sma-generator (Int $P where * > 0) {\n sub ($x) {\n state @a = 0 xx $P;\n @a.push($x).shift;\n @a.sum / $P;\n }\n}\n\n# Usage:\nmy &sma = sma-generator 3;\n\nfor 1, 2, 3, 2, 7 {\n printf \"append $_ --> sma = %.2f (with period 3)\\n\", sma $_;\n}\n\n```\n\nOutput:\n\n```\nappend 1 --> sma = 0.33 (with period 3)\nappend 2 --> sma = 1.00 (with period 3)\nappend 3 --> sma = 2.00 (with period 3)\nappend 2 --> sma = 2.33 (with period 3)\nappend 7 --> sma = 4.00 (with period 3)\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at AVL tree. 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 computer science, an **AVL tree** is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log *n*) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log *n*) time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor μ-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\nTask\n\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\nRelated task\n\nRed\\_black\\_tree\\_sort"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThis code has been translated from the Java version on\n<https://rosettacode.org>. Consequently, it should have the same\nlicense: GNU Free Document License 1.2. In addition to the translated\ncode, other public methods have been added as shown by the asterisks\nin the following list of all public methods:\n\n* insert node\n* delete node\n* show all node keys\n* show all node balances\n* \\*delete nodes by a list of node keys\n* \\*find and return node objects by key\n* \\*attach data per node\n* \\*return list of all node keys\n* \\*return list of all node objects\n\nNote one of the interesting features of Raku is the ability to use characters\nlike the apostrophe (') and hyphen (-) in identifiers.\n\n```\nclass AVL-Tree {\n has $.root is rw = 0;\n\n class Node {\n has $.key is rw = '';\n has $.parent is rw = 0;\n has $.data is rw = 0;\n has $.left is rw = 0;\n has $.right is rw = 0;\n has Int $.balance is rw = 0;\n has Int $.height is rw = 0;\n }\n\n #=====================================================\n # public methods\n #=====================================================\n\n #| returns a node object or 0 if not found\n method find($key) {\n return 0 if !$.root;\n self!find: $key, $.root;\n }\n\n #| returns a list of tree keys\n method keys() {\n return () if !$.root;\n my @list;\n self!keys: $.root, @list;\n @list;\n }\n\n #| returns a list of tree nodes\n method nodes() {\n return () if !$.root;\n my @list;\n self!nodes: $.root, @list;\n @list;\n }\n\n #| insert a node key, optionally add data (the `parent` arg is for\n #| internal use only)\n method insert($key, :$data = 0, :$parent = 0,) {\n return $.root = Node.new: :$key, :$parent, :$data if !$.root;\n my $n = $.root;\n while True {\n return False if $n.key eq $key;\n my $parent = $n;\n my $goLeft = $n.key > $key;\n $n = $goLeft ?? $n.left !! $n.right;\n if !$n {\n if $goLeft {\n $parent.left = Node.new: :$key, :$parent, :$data;\n }\n else {\n $parent.right = Node.new: :$key, :$parent, :$data;\n }\n self!rebalance: $parent;\n last\n }\n }\n True\n }\n\n #| delete one or more nodes by key\n method delete(*@del-key) {\n return if !$.root;\n for @del-key -> $del-key {\n my $child = $.root;\n while $child {\n my $node = $child;\n $child = $del-key >= $node.key ?? $node.right !! $node.left;\n if $del-key eq $node.key {\n self!delete: $node;\n next;\n }\n }\n }\n }\n\n #| show a list of all nodes by key\n method show-keys {\n self!show-keys: $.root;\n say()\n }\n\n #| show a list of all nodes' balances (not normally needed)\n method show-balances {\n self!show-balances: $.root;\n say()\n }\n\n #=====================================================\n # private methods\n #=====================================================\n\n method !delete($node) {\n if !$node.left && !$node.right {\n if !$node.parent {\n $.root = 0;\n }\n else {\n my $parent = $node.parent;\n if $parent.left === $node {\n $parent.left = 0;\n }\n else {\n $parent.right = 0;\n }\n self!rebalance: $parent;\n }\n return\n }\n\n if $node.left {\n my $child = $node.left;\n while $child.right {\n $child = $child.right;\n }\n $node.key = $child.key;\n self!delete: $child;\n }\n else {\n my $child = $node.right;\n while $child.left {\n $child = $child.left;\n }\n $node.key = $child.key;\n self!delete: $child;\n }\n }\n\n method !rebalance($n is copy) {\n self!set-balance: $n;\n\n if $n.balance == -2 {\n if self!height($n.left.left) >= self!height($n.left.right) {\n $n = self!rotate-right: $n;\n }\n else {\n $n = self!rotate-left'right: $n;\n }\n }\n elsif $n.balance == 2 {\n if self!height($n.right.right) >= self!height($n.right.left) {\n $n = self!rotate-left: $n;\n }\n else {\n $n = self!rotate-right'left: $n;\n }\n }\n\n if $n.parent {\n self!rebalance: $n.parent;\n }\n else {\n $.root = $n;\n }\n }\n\n method !rotate-left($a) {\n\n my $b = $a.right;\n $b.parent = $a.parent;\n\n $a.right = $b.left;\n\n if $a.right {\n $a.right.parent = $a;\n }\n\n $b.left = $a;\n $a.parent = $b;\n\n if $b.parent {\n if $b.parent.right === $a {\n $b.parent.right = $b;\n }\n else {\n $b.parent.left = $b;\n }\n }\n\n self!set-balance: $a, $b;\n $b;\n }\n\n method !rotate-right($a) {\n\n my $b = $a.left;\n $b.parent = $a.parent;\n\n $a.left = $b.right;\n\n if $a.left {\n $a.left.parent = $a;\n }\n\n $b.right = $a;\n $a.parent = $b;\n\n if $b.parent {\n if $b.parent.right === $a {\n $b.parent.right = $b;\n }\n else {\n $b.parent.left = $b;\n }\n }\n\n self!set-balance: $a, $b;\n\n $b;\n }\n\n method !rotate-left'right($n) {\n $n.left = self!rotate-left: $n.left;\n self!rotate-right: $n;\n }\n\n method !rotate-right'left($n) {\n $n.right = self!rotate-right: $n.right;\n self!rotate-left: $n;\n }\n\n method !height($n) {\n $n ?? $n.height !! -1;\n }\n\n method !set-balance(*@n) {\n for @n -> $n {\n self!reheight: $n;\n $n.balance = self!height($n.right) - self!height($n.left);\n }\n }\n\n method !show-balances($n) {\n if $n {\n self!show-balances: $n.left;\n printf \"%s \", $n.balance;\n self!show-balances: $n.right;\n }\n }\n\n method !reheight($node) {\n if $node {\n $node.height = 1 + max self!height($node.left), self!height($node.right);\n }\n }\n\n method !show-keys($n) {\n if $n {\n self!show-keys: $n.left;\n printf \"%s \", $n.key;\n self!show-keys: $n.right;\n }\n }\n\n method !nodes($n, @list) {\n if $n {\n self!nodes: $n.left, @list;\n @list.push: $n if $n;\n self!nodes: $n.right, @list;\n }\n }\n\n method !keys($n, @list) {\n if $n {\n self!keys: $n.left, @list;\n @list.push: $n.key if $n;\n self!keys: $n.right, @list;\n }\n }\n\n method !find($key, $n) {\n if $n {\n self!find: $key, $n.left;\n return $n if $n.key eq $key;\n self!find: $key, $n.right;\n }\n }\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGenerate a B-spline curve with a list of 12 points and plot or save image.\n\nCoordinates of control points:\n\n```\n start=171,171 \n 1 185,111, \n 2 202,109, \n 3 202,189 \n 4 328,160 \n 5 208,254 \n 6 241,330 \n 7 164,252 \n 8 69,278 \n 9 139,208 \n 10 72,148 \n end=168,172\n\n```\n\nRules!!!!\n\nDo not use third party libraries or functions\n\nSee also\n\n* B-splines"
},
{
"role": "assistant",
"content": "A minimal translation of this C program, by Bernhard R. Fischer.\n\n```\n# 20211112 Raku programming solution\n\nuse Cairo;\n\n# class point_t { has Num ($.x,$.y) is rw } # get by with two element lists\nclass line_t { has ($.A,$.B) is rw }\n\nmy (\\WIDTH, \\HEIGHT, \\W_LINE, \\CURVE_F, \\DETACHED, \\OUTPUT ) = \n 400, 400, 2, 0.25, 0, './b-spline.png' ;\n\nmy \\cnt = #`(Number of points) ( my \\pt = [\n [171, 171], [185, 111], [202, 109], [202, 189], [328, 160], [208, 254],\n [241, 330], [164, 252], [ 69, 278], [139, 208], [ 72, 148], [168, 172], ]\n).elems;\n\nsub angle(\\g) { atan2(g.B.[1] - g.A.[1], g.B.[0] - g.A.[0]) }\n\nsub control_points(\\g, \\l, @p1, @p2){\n\n#`[ This function calculates the control points. It takes two lines g and l as\n * arguments but it takes three lines into account for calculation. This is\n * line g (P0/P1), line h (P1/P2), and line l (P2/P3). The control points being\n * calculated are actually those for the middle line h, this is from P1 to P2.\n * Line g is the predecessor and line l the successor of line h.\n * @param g Pointer to first line (P0 to P1)\n * @param l Pointer to third line (P2 to P3)\n * @param p1 Pointer to memory of first control point. \n * @param p2 Pointer to memory of second control point. ]\n \n my \\h = $ = line_t.new;\n\n my \\lgt = sqrt([+]([ g.B.[0]-l.A.[0], g.B.[1]-l.A.[1] ]>>²));#length of P1 to P2\n\n h.B = l.A.clone; # end point of 1st tangent\n # start point of tangent at same distance as end point along 'g'\n h.A = g.B.[0] - lgt * cos(angle g) , g.B.[1] - lgt * sin(angle g);\n\n my $a = angle h ; # angle of tangent\n # 1st control point on tangent at distance 'lgt * CURVE_F'\n @p1 = g.B.[0] + lgt * cos($a) * CURVE_F, g.B.[1] + lgt * sin($a) * CURVE_F;\n\n h.A = g.B.clone; # start point of 2nd tangent\n # end point of tangent at same distance as start point along 'l'\n h.B = l.A.[0] + lgt * cos(angle l) , l.A.[1] + lgt * sin(angle l);\n\n $a = angle h; # angle of tangent\n # 2nd control point on tangent at distance 'lgt * CURVE_F'\n @p2 = l.A.[0] - lgt * cos($a) * CURVE_F, l.A.[1] - lgt * sin($a) * CURVE_F;\n}\n\n\ngiven Cairo::Image.create(Cairo::FORMAT_ARGB32, WIDTH, HEIGHT) {\n given Cairo::Context.new($_) {\n my line_t ($g,$l);\n my (@p1,@p2);\n\n .line_width = W_LINE;\n .move_to(pt[DETACHED - 1 + cnt].[0], pt[DETACHED - 1 + cnt].[1]);\n\n for DETACHED..^cnt -> \\j { \n $g = line_t.new: A=>pt[(j + cnt - 2) % cnt], B=>pt[(j + cnt - 1) % cnt];\n $l = line_t.new: A=>pt[(j + cnt + 0) % cnt], B=>pt[(j + cnt + 1) % cnt];\n \n # Calculate controls points for points pt[j-1] and pt[j].\n control_points($g, $l, @p1, @p2);\n \n .curve_to(@p1[0], @p1[1], @p2[0], @p2[1], pt[j].[0], pt[j].[1]);\n }\n .stroke;\n };\n .write_png(OUTPUT) and die # C return\n}\n\n```\n\nOutput: (Offsite image file)"
}
]
|
[
{
"role": "user",
"content": "Charles Babbage\n\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n\nWhat is the smallest positive integer whose square ends in the digits 269,696?\n\n— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, *Electronic Computers*, second edition, 1970, p. 125.\n\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\nTask\n\nThe task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.\nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\nMotivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis could certainly be written more concisely. Extra verbiage is included to make the process more clear.\n\n```\n# For all positive integers from 1 to Infinity\nfor 1 .. Inf -> $integer {\n \n # calculate the square of the integer\n my $square = $integer²;\n \n # print the integer and square and exit if the square modulo 1000000 is equal to 269696\n print \"{$integer}² equals $square\" and exit if $square mod 1000000 == 269696;\n}\n\n```\n\nOutput:\n\n```\n25264² equals 638269696\n```\n\nMore concisely (but clear enough to allow Mr. Babbage to understand what's going on?):\n\n```\n.say and exit if $_² % 1e6 == 269696 for ^∞;\n\n```\n\nOutput:\n\n```\n25264\n```\n\nNotice that `exit` ends the process itself instead of ending just the loop, as `last` would. `exit` would arguably be easier to understand for Babbage though, so it may better fill the task requirement."
}
]
|
[
{
"role": "user",
"content": "f\nThe **Babylonian spiral** is a sequence of points in the plane that are created so as to\ncontinuously minimally increase in vector length and minimally bend in vector direction,\nwhile always moving from point to point on strictly integral coordinates. Of the two criteria\nof length and angle, the length has priority.\n\nExamples\n\nP(1) and P(2) are defined to be at (x = 0, y = 0) and (x = 0, y = 1). The first vector is\nfrom P(1) to P(2). It is vertical and of length 1. Note that the square of that length is 1.\n\nNext in sequence is the vector from P(2) to P(3). This should be the smallest distance to a\npoint with integral (x, y) which is longer than the last vector (that is, 1). It should also bend clockwise\nmore than zero radians, but otherwise to the least degree.\n\nThe point chosen for P(3) that fits criteria is (x = 1, y = 2). Note the length of the vector\nfrom P(2) to P(3) is √2, which squared is 2. The lengths of the vectors thus determined can be given by a sorted\nlist of possible sums of two integer squares, including 0 as a square.\n\nTask\n\nFind and show the first 40 (x, y) coordinates of the Babylonian spiral.\n\nStretch task\n\nShow in your program how to calculate and plot the first 10000 points in the sequence. Your result\nshould look similar to the graph shown at the OEIS:\n\nSee also\n\n* OEIS:A256111 - squared distance to the origin of the n-th vertex on a Babylonian Spiral. * OEIS:A297346 - List of successive x-coordinates in the Babylonian Spiral. * OEIS:A297347 - List of successive y-coordinates in the Babylonian Spiral."
},
{
"role": "assistant",
"content": "**Translation of**: Wren\n\n### Translation\n\n```\nsub babylonianSpiral (\\nsteps) {\n my @squareCache = (0..nsteps).hyper.map: *²;\n my @dxys = [0, 0], [0, 1];\n my $dsq = 1;\n\n for ^(nsteps-2) {\n my \\Θ = atan2 |@dxys[*-1][1,0];\n my @candidates;\n\n until @candidates.elems {\n $dsq++;\n for @squareCache.kv -> \\i, \\a {\n last if a > $dsq/2;\n for reverse 0 .. $dsq.sqrt.ceiling -> \\j {\n last if $dsq > (a + my \\b = @squareCache[j]);\n next if $dsq != a + b;\n @candidates.append: [i, j], [-i, j], [i, -j], [-i, -j],\n [j, i], [-j, i], [j, -i], [-j, -i]\n }\n }\n }\n @dxys.push: @candidates.min: { ( Θ - atan2 |.[1,0] ) % τ };\n }\n\n [\\»+«] @dxys\n}\n\n# The task\nsay \"The first $_ Babylonian spiral points are:\\n\",\n(babylonianSpiral($_).map: { sprintf '(%3d,%4d)', @$_ }).batch(10).join(\"\\n\") given 40;\n\n# Stretch\nuse SVG;\n\n'babylonean-spiral-raku.svg'.IO.spurt: SVG.serialize(\n svg => [\n :width<100%>, :height<100%>,\n :rect[:width<100%>, :height<100%>, :style<fill:white;>],\n :polyline[ :points(flat babylonianSpiral(10000)),\n :style(\"stroke:red; stroke-width:6; fill:white;\"),\n :transform(\"scale (.05, -.05) translate (1000,-10000)\")\n ],\n ],\n);\n\n```\n\nOutput:\n\n```\nThe first 40 Babylonian spiral points are:\n( 0, 0) ( 0, 1) ( 1, 2) ( 3, 2) ( 5, 1) ( 7, -1) ( 7, -4) ( 6, -7) ( 4, -10) ( 0, -10)\n( -4, -9) ( -7, -6) ( -9, -2) ( -9, 3) ( -8, 8) ( -6, 13) ( -2, 17) ( 3, 20) ( 9, 20) ( 15, 19)\n( 21, 17) ( 26, 13) ( 29, 7) ( 29, 0) ( 28, -7) ( 24, -13) ( 17, -15) ( 10, -12) ( 4, -7) ( 4, 1)\n( 5, 9) ( 7, 17) ( 13, 23) ( 21, 26) ( 28, 21) ( 32, 13) ( 32, 4) ( 31, -5) ( 29, -14) ( 24, -22)\n```\n\nStretch goal:\n\n(offsite SVG image - 96 Kb) - babylonean-spiral-raku.svg\n\n### Independent implementation\n\nExact same output; about one tenth the execution time.\n\n```\nmy @next = { :x(1), :y(1), :2hyp },;\n\nsub next-interval (Int $int) {\n @next.append: (0..$int).map: { %( :x($int), :y($_), :hyp($int² + .²) ) };\n @next = |@next.sort: *.<hyp>;\n}\n\nmy @spiral = [\\»+«] lazy gather {\n my $interval = 1;\n take [0,0];\n take my @tail = 0,1;\n loop {\n my \\Θ = atan2 |@tail[1,0];\n my @this = @next.shift;\n @this.push: @next.shift while @next and @next[0]<hyp> == @this[0]<hyp>;\n my @candidates = @this.map: {\n my (\\i, \\j) = .<x y>;\n next-interval(++$interval) if $interval == i;\n |((i,j),(-i,j),(i,-j),(-i,-j),(j,i),(-j,i),(j,-i),(-j,-i))\n }\n take @tail = |@candidates.min: { ( Θ - atan2 |.[1,0] ) % τ };\n }\n}\n\n# The task\nsay \"The first $_ Babylonian spiral points are:\\n\",\n@spiral[^$_].map({ sprintf '(%3d,%4d)', |$_ }).batch(10).join: \"\\n\" given 40;\n\n# Stretch\nuse SVG;\n\n'babylonean-spiral-raku.svg'.IO.spurt: SVG.serialize(\n svg => [\n :width<100%>, :height<100%>,\n :rect[:width<100%>, :height<100%>, :style<fill:white;>],\n :polyline[ :points(flat @spiral[^10000]),\n :style(\"stroke:red; stroke-width:6; fill:white;\"),\n :transform(\"scale (.05, -.05) translate (1000,-10000)\")\n ],\n ],\n);\n\n```\n\nSame output:"
}
]
|
[
{
"role": "user",
"content": "Bacon's cipher is a method of steganography created by Francis Bacon.\nThis task is to implement a program for encryption and decryption of plaintext using the simple alphabet of the Baconian cipher or some other kind of representation of this alphabet (make anything signify anything).\n\nThe Baconian alphabet:\n\n```\na AAAAA g AABBA n ABBAA t BAABA\nb AAAAB h AABBB o ABBAB u-v BAABB\nc AAABA i-j ABAAA p ABBBA w BABAA\nd AAABB k ABAAB q ABBBB x BABAB\ne AABAA l ABABA r BAAAA y BABBA\nf AABAB m ABABB s BAAAB z BABBB\n\n```\n\n1. The Baconian alphabet may optionally be extended to encode all lower case characters individually and/or adding a few punctuation characters such as the space.\n2. It is impractical to use the original change in font for the steganography. For this task you must provide an example that uses a change in the case of successive alphabetical characters instead. Other examples for the language are encouraged to explore alternative steganographic means.\n3. Show an example plaintext message encoded and then decoded here on this page."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### alternative steganography algorithm\n\nNot truly a Bacon Cipher as it doesn't encode using font variations. But fits with the spirit if not the exact definition.\n\n**Works with**: Rakudo version 2015-11-20\n\n```\nmy $secret = q:to/END/;\n This task is to implement a program for encryption and decryption\n of plaintext using the simple alphabet of the Baconian cipher or\n some other kind of representation of this alphabet (make anything\n signify anything). This example will work with anything in the\n ASCII range... even code! $r%_-^&*(){}+~ #=`/\\';*1234567890\"'\n END\n\nmy $text = q:to/END/;\n Bah. It isn't really practical to use typeface changes to encode\n information, it is too easy to tell that there is something going\n on and will attract attention. Font changes with enough regularity\n to encode mesages relatively efficiently would need to happen so\n often it would be obvious that there was some kind of manipulation\n going on. Steganographic encryption where it is obvious that there\n has been some tampering with the carrier is not going to be very\n effective. Not that any of these implementations would hold up to\n serious scrutiny anyway. Anyway, here's a semi-bogus implementation\n that hides information in white space. The message is hidden in this\n paragraph of text. Yes, really. It requires a fairly modern file\n viewer to display (not display?) the hidden message, but that isn't\n too unlikely any more. It may be stretching things to call this a\n Bacon cipher, but I think it falls within the spirit of the task,\n if not the exact definition.\n END\n#'\nmy @enc = \"\", \"\";\nmy %dec = @enc.pairs.invert;\n\nsub encode ($c) { @enc[($c.ord).fmt(\"%07b\").comb].join('') }\n\nsub hide ($msg is copy, $text) { \n $msg ~= @enc[0] x (0 - ($msg.chars % 8)).abs;\n my $head = $text.substr(0,$msg.chars div 8);\n my $tail = $text.substr($msg.chars div 8, *-1);\n ($head.comb «~» $msg.comb(/. ** 8/)).join('') ~ $tail;\n}\n\nsub reveal ($steg) {\n join '', map { :2(%dec{$_.comb}.join('')).chr }, \n $steg.subst( /\\w | <punct> | \" \" | \"\\n\" /, '', :g).comb(/. ** 7/);\n}\n\nmy $hidden = join '', map { .&encode }, $secret.comb;\n\nmy $steganography = hide $hidden, $text;\n\nsay \"Steganograpic message hidden in text:\";\nsay $steganography;\n\nsay '*' x 70;\n\nsay \"Hidden message revealed:\";\nsay reveal $steganography;\n\n```\n\nOutput:\n\n```\nSteganograpic message hidden in text:\nBah. It isn't really practical to use typeface changes to encode\ninformation, it is too easy to tell that there is something going\non and will attract attention. Font changes with enough regularity\nto encode mesages relatively efficiently would need to happen so\noften it would be obvious that there was some kind of manipulation\ngoing on. Steganographic encryption where it is obvious that there\nhas been some tampering with the carrier is not going to be very\neffective. Not that any of these implementations would hold up to\nserious scrutiny anyway. Anyway, here's a semi-bogus implementation\nthat hides information in white space. The message is hidden in this\nparagraph of text. Yes, really. It requires a fairly modern file\nviewer to display (not display?) the hidden message, but that isn't\ntoo unlikely any more. It may be stretching things to call this a\nBacon cipher, but I think it falls within the spirit of the task,\nif not the exact definition.\n**********************************************************************\nHidden message revealed:\nThis task is to implement a program for encryption and decryption\nof plaintext using the simple alphabet of the Baconian cipher or\nsome other kind of representation of this alphabet (make anything\nsignify anything). This example will work with anything in the\nASCII range... even code! $r%_-^&*(){}+~ #=`/\\';*1234567890\"'\n```\n\n### Bacon cipher solution\n\n```\nmy @abc = 'a' .. 'z';\nmy @symb = ' ', |@abc; # modified Baconian charset - space and full alphabet\n# TODO original one with I=J U=V, nice for Latin\n\nmy %bacon = @symb Z=> (^@symb).map(*.base(2).fmt(\"%05s\"));\nmy %nocab = %bacon.antipairs;\n\nsub bacon ($s, $msg) {\n my @raw = $s.lc.comb;\n my @txt := @raw[ (^@raw).grep({@raw[$_] (elem) @abc}) ];\n for $msg.lc.comb Z @txt.batch(5) -> ($c-msg, @a) {\n for @a.kv -> $i, $c-str {\n (my $x := @a[$i]) = $x.uc if %bacon{$c-msg}.comb[$i].Int.Bool;\n } }\n @raw.join;\n}\n\nsub unbacon ($s) {\n my $chunks = ($s ~~ m:g/\\w+/)>>.Str.join.comb(/.**5/);\n $chunks.map(*.comb.map({.uc eq $_})».Int».Str.join).map({%nocab{$_}}).join;\n}\n\nmy $msg = \"Omnes homines dignitate et iure liberi et pares nascuntur\";\n\nmy $str = <Lorem ipsum dolor sit amet, consectetur adipiscing elit,\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi\nut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit\nin voluptate velit esse cillum dolore eu fugiat nulla pariatur.\nExcepteur sint occaecat cupidatat non proident, sunt in culpa\nqui officia deserunt mollit anim id est laborum.>;\n\nmy $baconed = bacon $str, $msg;\n$baconed = $baconed.?naive-word-wrapper || $baconed;\n# FIXME ^^^ makes dbl space after .\nsay \"text:\\n$baconed\\n\";\nmy $unbaconed = unbacon($baconed).trim.uc;\nsay \"hidden message:\\n$unbaconed\";\n\n```\n\nOutput:\n\n```\ntext:\nlOREM iPSuM dOLOr siT aMEt, cONsectetUr adiPISCiNG eLiT, seD dO EIusmOd\nTEmpOR incididUnt uT laBorE ET dOLOre MagNA aLiqua. ut ENiM ad miNiM\nveniam, qUiS NoStrud exerCitATiOn ULlaMco lAbOris nisI Ut alIquIp ex Ea\ncoMmODo cOnsEquAt. duis auTe IRuRe dolor iN reprehenDEriT in vOlUPtaTE\nvelit eSSE cilluM DolORe eu FUGiAt NuLLA pArIatUr. ExCEptEur sint\noccaecat cupidatat non proident, sunt in culpa qui officia deserunt\nmollit anim id est laborum.\n\nhidden message:\nOMNES HOMINES DIGNITATE ET IURE LIBERI ET PARES NASCUNTUR\n```"
}
]
|
[
{
"role": "user",
"content": "**Task**:\n\n* Generate a string with **N** opening brackets **[** and with **N** closing brackets **]**, in some arbitrary order.\n* Determine whether the generated string is *balanced*; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\nExamples\n\n```\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThere's More Than One Way To Do It.\n\n### Depth counter\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub balanced($s) {\n my $l = 0;\n for $s.comb {\n when \"]\" {\n --$l;\n return False if $l < 0;\n }\n when \"[\" {\n ++$l;\n }\n }\n return $l == 0;\n}\n\nmy $n = prompt \"Number of brackets\";\nmy $s = (<[ ]> xx $n).flat.pick(*).join;\nsay \"$s {balanced($s) ?? \"is\" !! \"is not\"} well-balanced\"\n```\n\n### FP oriented\n\nHere's a more idiomatic solution using a hyperoperator to compare all the characters to a backslash (which is between the brackets in ASCII), a triangle reduction to return the running sum, a given to make that list the topic, and then a topicalized junction and a topicalized subscript to test the criteria for balance.\n\n```\nsub balanced($s) {\n .none < 0 and .[*-1] == 0\n given ([\\+] '\\\\' «leg« $s.comb).cache;\n}\n\nmy $n = prompt \"Number of bracket pairs: \";\nmy $s = <[ ]>.roll($n*2).join;\nsay \"$s { balanced($s) ?? \"is\" !! \"is not\" } well-balanced\"\n```\n\n### String munging\n\nOf course, a Perl 5 programmer might just remove as many inner balanced pairs as possible and then see what's left.\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub balanced($_ is copy) {\n Nil while s:g/'[]'//;\n $_ eq '';\n}\n\nmy $n = prompt \"Number of bracket pairs: \";\nmy $s = <[ ]>.roll($n*2).join;\nsay \"$s is\", ' not' x not balanced($s), \" well-balanced\";\n```\n\n### Parsing with a grammar\n\n**Works with**: Rakudo version 2015.12\n\n```\ngrammar BalBrack { token TOP { '[' <TOP>* ']' } }\n\nmy $n = prompt \"Number of bracket pairs: \";\nmy $s = ('[' xx $n, ']' xx $n).flat.pick(*).join;\nsay \"$s { BalBrack.parse($s) ?? \"is\" !! \"is not\" } well-balanced\";\n```"
}
]
|
[
{
"role": "user",
"content": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.\n\nExamples\n\nDecimal 11 = 32 + 31 − 30, thus it can be written as \"++−\"\n\nDecimal 6 = 32 − 31 + 0 × 30, thus it can be written as \"+−0\"\n\nTask\n\nImplement balanced ternary representation of integers with the following:\n\n1. Support arbitrarily large integers, both positive and negative;\n2. Provide ways to convert to and from text strings, using digits '+', '−' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n3. Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type *is* balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n4. Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do *not* convert to native integers first.\n5. Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n**Test case** With balanced ternaries *a* from string \"+−0++0+\", *b* from native integer −436, *c* \"+−++−\":\n\n* write out *a*, *b* and *c* in decimal notation;\n* calculate *a* × (*b* − *c*), write out the result in both ternary and decimal notations.\n\n**Note:** The pages generalised floating point addition and generalised floating point multiplication have code implementing arbitrary precision floating point balanced ternary."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2017.01\n\n```\nclass BT {\n has @.coeff;\n\n my %co2bt = '-1' => '-', '0' => '0', '1' => '+';\n my %bt2co = %co2bt.invert;\n\n multi method new (Str $s) {\n\tself.bless(coeff => %bt2co{$s.flip.comb});\n }\n multi method new (Int $i where $i >= 0) {\n\tself.bless(coeff => carry $i.base(3).comb.reverse);\n }\n multi method new (Int $i where $i < 0) {\n\tself.new(-$i).neg;\n }\n\n method Str () { %co2bt{@!coeff}.join.flip }\n method Int () { [+] @!coeff Z* (1,3,9...*) }\n\n multi method neg () {\n\tself.new: coeff => carry self.coeff X* -1;\n }\n}\n\nsub carry (*@digits is copy) {\n loop (my $i = 0; $i < @digits; $i++) {\n\twhile @digits[$i] < -1 { @digits[$i] += 3; @digits[$i+1]--; }\n\twhile @digits[$i] > 1 { @digits[$i] -= 3; @digits[$i+1]++; }\n }\n pop @digits while @digits and not @digits[*-1];\n @digits;\n}\n\nmulti prefix:<-> (BT $x) { $x.neg }\n\nmulti infix:<+> (BT $x, BT $y) {\n my ($b,$a) = sort +*.coeff, ($x, $y);\n BT.new: coeff => carry ($a.coeff Z+ |$b.coeff, |(0 xx $a.coeff - $b.coeff));\n}\n\nmulti infix:<-> (BT $x, BT $y) { $x + $y.neg }\n\nmulti infix:<*> (BT $x, BT $y) {\n my @x = $x.coeff;\n my @y = $y.coeff;\n my @z = 0 xx @x+@y-1;\n my @safe;\n for @x -> $xd {\n\t@z = @z Z+ |(@y X* $xd), |(0 xx @z-@y);\n\[email protected]: @z.shift;\n }\n BT.new: coeff => carry @safe, @z;\n}\n\nmy $a = BT.new: \"+-0++0+\";\nmy $b = BT.new: -436;\nmy $c = BT.new: \"+-++-\";\nmy $x = $a * ( $b - $c );\n\nsay 'a == ', $a.Int;\nsay 'b == ', $b.Int;\nsay 'c == ', $c.Int;\nsay \"a × (b − c) == \", ~$x, ' == ', $x.Int;\n\n```\n\nOutput:\n\n```\na == 523\nb == -436\nc == 65\na × (b − c) == ----0+--0++0 == -262023\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Banker's 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\nThe **Banker's algorithm** is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a \"s-state\" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue.\n\nExample input\n\nAssuming that the system distinguishes between four types of resources, (A, B, C and D), the following is an example of how those resources could be distributed.\n\n*Note that this example shows the system at an instant before a new request for resources arrives. Also, the types and number of resources are abstracted. Real systems, for example, would deal with much larger quantities of each resource.*\n\n```\nTotal resources in system:\nA B C D\n6 5 7 6\n\n```\n\n```\nAvailable system resources are:\nA B C D\n3 1 1 2\n\n```\n\n```\nProcesses (currently allocated resources):\n A B C D\nP1 1 2 2 1\nP2 1 0 3 3\nP3 1 2 1 0\n\n```\n\n```\nProcesses (maximum resources):\n A B C D\nP1 3 3 2 2\nP2 1 2 3 4\nP3 1 3 5 0\n\n```\n\n```\nNeed= maximum resources - currently allocated resources\nProcesses (need resources):\n A B C D\nP1 2 1 0 1\nP2 0 2 0 1\nP3 0 1 4 0\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nBased on the Python3 solution by Shubham Singh found\nhere\n\n```\nmy @avail = <3 1 1 2>; # Available instances of resource\nmy @maxm = <3 3 2 2>, <1 2 3 4>, <1 3 5 0>; # Maximum resources that can be allocated to processes\nmy @allot = <1 2 2 1>, <1 0 3 3>, <1 2 1 0>; # Resources allocated to processes\n\n# Function to find the system is in safe state or not\nsub isSafe(\\work is copy, \\maxm, \\allot) {\n my \\P = allot.elems; # Number of processes\n my \\Pool = (^P).SetHash; # Process pool\n my \\R = work.elems; # Number of resources \n my \\need = maxm »-« allot; # the need matrix\n my @safe-sequence;\n\n # While all processes are not finished or system is not in safe state\n my $count = 0;\n while $count < P {\n my $found = False;\n for Pool.keys -> \\p { \n if all need[p] »≤« work { # now process can be finished\n work »+=« allot[p;^R]; # Free the resources\n say 'available resources: ' ~ work;\n @safe-sequence.push: p; # Add this process to safe sequence\n Pool{p}--; # Remove this process from Pool\n $count += 1;\n $found = True\n }\n }\n # If we could not find a next process in safe sequence\n return False, \"System is not in safe state.\" unless $found;\n }\n # If system is in safe state then safe sequence will be as below\n return True, \"Safe sequence is: \" ~ @safe-sequence\n}\n\n# Check if system is in a safe state\nmy ($safe-state,$status-message) = isSafe @avail, @maxm, @allot;\nsay \"Safe state? $safe-state\";\nsay \"Message: $status-message\";\n\n```\n\nOutput:\n\n```\navailable resources: 4 3 3 3\navailable resources: 5 3 6 6\navailable resources: 6 5 7 6\nSafe state? True\nMessage: Safe sequence is: 0 1 2\n```"
}
]
|
[
{
"role": "user",
"content": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\nTask\n\nCreate this fractal fern, using the following transformations:\n\n* ƒ1 (chosen 1% of the time)\n\n```\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n```\n\n* ƒ2 (chosen 85% of the time)\n\n```\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = −0.04 xn + 0.85 yn + 1.6\n\n```\n\n* ƒ3 (chosen 7% of the time)\n\n```\n xn + 1 = 0.2 xn − 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n```\n\n* ƒ4 (chosen 7% of the time)\n\n```\n xn + 1 = −0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\n```\n\nStarting position: x = 0, y = 0"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.03\n\n**Translation of**: Perl\n\n```\nuse Image::PNG::Portable;\n\nmy ($w, $h) = (640, 640);\n\nmy $png = Image::PNG::Portable.new: :width($w), :height($h);\n\nmy ($x, $y) = (0, 0);\n\nfor ^2e5 {\n my $r = 100.rand;\n ($x, $y) = do given $r {\n when $r <= 1 { ( 0, 0.16 * $y ) }\n when $r <= 8 { ( 0.20 * $x - 0.26 * $y, 0.23 * $x + 0.22 * $y + 1.60) }\n when $r <= 15 { (-0.15 * $x + 0.28 * $y, 0.26 * $x + 0.24 * $y + 0.44) }\n default { ( 0.85 * $x + 0.04 * $y, -0.04 * $x + 0.85 * $y + 1.60) }\n };\n $png.set(($w / 2 + $x * 60).Int, ($h - $y * 60).Int, 0, 255, 0);\n}\n\n$png.write: 'Barnsley-fern-perl6.png';\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow in decimal notation all positive integers (less than **501**) which, when converted to hexadecimal notation, cannot be written without using at least one non-decimal digit ('a' to 'f')."
},
{
"role": "assistant",
"content": "Yet another poorly specced, poorly named, trivial task.\n\nHow many integers in base 16 cannot be written without using a hexadecimal digit? All of them. Or none of them.\n\nBase 16 is not hexadecimal. Hexadecimal is *an implementation* of base 16.\n\n```\nuse Base::Any;\nset-digits <⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ㉑ ㉒ ㉓ ㉔ ㉕>;\nsay (7**35).&to-base(16);\n\n# ⑭㉒⑱⑩⑰⑰⑳⑮⑱⑳⑩⑳⑱㉒㉑⑰㉒⑫⑭⑲⑯⑩㉔⑮⑰\n\n```\n\nHow many of those glyphs are decimal digits? And yet it **is** in base 16, albeit with non-standard digit glyphs. So they **all** can be written without using a hexadecimal digit.\n\nBut wait a minute; is 2 a hexadecimal digit? Why yes, yes it is. So *none* of them can be written in hexadecimal without using a hexadecimal digit.\n\nBah. Show which when written in base 16, contain a digit glyph with a value greater than 9:\n\n```\nput display :20cols, :fmt('%3d'), (^501).grep( { so any |.map: { .polymod(16 xx *) »>» 9 } } );\n\nsub display ($list, :$cols = 10, :$fmt = '%6d', :$title = \"{+$list} matching:\\n\" ) {\n cache $list;\n $title ~ $list.batch($cols)».fmt($fmt).join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\n301 matching:\n 10 11 12 13 14 15 26 27 28 29 30 31 42 43 44 45 46 47 58 59\n 60 61 62 63 74 75 76 77 78 79 90 91 92 93 94 95 106 107 108 109\n110 111 122 123 124 125 126 127 138 139 140 141 142 143 154 155 156 157 158 159\n160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179\n180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199\n200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219\n220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239\n240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 266 267 268 269\n270 271 282 283 284 285 286 287 298 299 300 301 302 303 314 315 316 317 318 319\n330 331 332 333 334 335 346 347 348 349 350 351 362 363 364 365 366 367 378 379\n380 381 382 383 394 395 396 397 398 399 410 411 412 413 414 415 416 417 418 419\n420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439\n440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459\n460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479\n480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499\n500\n```\n\nBut wait a minute. Let's take another look at the the task title. **Base-16 representation**. It isn't talking about Base 16 at all. It's talking about Base**-16**... so let's do it in base -16.\n\n```\nuse Base::Any;\n\nput display :20cols, :fmt('%3d'), (^501).grep( { .&to-base(-16).contains: /<[A..F]>/ } );\n\nsub display ($list, :$cols = 10, :$fmt = '%6d', :$title = \"{+$list} matching:\\n\" ) {\n cache $list;\n $title ~ $list.batch($cols)».fmt($fmt).join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\n306 matching:\n 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29\n 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49\n 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69\n 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89\n 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109\n110 111 122 123 124 125 126 127 138 139 140 141 142 143 154 155 156 157 158 159\n170 171 172 173 174 175 186 187 188 189 190 191 202 203 204 205 206 207 218 219\n220 221 222 223 234 235 236 237 238 239 250 251 252 253 254 255 266 267 268 269\n270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289\n290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309\n310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329\n330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349\n350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 378 379\n380 381 382 383 394 395 396 397 398 399 410 411 412 413 414 415 426 427 428 429\n430 431 442 443 444 445 446 447 458 459 460 461 462 463 474 475 476 477 478 479\n490 491 492 493 494 495\n```\n\nOf course, if you are looking for the **count** of the hexadecimal numbers up to some threshold that only use \"decimal\" digits, it is silly and counter-productive to iterate through them and check ***each*** when you really only need to check ***one***.\n\n```\nuse Lingua::EN::Numbers;\n\nfor 500\n ,10**8\n ,10**25\n ,10**35\n -> $threshold {\n my $limit = $threshold.base(16);\n my $i = $limit.index: ['A'..'F'];\n quietly $limit = $limit.substr(0, $i) ~ ('9' x ($limit.chars - $i)) if $i.Str;\n\n for ' CAN ', $limit,\n 'CAN NOT', $threshold - $limit {\n printf( \"Quantity of numbers up to %s that %s be expressed in hexadecimal without using any alphabetics: %*s\\n\",\n comma($threshold), $^a, comma($threshold).chars, comma($^c) )\n }\n\n say '';\n}\n\n```\n\nOutput:\n\n```\nQuantity of numbers up to 500 that CAN be expressed in hexadecimal without using any alphabetics: 199\nQuantity of numbers up to 500 that CAN NOT be expressed in hexadecimal without using any alphabetics: 301\n\nQuantity of numbers up to 100,000,000 that CAN be expressed in hexadecimal without using any alphabetics: 5,999,999\nQuantity of numbers up to 100,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics: 94,000,001\n\nQuantity of numbers up to 10,000,000,000,000,000,000,000,000 that CAN be expressed in hexadecimal without using any alphabetics: 845,951,614,014,849,999,999\nQuantity of numbers up to 10,000,000,000,000,000,000,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics: 9,999,154,048,385,985,150,000,001\n\nQuantity of numbers up to 100,000,000,000,000,000,000,000,000,000,000,000 that CAN be expressed in hexadecimal without using any alphabetics: 134,261,729,999,999,999,999,999,999,999\nQuantity of numbers up to 100,000,000,000,000,000,000,000,000,000,000,000 that CAN NOT be expressed in hexadecimal without using any alphabetics: 99,999,865,738,270,000,000,000,000,000,000,001\n```"
}
]
|
[
{
"role": "user",
"content": "The popular encoding of small and medium-sized checksums is base16, that is more compact than usual base10 and is human readable... For checksums resulting in *hash digests* bigger than ~100 bits, the base16 is too long: base58 is shorter and (when using good alphabet) preserves secure human readability. The most popular alphabet of base58 is the variant used in bitcoin address (see Bitcoin/address validation), so it is the \"default base58 alphabet\".\n\nWrite a program that takes a checksum (resultant hash digest) *integer binary* representation as argument, and converts (encode it) into base58 with the standard Bitcoin alphabet — which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n\n: : : * **O** the uppercase letter \"oh\",\n * **I** the uppercase letter \"eye\",\n * **l** the lowercase letter \"ell\", and\n * **0** the digit zero.\n\nThe *reference algorithm* is at the Bitcoin's Base58Check page."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub encode_Base58 ( Int $x ) {\n constant @codes = <\n 1 2 3 4 5 6 7 8 9\n A B C D E F G H J K L M N P Q R S T U V W X Y Z\n a b c d e f g h i j k m n o p q r s t u v w x y z\n >;\n\n return @codes[ $x.polymod( 58 xx * ) ].join.flip;\n}\n\nmy @tests = \n 25420294593250030202636073700053352635053786165627414518 => '6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM',\n 0x61 => '2g',\n 0x626262 => 'a3gV',\n 0x636363 => 'aPEr',\n 0x73696d706c792061206c6f6e6720737472696e67 => '2cFupjhnEsSn59qHXstmK2ffpLv2',\n 0x516b6fcd0f => 'ABnLTmg',\n 0xbf4f89001e670274dd => '3SEo3LWLoPntC',\n 0x572e4794 => '3EFU7m',\n 0xecac89cad93923c02321 => 'EJDM8drfXA6uyA',\n 0x10c8511e => 'Rt5zm',\n;\nuse Test;\nfor @tests {\n is encode_Base58(.key), .value, \"{.key} encodes to {.value}\";\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "See Base64 encode data.\n\nNow write a program that takes the output of the Base64 encode data task as input and regenerate the original file.\n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\n```\nmy $e64 = '\nVG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2\n9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\n';\n\nmy @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';\nmy %base64 is default(0) = @base64map.pairs.invert;\n\nsub base64-decode-slow ($enc) {\n my $buf = Buf.new;\n for $enc.subst(/\\s/, '', :g).comb(4) -> $chunck {\n $buf.append: |(sprintf \"%06d%06d%06d%06d\", |$chunck.comb.map:\n {%base64{$_}.base(2)}).comb(8).map: {:2($_)};\n }\n $buf\n}\n\nsay 'Slow:';\nsay base64-decode-slow($e64).decode('utf8');\n\n\n# Of course, the above routine is slow and is only for demonstration purposes.\n# For real code you should use a module, which is MUCH faster and heavily tested.\nsay \"\\nFast:\";\nuse Base64::Native;\nsay base64-decode($e64).decode('utf8');\n\n```\n\nOutput:\n\n```\nSlow:\nTo err is human, but to really foul things up you need a computer.\n -- Paul R. Ehrlich\n\nFast:\nTo err is human, but to really foul things up you need a computer.\n -- Paul R. Ehrlich\n```"
}
]
|
[
{
"role": "user",
"content": "Convert an array of bytes or binary string to the base64-encoding of that string and output that value. Use the icon for Rosetta Code as the data to convert.\n\nSee also Base64 decode data."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub MAIN {\n my $buf = slurp(\"./favicon.ico\", :bin);\n say buf-to-Base64($buf);\n}\n\nmy @base64map = flat 'A' .. 'Z', 'a' .. 'z', ^10, '+', '/';\n\nsub buf-to-Base64($buf) {\n join '', gather for $buf.list -> $a, $b = [], $c = [] {\n my $triplet = ($a +< 16) +| ($b +< 8) +| $c;\n take @base64map[($triplet +> (6 * 3)) +& 0x3F];\n take @base64map[($triplet +> (6 * 2)) +& 0x3F];\n if $c.elems {\n take @base64map[($triplet +> (6 * 1)) +& 0x3F];\n take @base64map[($triplet +> (6 * 0)) +& 0x3F];\n }\n elsif $b.elems {\n take @base64map[($triplet +> (6 * 1)) +& 0x3F];\n take '=';\n }\n else { take '==' }\n }\n}\n\n```\n\nOutput:\n\n```\nAAABAAIAEBAAAAAAAABoBQAAJgAAACAgAA...QAAAAEAAAABAAAAAQAAAAE=\n```"
}
]
|
[
{
"role": "user",
"content": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly **n** elements. Each element of the sequence **Bn** is the number of partitions of a set of size **n** where order of the elements and order of the partitions are non-significant. E.G.: **{a b}** is the same as **{b a}** and **{a} {b}** is the same as **{b} {a}**.\n\nSo\n\n: **B0 = 1** trivially. There is only one way to partition a set with zero elements. **{ }**\n\n: **B1 = 1** There is only one way to partition a set with one element. **{a}**\n\n: **B2 = 2** Two elements may be partitioned in two ways. **{a} {b}, {a b}**\n\n: **B3 = 5** Three elements may be partitioned in five ways **{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}**\n\n: and so on.\n\nA simple way to find the Bell numbers is construct a **Bell triangle**, also known as an **Aitken's array** or **Peirce triangle**, and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\nTask\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the **first 15** and (if your language supports big Integers) **50th** elements of the sequence.\n\nIf you *do* use the Bell triangle method to generate the numbers, also show the **first ten rows** of the Bell triangle.\n\nSee also\n\n: * **OEIS:A000110 Bell or exponential numbers**\n * **OEIS:A011971 Aitken's array**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### via Aitken's array\n\n**Works with**: Rakudo version 2019.03\n\n```\n my @Aitkens-array = lazy [1], -> @b {\n my @c = @b.tail;\n @c.push: @b[$_] + @c[$_] for ^@b;\n @c\n } ... *;\n\n my @Bell-numbers = @Aitkens-array.map: { .head };\n\nsay \"First fifteen and fiftieth Bell numbers:\";\nprintf \"%2d: %s\\n\", 1+$_, @Bell-numbers[$_] for flat ^15, 49;\n\nsay \"\\nFirst ten rows of Aitken's array:\";\n.say for @Aitkens-array[^10];\n\n```\n\nOutput:\n\n```\nFirst fifteen and fiftieth Bell numbers:\n 1: 1\n 2: 1\n 3: 2\n 4: 5\n 5: 15\n 6: 52\n 7: 203\n 8: 877\n 9: 4140\n10: 21147\n11: 115975\n12: 678570\n13: 4213597\n14: 27644437\n15: 190899322\n50: 10726137154573358400342215518590002633917247281\n\nFirst ten rows of Aitken's array:\n[1]\n[1 2]\n[2 3 5]\n[5 7 10 15]\n[15 20 27 37 52]\n[52 67 87 114 151 203]\n[203 255 322 409 523 674 877]\n[877 1080 1335 1657 2066 2589 3263 4140]\n[4140 5017 6097 7432 9089 11155 13744 17007 21147]\n[21147 25287 30304 36401 43833 52922 64077 77821 94828 115975]\n```\n\n### via Recurrence relation\n\n**Works with**: Rakudo version 2019.03\n\n```\nsub binomial { [*] ($^n … 0) Z/ 1 .. $^p }\n\nmy @bell = 1, -> *@s { [+] @s »*« @s.keys.map: { binomial(@s-1, $_) } } … *;\n\n.say for @bell[^15], @bell[50 - 1];\n\n```\n\nOutput:\n\n```\n(1 1 2 5 15 52 203 877 4140 21147 115975 678570 4213597 27644437 190899322)\n10726137154573358400342215518590002633917247281\n```\n\n### via Stirling sums\n\n**Works with**: Rakudo version 2019.03\n\n```\nmy @Stirling_numbers_of_the_second_kind =\n (1,),\n { (0, |@^last) »+« (|(@^last »*« @^last.keys), 0) } … *\n;\nmy @bell = @Stirling_numbers_of_the_second_kind.map: *.sum;\n\n.say for @bell.head(15), @bell[50 - 1];\n\n```\n\nOutput:\n\n```\n(1 1 2 5 15 52 203 877 4140 21147 115975 678570 4213597 27644437 190899322)\n10726137154573358400342215518590002633917247281 \n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Benford's\\_law. 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\n**Benford's law**, also called the **first-digit law**, refers to the frequency distribution of digits in many (but not all) real-life sources of data.\n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.\n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit \n\nd\n{\\displaystyle {\\displaystyle d}}\n (\n\nd\n∈\n{\n1\n,\n…\n,\n9\n}\n{\\displaystyle {\\displaystyle d\\in \\{1,\\ldots ,9\\}}}\n) occurs with probability\n\n: : : : P\n (\n d\n )\n =\n\n log\n\n 10\n \n (\n d\n +\n 1\n )\n −\n\n log\n\n 10\n \n (\n d\n )\n =\n\n log\n\n 10\n \n\n (\n\n 1\n +\n\n\n 1\n d\n )\n {\\displaystyle {\\displaystyle P(d)=\\log \\_{10}(d+1)-\\log \\_{10}(d)=\\log \\_{10}\\left(1+{\\frac {1}{d}}\\right)}}\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.\n\nYou can generate them or load them from a file; whichever is easiest.\n\nDisplay your actual vs expected distribution.\n\n*For extra credit:* Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\nSee also:\n\n* numberphile.com.\n* A starting page on Wolfram Mathworld is Benfords Law ."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016-10-24\n\n```\nsub benford(@a) { bag +« @a».substr(0,1) }\n\nsub show(%distribution) {\n printf \"%9s %9s %s\\n\", <Actual Expected Deviation>;\n for 1 .. 9 -> $digit {\n my $actual = %distribution{$digit} * 100 / [+] %distribution.values;\n my $expected = (1 + 1 / $digit).log(10) * 100;\n printf \"%d: %5.2f%% | %5.2f%% | %.2f%%\\n\",\n $digit, $actual, $expected, abs($expected - $actual);\n }\n}\n\nmulti MAIN($file) { show benford $file.IO.lines }\nmulti MAIN() { show benford ( 1, 1, 2, *+* ... * )[^1000] }\n\n```\n\n**Output:** First 1000 Fibonaccis\n\n```\n Actual Expected Deviation\n1: 30.10% | 30.10% | 0.00%\n2: 17.70% | 17.61% | 0.09%\n3: 12.50% | 12.49% | 0.01%\n4: 9.60% | 9.69% | 0.09%\n5: 8.00% | 7.92% | 0.08%\n6: 6.70% | 6.69% | 0.01%\n7: 5.60% | 5.80% | 0.20%\n8: 5.30% | 5.12% | 0.18%\n9: 4.50% | 4.58% | 0.08%\n```\n\n**Extra credit:** Square Kilometers of land under cultivation, by country / territory. First column from Wikipedia: Land use statistics by country.\n\n```\n Actual Expected Deviation\n1: 33.33% | 30.10% | 3.23%\n2: 18.31% | 17.61% | 0.70%\n3: 13.15% | 12.49% | 0.65%\n4: 8.45% | 9.69% | 1.24%\n5: 9.39% | 7.92% | 1.47%\n6: 5.63% | 6.69% | 1.06%\n7: 4.69% | 5.80% | 1.10%\n8: 5.16% | 5.12% | 0.05%\n9: 1.88% | 4.58% | 2.70%\n```"
}
]
|
[
{
"role": "user",
"content": "The **Berlekamp–Massey algorithm** is an efficient algorithm for finding the shortest linear feedback shift register (LFSR) that generates a given sequence over a finite field. It determines the minimal polynomial of a linearly recurrent sequence, which is crucial in applications like error-correcting codes, cryptography, and sequence analysis.\n\nOverview\n\nGiven a sequence of elements \n\ns\n\n0\n,\n\ns\n\n1\n,\n…\n,\n\ns\n\nn\n−\n1\n{\\displaystyle {\\displaystyle s\\_{0},s\\_{1},\\dots ,s\\_{n-1}}}\n from a finite field, the Berlekamp–Massey algorithm computes the shortest LFSR, characterized by its connection polynomial \n\nC\n(\nx\n)\n=\n1\n+\n\nc\n\n1\nx\n+\n\nc\n\n2\n\nx\n\n2\n+\n⋯\n+\n\nc\n\nL\n\nx\n\nL\n{\\displaystyle {\\displaystyle C(x)=1+c\\_{1}x+c\\_{2}x^{2}+\\dots +c\\_{L}x^{L}}}\n, such that the sequence satisfies the recurrence relation:\n\n: s\n\n i\n +\n L\n =\n −\n\n ∑\n\n k\n =\n 1\n\n L\n\n c\n\n k\n\n s\n\n i\n +\n L\n −\n k\n {\\displaystyle {\\displaystyle s\\_{i+L}=-\\sum \\_{k=1}^{L}c\\_{k}s\\_{i+L-k}}}\n\nfor all valid indices. The degree \n\nL\n{\\displaystyle {\\displaystyle L}}\n of the polynomial is the *linear complexity* of the sequence, representing the length of the shortest LFSR.\n\nHistory\n\nThe algorithm was independently developed by Elwyn Berlekamp in 1968 for decoding BCH codes and by James Massey in 1969 for cryptographic applications. It remains a cornerstone in coding theory and sequence analysis.\n\nAlgorithm Description\n\nThe Berlekamp–Massey algorithm iteratively constructs the connection polynomial by processing the input sequence element by element. It maintains a current polynomial \n\nC\n(\nx\n)\n{\\displaystyle {\\displaystyle C(x)}}\n and updates it whenever a discrepancy is found between the predicted and actual sequence values. The key steps are:\n\n1. Initialize \n\nC\n(\nx\n)\n=\n1\n{\\displaystyle {\\displaystyle C(x)=1}}\n, degree \n\nL\n=\n0\n{\\displaystyle {\\displaystyle L=0}}\n, and a temporary polynomial \n\nB\n(\nx\n)\n=\n1\n{\\displaystyle {\\displaystyle B(x)=1}}\n.\n2. For each sequence element \n\ns\n\ni\n{\\displaystyle {\\displaystyle s\\_{i}}}\n:\n\n```\n * Compute the discrepancy \n \n \n \n \n \n Δ\n =\n \n s\n \n i\n \n \n +\n \n ∑\n \n k\n =\n 1\n \n \n L\n \n \n \n c\n \n k\n \n \n \n s\n \n i\n −\n k\n \n \n \n \n \n \n {\\displaystyle {\\displaystyle \\Delta =s_{i}+\\sum _{k=1}^{L}c_{k}s_{i-k}}}\n \n.\n * If \n \n \n \n \n \n Δ\n ≠\n 0\n \n \n \n \n {\\displaystyle {\\displaystyle \\Delta \\neq 0}}\n \n:\n * Update \n \n \n \n \n \n C\n (\n x\n )\n ←\n C\n (\n x\n )\n −\n Δ\n x\n B\n (\n x\n )\n \n \n \n \n {\\displaystyle {\\displaystyle C(x)\\leftarrow C(x)-\\Delta xB(x)}}\n \n.\n * If the discrepancy indicates a need for a longer LFSR (i.e., \n \n \n \n \n \n 2\n L\n ≤\n i\n \n \n \n \n {\\displaystyle {\\displaystyle 2L\\leq i}}\n \n), update \n \n \n \n \n \n L\n \n \n \n \n {\\displaystyle {\\displaystyle L}}\n \n and adjust \n \n \n \n \n \n B\n (\n x\n )\n \n \n \n \n {\\displaystyle {\\displaystyle B(x)}}\n \n.\n\n```\n\n3. Output \n\nC\n(\nx\n)\n{\\displaystyle {\\displaystyle C(x)}}\n and \n\nL\n{\\displaystyle {\\displaystyle L}}\n.\n\nThe algorithm runs in \n\nO\n(\n\nn\n\n2\n)\n{\\displaystyle {\\displaystyle O(n^{2})}}\n time, where \n\nn\n{\\displaystyle {\\displaystyle n}}\n is the sequence length, and uses \n\nO\n(\nn\n)\n{\\displaystyle {\\displaystyle O(n)}}\n space.\n\nApplications\n\n* **Error Correction**: Used in decoding Reed–Solomon codes and BCH codes.\n* **Cryptography**: Analyzes the linear complexity of sequences in stream ciphers to assess security.\n* **Sequence Analysis**: Identifies patterns in sequences for signal processing and data compression.\n\nExample\n\nFor the binary sequence \n\n0\n,\n0\n,\n1\n,\n1\n,\n0\n,\n1\n,\n0\n{\\displaystyle {\\displaystyle 0,0,1,1,0,1,0}}\n over \n\nG\nF\n(\n2\n)\n{\\displaystyle {\\displaystyle GF(2)}}\n, the algorithm yields the connection polynomial \n\nC\n(\nx\n)\n=\n1\n+\nx\n+\n\nx\n\n3\n{\\displaystyle {\\displaystyle C(x)=1+x+x^{3}}}\n, indicating a linear complexity of 3."
},
{
"role": "assistant",
"content": "**Translation of**: Python\n\n```\n# 20250510 Raku programming solution\n\nconstant MOD = 2;\n\nsub berlekamp_massey(@a) {\n my ($n, $w, $delta, @ans_coef, @lst) = @a.elems - 1, 0;\n for 1 .. $n -> $i {\n my $tmp = 0;\n for ^@ans_coef.elems -> $j {\n if $i - 1 - $j >= 1 {\n $tmp = ($tmp + @a[$i - 1 - $j] * @ans_coef[$j]) % MOD;\n }\n }\n my $discrepancy = (@a[$i] - $tmp + MOD) % MOD;\n next if $discrepancy == 0;\n if $w == 0 {\n @ans_coef = (0 xx $i);\n $w = $i;\n $delta = $discrepancy;\n next;\n }\n my @now = @ans_coef;\n my $mul = $discrepancy * expmod($delta, MOD - 2, MOD);\n my $needed_len = @lst.elems + $i - $w;\n if @ans_coef.elems < $needed_len {\n @ans_coef.append: (0 xx ($needed_len - @ans_coef.elems));\n }\n if $i - $w - 1 >= 0 {\n @ans_coef[$i - $w - 1] = (@ans_coef[$i - $w - 1] + $mul) % MOD;\n }\n for ^@lst.elems -> $j {\n my $idx = $i - $w + $j;\n if $idx < @ans_coef.elems {\n my $term_to_subtract = ($mul * @lst[$j]) % MOD;\n @ans_coef[$idx] = (@ans_coef[$idx] - $term_to_subtract + MOD) % MOD;\n }\n }\n if @ans_coef.elems > @now.elems {\n @lst = @now;\n $w = $i;\n $delta = $discrepancy;\n }\n }\n return @ans_coef.map: { ($^x + MOD) % MOD };\n}\n\nsub calculate_term($m, @coef, @h) {\n if $m < @h.elems { return (@h[$m] + MOD) % MOD }\n if ( my $k = @coef.elems ) == 0 { return 0 } \n my @p_coeffs = (1, |@coef);\n sub poly_mul(@a, @b, $degree_k, @p_poly) {\n my @res = (0 xx (2 * $degree_k));\n for ^$degree_k X ^$degree_k -> ($i, $j) {\n next if @a[$i] == 0;\n @res[$i + $j] = (@res[$i + $j] + @a[$i] * @b[$j]) % MOD;\n }\n for ( 2 * $degree_k - 1 ... $degree_k ) -> $i {\n next if @res[$i] == 0; \n my $term = @res[$i];\n @res[$i] = 0;\n for 0 .. $degree_k -> $j {\n if ( my $idx = $i - $j ) >= 0 { \n @res[$idx] = (@res[$idx] + $term * @p_poly[$j]) % MOD; \n }\n }\n }\n return @res[0 ... ^$degree_k];\n }\n my @f = (1, |(0 xx ($k - 1)));\n my @g = $k == 1 ?? (@p_coeffs[1],) !! (0, 1, |(0 xx ($k - 2)));\n my $power = $m;\n while $power > 0 {\n unless $power %% 2 { @f = poly_mul(@f, @g, $k, @p_coeffs) }\n @g = poly_mul(@g, @g, $k, @p_coeffs);\n $power div= 2;\n }\n my $final_ans = 0;\n for ^$k -> \\k {\n if k+1 < @h.elems { $final_ans = ($final_ans + @h[k+1] * @f[k]) % MOD }\n } \n return ($final_ans + MOD) % MOD;\n}\n\nsub solve {\n my @h_input = 0,0,1,1,0,1,0;\n my $n = @h_input.elems;\n my @h = 0, |@h_input;\n my @ans_coef = berlekamp_massey(@h);\n say @ans_coef.map({ ($^x + MOD) % MOD }).Str;\n my $m = 10;\n my $result = calculate_term($m, @ans_coef, @h);\n say ($result + MOD) % MOD;\n}\n\nsolve();\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Bernoulli numbers are used in some series expansions of several functions (trigonometric, hyperbolic, gamma, etc.), and are extremely important in number theory and analysis.\n\nNote that there are two definitions of Bernoulli numbers; this task will be using the modern usage (as per *The National Institute of Standards and Technology convention*).\n\nThe nth Bernoulli number is expressed as **B**n.\n\nTask\n\n: * show the Bernoulli numbers **B**0 through **B**60.\n * suppress the output of values which are equal to zero. (Other than **B**1 , all *odd* Bernoulli numbers have a value of zero.)\n * express the Bernoulli numbers as fractions (most are improper fractions).\n * the fractions should be reduced.\n * index each number in some way so that it can be discerned which Bernoulli number is being displayed.\n * align the solidi (**/**) if used (extra credit).\n\nAn algorithm\n\nThe Akiyama–Tanigawa algorithm for the \"second Bernoulli numbers\" as taken from wikipedia is as follows:\n\n```\n for m from 0 by 1 to n do\n A[m] ← 1/(m+1)\n for j from m by -1 to 1 do\n A[j-1] ← j×(A[j-1] - A[j])\n return A[0] (which is Bn)\n\n```\n\nSee also\n\n* Sequence A027641 Numerator of Bernoulli number B\\_n on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A027642 Denominator of Bernoulli number B\\_n on The On-Line Encyclopedia of Integer Sequences.\n* Entry Bernoulli number on The Eric Weisstein's World of Mathematics (TM).\n* Luschny's The Bernoulli Manifesto for a discussion on **B1 = -½** versus **+½**."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Simple\n\nFirst, a straighforward implementation of the naïve algorithm in the task description.\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub bernoulli($n) {\n my @a;\n for 0..$n -> $m {\n @a[$m] = FatRat.new(1, $m + 1);\n for reverse 1..$m -> $j {\n @a[$j - 1] = $j * (@a[$j - 1] - @a[$j]);\n }\n }\n return @a[0];\n}\n\nconstant @bpairs = grep *.value.so, ($_ => bernoulli($_) for 0..60);\n\nmy $width = max @bpairs.map: *.value.numerator.chars;\nmy $form = \"B(%2d) = \\%{$width}d/%d\\n\";\n\nprintf $form, .key, .value.nude for @bpairs;\n\n```\n\nOutput:\n\n```\nB( 0) = 1/1\nB( 1) = 1/2\nB( 2) = 1/6\nB( 4) = -1/30\nB( 6) = 1/42\nB( 8) = -1/30\nB(10) = 5/66\nB(12) = -691/2730\nB(14) = 7/6\nB(16) = -3617/510\nB(18) = 43867/798\nB(20) = -174611/330\nB(22) = 854513/138\nB(24) = -236364091/2730\nB(26) = 8553103/6\nB(28) = -23749461029/870\nB(30) = 8615841276005/14322\nB(32) = -7709321041217/510\nB(34) = 2577687858367/6\nB(36) = -26315271553053477373/1919190\nB(38) = 2929993913841559/6\nB(40) = -261082718496449122051/13530\nB(42) = 1520097643918070802691/1806\nB(44) = -27833269579301024235023/690\nB(46) = 596451111593912163277961/282\nB(48) = -5609403368997817686249127547/46410\nB(50) = 495057205241079648212477525/66\nB(52) = -801165718135489957347924991853/1590\nB(54) = 29149963634884862421418123812691/798\nB(56) = -2479392929313226753685415739663229/870\nB(58) = 84483613348880041862046775994036021/354\nB(60) = -1215233140483755572040304994079820246041491/56786730\n```\n\n### With memoization\n\nHere is a much faster way, following the Perl solution that avoids recalculating previous values each time through the function. We do this in Raku by not defining it as a function at all, but by defining it as an infinite sequence that we can read however many values we like from (52, in this case, to get up to B(100)). In this solution we've also avoided subscripting operations; rather we use a sequence operator (...) iterated over the list of the previous solution to find the next solution. We reverse the array in this case to make reference to the previous value in the list more natural, which means we take the last value of the list rather than the first value, and do so conditionally to avoid 0 values.\n\n**Works with**: Rakudo version 2015.12\n\n```\nconstant bernoulli = gather {\n my @a;\n for 0..* -> $m {\n @a = FatRat.new(1, $m + 1),\n -> $prev {\n my $j = @a.elems;\n $j * (@a.shift - $prev);\n } ... { not @a.elems }\n take $m => @a[*-1] if @a[*-1];\n }\n}\n\nconstant @bpairs = bernoulli[^52];\n\nmy $width = max @bpairs.map: *.value.numerator.chars;\nmy $form = \"B(%d)\\t= \\%{$width}d/%d\\n\";\n\nprintf $form, .key, .value.nude for @bpairs;\n\n```\n\nOutput:\n\n```\nB(0)\t= 1/1\nB(1)\t= 1/2\nB(2)\t= 1/6\nB(4)\t= -1/30\nB(6)\t= 1/42\nB(8)\t= -1/30\nB(10)\t= 5/66\nB(12)\t= -691/2730\nB(14)\t= 7/6\nB(16)\t= -3617/510\nB(18)\t= 43867/798\nB(20)\t= -174611/330\nB(22)\t= 854513/138\nB(24)\t= -236364091/2730\nB(26)\t= 8553103/6\nB(28)\t= -23749461029/870\nB(30)\t= 8615841276005/14322\nB(32)\t= -7709321041217/510\nB(34)\t= 2577687858367/6\nB(36)\t= -26315271553053477373/1919190\nB(38)\t= 2929993913841559/6\nB(40)\t= -261082718496449122051/13530\nB(42)\t= 1520097643918070802691/1806\nB(44)\t= -27833269579301024235023/690\nB(46)\t= 596451111593912163277961/282\nB(48)\t= -5609403368997817686249127547/46410\nB(50)\t= 495057205241079648212477525/66\nB(52)\t= -801165718135489957347924991853/1590\nB(54)\t= 29149963634884862421418123812691/798\nB(56)\t= -2479392929313226753685415739663229/870\nB(58)\t= 84483613348880041862046775994036021/354\nB(60)\t= -1215233140483755572040304994079820246041491/56786730\nB(62)\t= 12300585434086858541953039857403386151/6\nB(64)\t= -106783830147866529886385444979142647942017/510\nB(66)\t= 1472600022126335654051619428551932342241899101/64722\nB(68)\t= -78773130858718728141909149208474606244347001/30\nB(70)\t= 1505381347333367003803076567377857208511438160235/4686\nB(72)\t= -5827954961669944110438277244641067365282488301844260429/140100870\nB(74)\t= 34152417289221168014330073731472635186688307783087/6\nB(76)\t= -24655088825935372707687196040585199904365267828865801/30\nB(78)\t= 414846365575400828295179035549542073492199375372400483487/3318\nB(80)\t= -4603784299479457646935574969019046849794257872751288919656867/230010\nB(82)\t= 1677014149185145836823154509786269900207736027570253414881613/498\nB(84)\t= -2024576195935290360231131160111731009989917391198090877281083932477/3404310\nB(86)\t= 660714619417678653573847847426261496277830686653388931761996983/6\nB(88)\t= -1311426488674017507995511424019311843345750275572028644296919890574047/61410\nB(90)\t= 1179057279021082799884123351249215083775254949669647116231545215727922535/272118\nB(92)\t= -1295585948207537527989427828538576749659341483719435143023316326829946247/1410\nB(94)\t= 1220813806579744469607301679413201203958508415202696621436215105284649447/6\nB(96)\t= -211600449597266513097597728109824233673043954389060234150638733420050668349987259/4501770\nB(98)\t= 67908260672905495624051117546403605607342195728504487509073961249992947058239/6\nB(100)\t= -94598037819122125295227433069493721872702841533066936133385696204311395415197247711/33330\n```\n\n### Functional\n\nAnd if you're a pure enough FP programmer to dislike destroying and reconstructing the array each time, here's the same algorithm without side effects. We use zip with the pair constructor => to keep values associated with their indices. This provides sufficient local information that we can define our own binary operator \"bop\" to reduce between each two terms, using the \"triangle\" form (called \"scan\" in Haskell) to return the intermediate results that will be important to compute the next Bernoulli number.\n\n**Works with**: Rakudo version 2016.12\n\n```\nsub infix:<bop>(\\prev, \\this) {\n this.key => this.key * (this.value - prev.value)\n}\n\nsub next-bernoulli ( (:key($pm), :value(@pa)) ) {\n $pm + 1 => [\n map *.value,\n [\\bop] ($pm + 2 ... 1) Z=> FatRat.new(1, $pm + 2), |@pa\n ]\n}\n\nconstant bernoulli =\n grep *.value,\n map { .key => .value[*-1] },\n (0 => [FatRat.new(1,1)], &next-bernoulli ... *)\n;\n\nconstant @bpairs = bernoulli[^52];\n \nmy $width = max @bpairs.map: *.value.numerator.chars;\nmy $form = \"B(%d)\\t= \\%{$width}d/%d\\n\";\n \nprintf $form, .key, .value.nude for @bpairs;\n\n```\n\nSame output as memoization example"
}
]
|
[
{
"role": "user",
"content": "The \n\nn\n+\n1\n{\\displaystyle {\\displaystyle n+1}}\n Bernstein basis polynomials of degree \n\nn\n{\\displaystyle {\\displaystyle n}}\n are defined as\n\n: b\n\n k\n ,\n n\n (\n t\n )\n =\n\n (\n\n n\n k\n\n )\n\n t\n\n k\n\n\n (\n\n 1\n −\n t\n )\n\n n\n −\n k\n ,\n\n k\n =\n 0\n ,\n …\n ,\n n\n {\\displaystyle {\\displaystyle b\\_{k,n}(t)={\\binom {n}{k}}t^{k}\\left(1-t\\right)^{n-k},\\quad k=0,\\ldots ,n}}\n\nAny real polynomial can written as a linear combination of such Bernstein basis polynomials. Let us call the coefficients in such linear combinations *Bernstein coefficients*.\n\nThe goal of this task is to write subprograms for working with degree-2 and degree-3 Bernstein coefficients. A programmer is likely to have to deal with such representations. For example, OpenType fonts store glyph outline data as as either degree-2 or degree-3 Bernstein coefficients.\n\nThe task is as follows:\n\n1. Write a subprogram (which we will call *Subprogram (1)*) to transform the ordinary monomial coefficients of a real polynomial, of degree 2 or less, to Bernstein coefficients for the degree-2 basis.\n2. Write *Subprogram (2)* to evaluate, at a given point, a real polynomial written in degree-2 Bernstein coefficients. For this use de Casteljau's algorithm.\n3. Write *Subprogram (3)* to transform the monomial coefficients of a real polynomial, of degree 3 or less, to Bernstein coefficients for degree 3.\n4. Write *Subprogram (4)* to evaluate, at a given point, a real polynomial written in degree-3 Bernstein coefficients. Use de Casteljau's algorithm.\n5. Write *Subprogram (5)* to transform Bernstein coefficients for degree 2 to Bernstein coefficients for degree 3.\n6. For the following polynomials, use *Subprogram (1)* to find Bernstein coefficients for the degree-2 basis: \n\n p\n (\n x\n )\n =\n 1\n {\\displaystyle {\\displaystyle p(x)=1}}\n , \n\n q\n (\n x\n )\n =\n 1\n +\n 2\n x\n +\n 3\n\n x\n\n 2\n {\\displaystyle {\\displaystyle q(x)=1+2x+3x^{2}}}\n . Display the results.\n7. Use *Subprogram (2)* to evaluate \n\n p\n (\n x\n )\n {\\displaystyle {\\displaystyle p(x)}}\n and \n\n q\n (\n x\n )\n {\\displaystyle {\\displaystyle q(x)}}\n at \n\n x\n =\n 0.25\n {\\displaystyle {\\displaystyle x=0.25}}\n and at \n\n x\n =\n 7.50\n {\\displaystyle {\\displaystyle x=7.50}}\n . Display the results. Optionally also evaluate the polynomials in the monomial basis and display the results. (For the monomial basis it is best to use a Horner scheme.)\n8. Use *Subprogram (3)* to find degree-3 Bernstein coefficients for \n\n p\n (\n x\n )\n {\\displaystyle {\\displaystyle p(x)}}\n and \n\n q\n (\n x\n )\n {\\displaystyle {\\displaystyle q(x)}}\n , and additionally also for \n\n r\n (\n x\n )\n =\n 1\n +\n 2\n x\n +\n 3\n\n x\n\n 2\n +\n 4\n\n x\n\n 3\n {\\displaystyle {\\displaystyle r(x)=1+2x+3x^{2}+4x^{3}}}\n . Display the results.\n9. Use *Subprogram (4)* to evaluate \n\n p\n (\n x\n )\n {\\displaystyle {\\displaystyle p(x)}}\n , \n\n q\n (\n x\n )\n {\\displaystyle {\\displaystyle q(x)}}\n , and \n\n r\n (\n x\n )\n {\\displaystyle {\\displaystyle r(x)}}\n at \n\n x\n =\n 0.25\n {\\displaystyle {\\displaystyle x=0.25}}\n and \n\n x\n =\n 7.50\n {\\displaystyle {\\displaystyle x=7.50}}\n . Display the results. Optionally also evaluate them in the monomial basis and display the results. (You may have done that already for \n\n p\n (\n x\n )\n {\\displaystyle {\\displaystyle p(x)}}\n and \n\n q\n (\n x\n )\n {\\displaystyle {\\displaystyle q(x)}}\n .)\n10. Use *Subprogram (5)* to get degree-3 Bernstein coefficients for \n\n p\n (\n x\n )\n {\\displaystyle {\\displaystyle p(x)}}\n and \n\n q\n (\n x\n )\n {\\displaystyle {\\displaystyle q(x)}}\n from their degree-2 Bernstein coefficients. Display the results.\n\nALGOL 60 and Python implementations are provided as initial examples. The latter does the optional monomial-basis evaluations.\n\nYou can use the following algorithms. They are written in unambiguous Algol 60 reference language instead of a made up pseudo-language. The ALGOL 60 example was necessary to check my work, but these reference versions are in the actual standard language designed for the printing of algorithms.\n\n```\nprocedure tobern2 (a0, a1, a2, b0, b1, b2);\n value a0, a1, a2; comment pass by value;\n real a0, a1, a2;\n real b0, b1, b2;\ncomment Subprogram (1): transform monomial coefficients a0, a1, a2 to Bernstein coefficients b0, b1, b2;\nbegin\n b0 := a0;\n b1 := a0 + ((1/2) × a1);\n b2 := a0 + a1 + a2\nend tobern2;\n\n```\n\n```\nreal procedure evalbern2 (b0, b1, b2, t);\n value b0, b1, b2, t;\n real b0, b1, b2, t;\ncomment Subprogram (2): evaluate, at t, the polynomial with Bernstein coefficients b0, b1, b2. Use de Casteljau’s algorithm;\nbegin\n real s, b01, b12, b012;\n s := 1 - t;\n b01 := (s × b0) + (t × b1);\n b12 := (s × b1) + (t × b2);\n b012 := (s × b01) + (t × b12);\n evalbern2 := b012\nend evalbern2;\n\n```\n\n```\nprocedure tobern3 (a0, a1, a2, a3, b0, b1, b2, b3);\n value a0, a1, a2, a3;\n real a0, a1, a2, a3;\n real b0, b1, b2, b3;\ncomment Subprogram (3): transform monomial coefficients a0, a1, a2, a3 to Bernstein coefficients b0, b1, b2, b3;\nbegin\n b0 := a0;\n b1 := a0 + ((1/3) × a1);\n b2 := a0 + ((2/3) × a1) + ((1/3) × a2);\n b3 := a0 + a1 + a2 + a3\nend tobern3; \n\n```\n\n```\nreal procedure evalbern3 (b0, b1, b2, b3, t);\n value b0, b1, b2, b3, t;\n real b0, b1, b2, b3, t;\ncomment Subprogram (4): evaluate, at t, the polynomial with Bernstein coefficients b0, b1, b2, b3. Use de Casteljau's algorithm;\nbegin\n real s, b01, b12, b23, b012, b123, b0123;\n s := 1 - t;\n b01 := (s × b0) + (t × b1);\n b12 := (s × b1) + (t × b2);\n b23 := (s × b2) + (t × b3);\n b012 := (s × b01) + (t × b12);\n b123 := (s × b12) + (t × b23);\n b0123 := (s × b012) + (t × b123);\n evalbern3 := b0123\nend evalbern3;\n\n```\n\n```\nprocedure bern2to3 (q0, q1, q2, c0, c1, c2, c3);\n value q0, q1, q2;\n real q0, q1, q2;\n real c0, c1, c2, c3;\ncomment Subprogram (5): transform the quadratic Bernstein coefficients q0, q1, q2 to the cubic Bernstein coefficients c0, c1, c2, c3;\nbegin\n c0 := q0;\n c1 := ((1/3) × q0) + ((2/3) × q1);\n c2 := ((2/3) × q1) + ((1/3) × q2);\n c3 := q2\nend bern2to3;\n\n```"
},
{
"role": "assistant",
"content": "**Translation of**: Wren\n\n```\n# 20230601 Raku programming solution\n\nsub toBern2 { [ @_[0], @_[0]+@_[1]/2, @_[0..2].sum ] }\n\nsub toBern3 (@a) { @a[0], @a[0]+@a[1]/3, @a[0]+@a[1]*2/3+@a[2]/3, @a[0..3].sum }\n\nsub evalBern-N (@b, $t) { # uses de Casteljau's algorithm\n my ($s, @bern) = 1 - $t, @b.Slip;\n while ( @bern.elems > 2 ) { \n @bern = @bern.rotor(2 => -1).map: { $s * .[0] + $t * .[1] };\n }\n return $s * @bern[0] + $t * @bern[1] \n}\n\nsub evaluations (@m, @b, $x) {\n my $m = ([o] map { $_ + $x * * }, @m)(0); # Horner's rule\n return \"p({$x.fmt: '%.2f'}) = { evalBern-N @b, $x } (mono $m)\";\n}\n\nsub bern2to3 (@a) { @a[0], @a[0]/3+@a[1]*2/3, @a[1]*2/3+@a[2]/3, @a[2] }\n\nmy (@pm,@qm,@rm) := ([1, 0, 0], [1, 2, 3], [1, 2, 3, 4]);\n\nsay \"Subprogram(1) examples:\";\n\nmy (@pb2,@qb2) := (@pm,@qm).map: { toBern2 $_ };\nsay \"mono [{.[0]}] --> bern [{.[1]}]\" for (@pm,@pb2,@qm,@qb2).rotor: 2;\n\nsay \"\\nSubprogram(2) examples:\";\n\nfor (@pm,@pb2,@qm,@qb2).rotor(2) X (0.25,7.5) -> [[@m,@b], $x] {\n say evaluations @m, @b, $x \n}\n\nsay \"\\nSubprogram(3) examples:\";\n\n.push(0) for (@pm,@qm);\nmy (@pb3,@qb3,@rb3) := (@pm,@qm,@rm).map: { toBern3 $_ };\nsay \"mono [{.[0]}] --> bern [{.[1]}]\" for (@pm,@pb3,@qm,@qb3,@rm,@rb3).rotor: 2;\n\nsay \"\\nSubprogram(4) examples:\";\n\nfor (@pm,@pb3,@qm,@qb3,@rm,@rb3).rotor(2) X (0.25,7.5) -> [[@m,@b], $x] {\n say evaluations @m, @b, $x\n}\n\nsay \"\\nSubprogram(5) examples:\";\n\nmy (@pc,@qc) := (@pb2,@qb2).map: { bern2to3 $_ };\nsay \"mono [{.[1]}] --> bern [{.[0]}]\" for (@pc,@pb2,@qc,@qb2).rotor: 2;\n\n```\n\nOutput:\n\n```\nSubprogram(1) examples:\nmono [1 0 0] --> bern [1 1 1]\nmono [1 2 3] --> bern [1 2 6]\n\nSubprogram(2) examples:\np(0.25) = 1 (mono 1)\np(7.50) = 1 (mono 1)\np(0.25) = 1.6875 (mono 1.6875)\np(7.50) = 184.75 (mono 184.75)\n\nSubprogram(3) examples:\nmono [1 0 0 0] --> bern [1 1 1 1]\nmono [1 2 3 0] --> bern [1 1.666667 3.333333 6]\nmono [1 2 3 4] --> bern [1 1.666667 3.333333 10]\n\nSubprogram(4) examples:\np(0.25) = 1 (mono 1)\np(7.50) = 1 (mono 1)\np(0.25) = 1.6875 (mono 1.6875)\np(7.50) = 184.75 (mono 184.75)\np(0.25) = 1.75 (mono 1.75)\np(7.50) = 1872.25 (mono 1872.25)\n\nSubprogram(5) examples:\nmono [1 1 1] --> bern [1 1 1 1]\nmono [1 2 6] --> bern [1 1.666667 3.333333 6]\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShuffle the characters of a string in such a way that as many of the character values are in a different position as possible.\n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows:\n\n```\noriginal string, shuffled string, (score) \n\n```\n\nThe score gives the number of positions whose character value did *not* change.\n\nExample\n\n```\ntree, eetr, (0)\n\n```\n\nTest cases\n\n```\nabracadabra\nseesaw\nelk\ngrrrrrr\nup\na\n\n```\n\nRelated tasks\n\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\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**Translation of**: Sidef\n\n```\nsub best-shuffle(Str $orig) {\n my @s = $orig.comb;\n my @t = @s.pick(*);\n\n for flat ^@s X ^@s -> \\i,\\j {\n if i != j and @t[i] ne @s[j] and @t[j] ne @s[i] {\n @t[i,j] = @t[j,i] and last\n }\n }\n\n my $count = 0;\n for @t.kv -> $k,$v {\n ++$count if $v eq @s[$k]\n }\n\n @t.join, $count;\n}\n\nprintf \"%s, %s, (%d)\\n\", $_, best-shuffle $_ for <abracadabra seesaw elk grrrrrr up a>;\n\n```\n\nOutput:\n\n```\nabracadabra, raacarabadb, (0)\nseesaw, wssaee, (0)\nelk, lke, (0)\ngrrrrrr, rrrgrrr, (5)\nup, pu, (0)\na, a, (1)\n```"
}
]
|
[
{
"role": "user",
"content": "Description\n\nThe Bifid cipher is a polygraphic substitution cipher which was invented by Félix Delastelle in around 1901. It uses a 5 x 5 Polybius square combined with transposition and fractionation to encrypt a message. Any 5 x 5 Polybius square can be used but, as it only has 25 cells and there are 26 letters of the (English) alphabet, one cell needs to represent two letters - I and J being a common choice.\n\nOperation\n\nSuppose we want to encrypt the message \"ATTACKATDAWN\".\n\nWe use this archetypal Polybius square where I and J share the same position.\n\n```\nx/y 1 2 3 4 5\n-------------\n1 | A B C D E\n2 | F G H I K\n3 | L M N O P\n4 | Q R S T U \n5 | V W X Y Z\n\n```\n\nThe message is first converted to its x, y coordinates, but they are written vertically beneath.\n\n```\nA T T A C K A T D A W N\n1 4 4 1 1 2 1 4 1 1 5 3\n1 4 4 1 3 5 1 4 4 1 2 3\n\n```\n\nThey are then arranged in a row.\n\n```\n1 4 4 1 1 2 1 4 1 1 5 3 1 4 4 1 3 5 1 4 4 1 2 3\n\n```\n\nFinally, they are divided up into pairs which are used to look up the encrypted letters in the square.\n\n```\n14 41 12 14 11 53 14 41 35 14 41 23\nD Q B D A X D Q P D Q H\n\n```\n\nThe encrypted message is therefore \"DQBDAXDQPDQH\".\n\nDecryption can be achieved by simply reversing these steps.\n\nTask\n\nWrite routines in your language to encrypt and descrypt a message using the Bifid cipher.\n\nUse them to verify (including subsequent decryption):\n\n1. The above example.\n\n2. The example in the Wikipedia article using the message and Polybius square therein.\n\n3. The above example but using the Polybius square in the Wikipedia article to illustrate that it doesn't matter which square you use as long, of course, as the same one is used for both encryption and decryption.\n\nIn addition, encrypt and decrypt the message \"The invasion will start on the first of January\" using any Polybius square you like. Convert the message to upper case and ignore spaces.\n\nBonus\n\nSuggest a way in which the cipher could be modified so that ALL 26 letters can be uniquely encrypted.\n\nRelated task\n\nPlayfair cipher"
},
{
"role": "assistant",
"content": "Technically incorrect as the third part doesn't \"Convert ... to upper case and ignore spaces\".\n\n```\nsub polybius ($text) {\n my $n = $text.chars.sqrt.narrow;\n $text.comb.kv.map: { $^v => ($^k % $n, $k div $n).join: ' ' }\n}\n\nsub encrypt ($message, %poly) {\n %poly.invert.hash{(flat reverse [Z] %poly{$message.comb}».words).batch(2)».reverse».join: ' '}.join\n}\n\nsub decrypt ($message, %poly) {\n %poly.invert.hash{reverse [Z] (reverse flat %poly{$message.comb}».words».reverse).batch($message.chars)}.join\n}\n\n\nfor 'ABCDEFGHIKLMNOPQRSTUVWXYZ', 'ATTACKATDAWN',\n 'BGWKZQPNDSIOAXEFCLUMTHYVR', 'FLEEATONCE',\n (flat '_', '.', 'A'..'Z', 'a'..'z', 0..9).pick(*).join, 'The invasion will start on the first of January 2023.'.subst(/' '/, '_', :g)\n -> $polybius, $message {\n my %polybius = polybius $polybius;\n say \"\\nUsing polybius:\\n\\t\" ~ $polybius.comb.batch($polybius.chars.sqrt.narrow).join: \"\\n\\t\";\n say \"\\n Message : $message\";\n say \"Encrypted : \" ~ my $encrypted = encrypt $message, %polybius;\n say \"Decrypted : \" ~ decrypt $encrypted, %polybius;\n}\n\n```\n\nOutput:\n\n```\nUsing polybius:\n\tA B C D E\n\tF G H I K\n\tL M N O P\n\tQ R S T U\n\tV W X Y Z\n\n Message : ATTACKATDAWN\nEncrypted : DQBDAXDQPDQH\nDecrypted : ATTACKATDAWN\n\nUsing polybius:\n\tB G W K Z\n\tQ P N D S\n\tI O A X E\n\tF C L U M\n\tT H Y V R\n\n Message : FLEEATONCE\nEncrypted : UAEOLWRINS\nDecrypted : FLEEATONCE\n\nUsing polybius:\n\tH c F T N 5 f i\n\t_ U k R B Z V W\n\t3 G e v s w j x\n\tq S 2 8 y Q . O\n\tm 0 E d h D r u\n\tM p 7 Y 4 A 9 a\n\tt X l I 6 g b z\n\tJ P n 1 K L C o\n\n Message : The_invasion_will_start_on_the_first_of_January_2023.\nEncrypted : NGiw3okfXj4XoVE_NjWcLK4Sy28EivKo3aeNiti3N3z6HCHno6Fkf\nDecrypted : The_invasion_will_start_on_the_first_of_January_2023.\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nBilinear interpolation is linear interpolation in 2 dimensions, and is typically used for image scaling and for 2D finite element analysis.\n\nTask\n\nOpen an image file, enlarge it by 60% using bilinear interpolation, then either display the result or save the result to a file."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n#!/usr/bin/env perl6\n\nuse v6;\nuse GD::Raw;\n\n# Reference:\n# https://github.com/dagurval/perl6-gd-raw\n\nmy $fh1 = fopen('./Lenna100.jpg', \"rb\") or die;\nmy $img1 = gdImageCreateFromJpeg($fh1);\n\nmy $fh2 = fopen('./Lenna100-larger.jpg',\"wb\") or die;\n\nmy $img1X = gdImageSX($img1);\nmy $img1Y = gdImageSY($img1);\n\nmy $NewX = $img1X * 1.6;\nmy $NewY = $img1Y * 1.6;\n\ngdImageSetInterpolationMethod($img1, +GD_BILINEAR_FIXED);\n\nmy $img2 = gdImageScale($img1, $NewX.ceiling, $NewY.ceiling);\n\ngdImageJpeg($img2,$fh2,-1);\n\ngdImageDestroy($img1);\ngdImageDestroy($img2);\n\nfclose($fh1);\nfclose($fh2);\n\n```\n\nOutput:\n\n```\nfile Lenna100*\nLenna100.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 512x512, frames 3\nLenna100-larger.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: \"CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), default quality\", baseline, precision 8, 820x820, frames 3\n```"
}
]
|
[
{
"role": "user",
"content": "You are given a list of n ascending, unique numbers which are to form limits\nfor n+1 bins which count how many of a large set of input numbers fall in the\nrange of each bin.\n\n(Assuming zero-based indexing)\n\n```\n bin[0] counts how many inputs are < limit[0]\n bin[1] counts how many inputs are >= limit[0] and < limit[1]\n ..\n bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]\n bin[n] counts how many inputs are >= limit[n-1]\n\n```\n\nTask\n\nThe task is to create a function that given the ascending limits and a stream/\nlist of numbers, will return the bins; together with another function that\ngiven the same list of limits and the binning will *print the limit of each bin*\ntogether with the count of items that fell in the range*.*\n\nAssume the numbers to bin are too large to practically sort.\n\nTask examples\n\nPart 1: Bin using the following limits the given input data\n\n```\n limits = [23, 37, 43, 53, 67, 83]\n data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,\n 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]\n\n```\n\nPart 2: Bin using the following limits the given input data\n\n```\n limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]\n data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,\n 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,\n 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,\n 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,\n 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,\n 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]\n\n```\n\nShow output here, on this page."
},
{
"role": "assistant",
"content": "```\nsub bin_it ( @limits, @data ) {\n my @ranges = ( -Inf, |@limits, Inf ).rotor( 2 => -1 ).map: { .[0] ..^ .[1] };\n my @binned = @data.classify(-> $d { @ranges.grep(-> $r { $d ~~ $r }) });\n my %counts = @binned.map: { .key => .value.elems };\n return @ranges.map: { $_ => ( %counts{$_} // 0 ) };\n}\nsub bin_format ( @bins ) {\n return @bins.map: { .key.gist.fmt('%9s => ') ~ .value.fmt('%2d') };\n}\n\nmy @tests =\n {\n limits => (23, 37, 43, 53, 67, 83),\n data => (95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,16,8,9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55),\n },\n {\n limits => (14, 18, 249, 312, 389, 392, 513, 591, 634, 720),\n data => (\n 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,\n 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,\n 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,\n 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,\n 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749\n ),\n },\n;\nfor @tests -> ( :@limits, :@data ) {\n my @bins = bin_it( @limits, @data );\n .say for bin_format(@bins);\n say '';\n}\n\n```\n\nOutput:\n\n```\n-Inf..^23 => 11\n 23..^37 => 4\n 37..^43 => 2\n 43..^53 => 6\n 53..^67 => 9\n 67..^83 => 5\n 83..^Inf => 13\n\n-Inf..^14 => 3\n 14..^18 => 0\n 18..^249 => 44\n249..^312 => 10\n312..^389 => 16\n389..^392 => 2\n392..^513 => 28\n513..^591 => 16\n591..^634 => 6\n634..^720 => 16\n720..^Inf => 59\n\n```"
}
]
|
[
{
"role": "user",
"content": "Binary-Coded Decimal (or BCD for short) is a method of representing decimal numbers by storing what appears to be a decimal number but is actually stored as hexadecimal. Many CISC CPUs (e.g. X86 Assembly have special hardware routines for displaying these kinds of numbers.) On low-level hardware, such as 7-segment displays, binary-coded decimal is very important for outputting data in a format the end user can understand.\n\nTask\n\nUse your language's built-in BCD functions, OR create your own conversion function, that converts an addition of hexadecimal numbers to binary-coded decimal. You should get the following results with these test cases:\n\n* 0x19 + 1 = 0x20\n* 0x30 - 1 = 0x29\n* 0x99 + 1 = 0x100\n\nBonus Points\n\nDemonstrate the above test cases in both \"packed BCD\" (two digits per byte) and \"unpacked BCD\" (one digit per byte)."
},
{
"role": "assistant",
"content": "**Translation of**: Rust\n\n```\n# 20220930 Raku programming solution\n\nclass Bcd64 { has uint64 $.bits }\n\nmulti infix:<⊞> (Bcd64 \\p, Bcd64 \\q) {\n my $t1 = p.bits + 0x0666_6666_6666_6666;\n my $t2 = ( $t1 + q.bits ) % uint64.Range.max ; \n my $t3 = $t1 +^ q.bits; \n my $t4 = +^($t2 +^ $t3) +& 0x1111_1111_1111_1110;\n my $t5 = ($t4 +> 2) +| ($t4 +> 3);\n Bcd64.new: bits => ($t2 - $t5)\n}\n\nmulti prefix:<⊟> (Bcd64 \\p) {\n my $t1 = uint64.Range.max + 1 - p.bits ;\n my $t2 = ( $t1 + 0xFFFF_FFFF_FFFF_FFFF ) % uint64.Range.max;\n my $t3 = $t2 +^ 1;\n my $t4 = +^($t2 +^ $t3) +& 0x1111_1111_1111_1110;\n my $t5 = ($t4 +> 2) +| ($t4 +> 3);\n Bcd64.new: bits => ($t1 - $t5)\n}\n\nmulti infix:<⊟> (Bcd64 \\p, Bcd64 \\q) { p ⊞ ( ⊟q ) }\n\nmy ($one,$n19,$n30,$n99) = (0x01,0x19,0x30,0x99).map: { Bcd64.new: bits=>$_ };\n\n{ .bits.base(16).say } for ($n19 ⊞ $one,$n30 ⊟ $one,$n99 ⊞ $one);\n\n```\n\nOutput:\n\n```\n20\n29\n100\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate and display the sequence of binary digits for a given non-negative integer.\n\n```\n The decimal value 5 should produce an output of 101\n The decimal value 50 should produce an output of 110010\n The decimal value 9000 should produce an output of 10001100101000\n\n```\n\nThe results can be achieved using built-in radix functions within the language (if these are available), or alternatively a user defined function can be used.\n\nThe output produced should consist just of the binary digits of each number followed by a *newline*.\n\nThere should be no other whitespace, radix or sign markers in the produced output, and leading zeros should not appear in the results."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsay .fmt(\"%b\") for 5, 50, 9000;\n```\n\n```\n101\n110010\n10001100101000\n\n```\n\nAlternatively:\n\n```\nsay .base(2) for 5, 50, 9000;\n```\n\n```\n101\n110010\n10001100101000\n```"
}
]
|
[
{
"role": "user",
"content": "A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a \"divide and conquer\" algorithm.\n\nAs an analogy, consider the children's game \"guess a number.\" The scorer has a secret number, and will only tell the player if their guessed number is higher than, lower than, or equal to the secret number. The player then uses this information to guess a new number.\n\nAs the player, an optimal strategy for the general case is to start by choosing the range's midpoint as the guess, and then asking whether the guess was higher, lower, or equal to the secret number. If the guess was too high, one would select the point exactly between the range midpoint and the beginning of the range. If the original guess was too low, one would ask about the point exactly between the range midpoint and the end of the range. This process repeats until one has reached the secret number.\n\nTask\n\nGiven the starting point of a range, the ending point of a range, and the \"secret value\", implement a binary search through a sorted integer array for a certain number. Implementations can be recursive or iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print the index also.\n\nThere are several binary search algorithms commonly seen. They differ by how they treat multiple values equal to the given value, and whether they indicate whether the element was found or not. For completeness we will present pseudocode for all of them.\n\nAll of the following code examples use an \"inclusive\" upper bound (i.e. `high = N-1` initially). Any of the examples can be converted into an equivalent example using \"exclusive\" upper bound (i.e. `high = N` initially) by making the following simple changes (which simply increase `high` by 1):\n\n* change `high = N-1` to `high = N`\n* change `high = mid-1` to `high = mid`\n* (for recursive algorithm) change `if (high < low)` to `if (high <= low)`\n* (for iterative algorithm) change `while (low <= high)` to `while (low < high)`\n\nTraditional algorithm\n\nThe algorithms are as follows (from Wikipedia). The algorithms return the index of some element that equals the given value (if there are multiple such elements, it returns some arbitrary one). It is also possible, when the element is not found, to return the \"insertion point\" for it (the index that the value would have if it were inserted into the array).\n\n**Recursive Pseudocode**:\n\n```\n // initially called with low = 0, high = N-1\n BinarySearch(A[0..N-1], value, low, high) {\n // invariants: value > A[i] for all i < low\n value < A[i] for all i > high\n if (high < low)\n return not_found // value would be inserted at index \"low\"\n mid = (low + high) / 2\n if (A[mid] > value)\n return BinarySearch(A, value, low, mid-1)\n else if (A[mid] < value)\n return BinarySearch(A, value, mid+1, high)\n else\n return mid\n }\n\n```\n\n**Iterative Pseudocode**:\n\n```\n BinarySearch(A[0..N-1], value) {\n low = 0\n high = N - 1\n while (low <= high) {\n // invariants: value > A[i] for all i < low\n value < A[i] for all i > high\n mid = (low + high) / 2\n if (A[mid] > value)\n high = mid - 1\n else if (A[mid] < value)\n low = mid + 1\n else\n return mid\n }\n return not_found // value would be inserted at index \"low\"\n }\n\n```\n\nLeftmost insertion point\n\nThe following algorithms return the leftmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the lower (inclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than or equal to the given value (since if it were any lower, it would violate the ordering), or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level.\n\n**Recursive Pseudocode**:\n\n```\n // initially called with low = 0, high = N - 1\n BinarySearch_Left(A[0..N-1], value, low, high) {\n // invariants: value > A[i] for all i < low\n value <= A[i] for all i > high\n if (high < low)\n return low\n mid = (low + high) / 2\n if (A[mid] >= value)\n return BinarySearch_Left(A, value, low, mid-1)\n else\n return BinarySearch_Left(A, value, mid+1, high)\n }\n\n```\n\n**Iterative Pseudocode**:\n\n```\n BinarySearch_Left(A[0..N-1], value) {\n low = 0\n high = N - 1\n while (low <= high) {\n // invariants: value > A[i] for all i < low\n value <= A[i] for all i > high\n mid = (low + high) / 2\n if (A[mid] >= value)\n high = mid - 1\n else\n low = mid + 1\n }\n return low\n }\n\n```\n\nRightmost insertion point\n\nThe following algorithms return the rightmost place where the given element can be correctly inserted (and still maintain the sorted order). This is the upper (exclusive) bound of the range of elements that are equal to the given value (if any). Equivalently, this is the lowest index where the element is greater than the given value, or 1 past the last index if such an element does not exist. This algorithm does not determine if the element is actually found. This algorithm only requires one comparison per level. Note that these algorithms are almost exactly the same as the leftmost-insertion-point algorithms, except for how the inequality treats equal values.\n\n**Recursive Pseudocode**:\n\n```\n // initially called with low = 0, high = N - 1\n BinarySearch_Right(A[0..N-1], value, low, high) {\n // invariants: value >= A[i] for all i < low\n value < A[i] for all i > high\n if (high < low)\n return low\n mid = (low + high) / 2\n if (A[mid] > value)\n return BinarySearch_Right(A, value, low, mid-1)\n else\n return BinarySearch_Right(A, value, mid+1, high)\n }\n\n```\n\n**Iterative Pseudocode**:\n\n```\n BinarySearch_Right(A[0..N-1], value) {\n low = 0\n high = N - 1\n while (low <= high) {\n // invariants: value >= A[i] for all i < low\n value < A[i] for all i > high\n mid = (low + high) / 2\n if (A[mid] > value)\n high = mid - 1\n else\n low = mid + 1\n }\n return low\n }\n\n```\n\nExtra credit\n\nMake sure it does not have overflow bugs.\n\nThe line in the pseudo-code above to calculate the mean of two integers:\n\n```\nmid = (low + high) / 2\n```\n\ncould produce the wrong result in some programming languages when used with a bounded integer type, if the addition causes an overflow. (This can occur if the array size is greater than half the maximum integer value.) If signed integers are used, and `low + high` overflows, it becomes a negative number, and dividing by 2 will still result in a negative number. Indexing an array with a negative number could produce an out-of-bounds exception, or other undefined behavior. If unsigned integers are used, an overflow will result in losing the largest bit, which will produce the wrong result.\n\nOne way to fix it is to manually add half the range to the low number:\n\n```\nmid = low + (high - low) / 2\n```\n\nEven though this is mathematically equivalent to the above, it is not susceptible to overflow.\n\nAnother way for signed integers, possibly faster, is the following:\n\n```\nmid = (low + high) >>> 1\n```\n\nwhere `>>>` is the logical right shift operator. The reason why this works is that, for signed integers, even though it overflows, when viewed as an unsigned number, the value is still the correct sum. To divide an unsigned number by 2, simply do a logical right shift.\n\nRelated task\n: * Guess the number/With Feedback (Player)\n\nSee also\n: * wp:Binary search algorithm\n * Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nWith either of the below implementations of `binary_search`, one could write a function to search any object that does `Positional` this way:\n\n```\nsub search (@a, $x --> Int) {\n binary_search { $x cmp @a[$^i] }, 0, @a.end\n}\n```\n\n**Iterative**\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub binary_search (&p, Int $lo is copy, Int $hi is copy --> Int) {\n until $lo > $hi {\n my Int $mid = ($lo + $hi) div 2;\n given p $mid {\n when -1 { $hi = $mid - 1; } \n when 1 { $lo = $mid + 1; }\n default { return $mid; }\n }\n }\n fail;\n}\n```\n\n**Recursive**\n\n**Translation of**: Haskell\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub binary_search (&p, Int $lo, Int $hi --> Int) {\n $lo <= $hi or fail;\n my Int $mid = ($lo + $hi) div 2;\n given p $mid {\n when -1 { binary_search &p, $lo, $mid - 1 } \n when 1 { binary_search &p, $mid + 1, $hi }\n default { $mid }\n }\n}\n```"
}
]
|
[
{
"role": "user",
"content": "Many languages have powerful and useful (**binary safe**) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks.\n\nThis task is about creating functions to handle *binary* strings (strings made of arbitrary bytes, i.e. *byte strings* according to Wikipedia) for those languages that don't have built-in support for them.\n\nIf your language of choice does have this built-in support, show a possible alternative implementation for the *functions* or *abilities* already provided by the language.\n\nIn particular the functions you need to create are:\n\n* String creation and destruction (when needed and if there's no garbage collection or similar mechanism)\n* String assignment\n* String comparison\n* String cloning and copying\n* Check if a string is empty\n* Append a byte to a string\n* Extract a substring from a string\n* Replace every occurrence of a byte (or a string) in a string with another string\n* Join strings\n\nPossible contexts of use: compression algorithms (like LZW compression), L-systems (manipulation of symbols), many more."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\n# Raku is perfectly fine with NUL *characters* in strings:\nmy Str $s = 'nema' ~ 0.chr ~ 'problema!';\nsay $s;\n\n# However, Raku makes a clear distinction between strings\n# (i.e. sequences of characters), like your name, or …\nmy Str $str = \"My God, it's full of chars!\";\n# … and sequences of bytes (called Bufs), for example a PNG image, or …\nmy Buf $buf = Buf.new(255, 0, 1, 2, 3);\nsay $buf;\n\n# Strs can be encoded into Blobs …\nmy Blob $this = 'round-trip'.encode('ascii');\n# … and Blobs can be decoded into Strs …\nmy Str $that = $this.decode('ascii');\n\n# So it's all there. Nevertheless, let's solve this task explicitly\n# in order to see some nice language features:\n\n# We define a class …\nclass ByteStr {\n # … that keeps an array of bytes, and we delegate some\n # straight-forward stuff directly to this attribute:\n # (Note: \"has byte @.bytes\" would be nicer, but that is\n # not yet implemented in Rakudo.)\n has Int @.bytes handles(< Bool elems gist push >);\n\n # A handful of methods …\n method clone() {\n self.new(:@.bytes);\n }\n\n method substr(Int $pos, Int $length) {\n self.new(:bytes(@.bytes[$pos .. $pos + $length - 1]));\n }\n\n method replace(*@substitutions) {\n my %h = @substitutions;\n @.bytes.=map: { %h{$_} // $_ }\n }\n}\n\n# A couple of operators for our new type:\nmulti infix:<cmp>(ByteStr $x, ByteStr $y) { $x.bytes.join cmp $y.bytes.join }\nmulti infix:<~> (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes(|$x.bytes, |$y.bytes)) }\n\n# create some byte strings (destruction not needed due to garbage collection)\nmy ByteStr $b0 = ByteStr.new;\nmy ByteStr $b1 = ByteStr.new(:bytes( |'foo'.ords, 0, 10, |'bar'.ords ));\n\n# assignment ($b1 and $b2 contain the same ByteStr object afterwards):\nmy ByteStr $b2 = $b1;\n\n# comparing:\nsay 'b0 cmp b1 = ', $b0 cmp $b1;\nsay 'b1 cmp b2 = ', $b1 cmp $b2;\n\n# cloning:\nmy $clone = $b1.clone;\n$b1.replace('o'.ord => 0);\nsay 'b1 = ', $b1;\nsay 'b2 = ', $b2;\nsay 'clone = ', $clone;\n\n# to check for (non-)emptiness we evaluate the ByteStr in boolean context:\nsay 'b0 is ', $b0 ?? 'not empty' !! 'empty';\nsay 'b1 is ', $b1 ?? 'not empty' !! 'empty';\n\n# appending a byte:\n$b1.push: 123;\nsay 'appended = ', $b1;\n\n# extracting a substring:\nmy $sub = $b1.substr(2, 4);\nsay 'substr = ', $sub;\n\n# replacing a byte:\n$b2.replace(102 => 103);\nsay 'replaced = ', $b2;\n\n# joining:\nmy ByteStr $b3 = $b1 ~ $sub;\nsay 'joined = ', $b3;\n```\n\nOutput:\n\nNote: The ␀ represents a NUL byte.\n\n```\nnema␀problema!\nBuf:0x<ff 00 01 02 03>\nround-trip\nb0 cmp b1 = Less\nb1 cmp b2 = Same\nb1 = [102 0 0 0 10 98 97 114]\nb2 = [102 0 0 0 10 98 97 114]\nclone = [102 111 111 0 10 98 97 114]\nb0 is empty\nb1 is not empty\nappended = [102 0 0 0 10 98 97 114 123]\nsubstr = [0 0 10 98]\nreplaced = [103 0 0 0 10 98 97 114 123]\njoined = [103 0 0 0 10 98 97 114 123 0 0 10 98]\n```"
}
]
|
[
{
"role": "user",
"content": "The binomial transform is a bijective sequence transform based on convolution with binomial coefficients.\n\nIt may be thought of as an *nth* forward difference with odd differences carrying a negative sign.\n\nThere are two common variants of binomial transforms, one of which is self-inverting; *reapplying the transform to a transformed sequence returns the original sequence,* and one which has separate \"forward\" and \"inverse\" transform operations.\n\nThe two variants only differ in placement and quantity of signs. The variant standardized on by OEIS, *with the 'forward' and 'inverse' complementary operations*, will be used here.\n\nIn this variant, to transform the sequence *a* to sequence *b* and back:\n\nthe forward binomial transform is defined as: \n\nb\n\nn\n=\n\n∑\n\nk\n=\n0\n\nn\n\n(\n\nn\nk\n\n)\n\na\n\nk\n.\n{\\displaystyle {\\displaystyle b\\_{n}=\\sum \\_{k=0}^{n}{n \\choose k}a\\_{k}.}}\n\nand the inverse binomial transform is defined as: \n\na\n\nn\n=\n\n∑\n\nk\n=\n0\n\nn\n(\n−\n1\n\n)\n\nn\n−\nk\n\n(\n\nn\nk\n\n)\n\nb\n\nk\n{\\displaystyle {\\displaystyle a\\_{n}=\\sum \\_{k=0}^{n}(-1)^{n-k}{n \\choose k}b\\_{k}}}\n\nwhere \n\n(\n\nn\nk\n\n)\n{\\displaystyle {\\displaystyle {n \\choose k}}}\n is the binomial operator 'n choose k'\n\n*For reference, the self inverting binomial transform is defined as:* \n\nb\n\nn\n=\n\n∑\n\nk\n=\n0\n\nn\n(\n−\n1\n\n)\n\nk\n\n(\n\nn\nk\n\n)\n\na\n\nk\n{\\displaystyle {\\displaystyle b\\_{n}=\\sum \\_{k=0}^{n}(-1)^{k}{n \\choose k}a\\_{k}}}\n\nTask\n\n* Implement both a forward, and inverse binomial transform routine.\n* Use those routines to compute the forward binomial transform, the inverse binomial transform, and the inverse of the forward transform *(should return original sequence)* of a few representative sequences.\n* Show at least the first 15 values in each sequence.\n\n: *You may generate the sequences, or may choose to just hard code the values.*\n\n: Use the following sequences for testing:\n\n : Catalan numbers: `1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440`\n : Prime flip flop sequence: (for an: 1 if prime, 0 otherwise): `0 1 1 0 1 0 1 0 0 0 1 0 1 0 0`\n : Fibonacci sequence: `0 1 1 2 3 5 8 13 21 34 55 89 144 233 377`\n : Padovan sequence: (starting with values 1,0,0): `1 0 0 1 0 1 1 1 2 2 3 4 5 7 9`\n\nSee also\n\n* Wikipedia: Binomial transform * OEIS wiki: Binomial transform * Related task: Evaluate binomial coefficients * Related task: Catalan numbers * Related task: Riordan numbers * Related task: Fibonacci sequence * Related task: Padovan sequence\n\n: *first sequence*\n\n* OEIS:A007317 - Binomial transform of Catalan numbers * OEIS:A005043 - Riordan numbers (Inverse binomial transform of Catalan numbers)\n\n: *second sequence*\n\n* OEIS:A052467 - Binomial transform of {b(n)}, where b(n)=1 for prime n and b(n)=0 otherwise (Binomial transform of Prime flip-flop sequence\n\n: *third sequence*\n\n* OEIS:A001906 - F(2n) = bisection of Fibonacci sequence (Binomial transform of Fibonacci sequence) * OEIS:A039834 - a(n+2) = -a(n+1) + a(n) (signed Fibonacci numbers) with a(-2) = a(-1) = 1 (Inverse binomial transform of Fibonacci sequence)\n\n: *fourth sequence*\n\n* OEIS:A034943 - Binomial transform of Padovan sequence * OEIS:A144413 - a(n) = Sum\\_{k=0..n} (-1)^k \\* binomial(n, k) \\* A000931(n-k+4) (Inverse binomial transform of Padovan sequence)"
},
{
"role": "assistant",
"content": "Generates the sequences on the fly.\n\n```\nsub binomial { [×] ($^n … 0) Z/ 1 .. $^p }\n\nsub binomial-transform (*@seq) {\n @seq.keys.map: -> \\n { sum (0..n).map: -> \\k { binomial(n,k) × @seq[k] } }\n}\n\nsub inverse-binomial-transform (*@seq) {\n @seq.keys.map: -> \\n { sum (0..n).map: -> \\k { binomial(n,k) × @seq[k] × exp(n - k, -1) } }\n}\n\nsub si-binomial-transform (*@seq) { #self inverting\n @seq.keys.map: -> \\n { sum (0..n).map: -> \\k { binomial(n,k) × @seq[k] × exp(k, -1) } }\n}\n\nmy $upto = 20;\n\nfor 'Catalan number', (1, {[+] @_ Z× @_.reverse}…*),\n 'Prime flip-flop', (1..*).map({.is-prime ?? 1 !! 0}),\n 'Fibonacci number', (0,1,*+*…*),\n 'Padovan number', (1,0,0, -> $c,$b,$ {$b+$c}…*)\n -> $name, @seq {\n say qq:to/BIN/;\n $name sequence:\n {@seq[^$upto]}\n Forward binomial transform:\n {binomial-transform(@seq)[^$upto]}\n Inverse binomial transform:\n {inverse-binomial-transform(@seq)[^$upto]}\n Round trip:\n {inverse-binomial-transform(binomial-transform(@seq))[^$upto]}\n Self inverting:\n {si-binomial-transform(@seq)[^$upto]}\n Re inverted:\n {si-binomial-transform(si-binomial-transform(@seq))[^$upto]}\n BIN\n}\n\n```\n\nOutput:\n\n```\nCatalan number sequence:\n1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 35357670 129644790 477638700 1767263190\nForward binomial transform:\n1 2 5 15 51 188 731 2950 12235 51822 223191 974427 4302645 19181100 86211885 390248055 1777495635 8140539950 37463689775 173164232965\nInverse binomial transform:\n1 0 1 1 3 6 15 36 91 232 603 1585 4213 11298 30537 83097 227475 625992 1730787 4805595\nRound trip:\n1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 35357670 129644790 477638700 1767263190\nSelf inverting:\n1 0 1 -1 3 -6 15 -36 91 -232 603 -1585 4213 -11298 30537 -83097 227475 -625992 1730787 -4805595\nRe inverted:\n1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 35357670 129644790 477638700 1767263190\n\nPrime flip-flop sequence:\n0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0\nForward binomial transform:\n0 1 3 6 11 20 37 70 134 255 476 869 1564 2821 5201 9948 19793 40562 84271 174952\nInverse binomial transform:\n0 1 -1 0 3 -10 25 -56 118 -237 456 -847 1540 -2795 5173 -9918 19761 -40528 84235 -174914\nRound trip:\n0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0\nSelf inverting:\n0 -1 -1 0 3 10 25 56 118 237 456 847 1540 2795 5173 9918 19761 40528 84235 174914\nRe inverted:\n0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0\n\nFibonacci number sequence:\n0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181\nForward binomial transform:\n0 1 3 8 21 55 144 377 987 2584 6765 17711 46368 121393 317811 832040 2178309 5702887 14930352 39088169\nInverse binomial transform:\n0 1 -1 2 -3 5 -8 13 -21 34 -55 89 -144 233 -377 610 -987 1597 -2584 4181\nRound trip:\n0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181\nSelf inverting:\n0 -1 -1 -2 -3 -5 -8 -13 -21 -34 -55 -89 -144 -233 -377 -610 -987 -1597 -2584 -4181\nRe inverted:\n0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181\n\nPadovan number sequence:\n1 0 0 1 0 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37\nForward binomial transform:\n1 1 1 2 5 12 28 65 151 351 816 1897 4410 10252 23833 55405 128801 299426 696081 1618192\nInverse binomial transform:\n1 -1 1 0 -3 10 -24 49 -89 145 -208 245 -174 -176 1121 -3185 7137 -13920 24301 -37926\nRound trip:\n1 0 0 1 0 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37\nSelf inverting:\n1 1 1 0 -3 -10 -24 -49 -89 -145 -208 -245 -174 176 1121 3185 7137 13920 24301 37926\nRe inverted:\n1 0 0 1 0 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Given this string representing ordered DNA bases:\n\n```\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n```\n\nTask\n: * \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: (**A**, **C**, **G**, and **T**) in the sequence\n * print the total count of each base in the string.\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**Works with**: Rakudo version 2019.07.1\n\nIt's the Letter frequency task all over again, just simpler and dressed up in different clothes.\n\nThe specs for what \"pretty print\" means are sadly lacking. Ah well, just makes it easily defensible if I do *anything at all*.\n\n```\nmy $dna = join '', lines q:to/END/;\n CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\n CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\n AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\n GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\n CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\n TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\n TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\n CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\n TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\n GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n END\n\n\nput pretty($dna, 80);\nput \"\\nTotal bases: \", +my $bases = $dna.comb.Bag;\nput $bases.sort(~*.key).join: \"\\n\";\n\nsub pretty ($string, $wrap = 50) {\n $string.comb($wrap).map( { sprintf \"%8d: %s\", $++ * $wrap, $_ } ).join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\n 0: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCG\n 80: AGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTC\n 160: GTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGT\n 240: TCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCG\n 320: ATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\n 400: TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTT\n 480: TGTTAAACTACGAACGTAAT\n\nTotal bases: 500\nA\t129\nC\t97\nG\t119\nT\t155\n```"
}
]
|
[
{
"role": "user",
"content": "Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the\nsequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle.\n\nCurrent DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, \"AAGATGGA\", GGAGCGCATC\", and \"ATCGCAATAAGGA\" can be assembled into the sequence \"AAGATGGAGCGCATCGCAATAAGGA\" by noting that \"GGA\" is at the tail of the first string and head of the second string and \"ATC\" likewise is at the tail\nof the second and head of the third string.\n\nWhen looking for the best global alignment in the output strings produced by DNA sequences, there are\ntypically a large number of such overlaps among a large number of sequences. In such a case, the ordering\nthat results in the shortest common superstring is generrally preferred.\n\nFinding such a supersequence is an NP-hard problem, and many algorithms have been proposed to\nshorten calculations, especially when many very long sequences are matched.\n\nThe shortest common superstring as used in bioinfomatics here differs from the string task\nShortest\\_common\\_supersequence. In that task, a supersequence\nmay have other characters interposed as long as the characters of each subsequence appear in order,\nso that (abcbdab, abdcaba) -> abdcabdab. In this task, (abcbdab, abdcaba) -> abcbdabdcaba.\n\nTask\n: * Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences.\n\n: * Handle cases where two sequences are identical or one sequence is entirely contained in another.\n\n: * Print the resulting sequence along with its size (its base count) and a count of each base in the sequence.\n\n: * Find the shortest common superstring for the following four examples:\n\n```\n(\"TA\", \"AAG\", \"TA\", \"GAA\", \"TA\")\n\n```\n\n```\n(\"CATTAGGG\", \"ATTAG\", \"GGG\", \"TA\")\n\n```\n\n```\n(\"AAGAUGGA\", \"GGAGCGCAUC\", \"AUCGCAAUAAGGA\")\n\n```\n\n```\n(\"ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT\",\n\"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\",\n\"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n\"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n\"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\",\n\"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\",\n\"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\",\n\"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n\"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\",\n\"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\",\n\"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\",\n\"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\",\n\"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\")\n\n```\n\nRelated tasks\n: * Bioinformatics base count.\n * Bioinformatics sequence mutation."
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n**Translation of**: Julia\n\n```\n# 20210209 Raku programming solution\n\nsub printCounts(\\seq) {\n my $bases = seq.comb.Bag ;\n say \"\\nNucleotide counts for \", seq, \" :\";\n say $bases.kv, \" and total length = \", $bases.total\n}\n\nsub stringCentipede(\\s1, \\s2) {\n loop ( my $offset = 0, my \\S1 = $ = '' ; ; $offset++ ) {\n S1 = s1.substr: $offset ;\n with S1.index(s2.substr(0,1)) -> $p { $offset += $p } else { return False }\n return s1.chars - $offset if s2.starts-with: s1.substr: $offset\n }\n}\n\nsub deduplicate {\n my @sorted = @_.unique.sort: *.chars; # by length \n gather while ( my $target = shift @sorted ) {\n take $target unless @sorted.grep: { .contains: $target } \n }\n}\n\nsub shortestCommonSuperstring {\n my \\ß = $ = [~] my @ss = deduplicate @_ ; # ShortestSuper\n for @ss.permutations -> @perm {\n my \\sup = $ = @perm[0];\n for @perm.rotor(2 => -1) { sup ~= @_[1].substr: stringCentipede |@_ }\n ß = sup if sup.chars < ß.chars ;\n }\n ß\n}\n\n.&shortestCommonSuperstring.&printCounts for ( \n\n <TA AAG TA GAA TA>,\n\n <CATTAGGG ATTAG GGG TA>,\n\n <AAGAUGGA GGAGCGCAUC AUCGCAAUAAGGA> ,\n\n <ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT \n GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT\n CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\n TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\n AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\n GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC\n CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT\n TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\n CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC\n GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT\n TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC\n CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\n TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA\n >,\n)\n\n```\n\nOutput:\n\n```\n\n\nNucleotide counts for TAAGAA :\n(T 1 A 4 G 1) and total length = 6\n\nNucleotide counts for CATTAGGG :\n(G 3 A 2 T 2 C 1) and total length = 8\n\nNucleotide counts for AAGAUGGAGCGCAUCGCAAUAAGGA :\n(A 10 U 3 C 4 G 8) and total length = 25\n\nNucleotide counts for CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA :\n(C 57 G 75 A 74 T 94) and total length = 300\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:\n\n1. Choosing a random base position in the sequence.\n2. Mutate the sequence by doing one of either:\n 1. **S**wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)\n 2. **D**elete the chosen base at the position.\n 3. **I**nsert another base randomly chosen from A,C, G, or T into the sequence at that position.\n3. Randomly generate a test DNA sequence of at least 200 bases\n4. \"Pretty print\" the sequence and a count of its size, and the count of each base in the sequence\n5. Mutate the sequence ten times.\n6. \"Pretty print\" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.\n\nExtra credit\n\n* Give more information on the individual mutations applied.\n* Allow mutations to be weighted and/or chosen."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nUnweighted mutations at this point. The mutated DNA strand has a \"diff\" operation performed on it which (in this specific case) renders the mutated base in lower case so it may be picked out more easily.\n\n```\nmy @bases = <A C G T>;\n\n# The DNA strand\nmy $dna = @bases.roll(200).join;\n\n\n# The Task\nput \"ORIGINAL DNA STRAND:\";\nput pretty $dna;\nput \"\\nTotal bases: \", +my $bases = $dna.comb.Bag;\nput $bases.sort( ~*.key ).join: \"\\n\";\n\nput \"\\nMUTATED DNA STRAND:\";\nmy $mutate = $dna.&mutate(10);\nput pretty diff $dna, $mutate;\nput \"\\nTotal bases: \", +my $mutated = $mutate.comb.Bag;\nput $mutated.sort( ~*.key ).join: \"\\n\";\n\n\n# Helper subs\nsub pretty ($string, $wrap = 50) {\n $string.comb($wrap).map( { sprintf \"%8d: %s\", $++ * $wrap, $_ } ).join: \"\\n\"\n}\n\nsub mutate ($dna is copy, $count = 1) {\n $dna.substr-rw((^$dna.chars).roll, 1) = @bases.roll for ^$count;\n $dna\n}\n\nsub diff ($orig, $repl) {\n ($orig.comb Z $repl.comb).map( -> ($o, $r) { $o eq $r ?? $o !! $r.lc }).join\n}\n\n```\n\nOutput:\n\n```\nORIGINAL DNA STRAND:\n 0: ACGGATAGACCGTTCCTGCAAGCTGGTACGGTTCGAATGTTGACCTTATT\n 50: CTCCGCAGCGCACTACCCGATCGGGTAACGTACTCTATATGATGCCTATT\n 100: TTCCCCGCCTTACATCGGCGATCAATGTTCTTTTACGCTAACTAGGCGCA\n 150: CGTCGTGCCTTACCGAGAGCCAGTTCGAAATCGTGCTGAAAATATCTGGA\n\nTotal bases: 200\nA\t45\nC\t55\nG\t45\nT\t55\n\nMUTATED DNA STRAND:\n 0: ACGGATAGcCCGTTCCTGCAAGCTGGTACGGTTCGAATGTTGACCTTATT\n 50: CTCCGCAGCGCACTACCCGATCGGGTcACtcACTCTATATGAcGCCTAaT\n 100: TTCCCCGCCTTACATCGGCGATCAATGTTCTTTTACGCTAACTAGGCGCA\n 150: CGTCGTGCCTTACCcAGAGCCAGTTCGAAATCGTGCTGAAAATATCTGGA\n\nTotal bases: 200\nA\t44\nC\t60\nG\t43\nT\t53\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nRandomly generate a string of **200** DNA bases (represented by **A, C, G,** and **T**).\n\nWrite a routine to find all the positions of a randomly generated subsequence (four letters)."
},
{
"role": "assistant",
"content": "Chances are actually pretty small that a random 4 codon string will show up at all in a random 200 codon sequence. Bump up the sequence size to get a reasonable chance of multiple matches.\n\n```\nuse String::Splice:ver<0.0.3+>;\n\nmy $line = 80;\n\nmy $haystack = [~] <A C G T>.roll($line * 8);\n\nsay 'Needle: ' ~ my $needle = [~] <A C G T>.roll(4);\n\nmy $these = $haystack ~~ m:g/<$needle>/;\n\nmy @match = $these.map: { .from, .pos }\n\nprintf \"From: %3s to %3s\\n\", |$_ for @match;\n\nmy $disp = $haystack.comb.batch($line)».join.join(\"\\n\");\n\nfor @match.reverse {\n $disp.=&splice(.[1] + .[1] div $line, \"\\e[0m\" );\n $disp.=&splice(.[0] + .[0] div $line, \"\\e[31m\");\n}\n\nsay $disp;\n\n```\n\nOutput:\n\nShow in custom div to better display highlighting.\n\nNeedle: TAGC \nFrom: 159 to 163 \nFrom: 262 to 266 \nFrom: 315 to 319 \nFrom: 505 to 509 \nFrom: 632 to 636 \nCATATGTGACACTGACAGCTCGCGCGAAAATCCGTGTGACGGTCTGAACACTATACTATAGGCCCGGTCGGCATTTGTGG \nCTCCCCAGTGGAGAGACCACTCGTCAATTGCTGACGACTTAACACAAATCGAGTCGCCCTTAGTGCCAGACGGGACTCCT \nAGCAAAGGGCGGCACGTGGTGACTCCCAATATGTGAGCATGCCATCTAATTGATCTGGGGGGTTTCGCGGGAATACCTAG \nGGGCGTTCTGTCCATGGATCTCTAGCCCTGCGAAGAGATACCCGCAGTGAGTTGCACGTGCAAAGAACTTGTAACTAGCG \nTATTCTGTATCCGCCGCGCGATATGCTTCTGCGGGATGTACTTCTTGTGACTAAGACTTTGTTATCCAAATTGACCAATA \nTTCAACGGTCGACTCTCCGAGGCAGTATCGGTACGCCGAAAAATGGTTACTTCGGCCATACGTAACCTCTCAAGTCACGA \nTTACAGCCCACGGGGGCTTACAGCATAGCTCCAAAGACATTCCAATTGAGCTACAACGTGTTCAGTGCGGAGCAGTATCC \nAGTACTCGACTGTTATGGTAAAAGGGCATCGTGATCGTTTATATTAATCATTGGGACAGGTGGTTAATGTCATAGCTTAG"
}
]
|
[
{
"role": "user",
"content": "For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in \"Things to Do with your Pocket Calculator\" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.\n\nIt's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives – specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!\n\nTo compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in Days between dates are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.\n\nThe three cycles and their lengths are as follows:\n\n: : : | Cycle | Length |\n | --- | --- |\n | Physical | 23 days |\n | Emotional | 28 days |\n | Mental | 33 days |\n\nThe first half of each cycle is in \"plus\" territory, with a peak at the quarter-way point; the second half in \"minus\" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the *k*th day of an *n*-day cycle by computing **sin( 2π*k* / *n* )**. The days where a cycle crosses the axis in either direction are called \"critical\" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.\n\nThe task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. \"up and rising\", \"peak\", \"up but falling\", \"critical\", \"down and falling\", \"valley\", \"down but rising\"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.\n\nExample run of my Raku implementation:\n\n```\nraku br.raku 1943-03-09 1972-07-11\n\n```\n\nOutput:\n\n```\nDay 10717:\nPhysical day 22: -27% (down but rising, next transition 1972-07-12)\nEmotional day 21: valley\nMental day 25: valley\n\n```\n\nDouble valley! This was apparently not a good day for Mr. Fischer to begin a chess tournament..."
},
{
"role": "assistant",
"content": "```\n#!/usr/bin/env raku\nunit sub MAIN($birthday=%*ENV<BIRTHDAY>, $date = Date.today()) {\n\nmy %cycles = ( :23Physical, :28Emotional, :33Mental );\nmy @quadrants = [ ('up and rising', 'peak'),\n ('up but falling', 'transition'),\n ('down and falling', 'valley'),\n ('down but rising', 'transition') ];\n\nif !$birthday {\n die \"Birthday not specified.\\n\" ~\n \"Supply --birthday option or set \\$BIRTHDAY in environment.\\n\";\n}\n\nmy ($bday, $target) = ($birthday, $date).map: { Date.new($_) };\nmy $days = $target - $bday;\n\nsay \"Day $days:\";\nfor %cycles.sort(+*.value)».kv -> ($label, $length) {\n my $position = $days % $length;\n my $quadrant = floor($position / $length * 4);\n my $percentage = floor(sin($position / $length * 2 * π )*1000)/10;\n my $description;\n if $percentage > 95 {\n $description = 'peak';\n } elsif $percentage < -95 {\n $description = 'valley'; \n } elsif abs($percentage) < 5 {\n $description = 'critical transition'\n } else {\n my $transition = $target + floor(($quadrant + 1)/4 * $length) - $position;\n my ($trend, $next) = @quadrants[$quadrant];\n $description = \"$percentage% ($trend, next $next $transition)\";\n }\n say \"$label day $position: $description\";\n }\n}\n\n```\n\nOutput:\n\n```\n$ br 1809-01-12 1863-11-19\nDay 20034:\nPhysical day 1: 26.9% (up and rising, next peak 1863-11-23)\nEmotional day 14: critical transition\nMental day 3: 54% (up and rising, next peak 1863-11-24)\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The current wikipedia article is at Birthday Problem. The original RosettaCode article was extracted from the wikipedia article № 296054030 of 21:44, 12 June 2009 . The list of authors can be seen in the page history. As with Rosetta Code, the pre **5 June 2009** text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn probability theory, the **birthday problem**, or **birthday paradox** This is not a paradox in the sense of leading to a logical contradiction, but is called a paradox because the mathematical truth contradicts naïve intuition: most people estimate that the chance is much lower than 50%. pertains to the probability that in a set of randomly chosen people some pair of them will have the same birthday. In a group of at least 23 randomly chosen people, there is more than 50% probability that some pair of them will both have been born on the same day. For 57 or more people, the probability is more than 99%, and it reaches 100% when the number of people reaches 366 (by the pigeon hole principle, ignoring leap years). The mathematics behind this problem leads to a well-known cryptographic attack called the birthday attack.\n\nTask\n\nUsing simulation, estimate the number of independent people required in a group before we can expect a *better than even chance* that at least 2 independent people in a group share a common birthday. Furthermore: Simulate and thus estimate when we can expect a *better than even chance* that at least 3, 4 & 5 independent people of the group share a common birthday. For simplicity assume that all of the people are alive...\n\nSuggestions for improvement\n\n* Estimating the error in the estimate to help ensure the estimate is accurate to 4 decimal places.\n* Converging to the \n\n n\n {\\displaystyle {\\displaystyle n}}\n th solution using a root finding method, as opposed to using an extensive search.\n* Kudos (κῦδος) for finding the solution by proof (in a programming language) rather than by construction and simulation.\n\nSee also\n\n* Wolfram entry: Birthday Problem"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nGives correct answers, but more of a proof-of-concept at this point, even with max-trials at 250K it is too slow to be practical.\n\n```\nsub simulation ($c) {\n my $max-trials = 250_000;\n my $min-trials = 5_000;\n my $n = floor 47 * ($c-1.5)**1.5; # OEIS/A050256: 16 86 185 307\n my $N = min $max-trials, max $min-trials, 1000 * sqrt $n;\n\n loop {\n my $p = $N R/ elems grep { .elems > 0 }, ((grep { $_>=$c }, values bag (^365).roll($n)) xx $N);\n return($n, $p) if $p > 0.5;\n $N = min $max-trials, max $min-trials, floor 1000/(0.5-$p);\n $n++;\n }\n}\n\nprintf \"$_ people in a group of %s share a common birthday. (%.3f)\\n\", simulation($_) for 2..5;\n\n```\n\nOutput:\n\n```\n2 people in a group of 23 share a common birthday. (0.506)\n3 people in a group of 88 share a common birthday. (0.511)\n4 people in a group of 187 share a common birthday. (0.500)\n5 people in a group of 313 share a common birthday. (0.507)\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| **Warning:** Many of these snippets are incomplete. It is recommended that you use an established library for any projects that are likely to see external use |\n\nTask\n\nWrite a program that takes a bitcoin address as argument,\nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n\n: : : * 0 zero\n * O uppercase oh\n * I uppercase eye\n * l lowercase ell\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a RIPEMD-160 digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double SHA-256 digest of the previous 21 bytes.\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for SHA-256.\n\nExample of a bitcoin address\n\n```\n1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n```\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software.\n \nYou can change a few characters in this string and check that it'll fail the test."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub sha256(blob8 $b) returns blob8 {\n given run <openssl dgst -sha256 -binary>, :in, :out, :bin {\n .in.write: $b;\n .in.close;\n return .out.slurp;\n }\n}\n\nmy $bitcoin-address = rx/\n << <+alnum-[0IOl]> ** 26..* >> # an address is at least 26 characters long\n <?{\n .subbuf(21, 4) eq sha256(sha256 .subbuf(0, 21)).subbuf(0, 4) given\n blob8.new: <\n 1 2 3 4 5 6 7 8 9\n A B C D E F G H J K L M N P Q R S T U V W X Y Z\n a b c d e f g h i j k m n o p q r s t u v w x y z\n >.pairs.invert.hash{$/.comb}\n .reduce(* * 58 + *)\n .polymod(256 xx 24)\n .reverse;\n }>\n/;\n \nsay \"Here is a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\" ~~ $bitcoin-address;\n\n```\n\nOutput:\n\n```\n「1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i」\n```"
}
]
|
[
{
"role": "user",
"content": "Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.\n\nThe encoding steps are:\n\n* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;\n* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;\n* compute the SHA-256 of this string ;\n* compute the RIPEMD-160 of this SHA-256 digest ;\n* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in bitcoin/address validation ;\n* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum\n\nThe base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.\n\nHere is an example public point:\n\n```\nX = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352\nY = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6\n```\n\nThe corresponding address should be:\n16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n\nNb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.\n\n*Extra credit:* add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub dgst(blob8 $b, Str :$dgst) returns blob8 {\n given run «openssl dgst \"-$dgst\" -binary», :in, :out, :bin {\n .in.write: $b;\n .in.close;\n return .out.slurp;\n }\n}\nsub sha256($b) { dgst $b, :dgst<sha256> }\nsub rmd160($b) { dgst $b, :dgst<rmd160> }\n \nsub public_point_to_address( UInt $x, UInt $y ) {\n my @bytes = flat ($y,$x).map: *.polymod( 256 xx * )[^32];\n my $hash = rmd160 sha256 blob8.new: 4, @bytes.reverse;\n my $checksum = sha256(sha256 blob8.new: 0, $hash.list).subbuf: 0, 4;\n [R~] <\n 1 2 3 4 5 6 7 8 9\n A B C D E F G H J K L M N P Q R S T U V W X Y Z\n a b c d e f g h i j k m n o p q r s t u v w x y z\n >[ .polymod: 58 xx * ] given\n reduce * * 256 + * , flat 0, ($hash, $checksum)».list \n}\n \nsay public_point_to_address\n 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352,\n 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6;\n\n```\n\nOutput:\n\n```\n6UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM\n```"
}
]
|
[
{
"role": "user",
"content": "Show a basic storage type to handle a simple RGB raster graphics image,\nand some primitive associated functions.\n\nIf possible provide a function to allocate an uninitialised image,\ngiven its width and height, and provide 3 additional functions:\n\n: : * one to fill an image with a plain RGB color,\n * one to set a given pixel with a color,\n * one to get the color of a pixel.\n\n(If there are specificities about the storage or the allocation, explain those.)\n\n*These functions are used as a base for the articles in the category raster graphics operations,* \nand a basic output function to check the results\nis available in the article write ppm file."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n\t$i where ^$!width,\n\t$j where ^$!height\n\t--> Pixel\n ) is rw { @!data[$i + $j * $!width] }\n\n method set-pixel ($i, $j, Pixel $p) {\n\tself.pixel($i, $j) = $p.clone;\n }\n method get-pixel ($i, $j) returns Pixel {\n\tself.pixel($i, $j);\n }\n}\n\nmy Bitmap $b = Bitmap.new( width => 10, height => 10);\n\n$b.fill( Pixel.new( R => 0, G => 0, B => 200) );\n\n$b.set-pixel( 7, 5, Pixel.new( R => 100, G => 200, B => 0) );\n\nsay $b.perl;\n\n```\n\nThanks to the rw trait on the pixel method, we don't actually need to define two separate methods, set-pixel and get-pixel, but that is an explicit requirement of the task. (Beware your presuppositions! In Raku, accessors only determine identity, not use. In particular, identity is considered orthogonal to lvalue/rvalue context.)"
}
]
|
[
{
"role": "user",
"content": "Task\n\nUsing the data storage type defined on the Bitmap page for raster graphics images,\n \ndraw a line given two points with Bresenham's line algorithm."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nBitmap class from Bitmap task.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n \n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n\t$i where ^$!width,\n\t$j where ^$!height\n\t--> Pixel\n ) is rw { @!data[$i + $j * $!width] }\n \n method set-pixel ($i, $j, Pixel $p) {\n\tself.pixel($i, $j) = $p.clone;\n }\n method get-pixel ($i, $j) returns Pixel {\n\tself.pixel($i, $j);\n }\n}\n \nsub line(Bitmap $bitmap, $x0 is copy, $x1 is copy, $y0 is copy, $y1 is copy) {\n my $steep = abs($y1 - $y0) > abs($x1 - $x0);\n if $steep {\n ($x0, $y0) = ($y0, $x0);\n ($x1, $y1) = ($y1, $x1);\n } \n if $x0 > $x1 {\n ($x0, $x1) = ($x1, $x0);\n ($y0, $y1) = ($y1, $y0);\n }\n my $Δx = $x1 - $x0;\n my $Δy = abs($y1 - $y0);\n my $error = 0;\n my $Δerror = $Δy / $Δx;\n my $y-step = $y0 < $y1 ?? 1 !! -1;\n my $y = $y0;\n for $x0 .. $x1 -> $x {\n my $pix = Pixel.new(R => 100, G => 200, B => 0); \n if $steep {\n $bitmap.set-pixel($y, $x, $pix);\n } else {\n $bitmap.set-pixel($x, $y, $pix);\n } \n $error += $Δerror;\n if $error >= 0.5 {\n $y += $y-step;\n $error -= 1.0;\n } \n } \n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Using the data storage type defined on this page for raster images, and the draw\\_line function defined in this other one, draw a **cubic bezier curve**\n(definition on Wikipedia)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses pieces from Bitmap, and Bresenham's line algorithm tasks. They are included here to make a complete, runnable program.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n\t $i where ^$!width,\n\t $j where ^$!height\n\t --> Pixel\n ) is rw { @!data[$i + $j * $!width] }\n\n method set-pixel ($i, $j, Pixel $p) {\n self.pixel($i, $j) = $p.clone;\n }\n method get-pixel ($i, $j) returns Pixel {\n\t self.pixel($i, $j);\n }\n\n method line(($x0 is copy, $y0 is copy), ($x1 is copy, $y1 is copy), $pix) {\n my $steep = abs($y1 - $y0) > abs($x1 - $x0);\n if $steep {\n ($x0, $y0) = ($y0, $x0);\n ($x1, $y1) = ($y1, $x1);\n }\n if $x0 > $x1 {\n ($x0, $x1) = ($x1, $x0);\n ($y0, $y1) = ($y1, $y0);\n }\n my $Δx = $x1 - $x0;\n my $Δy = abs($y1 - $y0);\n my $error = 0;\n my $Δerror = $Δy / $Δx;\n my $y-step = $y0 < $y1 ?? 1 !! -1;\n my $y = $y0;\n for $x0 .. $x1 -> $x {\n if $steep {\n self.set-pixel($y, $x, $pix);\n } else {\n self.set-pixel($x, $y, $pix);\n }\n $error += $Δerror;\n if $error >= 0.5 {\n $y += $y-step;\n $error -= 1.0;\n }\n }\n }\n\n method dot (($px, $py), $pix, $radius = 2) {\n for $px - $radius .. $px + $radius -> $x {\n for $py - $radius .. $py + $radius -> $y {\n self.set-pixel($x, $y, $pix) if ( $px - $x + ($py - $y) * i ).abs <= $radius;\n }\n }\n }\n\n method cubic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), ($x4, $y4), $pix, $segments = 30 ) {\n my @line-segments = map -> $t {\n my \\a = (1-$t)³;\n my \\b = $t * (1-$t)² * 3;\n my \\c = $t² * (1-$t) * 3;\n my \\d = $t³;\n (a*$x1 + b*$x2 + c*$x3 + d*$x4).round(1),(a*$y1 + b*$y2 + c*$y3 + d*$y4).round(1)\n }, (0, 1/$segments, 2/$segments ... 1);\n for @line-segments.rotor(2=>-1) -> ($p1, $p2) { self.line( $p1, $p2, $pix) };\n }\n\n method data { @!data }\n}\n\nrole PPM {\n method P6 returns Blob {\n\t\"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nsub color( $r, $g, $b) { Pixel.new(R => $r, G => $g, B => $b) }\n\nmy Bitmap $b = Bitmap.new( width => 600, height => 400) but PPM;\n\n$b.fill( color(2,2,2) );\n\nmy @points = (85,390), (5,5), (580,370), (270,10);\n\nmy %seen;\nmy $c = 0;\nfor @points.permutations -> @this {\n %seen{@this.reverse.join.Str}++;\n next if %seen{@this.join.Str};\n $b.cubic( |@this, color(255-$c,127,$c+=22) );\n}\n\[email protected]: { $b.dot( $_, color(255,0,0), 3 )}\n\n$*OUT.write: $b.P6;\n\n```\n\nSee example image here, (converted to a .png as .ppm format is not widely supported)."
}
]
|
[
{
"role": "user",
"content": "Using the data storage type defined on this page for raster images, and the draw\\_line function defined in this one, draw a *quadratic bezier curve*\n(definition on Wikipedia)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses pieces from Bitmap, and Bresenham's line algorithm tasks. They are included here to make a complete, runnable program.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n\t $i where ^$!width,\n\t $j where ^$!height\n\t --> Pixel\n ) is rw { @!data[$i + $j * $!width] }\n\n method set-pixel ($i, $j, Pixel $p) {\n return if $j >= $!height;\n self.pixel($i, $j) = $p.clone;\n }\n method get-pixel ($i, $j) returns Pixel {\n\t self.pixel($i, $j);\n }\n\n method line(($x0 is copy, $y0 is copy), ($x1 is copy, $y1 is copy), $pix) {\n my $steep = abs($y1 - $y0) > abs($x1 - $x0);\n if $steep {\n ($x0, $y0) = ($y0, $x0);\n ($x1, $y1) = ($y1, $x1);\n }\n if $x0 > $x1 {\n ($x0, $x1) = ($x1, $x0);\n ($y0, $y1) = ($y1, $y0);\n }\n my $Δx = $x1 - $x0;\n my $Δy = abs($y1 - $y0);\n my $error = 0;\n my $Δerror = $Δy / $Δx;\n my $y-step = $y0 < $y1 ?? 1 !! -1;\n my $y = $y0;\n for $x0 .. $x1 -> $x {\n if $steep {\n self.set-pixel($y, $x, $pix);\n } else {\n self.set-pixel($x, $y, $pix);\n }\n $error += $Δerror;\n if $error >= 0.5 {\n $y += $y-step;\n $error -= 1.0;\n }\n }\n }\n\n method dot (($px, $py), $pix, $radius = 2) {\n for $px - $radius .. $px + $radius -> $x {\n for $py - $radius .. $py + $radius -> $y {\n self.set-pixel($x, $y, $pix) if ( $px - $x + ($py - $y) * i ).abs <= $radius;\n }\n }\n }\n\n method quadratic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), $pix, $segments = 30 ) {\n my @line-segments = map -> $t {\n my \\a = (1-$t)²;\n my \\b = $t * (1-$t) * 2;\n my \\c = $t²;\n (a*$x1 + b*$x2 + c*$x3).round(1),(a*$y1 + b*$y2 + c*$y3).round(1)\n }, (0, 1/$segments, 2/$segments ... 1);\n for @line-segments.rotor(2=>-1) -> ($p1, $p2) { self.line( $p1, $p2, $pix) };\n }\n\n method data { @!data }\n}\n\nrole PPM {\n method P6 returns Blob {\n\t\"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nsub color( $r, $g, $b) { Pixel.new(R => $r, G => $g, B => $b) }\n\nmy Bitmap $b = Bitmap.new( width => 600, height => 400) but PPM;\n\n$b.fill( color(2,2,2) );\n\nmy @points = (65,25), (85,380), (570,15);\n\nmy %seen;\nmy $c = 0;\nfor @points.permutations -> @this {\n %seen{@this.reverse.join.Str}++;\n next if %seen{@this.join.Str};\n $b.quadratic( |@this, color(255-$c,127,$c+=80) );\n}\n\[email protected]: { $b.dot( $_, color(255,0,0), 3 )}\n\n$*OUT.write: $b.P6;\n\n```\n\nSee example image here, (converted to a .png as .ppm format is not widely supported)."
}
]
|
[
{
"role": "user",
"content": "Implement a flood fill.\n\nA flood fill is a way of filling an area using *color banks* to define the contained area or a *target color* which \"determines\" the area (the *valley* that can be flooded; Wikipedia uses the term *target color*). It works almost like a water flooding from a point towards the banks (or: inside the valley): if there's a hole in the banks, the flood is not contained and all the image (or all the \"connected valleys\") get filled.\n\nTo accomplish the task, you need to implement just one of the possible algorithms (examples are on Wikipedia). Variations on the *theme* are allowed (e.g. adding a tolerance parameter or argument for color-matching of the *banks* or *target* color).\n\n**Testing**: the basic algorithm is not suitable for *truecolor* images; a possible test image is the one shown on the right box; you can try to fill the white area, or the black inner circle."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\nUsing bits and pieces from various other bitmap tasks.\n\n```\nclass Pixel { has Int ($.R, $.G, $.B) }\nclass Bitmap {\n has Int ($.width, $.height);\n has Pixel @.data;\n\n method pixel(\n\t $i where ^$!width,\n\t $j where ^$!height\n\t --> Pixel\n ) is rw { @!data[$i + $j * $!width] }\n}\n\nrole PPM {\n method P6 returns Blob {\n\t\"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nsub load-ppm ( $ppm ) {\n my $fh = $ppm.IO.open( :enc('ISO-8859-1') );\n my $type = $fh.get;\n my ($width, $height) = $fh.get.split: ' ';\n my $depth = $fh.get;\n Bitmap.new( width => $width.Int, height => $height.Int,\n data => ( $fh.slurp.ords.rotor(3).map:\n { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } )\n )\n}\n\nsub color-distance (Pixel $c1, Pixel $c2) {\n sqrt( ( ($c1.R - $c2.R)² + ($c1.G - $c2.G)² + ($c1.B - $c2.B)² ) / ( 255 * sqrt(3) ) );\n}\n\nsub flood ($img, $x, $y, $c1) {\n my $c2 = $img.pixel($x, $y);\n my $max-distance = 10;\n my @queue;\n my %checked;\n check($x, $y);\n for @queue -> [$x, $y] {\n $img.pixel($x, $y) = $c1.clone;\n }\n\n sub check ($x, $y) {\n my $c3 = $img.pixel($x, $y);\n\n if color-distance($c2, $c3) < $max-distance {\n @queue.push: [$x,$y];\n @queue.elems;\n %checked{\"$x,$y\"} = 1;\n check($x - 1, $y) if $x > 0 and %checked{\"{$x - 1},$y\"}:!exists;\n check($x + 1, $y) if $x < $img.width - 1 and %checked{\"{$x + 1},$y\"}:!exists;\n check($x, $y - 1) if $y > 0 and %checked{\"$x,{$y - 1}\"}:!exists;\n check($x, $y + 1) if $y < $img.height - 1 and %checked{\"$x,{$y + 1}\"}:!exists;\n }\n }\n}\n\nmy $infile = './Unfilled-Circle.ppm';\n\nmy Bitmap $b = load-ppm( $infile ) but PPM;\n\nflood($b, 5, 5, Pixel.new(:255R, :0G, :0B));\nflood($b, 5, 125, Pixel.new(:255R, :0G, :0B));\nflood($b, 125, 5, Pixel.new(:255R, :0G, :0B));\nflood($b, 125, 125, Pixel.new(:255R, :0G, :0B));\nflood($b, 50, 50, Pixel.new(:0R, :0G, :255B));\n\nmy $outfile = open('./Bitmap-flood-perl6.ppm', :w, :bin);\n\n$outfile.write: $b.P6;\n\n```\n\nSee output image Bitmap-flood-perl6 (offsite image file, converted to PNG for ease of viewing)"
}
]
|
[
{
"role": "user",
"content": "Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, where N is the image width and M is the image height.\n\n**Test task**\n\nHistogram is useful for many image processing operations. As an example, use it to convert an image into black and white art. The method works as follows:\n\n* Convert image to grayscale;\n* Compute the histogram\n* Find the median: defined as the luminance such that the image has an approximately equal number of pixels with lesser and greater luminance.\n* Replace each pixel of luminance lesser than the median to black, and others to white.\n\nUse read/write ppm file, and grayscale image solutions."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses pieces from Bitmap, Write a PPM file and Grayscale image tasks. Included here to make a complete, runnable program.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @.data;\n}\n\nrole PBM {\n has @.BM;\n method P4 returns Blob {\n\t\"P4\\n{self.width} {self.height}\\n\".encode('ascii')\n\t~ Blob.new: self.BM\n }\n}\n\nsub getline ( $fh ) {\n my $line = '#'; # skip comments when reading image file\n $line = $fh.get while $line.substr(0,1) eq '#';\n $line;\n}\n\nsub load-ppm ( $ppm ) {\n my $fh = $ppm.IO.open( :enc('ISO-8859-1') );\n my $type = $fh.&getline;\n my ($width, $height) = $fh.&getline.split: ' ';\n my $depth = $fh.&getline;\n Bitmap.new( width => $width.Int, height => $height.Int,\n data => ( $fh.slurp.ords.rotor(3).map:\n { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } )\n )\n}\n\nsub grayscale ( Bitmap $bmp ) {\n map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data;\n}\n\nsub histogram ( Bitmap $bmp ) {\n my @gray = grayscale($bmp);\n my $threshold = @gray.sum / @gray;\n for @gray.rotor($bmp.width) {\n my @row = $_.list;\n @row.push(0) while @row % 8;\n $bmp.BM.append: @row.rotor(8).map: { :2(($_ X< $threshold)».Numeric.join) }\n }\n}\n\nmy $filename = './Lenna.ppm';\n\nmy Bitmap $b = load-ppm( $filename ) but PBM;\n\nhistogram($b);\n\n'./Lenna-bw.pbm'.IO.open(:bin, :w).write: $b.P4;\n\n```\n\nSee Lenna, and Lenna-bw images. (converted to .png as .ppm format is not widely supported)."
}
]
|
[
{
"role": "user",
"content": "Task\n\nUsing the data storage type defined on this page for raster images,\nwrite an implementation of the **midpoint circle algorithm** (also known as **Bresenham's circle algorithm**).\n\n(definition on Wikipedia)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: C\n\nWe'll augment the Pixel and Bitmap classes from the Bitmap task.\n\n```\nuse MONKEY-TYPING;\n\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel \\p) {\n @!data = p xx ($!width × $!height)\n }\n\n method pixel( \\i where ^$!width, \\j where ^$!height --> Pixel) is rw {\n @!data[i × $!width + j]\n }\n\n method set-pixel (\\i, \\j, Pixel \\p) {\n self.pixel(i, j) = p;\n }\n\n method get-pixel (\\i, \\j) returns Pixel {\n self.pixel(i, j);\n }\n}\n\naugment class Pixel { method Str { \"$.R $.G $.B\" } }\naugment class Bitmap {\n method P3 {\n join \"\\n\", «P3 \"$.width $.height\" 255»,\n do for ^($.width × $.height) { join ' ', @!data[$_] }\n }\n\n method raster-circle ( \\x0, \\y0, \\r, Pixel \\value ) {\n my $ddF_x = 0;\n my $ddF_y = -2 × r;\n my $f = 1 - r;\n my ($x, $y) = 0, r;\n for flat (0 X 1,-1),(1,-1 X 0) -> \\i, \\j {\n self.set-pixel(x0 + i×r, y0 + j×r, value)\n }\n\n while $x < $y {\n ($y--; $f += ($ddF_y += 2)) if $f ≥ 0;\n $x++; $f += 1 + ($ddF_x += 2);\n for flat (1,-1) X (1,-1) -> \\i, \\j {\n self.set-pixel(x0 + i×$x, y0 + j×$y, value);\n self.set-pixel(x0 + i×$y, y0 + j×$x, value);\n }\n }\n }\n}\n\nmy Bitmap $b = Bitmap.new( width => 32, height => 32);\n$b.fill( Pixel.new( R => 0, G => 0, B => 0) );\n$b.raster-circle(16, 16, 15, Pixel.new(R=>0, G=>0, B=>100));\nsay $b.P3;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a **pipe** using the output\\_ppm function defined on this other page.\n\nThere are various utilities that can be used for this task, for example: **cjpeg** (package *\"jpeg-progs\"* on Linux, or *\"media-libs/libjpeg-turbo\"* on Gentoo), **ppmtojpeg** (package *\"netpbm\"* on Linux), **convert** (from *ImageMagick*, multi-platform)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n# Reference:\n# https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file#Raku\n\nuse v6;\n\nclass Pixel { has uint8 ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n $i where ^$!width,\n $j where ^$!height\n --> Pixel\n ) is rw { @!data[$i*$!height + $j] }\n\n method data { @!data }\n}\n\nrole PPM {\n method P6 returns Blob {\n \"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n ~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nmy Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;\nfor flat ^$b.height X ^$b.width -> $i, $j {\n $b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);\n}\n\nmy $proc = run '/usr/bin/convert','-','output_piped.jpg', :in;\n$proc.in.write: $b.P6;\n$proc.in.close;\n\n```\n\nOutput:\n\n```\nfile output_piped.jpg\noutput_piped.jpg: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 125x125, frames 3\n```"
}
]
|
[
{
"role": "user",
"content": "Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered).\n(Read the definition of PPM file on Wikipedia.)\n\n**Task**: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses pieces from Bitmap, Write a PPM file and Grayscale image tasks. Included here to make a complete, runnable program.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @.data;\n}\n\nrole PGM {\n has @.GS;\n method P5 returns Blob {\n\t\"P5\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: self.GS\n }\n}\n\nsub load-ppm ( $ppm ) {\n my $fh = $ppm.IO.open( :enc('ISO-8859-1') );\n my $type = $fh.get;\n my ($width, $height) = $fh.get.split: ' ';\n my $depth = $fh.get;\n Bitmap.new( width => $width.Int, height => $height.Int,\n data => ( $fh.slurp.ords.rotor(3).map:\n { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } )\n )\n}\n\nsub grayscale ( Bitmap $bmp ) {\n $bmp.GS = map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data;\n}\n\nmy $filename = './camelia.ppm';\n\nmy Bitmap $b = load-ppm( $filename ) but PGM;\n\ngrayscale($b);\n\n'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5;\n\n```\n\nSee camelia, and camelia-gs images. (converted to .png as .ppm format is not widely supported)."
}
]
|
[
{
"role": "user",
"content": "This task is the *opposite* of the PPM conversion through a pipe. In this task, using a delegate tool (like **cjpeg**, one of the netpbm package, or **convert** of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses pieces from Bitmap and Read a PPM file tasks. Included here to make a complete, runnable program.\n\nUses imagemagick convert to pipe the image in.\n\n```\nclass Pixel { has UInt ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @.data;\n}\n\nrole PPM {\n method P6 returns Blob {\n\t\"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nsub getline ( $proc ) {\n my $line = '#'; # skip comment when reading a .png\n $line = $proc.out.get while $line.substr(0,1) eq '#';\n $line;\n}\n\nmy $filename = './camelia.png';\n\nmy $proc = run 'convert', $filename, 'ppm:-', :enc('ISO-8859-1'), :out;\n\nmy $type = getline($proc);\nmy ($width, $height) = getline($proc).split: ' ';\nmy $depth = getline($proc);\n\nmy Bitmap $b = Bitmap.new( width => $width.Int, height => $height.Int) but PPM;\n\n$b.data = $proc.out.slurp.ords.rotor(3).map:\n { Pixel.new(R => .[0], G => .[1], B => .[2]) };\n\n'./camelia.ppm'.IO.open(:bin, :w).write: $b.P6;\n\n```\n\nSee camelia image here."
}
]
|
[
{
"role": "user",
"content": "Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 preferred).\n\n(Read the definition of PPM file on Wikipedia.)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016-01\n\n```\nclass Pixel { has uint8 ($.R, $.G, $.B) }\nclass Bitmap {\n has UInt ($.width, $.height);\n has Pixel @!data;\n\n method fill(Pixel $p) {\n @!data = $p.clone xx ($!width*$!height)\n }\n method pixel(\n\t $i where ^$!width,\n\t $j where ^$!height\n\t --> Pixel\n ) is rw { @!data[$i*$!height + $j] }\n\n method data { @!data }\n}\n\nrole PPM {\n method P6 returns Blob {\n\t\"P6\\n{self.width} {self.height}\\n255\\n\".encode('ascii')\n\t~ Blob.new: flat map { .R, .G, .B }, self.data\n }\n}\n\nmy Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;\nfor flat ^$b.height X ^$b.width -> $i, $j {\n $b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);\n}\n\n$*OUT.write: $b.P6;\n\n```\n\nConverted to a png. (ppm files not locally supported)"
}
]
|
[
{
"role": "user",
"content": "The aim of this task is to write functions (or create a class if your\n\nlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n*quantized* by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0**000** (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a **rough** (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see LZW compression) use fixed or variable *words*\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub encode-ascii(Str $s) {\n my @b = flat $s.ords».fmt(\"%07b\")».comb;\n @b.push(0) until @b %% 8; # padding\n Buf.new: gather while @b { take reduce * *2+*, (@b.pop for ^8) }\n}\n\nsub decode-ascii(Buf $b) {\n my @b = flat $b.list».fmt(\"%08b\")».comb;\n @b.shift until @b %% 7; # remove padding\n @b = gather while @b { take reduce * *2+*, (@b.pop for ^7) }\n return [~] @b».chr;\n}\nsay my $encode = encode-ascii 'STRING';\nsay decode-ascii $encode;\n\n```\n\nOutput:\n\n```\nBuf:0x<03 8b 99 29 4a e5>\nSTRING\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a routine to perform a bitwise AND, OR, and XOR on two integers, a bitwise NOT on the first integer, a left shift, right shift, right arithmetic shift, left rotate, and right rotate.\n\nAll shifts and rotates should be done on the first integer with a shift/rotate amount of the second integer.\n\nIf any operation is not available in your language, note it."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\n```\nconstant MAXINT = uint.Range.max;\nconstant BITS = MAXINT.base(2).chars;\n\n# define rotate ops for the fun of it\nmulti sub infix:<⥁>(Int:D \\a, Int:D \\b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] }\nmulti sub infix:<⥀>(Int:D \\a, Int:D \\b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.list.rotate(b)] }\n\nsub int-bits (Int $a, Int $b) {\n say '';\n say_bit \"$a\", $a;\n say '';\n say_bit \"1's complement (not) $a\", +^$a;\n say_bit \"2's complement $a\", +^$a + 1;\n say_bit \"$a and $b\", $a +& $b;\n say_bit \"$a or $b\", $a +| $b;\n say_bit \"$a xor $b\", $a +^ $b;\n say_bit \"$a unsigned shift right $b\", ($a +& MAXINT) +> $b;\n say_bit \"$a signed shift right $b\", $a +> $b;\n say_bit \"$a rotate right $b\", $a ⥁ $b;\n say_bit \"$a shift left $b\", $a +< $b;\n say_bit \"$a rotate left $b\", $a ⥀ $b;\n}\n\nint-bits(7,2);\nint-bits(-65432,31);\n\nsub say_bit ($message, $value) {\n printf(\"%30s: %{'0' ~ BITS}b\\n\", $message, $value +& MAXINT);\n}\n```\n\nOutput:\n\n```\n 7: 0000000000000000000000000000000000000000000000000000000000000111\n\n 1's complement (not) 7: 1111111111111111111111111111111111111111111111111111111111111000\n 2's complement 7: 1111111111111111111111111111111111111111111111111111111111111001\n 7 and 2: 0000000000000000000000000000000000000000000000000000000000000010\n 7 or 2: 0000000000000000000000000000000000000000000000000000000000000111\n 7 xor 2: 0000000000000000000000000000000000000000000000000000000000000101\n 7 unsigned shift right 2: 0000000000000000000000000000000000000000000000000000000000000001\n 7 signed shift right 2: 0000000000000000000000000000000000000000000000000000000000000001\n 7 rotate right 2: 1100000000000000000000000000000000000000000000000000000000000001\n 7 shift left 2: 0000000000000000000000000000000000000000000000000000000000011100\n 7 rotate left 2: 0000000000000000000000000000000000000000000000000000000000011100\n\n -65432: 1111111111111111111111111111111111111111111111110000000001101000\n\n 1's complement (not) -65432: 0000000000000000000000000000000000000000000000001111111110010111\n 2's complement -65432: 0000000000000000000000000000000000000000000000001111111110011000\n -65432 and 31: 0000000000000000000000000000000000000000000000000000000000001000\n -65432 or 31: 1111111111111111111111111111111111111111111111110000000001111111\n -65432 xor 31: 1111111111111111111111111111111111111111111111110000000001110111\n-65432 unsigned shift right 31: 0000000000000000000000000000000111111111111111111111111111111111\n -65432 signed shift right 31: 1111111111111111111111111111111111111111111111111111111111111111\n -65432 rotate right 31: 1111111111111110000000001101000111111111111111111111111111111111\n -65432 shift left 31: 1111111111111111100000000011010000000000000000000000000000000000\n -65432 rotate left 31: 1111111111111111100000000011010001111111111111111111111111111111\n```"
}
]
|
[
{
"role": "user",
"content": "The Blossom Algorithm\n: The Blossom algorithm, developed by Jack Edmonds in 1965, is a seminal algorithm that solves the maximum matching problem for general graphs by extending the augmenting path concept to handle odd cycles.\n\nCore Idea\n: Shrinking Blossoms\n: The key insight of the Blossom algorithm is to identify an odd cycle (a blossom) when encountered during the search for an augmenting path. When a blossom is detected, the algorithm *contracts* or *shrinks* the entire cycle into a single \"pseudo-vertex\". This creates a smaller, auxiliary graph.\n: The search for an augmenting path then continues in this contracted graph. If an augmenting path is found in the contracted graph that involves a pseudo-vertex (representing a shrunk blossom), this path can be \"lifted\" back to the original graph. The structure of the blossom allows the algorithm to find a corresponding augmenting path in the original graph that utilizes edges within the blossom.\n: This process of shrinking blossoms, searching for augmenting paths in the contracted graph, and expanding blossoms to find paths in the original graph is repeated until no more augmenting paths are found, at which point the current matching is maximum.\n\nProblem\n: Maximum Matching in General Graphs\n: The problem addressed by the Blossom algorithm is finding a Maximum matching|maximum matching in a Graph (discrete mathematics)|general graph. Unlike Bipartite graph|bipartite graphs, general graphs can contain Cycle (graph theory)|odd-length cycles.\n\nGraph and Matching Definition\n: A Graph (discrete mathematics)|graph **G** is formally defined by a set of Vertex (graph theory)|vertices **V** and a set of Edge (graph theory)|edges **E**, denoted as \n\n G\n =\n (\n V\n ,\n E\n )\n {\\displaystyle {\\displaystyle G=(V,E)}}\n . An edge connects two vertices.\n: A Matching (graph theory)|matching **M** in **G** is a subset of the edges **E** such that no two edges in **M** share a common vertex. That is, for any two distinct edges \n\n e\n\n 1\n =\n\n\n u\n\n 1\n ,\n\n v\n\n 1\n ∈\n M\n {\\displaystyle {\\displaystyle e\\_{1}={u\\_{1},v\\_{1}}\\in M}}\n and \n\n e\n\n 2\n =\n\n\n u\n\n 2\n ,\n\n v\n\n 2\n ∈\n M\n {\\displaystyle {\\displaystyle e\\_{2}={u\\_{2},v\\_{2}}\\in M}}\n , the sets of vertices \n\n u\n\n 1\n ,\n\n v\n\n 1\n {\\displaystyle {\\displaystyle {u\\_{1},v\\_{1}}}}\n and \n\n u\n\n 2\n ,\n\n v\n\n 2\n {\\displaystyle {\\displaystyle {u\\_{2},v\\_{2}}}}\n are disjoint.\n\nMaximum Matching\n: A Maximum matching|maximum matching is a matching **M** with the largest possible number of edges among all possible matchings in the graph **G**. The size of the matching is \n\n |\n M\n\n |\n {\\displaystyle {\\displaystyle |M|}}\n .\n: The objective of the maximum matching problem is to find a matching **M** such that \n\n |\n M\n\n |\n {\\displaystyle {\\displaystyle |M|}}\n is maximized.\n\nChallenge in General Graphs\n: Odd Cycles\n: For Bipartite graph|bipartite graphs, efficient algorithms exist (e.g., Hopcroft-Karp algorithm) that rely on finding Augmenting path|augmenting paths. An augmenting path with respect to a matching **M** is a path that starts and ends at unmatched vertex|unmatched vertices, and its edges alternate between being outside **M** and inside **M**. If such a path exists, the matching can be increased by one edge by flipping the edges along the path (taking edges not in **M** and removing edges in **M** along the path). Berge's lemma states that a matching is maximum if and only if it has no augmenting path.\n: However, the presence of Cycle (graph theory)|odd-length cycles in general graphs complicates the search for augmenting paths. Standard Breadth-first search|BFS techniques used for bipartite graphs can get \"confused\" by odd cycles, which are sometimes called *blossoms* or *flowers* in this context. An odd cycle can contain an even number of matched edges and an odd number of unmatched edges with respect to an alternating path leading into it, potentially preventing the discovery of a true augmenting path using simple methods.\n\nObjective\n: Given a general graph \n\n G\n =\n (\n V\n ,\n E\n )\n {\\displaystyle {\\displaystyle G=(V,E)}}\n , the problem is to compute a matching \n\n M\n ⊆\n E\n {\\displaystyle {\\displaystyle M\\subseteq E}}\n such that its size \n\n |\n M\n\n |\n {\\displaystyle {\\displaystyle |M|}}\n is maximum. The Blossom algorithm provides a polynomial-time solution to this problem.\n\nComplexity\n: The original Blossom algorithm by Edmonds has a time complexity of \n\n O\n (\n\n |\n V\n\n\n |\n\n 2\n\n |\n E\n\n |\n )\n {\\displaystyle {\\displaystyle O(|V|^{2}|E|)}}\n . Subsequent improvements by Edmonds and others, including Robert Tarjan|Tarjan, led to more efficient versions. Modern implementations using advanced data structures achieve a time complexity of \n\n O\n (\n\n |\n E\n\n |\n\n |\n V\n\n |\n )\n {\\displaystyle {\\displaystyle O(|E|{\\sqrt {|V|}})}}\n , which is generally considered very efficient for this problem. An \n\n O\n (\n\n |\n V\n\n\n |\n\n 3\n )\n {\\displaystyle {\\displaystyle O(|V|^{3})}}\n variant is also commonly cited and easier to implement."
},
{
"role": "assistant",
"content": "**Translation of**: Phix\n\n**Translation of**: Python\n\n```\n# 20250512 Raku programming solution\n\n# least common ancestor of x and y in the alternating forest\nsub lca($x is copy, $y is copy, @bases, @matches, @paths, $n) {\n my @usedPath = False xx $n;\n loop {\n @usedPath[$x = @bases[$x]] = True;\n @matches[$x] < 0 ?? ( last ) !! $x = @paths[@matches[$x]]\n }\n loop {\n @usedPath[$y = @bases[$y]].Bool ?? ( last ) !! $y = @paths[@matches[$y]] \n }\n return $y;\n}\n\n# mark path from v up to base0, setting parents to x\nsub markPath($v is copy, $base0, $x is copy, @bases, @matches, @paths, @blossom) {\n while @bases[$v] != $base0 {\n my $mv = @matches[$v];\n @blossom[@bases[$mv]] = @blossom[@bases[$v]] = True;\n @paths[$v] = $x;\n $v = @paths[ $x = $mv ];\n }\n}\n\n# attempt to find an augmenting path from root\nsub findPath(@adj, $root, $n, @matches is copy) {\n my @paths = -1 xx $n;\n my @bases = ^$n;\n my @queue = ($root);\n my (@used, @blossom) is default( False );\n @used[$root] = True;\n\n while my $v = @queue.shift {\n for @adj[$v].flat -> $u {\n next unless @bases[$v] != @bases[$u] && @matches[$v] != $u;\n if $u == $root || (@matches[$u] != -1 && @paths[@matches[$u]] != -1) {\n # Found a blossom; contract it\n my $curbase = lca($v, $u, @bases, @matches, @paths, $n);\n markPath($v, $curbase, $u, @bases, @matches, @paths, @blossom);\n markPath($u, $curbase, $v, @bases, @matches, @paths, @blossom);\n @queue.push: gather for ^$n -> $i {\n if @blossom[@bases[$i]] {\n @bases[$i] = $curbase;\n unless @used[$i] { @used[take $i] = True }\n }\n }\n } elsif @paths[$u] == -1 { # extend tree\n @paths[$u] = $v;\n if @matches[$u] == -1 { # augmenting path found\n my $v = $u;\n while $v != -1 {\n my $prev = @paths[$v];\n my $next = ( $prev != -1 ) ?? @matches[$prev] !! -1;\n @matches[$v] = $prev;\n @matches[$prev] = $v if $prev != -1;\n $v = $next;\n }\n return (@matches, True);\n }\n @used[@matches[$u]] = True;\n @queue.push: @matches[$u];\n }\n }\n }\n return (@matches, False);\n}\n\n# find and return the matching array and the size of the matching\nsub solve(@adj) {\n my @matches = -1 xx ( my $n = @adj.elems ); \n my $res = 0;\n\n for ^$n -> $v {\n if @matches[$v] == -1 {\n my ($new_matches, $found) = findPath(@adj, $v, $n, @matches);\n if $found {\n @matches = @$new_matches;\n $res++;\n }\n }\n }\n return (@matches, $res);\n}\n\n# Example: 5-cycle (0–1–2–3–4–0)\nmy $n = 5;\nmy @edges = (0,1), (1,2), (2,3), (3,4), (4,0);\nmy @adj = [ [] xx $n ];\nfor @edges -> ($u, $v) {\n @adj[$u].push($v);\n @adj[$v].push($u);\n}\n\nmy ($matches, $msize) = solve(@adj);\nsay \"Maximum matching size: $msize\";\nsay \"Matched pairs:\";\nfor $matches.kv -> $u, $v { say \" $u – $v\" if $v != -1 && $u < $v }\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nA positive integer **n** is a **Blum integer** if *n = p x q* is a semi-prime for which *p* and *q* are distinct primes congruent to 3 mod 4. In other words, *p* and *q* must be of the form 4*t* + 3 where *t* is some non-negative integer.\n\nExample\n\n21 is a Blum integer because it has two prime factors: 3 (= 4 x 0 + 3) and 7 (= 4 x 1 + 3).\n\nTask\n\nFind and show on this page the first **50** Blum integers.\n\nAlso show the **26,828**th.\n\nStretch\n\nFind and show the **100,000**th, **200,000**th, **300,000**th and **400,000**th Blum integers.\n\nFor the first **400,000** Blum integers, show the percentage distribution by final decimal digit (to 3 decimal places). Clearly, such integers can only end in 1, 3, 7 or 9.\n\nRelated task\n\n* Semiprime\n\nReferences\n\n* Wikipedia article Blum integer\n* OEIS sequence A016105: Blum integers"
},
{
"role": "assistant",
"content": "```\nuse List::Divvy;\nuse Lingua::EN::Numbers;\n\nsub is-blum(Int $n ) {\n return False if $n.is-prime;\n my $factor = find-factor($n);\n return True if ($factor.is-prime && ( my $div = $n div $factor ).is-prime && ($div != $factor)\n && ($factor % 4 == 3) && ($div % 4 == 3));\n False;\n}\n\nsub find-factor ( Int $n, $constant = 1 ) {\n my $x = 2;\n my $rho = 1;\n my $factor = 1;\n while $factor == 1 {\n $rho *= 2;\n my $fixed = $x;\n for ^$rho {\n $x = ( $x * $x + $constant ) % $n;\n $factor = ( $x - $fixed ) gcd $n;\n last if 1 < $factor;\n }\n }\n $factor = find-factor( $n, $constant + 1 ) if $n == $factor;\n $factor;\n}\n\nmy @blum = lazy (2..Inf).hyper(:1000batch).grep: &is-blum;\nsay \"The first fifty Blum integers:\\n\" ~\n @blum[^50].batch(10)».fmt(\"%3d\").join: \"\\n\";\nsay '';\n\nprintf \"The %9s Blum integer: %9s\\n\", .&ordinal-digit(:c), comma @blum[$_-1] for 26828, 1e5, 2e5, 3e5, 4e5;\n\nsay \"\\nBreakdown by last digit:\";\nprintf \"%d => %%%7.4f:\\n\", .key, +.value / 4e3 for sort @blum[^4e5].categorize: {.substr(*-1)}\n\n```\n\nOutput:\n\n```\nThe first fifty Blum integers:\n 21 33 57 69 77 93 129 133 141 161\n177 201 209 213 217 237 249 253 301 309\n321 329 341 381 393 413 417 437 453 469\n473 489 497 501 517 537 553 573 581 589\n597 633 649 669 681 713 717 721 737 749\n\nThe 26,828th Blum integer: 524,273\nThe 100,000th Blum integer: 2,075,217\nThe 200,000th Blum integer: 4,275,533\nThe 300,000th Blum integer: 6,521,629\nThe 400,000th Blum integer: 8,802,377\n\nBreakdown by last digit:\n1 => %25.0013:\n3 => %25.0168:\n7 => %24.9973:\n9 => %24.9848:\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow how to represent the boolean states \"**true**\" and \"**false**\" in a language.\n\nIf other objects represent \"**true**\" or \"**false**\" in conditionals, note it.\n\nRelated tasks\n\n* Logical operations"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nRaku provides an enumeration `Bool` with two values, `True` and `False`. Values of enumerations can be used as ordinary values or as mixins:\n\n```\nmy Bool $crashed = False;\nmy $val = 0 but True;\n\n```\n\nFor a discussion of Boolean context (how Raku decides whether something is True or False): https://docs.raku.org/language/contexts#index-entry-Boolean\\_context."
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Boustrophedon transform. 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\nA boustrophedon transform is a procedure which maps one sequence to another using a series of integer additions.\n\nGenerally speaking, given a sequence: \n\n(\n\na\n\n0\n,\n\na\n\n1\n,\n\na\n\n2\n,\n…\n)\n{\\displaystyle {\\displaystyle (a\\_{0},a\\_{1},a\\_{2},\\ldots )}}\n, the boustrophedon transform yields another sequence: \n\n(\n\nb\n\n0\n,\n\nb\n\n1\n,\n\nb\n\n2\n,\n…\n)\n{\\displaystyle {\\displaystyle (b\\_{0},b\\_{1},b\\_{2},\\ldots )}}\n, where \n\nb\n\n0\n{\\displaystyle {\\displaystyle b\\_{0}}}\n is likely defined equivalent to \n\na\n\n0\n{\\displaystyle {\\displaystyle a\\_{0}}}\n.\n\nThere are a few different ways to effect the transform. You may construct a boustrophedon triangle and read off the edge values, or, may use the recurrence relationship:\n\n: T\n\n k\n ,\n 0\n =\n\n a\n\n k\n {\\displaystyle {\\displaystyle T\\_{k,0}=a\\_{k}}}\n: T\n\n k\n ,\n n\n =\n\n T\n\n k\n ,\n n\n −\n 1\n +\n\n T\n\n k\n −\n 1\n ,\n k\n −\n n\n {\\displaystyle {\\displaystyle T\\_{k,n}=T\\_{k,n-1}+T\\_{k-1,k-n}}}\n: with \n {\\displaystyle {\\displaystyle {\\text{with }}}}\n: k\n ,\n n\n ∈\n\n N\n {\\displaystyle {\\displaystyle \\quad k,n\\in \\mathbb {N} }}\n: k\n ≥\n n\n >\n 0\n {\\displaystyle {\\displaystyle \\quad k\\geq n>0}}\n .\n\nThe transformed sequence is defined by \n\nb\n\nn\n=\n\nT\n\nn\n,\nn\n{\\displaystyle {\\displaystyle b\\_{n}=T\\_{n,n}}}\n (for \n\nT\n\n2\n,\n2\n{\\displaystyle {\\displaystyle T\\_{2,2}}}\n and greater indices).\n\nYou are free to use a method most convenient for your language. If the boustrophedon transform is provided by a built-in, or easily and freely available library, it is acceptable to use that (with a pointer to where it may be obtained).\n\nTask\n\n* Write a procedure (routine, function, subroutine, whatever it may be called in your language) to perform a boustrophedon transform to a given sequence.\n* Use that routine to perform a boustrophedon transform on a few representative sequences. Show the first fifteen values from the transformed sequence.\n\n: *Use the following sequences for demonstration:*\n\n * (\n 1\n ,\n 0\n ,\n 0\n ,\n 0\n ,\n …\n )\n {\\displaystyle {\\displaystyle (1,0,0,0,\\ldots )}}\n ( one followed by an infinite series of zeros )\n * (\n 1\n ,\n 1\n ,\n 1\n ,\n 1\n ,\n …\n )\n {\\displaystyle {\\displaystyle (1,1,1,1,\\ldots )}}\n ( an infinite series of ones )\n * (\n 1\n ,\n −\n 1\n ,\n 1\n ,\n −\n 1\n ,\n …\n )\n {\\displaystyle {\\displaystyle (1,-1,1,-1,\\ldots )}}\n ( (-1)^n: alternating 1, -1, 1, -1 )\n * (\n 2\n ,\n 3\n ,\n 5\n ,\n 7\n ,\n 11\n ,\n …\n )\n {\\displaystyle {\\displaystyle (2,3,5,7,11,\\ldots )}}\n ( sequence of prime numbers )\n * (\n 1\n ,\n 1\n ,\n 2\n ,\n 3\n ,\n 5\n ,\n …\n )\n {\\displaystyle {\\displaystyle (1,1,2,3,5,\\ldots )}}\n ( sequence of Fibonacci numbers )\n * (\n 1\n ,\n 1\n ,\n 2\n ,\n 6\n ,\n 24\n ,\n …\n )\n {\\displaystyle {\\displaystyle (1,1,2,6,24,\\ldots )}}\n ( sequence of factorial numbers )\n\nStretch\n\nIf your language supports big integers, show the first and last 20 digits, and the digit count of the 1000th element of each sequence.\n\nSee also\n\n* Wikipedia - Boustrophedon transform * OEIS:A000111 - Euler, or up/down numbers * OEIS:A000667 - Boustrophedon transform of all-1's sequence * OEIS:A062162 - Boustrophedon transform of (-1)^n * OEIS:A000747 - Boustrophedon transform of primes * OEIS:A000744 - Boustrophedon transform of Fibonacci numbers * OEIS:A230960 - Boustrophedon transform of factorials"
},
{
"role": "assistant",
"content": "```\nsub boustrophedon-transform (@seq) { map *.tail, (@seq[0], {[[\\+] flat @seq[++$ ], .reverse]}…*) }\n\nsub abbr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '…' ~ .substr(*-20) ~ \" ({.chars} digits)\" }\n\nfor '1 followed by 0\\'s A000111', (flat 1, 0 xx *),\n 'All-1\\'s A000667', (flat 1 xx *),\n '(-1)^n A062162', (flat 1, [\\×] -1 xx *),\n 'Primes A000747', (^∞ .grep: &is-prime),\n 'Fibonaccis A000744', (1,1,*+*…*),\n 'Factorials A230960', (1,|[\\×] 1..∞)\n -> $name, $seq\n{ say \"\\n$name:\\n\" ~ (my $b-seq = boustrophedon-transform $seq)[^15] ~ \"\\n1000th term: \" ~ abbr $b-seq[999] }\n\n```\n\nOutput:\n\n```\n1 followed by 0's A000111:\n1 1 1 2 5 16 61 272 1385 7936 50521 353792 2702765 22368256 199360981\n1000th term: 61065678604283283233…63588348134248415232 (2369 digits)\n\nAll-1's A000667:\n1 2 4 9 24 77 294 1309 6664 38177 243034 1701909 13001604 107601977 959021574\n1000th term: 29375506567920455903…86575529609495110509 (2370 digits)\n\n(-1)^n A062162:\n1 0 0 1 0 5 10 61 280 1665 10470 73621 561660 4650425 41441530\n1000th term: 12694307397830194676…15354198638855512941 (2369 digits)\n\nPrimes A000747:\n2 5 13 35 103 345 1325 5911 30067 172237 1096319 7677155 58648421 485377457 4326008691\n1000th term: 13250869953362054385…82450325540640498987 (2371 digits)\n\nFibonaccis A000744:\n1 2 5 14 42 144 563 2526 12877 73778 469616 3288428 25121097 207902202 1852961189\n1000th term: 56757474139659741321…66135597559209657242 (2370 digits)\n\nFactorials A230960:\n1 2 5 17 73 381 2347 16701 134993 1222873 12279251 135425553 1627809401 21183890469 296773827547\n1000th term: 13714256926920345740…19230014799151339821 (2566 digits)\n```"
}
]
|
[
{
"role": "user",
"content": "Avast me hearties!\n\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass!\n\nTask description\n\n1. Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n2. Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n\n: `[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]`. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\nNotes;\n\n* The headings and indices can be calculated from this pseudocode:\n\n```\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n```\n\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page).."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub point (Int $index) {\n my $ix = $index % 32;\n if $ix +& 1\n { \"&point(($ix + 1) +& 28) by &point(((2 - ($ix +& 2)) * 4) + $ix +& 24)\" }\n elsif $ix +& 2\n { \"&point(($ix + 2) +& 24)-&point(($ix +| 4) +& 28)\" }\n elsif $ix +& 4\n { \"&point(($ix + 8) +& 16)&point(($ix +| 8) +& 24)\" }\n else\n { <north east south west>[$ix div 8]; }\n}\n\nsub test-angle ($ix) { $ix * 11.25 + (0, 5.62, -5.62)[ $ix % 3 ] }\nsub angle-to-point(\\𝜽) { floor 𝜽 / 360 * 32 + 0.5 }\n\nfor 0 .. 32 -> $ix {\n my \\𝜽 = test-angle($ix);\n printf \" %2d %6.2f° %s\\n\",\n $ix % 32 + 1,\n 𝜽,\n tc point angle-to-point 𝜽;\n}\n\n```\n\nOutput:\n\n```\n 1 0.00° North\n 2 16.87° North by east\n 3 16.88° North-northeast\n 4 33.75° Northeast by north\n 5 50.62° Northeast\n 6 50.63° Northeast by east\n 7 67.50° East-northeast\n 8 84.37° East by north\n 9 84.38° East\n 10 101.25° East by south\n 11 118.12° East-southeast\n 12 118.13° Southeast by east\n 13 135.00° Southeast\n 14 151.87° Southeast by south\n 15 151.88° South-southeast\n 16 168.75° South by east\n 17 185.62° South\n 18 185.63° South by west\n 19 202.50° South-southwest\n 20 219.37° Southwest by south\n 21 219.38° Southwest\n 22 236.25° Southwest by west\n 23 253.12° West-southwest\n 24 253.13° West by south\n 25 270.00° West\n 26 286.87° West by north\n 27 286.88° West-northwest\n 28 303.75° Northwest by west\n 29 320.62° Northwest\n 30 320.63° Northwest by north\n 31 337.50° North-northwest\n 32 354.37° North by west\n 1 354.38° North\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nThis algorithm is designed for pattern searching on certain types of devices which are backtracking-unfriendly such as Tape drives and Hard disks.\n\nIt works by first caching a segment of data from storage and match it against the pattern from the highest position backward to the lowest. If the matching fails, it will cache next segment of data and move the start point forward to skip the portion of data which will definitely fail to match. This continues until we successfully match the pattern or the pointer exceeds the data length.\n\nFollow this link for more information about this algorithm.\n\nTo properly test this algorithm, it would be good to search for a string which contains repeated subsequences, such as `alfalfa` and the text being searched should not only include a match but that match should be preceded by words which partially match, such as `alfredo`, `behalf`, `calfskin`, `halfhearted`, `malfunction` or `severalfold`."
},
{
"role": "assistant",
"content": "**Translation of**: Phix\n\n```\n# 20220818 Raku programming solution\n\nsub suffixes (@pat,\\m) {\n loop (my ($i,$f,$g,@suff)=m-2, 0, m-1, |flat 0 xx m-1,m; $i >= 0; --$i) {\n if $i > $g and @suff[$i + m - 1 - $f] < $i - $g {\n @suff[$i] = @suff[$i + m - 1 - $f]\n } else {\n\t $g = $i if $i < $g;\n $f = $i;\n\t while $g >= 0 and @pat[$g] eq @pat[$g + m - 1 - $f] { $g-- }\n @suff[$i] = $f - $g\n }\n }\n return @suff;\n}\n\nsub preBmGs (@pat,\\m) {\n my (@suff, @bmGs) := suffixes(@pat,m), [m xx m]; \n\n for m-1 ... 0 -> \\k {\n if @suff[k] == k + 1 {\n loop (my $j=0; $j < m-1-k; $j++) { @bmGs[k]=m-1-k if @bmGs[$j] == m }\n }\n }\n for ^(m-1) { @bmGs[m - 1 - @suff[$_]] = m - 1 - $_ }\n return @bmGs;\n}\n\nsub BM (@txt,@pat) {\n my (\\m, \\n, $j) = +@pat, +@txt, 0;\n my (@bmGs, %bmBc) := preBmGs(@pat,m), hash @pat Z=> ( m-1 ... 1 );\n\n return gather while $j <= n - m {\n loop (my $i = m - 1; $i >= 0 and @pat[$i] eq @txt[$i + $j]; ) { $i-- }\n if $i < 0 {\n\t take $j;\n $j += @bmGs[0]\n } else {\n $j += max @bmGs[$i], (%bmBc{@txt[$i + $j]} // m)-m+$i\n }\n }\n}\n\nmy @texts = [\n \"GCTAGCTCTACGAGTCTA\",\n \"GGCTATAATGCGTA\",\n \"there would have been a time for such a word\",\n \"needle need noodle needle\",\n \"BharôtভাৰতBharôtভারতIndiaBhāratભારતBhāratभारतBhārataಭಾರತBhāratभारतBhāratamഭാരതംBhāratभारतBhāratभारतBharôtôଭାରତBhāratਭਾਰਤBhāratamभारतम्Bārataபாரதம்BhāratamഭാരതംBhāratadēsamభారతదేశం\",\n \"InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented\",\n \"Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk.\",\n];\n\nmy @pats = [ \"TCTA\", \"TAATAAA\", \"word\", \"needle\", \"ഭാരതം\", \"put\", \"and\", \"alfalfa\"];\n\nsay \"text$_ = @texts[$_]\" for @texts.keys ;\nsay();\n\nfor @pats.keys {\n my \\j = $_ < 6 ?? $_ !! $_-1 ; # for searching text5 twice\n say \"Found '@pats[$_]' in 'text{j}' at indices \", BM @texts[j].comb, @pats[$_].comb\n}\n\n```\n\nOutput is the same as the Knuth-Morris-Pratt\\_string\\_search#Raku entry."
}
]
|
[
{
"role": "user",
"content": "Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter `enable_{audio,video}` would be interpreted as if both `enable_audio` and `enable_video` had been specified.\n\nTask\n\nWrite a function that can perform brace expansion on any input string, according to the following specification. \nDemonstrate how it would be used, and that it passes the four test cases given below.\n\nSpecification\n\nIn the input string, balanced pairs of braces containing comma-separated substrings (details below) represent *alternations* that specify multiple alternatives which are to appear at that position in the output. In general, one can imagine the information conveyed by the input string as a tree of nested alternations interspersed with literal substrings, as shown in the middle part of the following diagram:\n\n| | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| It{{em,alic}iz,erat}e{d,} | *parse* ―――――▶ | | | | | | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | It | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | | ⎧ ⎨ ⎩ | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | em | ⎫ ⎬ ⎭ | | alic | | iz | ⎫ ⎬ ⎭ | | erat | | | e | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | d | ⎫ ⎬ ⎭ | | | | | *expand* ―――――▶ | Itemized Itemize Italicized Italicize Iterated Iterate |\n| input string | | alternation tree | | output *(list of strings)* |\n\nThis tree can in turn be transformed into the intended list of output strings by, colloquially speaking, determining all the possible ways to walk through it from left to right while only descending into *one* branch of each alternation one comes across *(see the right part of the diagram)*. When implementing it, one can of course combine the parsing and expansion into a single algorithm, but this specification discusses them separately for the sake of clarity.\n\n**Expansion** of alternations can be more rigorously described by these rules:\n\n| | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | | | | | | | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | a | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | 2 | ⎫ ⎬ ⎭ | | 1 | | b | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | X | ⎫ ⎬ ⎭ | | Y | | X | | c | | ⟶ | | | | --- | | a2bXc | | a2bYc | | a2bXc | | a1bXc | | a1bYc | | a1bXc | |\n\n* An alternation causes the list of alternatives that will be produced by its parent branch to be increased 𝑛-fold, each copy featuring one of the 𝑛 alternatives produced by the alternation's child branches, in turn, at that position.\n* This means that multiple alternations inside the same branch are cumulative *(i.e. the complete list of alternatives produced by a branch is the string-concatenating \"Cartesian product\" of its parts)*.\n* All alternatives (even duplicate and empty ones) are preserved, and they are ordered like the examples demonstrate *(i.e. \"lexicographically\" with regard to the alternations)*.\n* The alternatives produced by the root branch constitute the final output.\n\n**Parsing** the input string involves some additional complexity to deal with escaped characters and \"incomplete\" brace pairs:\n\n| | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| a\\\\{\\\\\\{b,c\\,d} | ⟶ | | | | | | | | | --- | --- | --- | --- | --- | --- | | a\\\\ | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | \\\\\\{b | ⎫ ⎬ ⎭ | | c\\,d | | |\n| {a,b{c{,{d}}e}f | ⟶ | | | | | | | | | | --- | --- | --- | --- | --- | --- | --- | | {a,b{c | | | | | | --- | --- | --- | | ⎧ ⎨ ⎩ | | ⎫ ⎬ ⎭ | | {d} | | e}f | |\n\n* An unescaped *backslash* which precedes another character, escapes that character (to force it to be treated as literal). The backslashes are passed along to the output unchanged.\n* Balanced *brace pairs* are identified by, conceptually, going through the string from left to right and associating each unescaped closing brace that is encountered with the nearest still unassociated unescaped opening brace to its left (if any). Furthermore, each unescaped *comma* is associated with the innermost brace pair that contains it (if any). With that in mind:\n + Each brace pair that has at least one comma associated with it, forms an alternation (whose branches are the brace pair's contents split at its commas). The associated brace and comma characters themselves do not become part of the output.\n + Brace characters from pairs without any associated comma, as well as unassociated brace and comma characters, as well as all characters that are not covered by the preceding rules, are instead treated as literals.\n\nFor every possible input string, your implementation should produce exactly the output which this specification mandates. Please comply with this even when it's inconvenient, to ensure that all implementations are comparable. However, none of the above should be interpreted as instructions (or even recommendations) for **how** to implement it. Try to come up with a solution that is idiomatic in your programming language. *(See #Perl for a reference implementation.)*\n\nTest Cases\n\n: : : | Input *(single string)* | Ouput *(list/array of strings)* |\n | --- | --- |\n | `~/{Downloads,Pictures}/*.{jpg,gif,png}` | `~/Downloads/*.jpg` `~/Downloads/*.gif` `~/Downloads/*.png` `~/Pictures/*.jpg` `~/Pictures/*.gif` `~/Pictures/*.png` |\n | `It{{em,alic}iz,erat}e{d,}, please.` | `Itemized, please.` `Itemize, please.` `Italicized, please.` `Italicize, please.` `Iterated, please.` `Iterate, please.` |\n | `{,{,gotta have{ ,\\, again\\, }}more }cowbell!` | `cowbell!` `more cowbell!` `gotta have more cowbell!` `gotta have\\, again\\, more cowbell!` |\n | `{}} some }{,{\\\\{ edge, edge} \\,}{ cases, {here} \\\\\\\\\\}` | `{}} some }{,{\\\\ edge \\,}{ cases, {here} \\\\\\\\\\}` `{}} some }{,{\\\\ edge \\,}{ cases, {here} \\\\\\\\\\}` |\n\n---\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\n\n: * Brace\\_expansion\\_using\\_ranges"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThe task description allows the taking of shortcuts, but please note that we are not taking any shortcuts here. The solution is short because this particular problem happens to map quite naturally to the strengths of Raku.\n\nFirst, the parsing is handled with a grammar that can backtrack in the few places this problem needs it. The + quantifier matches one or more alternatives (we handle the case of a single alternative in the walk now), and the % modifier requires a comma between each quantified item to its left. Note that the \\* quantifiers do *not* backtrack here, because the token keyword suppresses that; all the backtracking here fails over to a different alternative in an outer alternation (that is, things separated by the | character in the grammar. Most of these failovers just nibble an uninteresting character and continue.)\n\nOn the other end, we recursively walk the parse tree returning expanded sublists, and we do the cartesian concatenation of sublists at each level by use of the X~ operator, which is a \"cross\" metaoperator used on a simple ~ concatenation. As a list infix operator, X~ does not care how many items are on either side, which is just what you want in this case, since some of the arguments are strings and some are lists. Here we use a fold or reduction form in square brackets to interpose the cross-concat between each value generated by the map, which returns a mixture of lists and literal strings. One other thing that might not be obvious: if we bind to the match variable, $/, we automatically get all the syntactic sugar for its submatches. In this case, $0 is short for $/[0], and represents all the submatches captured by 0th set of parens in either TOP or alt. $<meta> is likewise short for $/<meta>, and retrieves what was captured by that named submatch.\n\n```\ngrammar BraceExpansion {\n token TOP { ( <meta> | . )* }\n token meta { '{' <alts> '}' | \\\\ . }\n token alts { <alt>+ % ',' }\n token alt { ( <meta> | <-[ , } ]> )* }\n}\n\nsub crosswalk($/) {\n |[X~] flat '', $0.map: -> $/ { $<meta><alts><alt>.&alternatives or ~$/ }\n}\n\nsub alternatives($_) {\n when :not { () }\n when 1 { '{' X~ $_».&crosswalk X~ '}' }\n default { $_».&crosswalk }\n}\n\nsub brace-expand($s) { crosswalk BraceExpansion.parse($s) }\n\n# Testing:\n\nsub bxtest(*@s) {\n for @s -> $s {\n say \"\\n$s\";\n for brace-expand($s) {\n say \" \", $_;\n }\n }\n}\n\nbxtest Q:to/END/.lines;\n ~/{Downloads,Pictures}/*.{jpg,gif,png}\n It{{em,alic}iz,erat}e{d,}, please.\n {,{,gotta have{ ,\\, again\\, }}more }cowbell!\n a{b{1,2}c\n a{1,2}b}c\n a{1,{2},3}b\n more{ darn{ cowbell,},}\n ab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr\n {a,{\\,b}c\n a{b,{{c}}\n {a{\\}b,c}d\n END\n\n```\n\nOutput:\n\n```\n~/{Downloads,Pictures}/*.{jpg,gif,png}\n ~/Downloads/*.jpg\n ~/Downloads/*.gif\n ~/Downloads/*.png\n ~/Pictures/*.jpg\n ~/Pictures/*.gif\n ~/Pictures/*.png\n\nIt{{em,alic}iz,erat}e{d,}, please.\n Itemized, please.\n Itemize, please.\n Italicized, please.\n Italicize, please.\n Iterated, please.\n Iterate, please.\n\n{,{,gotta have{ ,\\, again\\, }}more }cowbell!\n cowbell!\n more cowbell!\n gotta have more cowbell!\n gotta have\\, again\\, more cowbell!\n\n{}} some {\\\\{edge,edgy} }{ cases, here\\\\\\}\n {}} some {\\\\edge }{ cases, here\\\\\\}\n {}} some {\\\\edgy }{ cases, here\\\\\\}\n\na{b{1,2}c\n a{b1c\n a{b2c\n\na{1,2}b}c\n a1b}c\n a2b}c\n\na{1,{2},3}b\n a1b\n a{2}b\n a3b\n\nmore{ darn{ cowbell,},}\n more darn cowbell\n more darn\n more\n\nab{c,d\\,e{f,g\\h},i\\,j{k,l\\,m}n,o\\,p}qr\n abcqr\n abd\\,efqr\n abd\\,eg\\hqr\n abi\\,jknqr\n abi\\,jl\\,mnqr\n abo\\,pqr\n\n{a,{\\,b}c\n {a,{\\,b}c\n\na{b,{{c}}\n a{b,{{c}}\n\n{a{\\}b,c}d\n {a\\}bd\n {acd\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nTask\n\nWrite and test a function which expands one or more Unix-style **numeric and alphabetic range braces** embedded in a larger string.\n\nSpecification\n\nThe brace strings used by Unix shells permit expansion of both:\n\n1. Recursive comma-separated lists (covered by the **related task**: Brace\\_expansion, and can be ignored here)\n2. ordered numeric and alphabetic **ranges**, which are the object of this task.\n\nThe general pattern of brace ranges is:\n\n```\n{<START>..<END>}\n```\n\nand, in more recent shells:\n\n```\n{<START>..<END>..<INCR>}\n```\n\n(See https://wiki.bash-hackers.org/syntax/expansion/brace)\n\nExpandable ranges of this kind can be ascending or descending:\n\n```\nsimpleNumber{1..3}.txt\nsimpleAlpha-{Z..X}.txt\n```\n\nand may have a third INCR element specifying ordinal intervals larger than one.\nThe increment value can be preceded by a **-** minus sign, but not by a **+** sign.\n\nThe effect of the minus sign is to always to **reverse** the natural order suggested by the START and END values.\n\nAny level of zero-padding used in either the START or END value of a numeric range is adopted in the expansions.\n\n```\nsteppedDownAndPadded-{10..00..5}.txt\nminusSignFlipsSequence {030..20..-5}.txt\n```\n\nA single string may contain more than one expansion range:\n\n```\ncombined-{Q..P}{2..1}.txt\n```\n\nAlphabetic range values are limited to a single character for START and END\nbut these characters are not confined to the ASCII alphabet.\n\n```\nemoji{🌵..🌶}{🌽..🌾}etc\n```\n\nUnmatched braces are simply ignored, as are empty braces, and braces which contain no range (or list).\n\n```\nli{teral\nrangeless{}empty\nrangeless{random}string\n```\n\nTests\n\nGenerate and display here the expansion of (at least) each of the ten example lines shown below.\n\nThe JavaScript implementation below uses parser combinators, aiming to encode a more or less full and legible description of the\n\n```\n<PREAMBLE><AMBLE><POSTSCRIPT>\n```\n\nrange brace grammar, but you should use any resource that suggests itself in your language, including parser libraries.\n\n(The grammar of range expansion, unlike that of nested list expansion, is not recursive, so even regular expressions should prove serviceable here).\n\nThe output of the JS implementation, which aims to match the brace expansion behaviour of the default **zsh** shell on current versions of macOS:\n\n```\nsimpleNumberRising{1..3}.txt -> \n simpleNumberRising1.txt\n simpleNumberRising2.txt\n simpleNumberRising3.txt\n\nsimpleAlphaDescending-{Z..X}.txt -> \n simpleAlphaDescending-Z.txt\n simpleAlphaDescending-Y.txt\n simpleAlphaDescending-X.txt\n\nsteppedDownAndPadded-{10..00..5}.txt -> \n steppedDownAndPadded-10.txt\n steppedDownAndPadded-05.txt\n steppedDownAndPadded-00.txt\n\nminusSignFlipsSequence {030..20..-5}.txt -> \n minusSignFlipsSequence 020.txt\n minusSignFlipsSequence 025.txt\n minusSignFlipsSequence 030.txt\n\nreverseSteppedNumberRising{1..6..-2}.txt -> \n reverseSteppedNumberRising5.txt\n reverseSteppedNumberRising3.txt\n reverseSteppedNumberRising1.txt\n\ncombined-{Q..P}{2..1}.txt -> \n combined-Q2.txt\n combined-Q1.txt\n combined-P2.txt\n combined-P1.txt\n\nemoji{🌵..🌶}{🌽..🌾}etc -> \n emoji🌵🌽etc\n emoji🌵🌾etc\n emoji🌶🌽etc\n emoji🌶🌾etc\n\nli{teral -> \n li{teral\n\nrangeless{}empty -> \n rangeless{}empty\n\nrangeless{random}string -> \n rangeless{random}string\n```\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\n\n* range expansion"
},
{
"role": "assistant",
"content": "**Works with**: Rakudo version 2020.08.1\n\nAlso implements some of the string list functions described on the bash-hackers page.\n\n```\nmy $range = rx/ '{' $<start> = <-[.]>+? '..' $<end> = <-[.]>+? ['..' $<incr> = ['-'?\\d+] ]? '}' /;\nmy $list = rx/ ^ $<prefix> = .*? '{' (<-[,}]>+) +%% ',' '}' $<postfix> = .* $/;\n\nsub expand (Str $string) {\n my @return = $string;\n if $string ~~ $range {\n quietly my ($start, $end, $incr) = $/<start end incr>».Str;\n $incr ||= 1;\n ($end, $start) = $start, $end if $incr < 0;\n $incr.=abs;\n\n if try all( +$start, +$end ) ~~ Numeric {\n $incr = - $incr if $start > $end;\n\n my ($sl, $el) = 0, 0;\n $sl = $start.chars if $start.starts-with('0');\n $el = $end.chars if $end.starts-with('0');\n\n my @this = $start < $end ?? (+$start, * + $incr …^ * > +$end) !! (+$start, * + $incr …^ * < +$end);\n @return = @this.map: { $string.subst($range, sprintf(\"%{'0' ~ max $sl, $el}d\", $_) ) }\n }\n elsif try +$start ~~ Numeric or +$end ~~ Numeric {\n return $string #fail\n }\n else {\n my @this;\n if $start.chars + $end.chars > 2 {\n return $string if $start.succ eq $start or $end.succ eq $end; # fail\n @this = $start lt $end ?? ($start, (*.succ xx $incr).tail …^ * gt $end) !! ($start, (*.pred xx $incr).tail …^ * lt $end);\n }\n else {\n $incr = -$incr if $start gt $end;\n @this = $start lt $end ?? ($start, (*.ord + $incr).chr …^ * gt $end) !! ($start, (*.ord + $incr).chr …^ * lt $end);\n }\n @return = @this.map: { $string.subst($range, sprintf(\"%s\", $_) ) }\n }\n }\n if $string ~~ $list {\n my $these = $/[0]».Str;\n my ($prefix, $postfix) = $/<prefix postfix>».Str;\n if ($prefix ~ $postfix).chars {\n @return = $these.map: { $string.subst($list, $prefix ~ $_ ~ $postfix) } if $these.elems > 1\n }\n else {\n @return = $these.join: ' '\n }\n }\n my $cnt = 1;\n while $cnt != +@return {\n $cnt = +@return;\n @return.=map: { |.&expand }\n }\n @return\n}\n\nfor qww<\n # Required tests\n\n simpleNumberRising{1..3}.txt\n simpleAlphaDescending-{Z..X}.txt\n steppedDownAndPadded-{10..00..5}.txt\n minusSignFlipsSequence{030..20..-5}.txt\n combined-{Q..P}{2..1}.txt\n emoji{🌵..🌶}{🌽..🌾}etc\n li{teral\n rangeless{}empty\n rangeless{random}string\n\n # Test some other features\n\n 'stop point not in sequence-{02..10..3}.txt'\n steppedAlphaRising{P..Z..2}.txt\n 'simple {just,give,me,money} list'\n {thatʼs,what,I,want}\n 'emoji {☃,☄}{★,🇺🇸,☆} lists'\n 'alphanumeric mix{ab7..ac1}.txt'\n 'alphanumeric mix{0A..0C}.txt'\n\n # fail by design\n\n 'mixed terms fail {7..C}.txt'\n 'multi char emoji ranges fail {🌵🌵..🌵🌶}'\n > -> $test {\n say \"$test ->\";\n say (' ' xx * Z~ expand $test).join: \"\\n\";\n say '';\n}\n\n```\n\nOutput:\n\n```\nsimpleNumberRising{1..3}.txt ->\n simpleNumberRising1.txt\n simpleNumberRising2.txt\n simpleNumberRising3.txt\n\nsimpleAlphaDescending-{Z..X}.txt ->\n simpleAlphaDescending-Z.txt\n simpleAlphaDescending-Y.txt\n simpleAlphaDescending-X.txt\n\nsteppedDownAndPadded-{10..00..5}.txt ->\n steppedDownAndPadded-10.txt\n steppedDownAndPadded-05.txt\n steppedDownAndPadded-00.txt\n\nminusSignFlipsSequence{030..20..-5}.txt ->\n minusSignFlipsSequence020.txt\n minusSignFlipsSequence025.txt\n minusSignFlipsSequence030.txt\n\ncombined-{Q..P}{2..1}.txt ->\n combined-Q2.txt\n combined-Q1.txt\n combined-P2.txt\n combined-P1.txt\n\nemoji{🌵..🌶}{🌽..🌾}etc ->\n emoji🌵🌽etc\n emoji🌵🌾etc\n emoji🌶🌽etc\n emoji🌶🌾etc\n\nli{teral ->\n li{teral\n\nrangeless{}empty ->\n rangeless{}empty\n\nrangeless{random}string ->\n rangeless{random}string\n\nstop point not in sequence-{02..10..3}.txt ->\n stop point not in sequence-02.txt\n stop point not in sequence-05.txt\n stop point not in sequence-08.txt\n\nsteppedAlphaRising{P..Z..2}.txt ->\n steppedAlphaRisingP.txt\n steppedAlphaRisingR.txt\n steppedAlphaRisingT.txt\n steppedAlphaRisingV.txt\n steppedAlphaRisingX.txt\n steppedAlphaRisingZ.txt\n\nsimple {just,give,me,money} list ->\n simple just list\n simple give list\n simple me list\n simple money list\n\n{thatʼs,what,I,want} ->\n thatʼs what I want\n\nemoji {☃,☄}{★,🇺🇸,☆} lists ->\n emoji ☃★ lists\n emoji ☃🇺🇸 lists\n emoji ☃☆ lists\n emoji ☄★ lists\n emoji ☄🇺🇸 lists\n emoji ☄☆ lists\n\nalphanumeric mix{ab7..ac1}.txt ->\n alphanumeric mixab7.txt\n alphanumeric mixab8.txt\n alphanumeric mixab9.txt\n alphanumeric mixac0.txt\n alphanumeric mixac1.txt\n\nalphanumeric mix{0A..0C}.txt ->\n alphanumeric mix0A.txt\n alphanumeric mix0B.txt\n alphanumeric mix0C.txt\n\nmixed terms fail {7..C}.txt ->\n mixed terms fail {7..C}.txt\n\nmulti char emoji ranges fail {🌵🌵..🌵🌶} ->\n multi char emoji ranges fail {🌵🌵..🌵🌶}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad *Olimpiada Iberoamericana de Matematica* in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number **N** has at least one natural number **B** where **1 < B < N-1** where the representation of **N** in **base B** has all equal digits.\n\nE.G.\n\n: * **1, 2 & 3** can not be Brazilian; there is no base **B** that satisfies the condition **1 < B < N-1**.\n * **4** is not Brazilian; **4** in **base 2** is **100**. The digits are not all the same.\n * **5** is not Brazilian; **5** in **base 2** is **101**, in **base 3** is **12**. There is no representation where the digits are the same.\n * **6** is not Brazilian; **6** in **base 2** is **110**, in **base 3** is **20**, in **base 4** is **12**. There is no representation where the digits are the same.\n * **7** *is* Brazilian; **7** in **base 2** is **111**. There is at least one representation where the digits are all the same.\n * **8** *is* Brazilian; **8** in **base 3** is **22**. There is at least one representation where the digits are all the same.\n * *and so on...*\n\nAll even integers **2P >= 8** are Brazilian because **2P = 2(P-1) + 2**, which is **22** in **base P-1** when **P-1 > 2**. That becomes true when **P >= 4**. \nMore common: for all all integers **R** and **S**, where **R > 1** and also **S-1 > R**, then **R\\*S** is Brazilian because **R\\*S = R(S-1) + R**, which is **RR** in **base S-1** \nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit **1**. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of **111** to base Integer(sqrt(prime number)). Must be an odd count of **1** to stay odd like primes > 2\n\nTask\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n: * the first **20** Brazilian numbers;\n * the first **20 odd** Brazilian numbers;\n * the first **20 prime** Brazilian numbers;\n\nSee also\n\n: * **OEIS:A125134 - Brazilian numbers**\n * **OEIS:A257521 - Odd Brazilian numbers**\n * **OEIS:A085104 - Prime Brazilian numbers**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n```\nmulti is-Brazilian (Int $n where $n %% 2 && $n > 6) { True }\n\nmulti is-Brazilian (Int $n) {\n LOOP: loop (my int $base = 2; $base < $n - 1; ++$base) {\n my $digit;\n for $n.polymod( $base xx * ) {\n $digit //= $_;\n next LOOP if $digit != $_;\n }\n return True\n }\n False\n}\n\nmy $upto = 20;\n\nput \"First $upto Brazilian numbers:\\n\", (^Inf).hyper.grep( &is-Brazilian )[^$upto];\n\nput \"\\nFirst $upto odd Brazilian numbers:\\n\", (^Inf).hyper.map( * * 2 + 1 ).grep( &is-Brazilian )[^$upto];\n\nput \"\\nFirst $upto prime Brazilian numbers:\\n\", (^Inf).hyper(:8degree).grep( { .is-prime && .&is-Brazilian } )[^$upto];\n\n```\n\nOutput:\n\n```\nFirst 20 Brazilian numbers:\n7 8 10 12 13 14 15 16 18 20 21 22 24 26 27 28 30 31 32 33\n\nFirst 20 odd Brazilian numbers:\n7 13 15 21 27 31 33 35 39 43 45 51 55 57 63 65 69 73 75 77\n\nFirst 20 prime Brazilian numbers:\n7 13 31 43 73 127 157 211 241 307 421 463 601 757 1093 1123 1483 1723 2551 2801\n```"
}
]
|
[
{
"role": "user",
"content": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.\nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.\nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded\nas unidiomatic at best, and poor programming practice at worst.\nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nWe may call into the MOP (Meta-Object Protocol) via the .^ operator, and the MOP knows all about the object, including any supposedly private bits. We ask for its attributes, find the correct one, and get its value.\n\n```\nclass Foo {\n has $!shyguy = 42;\n}\nmy Foo $foo .= new;\n\nsay $foo.^attributes.first('$!shyguy').get_value($foo);\n\n```\n\nOutput:\n\n```\n42\n```"
}
]
|
[
{
"role": "user",
"content": "**Brilliant numbers** are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers **that both have the same number of digits when expressed in base 10**.\n\n*Brilliant numbers are useful in cryptography and when testing prime factoring algorithms.*\n\nE.G.\n\n* **3 × 3** (9) is a brilliant number.\n* **2 × 7** (14) is a brilliant number.\n* **113 × 691** (78083) is a brilliant number.\n* **2 × 31** (62) is semiprime, but is **not** a brilliant number (different number of digits in the two factors).\n\nTask\n\n* Find and display the first 100 brilliant numbers.\n* For the orders of magnitude 1 through 6, find and show the first brilliant number greater than or equal to the order of magnitude, and, its position in the series (or the count of brilliant numbers up to that point).\n\nStretch\n\n* Continue for larger orders of magnitude.\n\nSee also\n\n* Numbers Aplenty - Brilliant numbers * - Like the task upper Limit 1E201 * OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits"
},
{
"role": "assistant",
"content": "1 through 7 are fast. 8 and 9 take a bit longer.\n\n```\nuse Lingua::EN::Numbers;\n\n# Find an abundance of primes to use to generate brilliants\nmy %primes = (2..100000).grep( &is-prime ).categorize: { .chars };\n\n# Generate brilliant numbers\nmy @brilliant = lazy flat (1..*).map: -> $digits {\n sort flat (^%primes{$digits}).race.map: { %primes{$digits}[$_] X× (flat %primes{$digits}[$_ .. *]) }\n};\n\n# The task\nput \"First 100 brilliant numbers:\\n\" ~ @brilliant[^100].batch(10)».fmt(\"%4d\").join(\"\\n\") ~ \"\\n\" ;\n\nfor 1 .. 7 -> $oom {\n my $threshold = exp $oom, 10;\n my $key = @brilliant.first: :k, * >= $threshold;\n printf \"First >= %13s is %9s in the series: %13s\\n\", comma($threshold), ordinal-digit(1 + $key, :u), comma @brilliant[$key];\n}\n\n```\n\nOutput:\n\n```\nFirst 100 brilliant numbers:\n 4 6 9 10 14 15 21 25 35 49\n 121 143 169 187 209 221 247 253 289 299\n 319 323 341 361 377 391 403 407 437 451\n 473 481 493 517 527 529 533 551 559 583\n 589 611 629 649 667 671 689 697 703 713\n 731 737 767 779 781 793 799 803 817 841\n 851 869 871 893 899 901 913 923 943 949\n 961 979 989 1003 1007 1027 1037 1067 1073 1079\n1081 1121 1139 1147 1157 1159 1189 1207 1219 1241\n1247 1261 1271 1273 1333 1343 1349 1357 1363 1369\n\nFirst >= 10 is 4ᵗʰ in the series: 10\nFirst >= 100 is 11ᵗʰ in the series: 121\nFirst >= 1,000 is 74ᵗʰ in the series: 1,003\nFirst >= 10,000 is 242ⁿᵈ in the series: 10,201\nFirst >= 100,000 is 2505ᵗʰ in the series: 100,013\nFirst >= 1,000,000 is 10538ᵗʰ in the series: 1,018,081\nFirst >= 10,000,000 is 124364ᵗʰ in the series: 10,000,043\nFirst >= 100,000,000 is 573929ᵗʰ in the series: 100,140,049\nFirst >= 1,000,000,000 is 7407841ˢᵗ in the series: 1,000,000,081\n```"
}
]
|
[
{
"role": "user",
"content": "Objective\n\nDevelop a program that identifies and lists all maximal cliques within an undirected graph. A *maximal clique* is a subset of vertices where every two distinct vertices are adjacent (i.e., there's an edge connecting them), and the clique cannot be extended by including any adjacent vertex not already in the clique.\n\nBackground\n\nIn graph theory, a *clique* is a subset of vertices of an undirected graph such that every two distinct vertices in the clique are connected by an edge. A *maximal clique* is a clique that cannot be extended by adding one more adjacent vertex, meaning it's not a subset of a larger clique.\n\nThe Bron-Kerbosch algorithm is a recursive backtracking algorithm used to find all maximal cliques in an undirected graph efficiently. The algorithm is particularly effective due to its use of pivot selection, which reduces the number of recursive calls and improves performance.\n\nProgram Functionality\n\n1. **Input Representation:**\n\n* The graph is represented as a list of edges, where each edge is a tuple of two vertices (e.g., `('a', 'b')` indicates an undirected edge between vertices `'a'` and `'b'`).\n\n1. **Graph Construction:**\n\n* Convert the list of edges into an adjacency list using a `HashMap<String, HashSet<String>>`. Each key in the hashmap represents a vertex, and its corresponding hash set contains all adjacent vertices (neighbors).\n\n1. **Bron-Kerbosch Algorithm Implementation:**\n\n* **Sets Used:**\n + *R* (Current Clique): *A set representing the current clique being constructed.*\n + *P* (Potential Candidates): *A set of vertices that can be added to* R *to form a larger clique.*\n + *X* (Excluded Vertices): *A set of vertices that have already been processed and should not be reconsidered for the current clique.*\n\n* **Algorithm Steps:**\n + If both *P* and *X* are empty, and *R* contains more than two vertices, *R* is a maximal clique and is added to the list of cliques.\n + Otherwise, select a *pivot vertex* from the union of *P* and *X* that has the maximum number of neighbors. This pivot helps minimize the number of recursive calls.\n + Iterate over all vertices in *P* that are \\*\\*not\\*\\* neighbors of the pivot. For each such vertex:\n - Add the vertex to *R*.\n - Update *P* and *X* to include only those vertices that are neighbors of the added vertex.\n - Recursively call the Bron-Kerbosch function with the updated sets.\n - After recursion, move the vertex from *P* to *X* to mark it as processed.\n\n1. **Output:**\n\n* After executing the algorithm, the program prints all maximal cliques with more than two vertices. Each clique is displayed as a comma-separated list of its constituent vertices.\n\nExample\n\nGiven the following edges:\n\n```\n('a', 'b'), ('b', 'a'), ('a', 'c'), ('c', 'a'), ('b', 'c'), ('c', 'b'),\n('d', 'e'), ('e', 'd'), ('d', 'f'), ('f', 'd'), ('e', 'f'), ('f', 'e')\n\n```\n\n**Expected Output:**\n\n```\na, b, c\nd, e, f\n\n```\n\nThese outputs represent the two maximal cliques in the graph: one comprising vertices `a`, `b`, and `c`, and the other comprising vertices `d`, `e`, and `f`.\n\nPseudocode\n\nBelow is the pseudocode for the Bron-Kerbosch algorithm with pivoting, closely following the Rust implementation provided earlier.\n\n```\nFUNCTION BronKerbosch(R, P, X, G, Cliques)\n // R: Current clique (Set)\n // P: Potential candidates to expand the clique (Set)\n // X: Vertices already processed (Set)\n // G: Graph represented as an adjacency list (Dictionary)\n // Cliques: List to store all maximal cliques (List of Lists)\n\n IF P is empty AND X is empty THEN\n IF size of R > 2 THEN\n SORT R lexicographically\n ADD R to Cliques\n END IF\n RETURN\n END IF\n\n // Select a pivot vertex from P ∪ X with the maximum degree\n Pivot := vertex in (P ∪ X) with the highest number of neighbors in G\n\n // Candidates are vertices in P that are not neighbors of the pivot\n Candidates := P - Neighbors(Pivot)\n\n FOR EACH vertex v IN Candidates DO\n // New clique including vertex v\n NewR := R ∪ {v}\n\n // New potential candidates are neighbors of v in P\n Neighbors_v := G[v]\n NewP := P ∩ Neighbors_v\n\n // New excluded vertices are neighbors of v in X\n NewX := X ∩ Neighbors_v\n\n // Recursive call with updated sets\n BronKerbosch(NewR, NewP, NewX, G, Cliques)\n\n // Move vertex v from P to X\n P := P - {v}\n X := X ∪ {v}\n END FOR\nEND FUNCTION\n\nFUNCTION Main()\n // Define input edges as a list of tuples\n Input := [\n ('a', 'b'), ('b', 'a'), ('a', 'c'), ('c', 'a'),\n ('b', 'c'), ('c', 'b'), ('d', 'e'), ('e', 'd'),\n ('d', 'f'), ('f', 'd'), ('e', 'f'), ('f', 'e')\n ]\n\n // Build the graph as an adjacency list\n Graph := empty Dictionary\n FOR EACH (src, dest) IN Input DO\n IF src NOT IN Graph THEN\n Graph[src] := empty Set\n END IF\n ADD dest TO Graph[src]\n END FOR\n\n // Initialize R, P, X\n R := empty Set\n P := set of all vertices in Graph\n X := empty Set\n\n // Initialize list to store cliques\n Cliques := empty List\n\n // Execute the Bron-Kerbosch algorithm\n BronKerbosch(R, P, X, Graph, Cliques)\n\n // Sort the cliques for consistent output\n SORT Cliques lexicographically\n\n // Print each clique\n FOR EACH Clique IN Cliques DO\n PRINT elements of Clique separated by commas\n END FOR\nEND FUNCTION\n\n```"
},
{
"role": "assistant",
"content": "```\n# Returns all maximal Cliques as sorted List of Lists.\nsub BronKerbosch ( @undirected_edges ) {\n\n #| Adjacency list of the whole Graph, as immutable hash (Map) of immutable Sets.\n my Map $G = @undirected_edges\n .map({ |( .[0,1], .[1,0] ) })\n .classify( {.[0]}, :as{.[1]} )\n .duckmap( *.Set )\n .Map;\n\n #| Number of neighbors in G\n my Map $degree = $G.map({ .key => .value.elems }).Map;\n\n return gather BK();\n\n sub BK (\n Set :$R = Set.new, #= Current clique\n SetHash :$P is copy = SetHash.new($G.keys), #= Potential candidates to expand the clique\n SetHash :$X is copy = SetHash.new, #= Vertices already processed\n ) {\n if !$P and !$X {\n take $R.keys.sort.cache if $R.elems > 2;\n return;\n }\n\n my $Pivot = ($P ∪ $X).max({ $degree{$_} }).key;\n\n my @Candidates = ( $P (-) $G{$Pivot} ).keys;\n\n for $G{@Candidates}:kv -> $v, $Neighbors_of_v {\n\n &?ROUTINE.( # Recursive call with updated sets\n R => ($R ∪ $v),\n P => ($P ∩ $Neighbors_of_v),\n X => ($X ∩ $Neighbors_of_v),\n );\n\n # Move vertex v from P to X\n $P{$v} = False;\n $X{$v} = True;\n }\n }\n}\n\nsay .join(\",\") for sort BronKerbosch <a-b a-c b-c d-e d-f e-f>».split(\"-\");\n\n```\n\nOutput:\n\n```\na,b,c\nd,e,f\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Brownian\\_tree. 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\nGenerate and draw a Brownian Tree.\n\nA Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes.\n\n1. The initial \"seed\" is placed somewhere within the field. Where is not particularly important; it could be randomized, or it could be a fixed point.\n2. Particles are injected into the field, and are individually given a (typically random) motion pattern.\n3. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree.\n\nBecause of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis solution spawns new Particles at a growing square border and displays the Tree every 50 particles and at the end using unicode UPPER/LOWER HALF BLOCK and FULL BLOCK.\n\n**Works with**: Rakudo version 2015.12\n\n```\nconstant size = 100;\nconstant particlenum = 1_000;\n\n\nconstant mid = size div 2;\n\nmy $spawnradius = 5;\nmy @map;\n\nsub set($x, $y) {\n @map[$x][$y] = True;\n}\n\nsub get($x, $y) {\n return @map[$x][$y] || False;\n}\n\nset(mid, mid);\nmy @blocks = \" \",\"\\c[UPPER HALF BLOCK]\", \"\\c[LOWER HALF BLOCK]\",\"\\c[FULL BLOCK]\";\n\nsub infix:<█>($a, $b) {\n @blocks[$a + 2 * $b]\n}\n\nsub display {\n my $start = 0;\n my $end = size;\n say (for $start, $start + 2 ... $end -> $y {\n (for $start..$end -> $x {\n if abs(($x&$y) - mid) < $spawnradius {\n get($x, $y) █ get($x, $y+1);\n } else {\n \" \"\n }\n }).join\n }).join(\"\\n\")\n}\n\nfor ^particlenum -> $progress {\n my Int $x;\n my Int $y;\n my &reset = {\n repeat {\n ($x, $y) = (mid - $spawnradius..mid + $spawnradius).pick, (mid - $spawnradius, mid + $spawnradius).pick;\n ($x, $y) = ($y, $x) if (True, False).pick();\n } while get($x,$y);\n }\n reset;\n\n while not get($x-1|$x|$x+1, $y-1|$y|$y+1) {\n $x = ($x-1, $x, $x+1).pick;\n $y = ($y-1, $y, $y+1).pick;\n if (False xx 3, True).pick {\n $x = $x >= mid ?? $x - 1 !! $x + 1;\n $y = $y >= mid ?? $y - 1 !! $y + 1;\n }\n if abs(($x | $y) - mid) > $spawnradius {\n reset;\n }\n }\n set($x,$y);\n if $spawnradius < mid && abs(($x|$y) - mid) > $spawnradius - 5 {\n $spawnradius = $spawnradius + 1;\n }\n}\n\ndisplay;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Description\n\nThe Brzozowski Algebraic Method is a technique used in automata theory, specifically for constructing the minimal deterministic finite automaton (DFA) from a given nondeterministic finite automaton (NFA). It was introduced by Janusz Brzozowski in 1962 and involves the use of algebraic transformations to simplify and optimize automata.\n\nAs the workings of the algorithm are clearly described in the linked article they will not be repeated here.\n\nTask\n\nImplement the Brzozowski Algebraic Method to convert an NFA representation into a regular expression. The implementation should:\n\n1. Take as input:\n\n```\n - A 2D array 'a' representing the transition matrix of the NFA\n - An array 'b' representing the final states\n\n```\n\n2. Include functionality to:\n\n```\n - Handle basic regular expression operations (Empty, Epsilon, Character, Union, Concatenation, Star)\n - Print regular expressions in a readable format\n - Simplify regular expressions using algebraic rules\n\n```\n\n3. Apply the Brzozowski algorithm to:\n\n```\n - Process the transition matrix in reverse order\n - Update transitions using Star and Concatenation operations\n - Combine paths using Union operations\n - Generate a final regular expression representing the language accepted by the NFA\n\n```\n\n4. Include simplification rules for:\n\n```\n - Eliminating redundant unions (e + e → e)\n - Handling identity elements (e·1 → e, 1·e → e)\n - Handling zero elements (e·0 → 0, 0·e → 0)\n - Simplifying star operations (0* → 1, 1* → 1)\n\n```\n\nThe implementation should be able to process the given example input and produce both the raw and simplified regular expressions as output."
},
{
"role": "assistant",
"content": "**Translation of**: Python\n\n```\n# 20241120 Raku programming solution\n\nrole RE1 { has $.c }\nrole RE2 { has ( $.e, $.f ) }\n\nclass Empty { method Str { '0' } }\nclass Epsilon { method Str { '1' } }\nclass Car does RE1 { method Str { $.c } } # Caractère ?\nclass Star does RE1 { method Str { \"($.c)*\" } }\nclass Union does RE2 { method Str { \"$.e+$.f\" } }\nclass Concat does RE2 { method Str { \"($.e)($.f)\" } }\n\nmy ($empty, $epsilon) = (Empty, Epsilon)>>.new;\n\nsub simple-re($e is rw) {\n sub do-simple($e) {\n given $e {\n when Union {\n my ($ee,$ef) = ($e.e, $e.f).map: { do-simple $_ };\n if $ee ~~ $ef { return $ee }\n elsif $ee ~~ Union { do-simple(Union.new(e => $ee.e, f => Union.new(e => $ee.f, f => $ef))) }\n elsif $ee ~~ Empty { return $ef }\n elsif $ef ~~ Empty { return $ee }\n else { Union.new: e => $ee, f => $ef }\n }\n when Concat {\n my ($ee,$ef) = ($e.e, $e.f).map: { do-simple $_ };\n if $ee ~~ Epsilon { return $ef }\n elsif $ef ~~ Epsilon { return $ee }\n elsif $ee ~~ Empty || $ef ~~ Empty { return Empty }\n elsif $ee ~~ Concat { do-simple(Concat.new(e => $ee.e, f => Concat.new(e => $ee.f, f => $ef))) }\n else { Concat.new: e => $ee, f => $ef }\n }\n when Star {\n given do-simple($e.c) {\n $_ ~~ Empty | Epsilon ?? return Epsilon !! Star.new: c => $_\n } \n }\n default { $e }\n }\n }\n my $prev = '';\n until $e === $prev or $e.Str eq $prev { ($prev, $e) = $e, do-simple($e) }\n return $e;\n}\n\nsub brzozowski(@a, @b) {\n for @a.elems - 1 ... 0 -> \\n {\n @b[n] = Concat.new(e => Star.new(c => @a[n;n]), f => @b[n]);\n for ^n -> \\j {\n @a[n;j] = Concat.new(e => Star.new(c => @a[n;n]), f => @a[n;j]);\n }\n for ^n -> \\i {\n @b[i] = Union.new(e => @b[i], f => Concat.new(e => @a[i;n], f => @b[n]));\n for ^n -> \\j {\n @a[i;j] = Union.new(e => @a[i;j], f => Concat.new(e => @a[i;n], f => @a[n;j]));\n }\n }\n for ^n -> \\i { @a[i;n] = $empty }\n }\n return @b[0]\n}\n\nmy @a = [\n [$empty, Car.new(c => 'a'), Car.new(c => 'b')],\n [Car.new(c => 'b'), $empty, Car.new(c => 'a')],\n [Car.new(c => 'a'), Car.new(c => 'b'), $empty],\n];\nmy @b = [$epsilon, $empty, $empty];\n\nsay ( my $re = brzozowski(@a, @b) ).Str;\nsay simple-re($re).Str;\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Bulls and Cows is an old game played with pencil and paper that was later implemented using computers.\n\nTask\n\nCreate a four digit random number from the digits **1** to **9**, without duplication.\n\nThe program should:\n\n: : : : : : * ask for guesses to this number\n * reject guesses that are malformed\n * print the score for the guess\n\nThe score is computed as:\n\n1. The player wins if the guess is the same as the randomly chosen number, and the program ends.\n2. A score of one **bull** is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.\n3. A score of one **cow** is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.\n\nRelated tasks\n\n* Bulls and cows/Player\n* Guess the number\n* Guess the number/With Feedback\n* Mastermind"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy $size = 4;\nmy @secret = pick $size, '1' .. '9';\n\nfor 1..* -> $guesses {\n my @guess;\n loop {\n @guess = (prompt(\"Guess $guesses: \") // exit).comb;\n last if @guess == $size and\n all(@guess) eq one(@guess) & any('1' .. '9');\n say 'Malformed guess; try again.';\n }\n my ($bulls, $cows) = 0, 0;\n for ^$size {\n when @guess[$_] eq @secret[$_] { ++$bulls; }\n when @guess[$_] eq any @secret { ++$cows; }\n }\n last if $bulls == $size;\n say \"$bulls bulls, $cows cows.\";\n}\n\nsay 'A winner is you!';\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a *player* of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts.\n\nOne method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. \nEither you guess correctly or run out of numbers to guess, which indicates a problem with the scoring.\n\nRelated tasks\n\n* Bulls and cows\n* Guess the number\n* Guess the number/With Feedback (Player)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\n**Translation of**: Perl\n\n```\n# we use the [] reduction meta operator along with the Cartesian Product\n# operator X to create the Cartesian Product of four times [1..9] and then get\n# all the elements where the number of unique digits is four.\nmy @candidates = ([X] [1..9] xx 4).grep: *.unique == 4;\n\nrepeat {\n\tmy $guess = @candidates.pick;\n\tmy ($bulls, $cows) = read-score;\n\t@candidates .= grep: &score-correct;\n\n\t# note how we declare our two subroutines within the repeat block. This\n\t# limits the scope in which the routines are known to the scope in which\n\t# they are needed and saves us a lot of arguments to our two routines.\n\tsub score-correct($a) {\n\t\tmy $exact = [+] $a >>==<< $guess;\n\n\t\t# number of elements of $a that match any element of $b\n\t\tmy $loose = +$a.grep: any @$guess;\n\n\t\treturn $bulls == $exact && $cows == $loose - $exact;\n\t}\n\n\tsub read-score() {\n\t\tloop {\n\t\t\tmy $score = prompt \"My guess: {$guess.join}.\\n\";\n\n\t\t\tif $score ~~ m:s/^ $<bulls>=(\\d) $<cows>=(\\d) $/\n\t\t\t\tand $<bulls> + $<cows> <= 4 {\n\t\t\t\treturn +$<bulls>, +$<cows>;\n\t\t\t}\n\n\t\t\tsay \"Please specify the number of bulls and cows\";\n\t\t}\n\t}\n} while @candidates > 1;\n\nsay @candidates\n\t?? \"Your secret number is {@candidates[0].join}!\"\n\t!! \"I think you made a mistake with your scoring.\";\n\n```\n\nOutput:\n\n```\nMy guess: 4235.\n2 1\nMy guess: 1435.\n2 1\nMy guess: 1245.\n2 1\nYour secret number is 1234!\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Burrows–Wheeler\\_transform. 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\nThe Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.\n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.\n\nMore importantly, the transformation is reversible, without needing to store any additional data.\n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\nSource: Burrows–Wheeler transform"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\n```\n# STX can be any character that doesn't appear in the text.\n# Using a visible character here for ease of viewing. \n \nconstant \\STX = '👍';\n\n# Burrows-Wheeler transform\nsub transform (Str $s is copy) {\n note \"String can't contain STX character.\" and exit if $s.contains: STX;\n $s = STX ~ $s;\n (^$s.chars).map({ $s.comb.list.rotate: $_ }).sort[*;*-1].join\n}\n \n# Burrows-Wheeler inverse transform\nsub ɯɹoɟsuɐɹʇ (Str $s) {\n my @t = $s.comb.sort;\n @t = ($s.comb Z~ @t).sort for 1..^$s.chars;\n @t.first( *.ends-with: STX ).chop\n}\n \n# TESTING\nfor |<BANANA dogwood SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES>,\n 'TO BE OR NOT TO BE OR WANT TO BE OR NOT?', \"Oops{STX}\"\n -> $phrase {\n say 'Original: ', $phrase;\n say 'Transformed: ', transform $phrase;\n say 'Inverse transformed: ', ɯɹoɟsuɐɹʇ transform $phrase;\n say '';\n}\n\n```\n\nOutput:\n\n```\nOriginal: BANANA\nTransformed: BNN👍AAA\nInverse transformed: BANANA\n\nOriginal: dogwood\nTransformed: 👍ooodwgd\nInverse transformed: dogwood\n\nOriginal: SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\nTransformed: TEXYDST.E.IXIXIXXSSMPPS.B..E.👍.UESFXDIIOIIITS\nInverse transformed: SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\n\nOriginal: TO BE OR NOT TO BE OR WANT TO BE OR NOT?\nTransformed: OOORREEETTRTW BBB ATTT NNOOONOO👍 ?\nInverse transformed: TO BE OR NOT TO BE OR WANT TO BE OR NOT?\n\nOriginal: Oops👍\nString can't contain STX character.\n```"
}
]
|
[
{
"role": "user",
"content": "You are given two planar quadratic Bézier curves, having control points \n\n(\n−\n1\n,\n0\n)\n,\n(\n0\n,\n10\n)\n,\n(\n1\n,\n0\n)\n{\\displaystyle {\\displaystyle (-1,0),(0,10),(1,0)}}\n and \n\n(\n2\n,\n1\n)\n,\n(\n−\n8\n,\n2\n)\n,\n(\n2\n,\n3\n)\n{\\displaystyle {\\displaystyle (2,1),(-8,2),(2,3)}}\n, respectively. They are parabolas intersecting at four points, as shown in the following diagram:\n\nThe task is to write a program that finds all four intersection points and prints their \n\n(\nx\n,\ny\n)\n{\\displaystyle {\\displaystyle (x,y)}}\n coordinates. You may use any algorithm you know of or can think of, including any of those that others have used.\n\n### See also\n\n* Bitmap/Bézier curves/Quadratic\n* Steffensen's method"
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n```\n# 20231025 Raku programming solution\n\nclass Point { has ($.x, $.y) is rw is default(0) }\n\nclass QuadSpline { has ($.c0, $.c1, $.c2) is rw is default(0) }\n\nclass QuadCurve { has QuadSpline ($.x, $.y) is rw }\n\nclass Workset { has QuadCurve ($.p, $.q) }\n\nsub subdivideQuadSpline($q, $t) {\n my $s = 1.0 - $t;\n my ($c0,$c1,$c2) = do given $q { .c0, .c1, .c2 }; \n my $u_c1 = $s*$c0 + $t*$c1;\n my $v_c1 = $s*$c1 + $t*$c2;\n my $u_c2 = $s*$u_c1 + $t*$v_c1;\n return ($c0, $u_c1, $u_c2), ($u_c2, $v_c1, $c2)\n}\n\nsub subdivideQuadCurve($q, $t, $u is rw, $v is rw) {\n with (subdivideQuadSpline($q.x,$t),subdivideQuadSpline($q.y,$t))».List.flat {\n $u=QuadCurve.new(x => QuadSpline.new(c0 => .[0],c1 => .[1],c2 => .[2]),\n y => QuadSpline.new(c0 => .[6],c1 => .[7],c2 => .[8]));\n $v=QuadCurve.new(x => QuadSpline.new(c0 => .[3],c1 => .[4],c2 => .[5]),\n y => QuadSpline.new(c0 => .[9],c1 => .[10],c2 => .[11]))\n }\n}\n\nsub seemsToBeDuplicate(@intersects, $xy, $spacing) {\n my $seemsToBeDup = False;\n for @intersects {\n $seemsToBeDup = abs(.x - $xy.x) < $spacing && abs(.y - $xy.y) < $spacing;\n last if $seemsToBeDup;\n }\n return $seemsToBeDup;\n}\n\nsub rectsOverlap($xa0, $ya0, $xa1, $ya1, $xb0, $yb0, $xb1, $yb1) {\n return $xb0 <= $xa1 && $xa0 <= $xb1 && $yb0 <= $ya1 && $ya0 <= $yb1\n}\n\nsub testIntersect($p,$q,$tol,$exclude is rw,$accept is rw,$intersect is rw) {\n my $pxmin = min($p.x.c0, $p.x.c1, $p.x.c2);\n my $pymin = min($p.y.c0, $p.y.c1, $p.y.c2);\n my $pxmax = max($p.x.c0, $p.x.c1, $p.x.c2);\n my $pymax = max($p.y.c0, $p.y.c1, $p.y.c2);\n my $qxmin = min($q.x.c0, $q.x.c1, $q.x.c2);\n my $qymin = min($q.y.c0, $q.y.c1, $q.y.c2);\n my $qxmax = max($q.x.c0, $q.x.c1, $q.x.c2);\n my $qymax = max($q.y.c0, $q.y.c1, $q.y.c2);\n ($exclude, $accept) = True, False;\n\n if rectsOverlap($pxmin,$pymin,$pxmax,$pymax,$qxmin,$qymin,$qxmax,$qymax) {\n $exclude = False;\n my ($xmin,$xmax) = max($pxmin, $qxmin), min($pxmax, $pxmax);\n if ($xmax < $xmin) { die \"Assertion failure: $xmax < $xmin\\n\" }\n my ($ymin,$ymax) = max($pymin, $qymin), min($pymax, $qymax);\n if ($ymax < $ymin) { die \"Assertion failure: $ymax < $ymin\\n\" }\n if $xmax - $xmin <= $tol and $ymax - $ymin <= $tol {\n $accept = True;\n given $intersect { (.x, .y) = 0.5 X* $xmin+$xmax, $ymin+$ymax }\n }\n }\n}\n\nsub find-intersects($p, $q, $tol, $spacing) {\n my Point @intersects;\n my @workload = Workset.new(p => $p, q => $q);\n\n while my $work = @workload.pop {\n my ($intersect,$exclude,$accept) = Point.new, False, False;\n testIntersect($work.p, $work.q, $tol, $exclude, $accept, $intersect); \n if $accept {\n unless seemsToBeDuplicate(@intersects, $intersect, $spacing) {\n @intersects.push: $intersect;\n }\n } elsif not $exclude {\n my QuadCurve ($p0, $p1, $q0, $q1);\n subdivideQuadCurve($work.p, 0.5, $p0, $p1);\n subdivideQuadCurve($work.q, 0.5, $q0, $q1);\n for $p0, $p1 X $q0, $q1 { \n @workload.push: Workset.new(p => .[0], q => .[1]) \n }\n }\n }\n return @intersects;\n}\n\nmy $p = QuadCurve.new( x => QuadSpline.new(c0 => -1.0,c1 => 0.0,c2 => 1.0),\n y => QuadSpline.new(c0 => 0.0,c1 => 10.0,c2 => 0.0));\nmy $q = QuadCurve.new( x => QuadSpline.new(c0 => 2.0,c1 => -8.0,c2 => 2.0),\n y => QuadSpline.new(c0 => 1.0,c1 => 2.0,c2 => 3.0));\nmy $spacing = ( my $tol = 0.0000001 ) * 10;\n.say for find-intersects($p, $q, $tol, $spacing);\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a Caesar cipher, both encoding and decoding. \nThe key is an integer from 1 to 25.\n\nThis cipher rotates (either towards left or right) the letters of the alphabet (A to Z).\n\nThe encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).\n \nSo key 2 encrypts \"HI\" to \"JK\", but key 20 encrypts \"HI\" to \"BC\".\n\nThis simple \"mono-alphabetic substitution cipher\" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.\n\nCaesar cipher is identical to Vigenère cipher with a key of length 1. \nAlso, Rot-13 is identical to Caesar cipher with key 13.\n\nRelated tasks\n\n* Rot-13\n* Substitution Cipher\n* Vigenère Cipher/Cryptanalysis"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy @alpha = 'A' .. 'Z';\nsub encrypt ( $key where 1..25, $plaintext ) {\n $plaintext.trans( @alpha Z=> @alpha.rotate($key) );\n}\nsub decrypt ( $key where 1..25, $cyphertext ) {\n $cyphertext.trans( @alpha.rotate($key) Z=> @alpha );\n}\n\nmy $original = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';\nmy $en = encrypt( 13, $original );\nmy $de = decrypt( 13, $en );\n\n.say for $original, $en, $de;\n\nsay 'OK' if $original eq all( map { .&decrypt(.&encrypt($original)) }, 1..25 );\n```\n\nOutput:\n\n```\nTHE FIVE BOXING WIZARDS JUMP QUICKLY\nGUR SVIR OBKVAT JVMNEQF WHZC DHVPXYL\nTHE FIVE BOXING WIZARDS JUMP QUICKLY\nOK\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCalculate the value of *e*.\n\n(*e* is also known as *Euler's number* and *Napier's constant*.)\n\nSee details: Calculating the value of e"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2023.09\n\n```\n# If you need high precision: Sum of a Taylor series method.\n# Adjust the terms parameter to suit. Theoretically the\n# terms could be ∞. Practically, calculating an infinite\n# series takes an awfully long time so limit to 500.\n\nconstant 𝑒 = [\\+] flat 1, [\\/] 1.FatRat..*;\n\n.say for 𝑒[500].comb(80);\n\nsay '';\n\n# Or, if you don't need high precision, it's a built-in.\nsay e;\n\n```\n\nOutput:\n\n```\n2.718281828459045235360287471352662497757247093699959574966967627724076630353547\n59457138217852516642742746639193200305992181741359662904357290033429526059563073\n81323286279434907632338298807531952510190115738341879307021540891499348841675092\n44761460668082264800168477411853742345442437107539077744992069551702761838606261\n33138458300075204493382656029760673711320070932870912744374704723069697720931014\n16928368190255151086574637721112523897844250569536967707854499699679468644549059\n87931636889230098793127736178215424999229576351482208269895193668033182528869398\n49646510582093923982948879332036250944311730123819706841614039701983767932068328\n23764648042953118023287825098194558153017567173613320698112509961818815930416903\n51598888519345807273866738589422879228499892086805825749279610484198444363463244\n96848756023362482704197862320900216099023530436994184914631409343173814364054625\n31520961836908887070167683964243781405927145635490613031072085103837505101157477\n04171898610687396965521267154688957035035402123407849819334321068170121005627880\n23519303322474501585390473041995777709350366041699732972508868769664035557071622\n68447162560798827\n\n2.718281828459045\n```"
}
]
|
[
{
"role": "user",
"content": "Create a routine that will generate a text calendar for any year.\nTest the calendar by generating a calendar for the year 1969, on a device of the time.\nChoose one of the following devices:\n\n* A line printer with a width of 132 characters.\n* An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.\n\n(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)\n\nKudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.\n\nThis task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.\n\n```\nTHE REAL PROGRAMMER'S NATURAL HABITAT\n\"Taped to the wall is a line-printer Snoopy calender for the year 1969.\"\n\n```\n\nFor further Kudos see task CALENDAR, where all code is to be in UPPERCASE.\n\nFor economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.\n\nSee Also\n: * Snoopy calendar 1969-2025 Marcel van der Veer - The deck is credited as being one of the first FOSS programs.\n\nRelated task\n: * Five weekends"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $months-per-row = 3;\nmy @weekday-names = <Mo Tu We Th Fr Sa Su>;\nmy @month-names = <Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec>;\n\nmy Int() $year = @*ARGS.shift || 1969;\nsay fmt-year($year);\n\nsub fmt-year ($year) {\n my @month-strs;\n @month-strs[$_] = [fmt-month($year, $_).lines] for 1 .. 12;\n my @C = ' ' x 30 ~ $year, '';\n for 1, 1+$months-per-row ... 12 -> $month {\n while @month-strs[$month] {\n for ^$months-per-row -> $column {\n @C[*-1] ~= @month-strs[$month+$column].shift ~ ' ' x 3 if @month-strs[$month+$column];\n }\n @C.push: '';\n }\n @C.push: '';\n }\n @C.join: \"\\n\";\n}\n\nsub fmt-month ($year, $month) {\n my $date = Date.new($year,$month,1);\n @month-names[$month-1].fmt(\"%-20s\\n\") ~ @weekday-names ~ \"\\n\" ~\n ((' ' xx $date.day-of-week - 1), (1..$date.days-in-month)».fmt('%2d')).flat.rotor(7, :partial).join(\"\\n\") ~\n (' ' if $_ < 7) ~ (' ' xx 7-$_).join(' ') given Date.new($year, $month, $date.days-in-month).day-of-week;\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nProvide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented *entirely without lowercase*.\n\nAlso - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.\n\n(Hint: manually convert the code from the Calendar task to all UPPERCASE)\n\nThis task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983.\n\n```\nTHE REAL PROGRAMMER'S NATURAL HABITAT\n\"Taped to the wall is a line-printer Snoopy calender for the year 1969.\"\n\n```\n\nMoreover this task is further inspired by the *long lost* corollary article titled:\n\n```\n\"Real programmers think in UPPERCASE\"!\n\n```\n\nNote: Whereas today we *only* need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all\n4-bit,\n5-bit,\n6-bit &\n7-bit depending on how the file was opened... **And** one rogue Soviet university went further and built a 1.5-bit based computer.\n\nOf course... as us Boomers have turned into Geezers we have become HARD OF HEARING,\nand suffer from chronic Presbyopia, hence programming in UPPERCASE\nis less to do with computer architecture and more to do with practically. :-)\n\nFor economy of size, do not actually include Snoopy generation\nin either the code or the output, instead just output a place-holder.\n\nFYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension.\n\n**Trivia:** The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed *minuscule* letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, *majuscule* letters, ended up in the harder to reach upper cases."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nUppercase is no challenge, who needs letters at all?\n[Requires the year to be supplied as a command-line argument, and Unixish *cal* command.]\n\n```\n$_=\"\\0\"..\"~\";<\n115 97 121 32 34 91 73 78 83 69 82 84 32 83 78 79 79 80 89 32 72 69 82 69 93 34\n59 114 117 110 32 60 99 97 108 62 44 64 42 65 82 71 83 91 48 93 47 47 49 57 54 57\n>.\"$_[99]$_[104]$_[114]$_[115]\"().\"$_[69]$_[86]$_[65]$_[76]\"()\n\n```"
}
]
|
[
{
"role": "user",
"content": "The **Calkin-Wilf sequence** contains every nonnegative rational number exactly once.\n\nIt can be calculated recursively as follows:\n\n```\n a1 = 1 \n an+1 = 1/(2⌊an⌋+1-an) for n > 1 \n\n```\n\nTask part 1\n\n* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.\n\nTo avoid floating point error, you may want to use a rational number data type.\n\nIt is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.\nIt only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:\n\n```\n [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] \n\n```\n\nExample\n\nThe fraction **9/4** has odd continued fraction representation 2; 3, 1, giving a binary representation of **100011**,\n \nwhich means **9/4** appears as the **35th** term of the sequence.\n\nTask part 2\n\n* Find the position of the number **83116****/****51639** in the Calkin-Wilf sequence.\n\nRelated tasks\n: * Fusc sequence.\n\nSee also\n\n* Wikipedia entry: Calkin-Wilf tree\n* Continued fraction\n* Continued fraction/Arithmetic/Construct from rational number"
},
{
"role": "assistant",
"content": "In Raku, arrays are indexed from 0. The Calkin-Wilf sequence does not have a term defined at 0.\n\nThis implementation includes a bogus undefined value at position 0, having the bogus first term shifts the indices up by one, making the ordinal position and index match. Useful due to how reversibility function works.\n\n```\nmy @calkin-wilf = Any, 1, {1 / (.Int × 2 + 1 - $_)} … *;\n\n# Rational to Calkin-Wilf index\nsub r2cw (Rat $rat) { :2( join '', flat (flat (1,0) xx *) Zxx reverse r2cf $rat ) }\n\n# The task\n\nsay \"First twenty terms of the Calkin-Wilf sequence: \",\n @calkin-wilf[1..20]».&prat.join: ', ';\n\nsay \"\\n99991st through 100000th: \",\n (my @tests = @calkin-wilf[99_991 .. 100_000])».&prat.join: ', ';\n\nsay \"\\nCheck reversibility: \", @tests».Rat».&r2cw.join: ', ';\n\nsay \"\\n83116/51639 is at index: \", r2cw 83116/51639;\n\n\n# Helper subs\nsub r2cf (Rat $rat is copy) { # Rational to continued fraction\n gather loop {\n\t $rat -= take $rat.floor;\n\t last if !$rat;\n\t $rat = 1 / $rat;\n }\n}\n\nsub prat ($num) { # pretty Rat\n return $num unless $num ~~ Rat|FatRat;\n return $num.numerator if $num.denominator == 1;\n $num.nude.join: '/';\n}\n\n```\n\nOutput:\n\n```\nFirst twenty terms of the Calkin-Wilf sequence: 1, 1/2, 2, 1/3, 3/2, 2/3, 3, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, 3/4, 4, 1/5, 5/4, 4/7, 7/3, 3/8\n\n99991st through 100000th: 1085/303, 303/1036, 1036/733, 733/1163, 1163/430, 430/987, 987/557, 557/684, 684/127, 127/713\n\nCheck reversibility: 99991, 99992, 99993, 99994, 99995, 99996, 99997, 99998, 99999, 100000\n\n83116/51639 is at index: 123456789\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow how a foreign language function can be called from the language.\n\nAs an example, consider calling functions defined in the C language. Create a string containing \"Hello World!\" of the string type typical to the language. Pass the string content to C's `strdup`. The content can be copied if necessary. Get the result from `strdup` and print it using language means. Do not forget to free the result of `strdup` (allocated in the heap).\n\nNotes\n\n* It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way.\n* C++ and C solutions can take some other language to communicate with.\n* It is *not* mandatory to use `strdup`, especially if the foreign function interface being demonstrated makes that uninformative.\n\nSee also\n\n* Use another language to call a function"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.07\n\n```\nuse NativeCall;\n\nsub strdup(Str $s --> Pointer) is native {*}\nsub puts(Pointer $p --> int32) is native {*}\nsub free(Pointer $p --> int32) is native {*}\n\nmy $p = strdup(\"Success!\");\nsay 'puts returns ', puts($p);\nsay 'free returns ', free($p);\n\n```\n\nOutput:\n\n```\nSuccess!\nputs returns 9\nfree returns 0\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDemonstrate the different syntax and semantics provided for calling a function.\n\nThis may include:\n\n: * Calling a function that requires no arguments\n * Calling a function with a fixed number of arguments\n * Calling a function with optional arguments\n * Calling a function with a variable number of arguments\n * Calling a function with named arguments\n * Using a function in statement context\n * Using a function in first-class context within an expression\n * Obtaining the return value of a function\n * Distinguishing built-in functions and user-defined functions\n * Distinguishing subroutines and functions\n * Stating whether arguments are passed by value or by reference\n * Is partial application possible and how\n\nThis task is *not* about defining functions."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Theory\n\nFundamentally, nearly everything you do in Raku is a function call if you look hard enough.\nAt the lowest level, a function call merely requires a reference to any\nkind of invokable object, and a call to its postcircumfix:<( )> method.\nHowever, there are various forms of sugar and indirection that you\ncan use to express these function calls differently. In particular,\noperators are all just sugar for function calls.\n\nCalling a function that requires no arguments:\n\n```\nfoo # as list operator\nfoo() # as function\nfoo.() # as function, explicit postfix form\n$ref() # as object invocation\n$ref.() # as object invocation, explicit postfix\n&foo() # as object invocation\n&foo.() # as object invocation, explicit postfix\n::($name)() # as symbolic ref\n```\n\nCalling a function with exactly one argument:\n\n```\nfoo 1 # as list operator\nfoo(1) # as named function\nfoo.(1) # as named function, explicit postfix\n$ref(1) # as object invocation (must be hard ref) \n$ref.(1) # as object invocation, explicit postfix\n1.$foo # as pseudo-method meaning $foo(1) (hard ref only)\n1.$foo() # as pseudo-method meaning $foo(1) (hard ref only)\n1.&foo # as pseudo-method meaning &foo(1) (is hard foo)\n1.&foo() # as pseudo-method meaning &foo(1) (is hard foo)\n1.foo # as method via dispatcher\n1.foo() # as method via dispatcher\n1.\"$name\"() # as method via dispatcher, symbolic\n+1 # as operator to prefix:<+> function\n```\n\nMethod calls are included here because they do eventually dispatch to a true\nfunction via a dispatcher. However, the dispatcher in question is not going\nto dispatch to the same set of functions that a function call of that name\nwould invoke. That's why there's a dispatcher, after all. Methods are declared\nwith a different keyword, method, in Raku, but all that does is\ninstall the actual function into a metaclass. Once it's there, it's merely\na function that expects its first argument to be the invocant object. Hence we\nfeel justified in including method call syntax as a form of indirect function call.\n\nOperators like + also go through a dispatcher, but in this case it is\nmultiply dispatched to all lexically scoped candidates for the function. Hence\nthe candidate list is bound early, and the function itself can be bound early\nif the type is known. Raku maintains a clear distinction between early-bound\nlinguistic constructs that force Perlish semantics, and late-bound OO dispatch\nthat puts the objects and/or classes in charge of semantics. (In any case, &foo,\nthough being a hard ref to the function named \"foo\", may actually be a ref to\na dispatcher to a list of candidates that, when called, makes all the candidates behave as a single unit.)\n\nCalling a function with exactly two arguments:\n\n```\nfoo 1,2 # as list operator\nfoo(1,2) # as named function\nfoo.(1,2) # as named function, explicit postfix\n$ref(1,2) # as object invocation (must be hard ref)\n$ref.(1,2) # as object invocation, explicit postfix\n1.$foo: 2 # as pseudo-method meaning $foo(1,2) (hard ref only)\n1.$foo(2) # as pseudo-method meaning $foo(1,2) (hard ref only)\n1.&foo: 2 # as pseudo-method meaning &foo(1,2) (is hard foo)\n1.&foo(2) # as pseudo-method meaning &foo(1,2) (is hard foo)\n1.foo: 2 # as method via dispatcher\n1.foo(2) # as method via dispatcher\n1.\"$name\"(2) # as method via dispatcher, symbolic\n1 + 2 # as operator to infix:<+> function\n```\n\nOptional arguments don't look any different from normal arguments.\nThe optionality is all on the binding end.\n\nCalling a function with a variable number of arguments (varargs):\n\n```\nfoo @args # as list operator\nfoo(@args) # as named function\nfoo.(@args) # as named function, explicit postfix\n$ref(@args) # as object invocation (must be hard ref)\n$ref.(@args) # as object invocation, explicit postfix\n1.$foo: @args # as pseudo-method meaning $foo(1,@args) (hard ref)\n1.$foo(@args) # as pseudo-method meaning $foo(1,@args) (hard ref)\n1.&foo: @args # as pseudo-method meaning &foo(1,@args)\n1.&foo(@args) # as pseudo-method meaning &foo(1,@args)\n1.foo: @args # as method via dispatcher\n1.foo(@args) # as method via dispatcher\n1.\"$name\"(@args) # as method via dispatcher, symbolic\n@args X @blargs # as list infix operator to infix:<X>\n```\n\nNote: whether a function may actually be called with a variable number of arguments depends entirely\non whether a signature accepts a list at that position in the argument list, but\ndescribing that is not the purpose of this task. Suffice to say that we assume here that the\nfoo function is declared with a signature of the form (\\*@params). The calls above might be interpreted as having a single array argument if the signature indicates a normal parameter instead of a variadic one. What you cannot do in Raku (unlike Perl 5) is pass an array as several fixed arguments. By default it must either represent a single argument, or be part of a variadic list. You can force the extra level of argument list interpolation using a prefix | however:\n\n```\nmy @args = 1,2,3;\nfoo(|@args); # equivalent to foo(1,2,3)\n```\n\nCalling a function with named arguments:\n\n```\nfoo :a, :b(4), :!c, d => \"stuff\"\nfoo(:a, :b(4), :!c, d => \"stuff\")\n```\n\n...and so on. Operators may also be called with named arguments, but only\ncolon adverbials are allowed:\n\n```\n1 + 1 :a :b(4) :!c :d(\"stuff\") # calls infix:<+>(1,1,:a, :b(4), :!c, d => \"stuff\")\n```\n\nUsing a function in statement context:\n\n```\nfoo(); bar(); baz(); # evaluate for side effects\n```\n\nUsing a function in first class context within an expression:\n\n```\n1 / find-a-func(1,2,3)(4,5,6) ** 2;\n```\n\nObtaining the return value of a function:\n\n```\nmy $result = somefunc(1,2,3) + 2;\n```\n\nThere is no difference between calling builtins and user-defined functions and operators (or\neven control stuctures). This was a major design goal of Raku, and apart from a very few\nlow-level primitives, all of Raku can be written in Raku.\n\nThere is no difference between calling subroutines and functions in Raku, other than that\ncalling a function in void context that has no side effects is likely to get you a \"Useless use of...\" warning.\nAnd, of course, the fact that pure functions can participate in more optimizations such as constant folding.\n\nBy default, arguments are passed readonly, which allows the implementation to decide whether pass-by-reference or pass-by-value is more efficient on a case-by-case basis. Explicit lvalue, reference, or copy semantics may be requested on a parameter-by-parameter basis, and the entire argument list may be processed raw if that level of control is needed.\n\n### Practice\n\nDemonstrating each of the above-mentioned function calls with actual running code, along with the various extra definitions required to make them work (in certain cases). Arguments are checked, and function name / run-sequence number are displayed upon success.\n\n```\n{\nstate $n;\n\nmulti f () { print ' f' ~ ++$n }\nmulti f ($a) { die if 1 != $a; print ' f' ~ ++$n }\nmulti f ($a,$b) { die if 3 != $a+$b; print ' f' ~ ++$n }\nmulti f (@a) { die if @a != [2,3,4]; print ' f' ~ ++$n }\nmulti f ($a,$b,$c) { die if 2 != $a || 4 != $c; print ' f' ~ ++$n }\nsub g ($a,*@b) { die if @b != [2,3,4] || 1 != $a; print ' g' ~ ++$n }\n\nmy \\i = -> { print ' i' ~ ++$n }\nmy \\l = -> $a { die if 1 != $a; print ' l' ~ ++$n }\nmy \\m = -> $a,$b { die if 1 != $a || 2 != $b; print ' m' ~ ++$n }\nmy \\n = -> @a { die if @a != [2,3,4]; print ' n' ~ ++$n }\n\nInt.^add_method( 'j', method ()\n { die if 1 != self; print ' j' ~ ++$n } );\nInt.^add_method( 'k', method ($a)\n { die if 1 != self || 2 != $a; print ' k' ~ ++$n } );\nInt.^add_method( 'h', method (@a)\n { die if @a != [2,3,4] || 1 != self; print ' h' ~ ++$n } );\n\nmy $ref = &f; # soft ref\nmy $f := &f; # hard ref\nmy $g := &g; # hard ref\nmy $f-sym = '&f'; # symbolic ref\nmy $g-sym = '&g'; # symbolic ref\nmy $j-sym = 'j'; # symbolic ref\nmy $k-sym = 'k'; # symbolic ref\nmy $h-sym = 'h'; # symbolic ref\n\n# Calling a function with no arguments:\n\nf; # 1 as list operator\nf(); # 2 as function\ni.(); # 3 as function, explicit postfix form # defined via pointy-block\n$ref(); # 4 as object invocation\n$ref.(); # 5 as object invocation, explicit postfix\n&f(); # 6 as object invocation\n&f.(); # 7 as object invocation, explicit postfix\n::($f-sym)(); # 8 as symbolic ref\n\n# Calling a function with exactly one argument:\n\nf 1; # 9 as list operator\nf(1); # 10 as named function\nl.(1); # 11 as named function, explicit postfix # defined via pointy-block\n$f(1); # 12 as object invocation (must be hard ref)\n$ref.(1); # 13 as object invocation, explicit postfix\n1.$f; # 14 as pseudo-method meaning $f(1) (hard ref only)\n1.$f(); # 15 as pseudo-method meaning $f(1) (hard ref only)\n1.&f; # 16 as pseudo-method meaning &f(1) (is hard f)\n1.&f(); # 17 as pseudo-method meaning &f(1) (is hard f)\n1.j; # 18 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.j(); # 19 as method via dispatcher\n1.\"$j-sym\"(); # 20 as method via dispatcher, symbolic\n\n# Calling a function with exactly two arguments:\n\nf 1,2; # 21 as list operator\nf(1,2); # 22 as named function\nm.(1,2); # 23 as named function, explicit postfix # defined via pointy-block\n$ref(1,2); # 24 as object invocation (must be hard ref)\n$ref.(1,2); # 25 as object invocation, explicit postfix\n1.$f: 2; # 26 as pseudo-method meaning $f(1,2) (hard ref only)\n1.$f(2); # 27 as pseudo-method meaning $f(1,2) (hard ref only)\n1.&f: 2; # 28 as pseudo-method meaning &f(1,2) (is hard f)\n1.&f(2); # 29 as pseudo-method meaning &f(1,2) (is hard f)\n1.k: 2; # 30 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.k(2); # 31 as method via dispatcher\n1.\"$k-sym\"(2); # 32 as method via dispatcher, symbolic\n\n# Calling a function with a variable number of arguments (varargs):\n\nmy @args = 2,3,4;\n\nf @args; # 33 as list operator\nf(@args); # 34 as named function\nn.(@args); # 35 as named function, explicit postfix # defined via pointy-block\n$ref(@args); # 36 as object invocation (must be hard ref)\n$ref.(@args); # 37 as object invocation, explicit postfix\n1.$g: @args; # 38 as pseudo-method meaning $f(1,@args) (hard ref)\n1.$g(@args); # 39 as pseudo-method meaning $f(1,@args) (hard ref)\n1.&g: @args; # 40 as pseudo-method meaning &f(1,@args)\n1.&g(@args); # 41 as pseudo-method meaning &f(1,@args)\n1.h: @args; # 42 as method via dispatcher # requires custom method, via 'Int.^add_method'\n1.h(@args); # 43 as method via dispatcher\n1.\"$h-sym\"(@args); # 44 as method via dispatcher, symbolic\nf(|@args); # 45 equivalent to f(1,2,3)\n\n}\n```\n\nOutput:\n\n```\nf1 f2 i3 f4 f5 f6 f7 f8 f9 f10 l11 f12 f13 f14 f15 f16 f17 j18 j19 j20 f21 f22 m23 f24 f25 f26 f27 f28 f29 k30 k31 k32 f33 f34 n35 f36 f37 g38 g39 g40 g41 h42 h43 h44 f45\n```"
}
]
|
[
{
"role": "user",
"content": "Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.\n\nThis is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.\n\nRelated task\n\n* OpenGL -- OpenGL is usually maintained as a shared library."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\n```\nuse NativeCall;\n\nsub XOpenDisplay(Str $s --> int64) is native('X11') {*}\nsub XCloseDisplay(int64 $i --> int32) is native('X11') {*}\n\nif try my $d = XOpenDisplay \":0.0\" {\n say \"ID = $d\";\n XCloseDisplay($d);\n}\nelse {\n say \"No X11 library!\";\n say \"Use this window instead --> ⬜\";\n}\n\n```\n\nOutput:\n\n```\nID = 94722089782960\n```"
}
]
|
[
{
"role": "user",
"content": "In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.\n\nShow how to call a static or class method, and an instance method of a class."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n### Basic method calls\n\n```\nclass Thing { \n method regular-example() { say 'I haz a method' }\n\n multi method multi-example() { say 'No arguments given' }\n multi method multi-example(Str $foo) { say 'String given' }\n multi method multi-example(Int $foo) { say 'Integer given' }\n};\n\n# 'new' is actually a method, not a special keyword:\nmy $thing = Thing.new;\n\n# No arguments: parentheses are optional\n$thing.regular-example;\n$thing.regular-example();\n$thing.multi-example;\n$thing.multi-example();\n\n# Arguments: parentheses or colon required\n$thing.multi-example(\"This is a string\");\n$thing.multi-example: \"This is a string\";\n$thing.multi-example(42);\n$thing.multi-example: 42;\n\n# Indirect (reverse order) method call syntax: colon required\nmy $foo = new Thing: ;\nmulti-example $thing: 42;\n\n```\n\n### Meta-operators\n\nThe `.` operator can be decorated with meta-operators.\n\n```\nmy @array = <a z c d y>;\n@array .= sort; # short for @array = @array.sort;\n\nsay @array».uc; # uppercase all the strings: A C D Y Z\n\n```\n\n### Classless methods\n\nA method that is not in a class can be called by using the `&` sigil explicitly.\n\n```\nmy $object = \"a string\"; # Everything is an object.\nmy method example-method {\n return \"This is { self }.\";\n}\n\nsay $object.&example-method; # Outputs \"This is a string.\"\n\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nLet **n** be a positive integer having **k** divisors (other than **1** and **n** itself) where **k** is exactly divisible by 3.\n\nAdd the first three eligible divisors, then the next three, and so on until the eligible divisors are exhausted. If the resulting partial sums are prime numbers, then **n** is called a Calmo number.\n\nExample\n\nConsider n = 165.\n\nIt has 6 eligible divisors, namely [3 5 11 15 33 55].\n\nThe sum of the first three is: 3 + 5 + 11 = 19 which is a prime number.\n\nThe sum of the next three is: 15 + 33 + 55 = 103 which is also a prime number.\n\nHence n is a Calmo number.\n\nTask\n\nFind and show here all Calmo numbers under 1000."
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor;\nuse List::Divvy;\n\nmy $upto = 1e3;\n\nmy @found = (2..Inf).hyper.grep({\n (so my @d = .&proper-divisors(:s)) &&\n (@d.elems %% 3) &&\n (all @d.batch(3)».sum».is-prime)\n}).&upto($upto);\n\nput \"{+@found} found before $upto using sums of proper-divisors:\\n\" ~\[email protected](10)».fmt(\"%4d\").join: \"\\n\";\n\n@found = (2..Inf).hyper.grep({\n (so my @d = .&proper-divisors(:s).&after: 1) &&\n (@d.elems %% 3) &&\n (all @d.batch(3)».sum».is-prime)\n}).&upto($upto);\n\nput \"\\n{+@found} found before $upto using sums of some bizarre\\nbespoke definition for divisors:\\n\" ~\[email protected](10)».fmt(\"%4d\").join: \"\\n\";\n\n```\n\nOutput:\n\n```\n85 found before 1000 using sums of proper-divisors:\n 8 21 27 35 39 55 57 65 77 85\n 111 115 125 129 155 161 185 187 201 203\n 205 209 221 235 237 265 291 299 305 309\n 319 323 327 335 341 365 371 377 381 391\n 413 415 437 451 485 489 493 497 505 515\n 517 535 579 611 623 649 655 667 669 671\n 687 689 697 707 731 737 755 767 779 781\n 785 831 835 851 865 893 899 901 917 921\n 939 955 965 979 989\n\n9 found before 1000 using sums of some bizarre\nbespoke definition for divisors:\n 165 273 385 399 561 595 665 715 957\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nLet p(1), p(2), p(3), ... , p(n) be consecutive prime numbers. If the sum of any consecutive sub-sequence of these numbers is a prime number, then the numbers in such a sub-sequence are called **CalmoSoft primes**.\n\nTask\n\nFind and show here the longest sequence of CalmoSoft primes for p(n) < 100.\n\nStretch\n\nShow a shortened version (first and last 6 primes) of the same for p(n) < fifty million. \nTip: if it takes longer than twenty seconds, you're doing it wrong."
},
{
"role": "assistant",
"content": "Longest sliding window prime sums\n\n```\nuse Lingua::EN::Numbers;\n\nsub sliding-window(@list, $window) { (^(+@list - $window)).map: { @list[$_ .. $_+$window] } }\n\nfor flat (1e2, 1e3, 1e4, 1e5).map: { (1, 2.5, 5) »×» $_ } -> $upto {\n\n my @primes = (^$upto).grep: &is-prime;\n\n for +@primes ... 1 {\n my @sums = @primes.&sliding-window($_).grep: { .sum.is-prime }\n next unless @sums;\n say \"\\nFor primes up to {$upto.Int.&cardinal}:\\nLongest sequence of consecutive primes yielding a prime sum: elements: {comma 1+$_}\";\n for @sums { say \" {join '...', .[0..5, *-5..*]».&comma».join(' + ')}, sum: {.sum.&comma}\" }\n last\n }\n}\n\n```\n\nOutput:\n\n```\nFor primes up to one hundred:\nLongest sequence of consecutive primes yielding a prime sum: elements: 21\n 7 + 11 + 13 + 17 + 19 + 23...71 + 73 + 79 + 83 + 89, sum: 953\n\nFor primes up to two hundred fifty:\nLongest sequence of consecutive primes yielding a prime sum: elements: 49\n 11 + 13 + 17 + 19 + 23 + 29...227 + 229 + 233 + 239 + 241, sum: 5,813\n\nFor primes up to five hundred:\nLongest sequence of consecutive primes yielding a prime sum: elements: 85\n 31 + 37 + 41 + 43 + 47 + 53...467 + 479 + 487 + 491 + 499, sum: 21,407\n\nFor primes up to one thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 163\n 13 + 17 + 19 + 23 + 29 + 31...971 + 977 + 983 + 991 + 997, sum: 76,099\n\nFor primes up to two thousand, five hundred:\nLongest sequence of consecutive primes yielding a prime sum: elements: 359\n 7 + 11 + 13 + 17 + 19 + 23...2,411 + 2,417 + 2,423 + 2,437 + 2,441, sum: 408,479\n\nFor primes up to five thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 665\n 7 + 11 + 13 + 17 + 19 + 23...4,967 + 4,969 + 4,973 + 4,987 + 4,993, sum: 1,543,127\n\nFor primes up to ten thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 1,223\n 3 + 5 + 7 + 11 + 13 + 17...9,887 + 9,901 + 9,907 + 9,923 + 9,929, sum: 5,686,633\n 7 + 11 + 13 + 17 + 19 + 23...9,907 + 9,923 + 9,929 + 9,931 + 9,941, sum: 5,706,497\n\nFor primes up to twenty-five thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 2,759\n 7 + 11 + 13 + 17 + 19 + 23...24,967 + 24,971 + 24,977 + 24,979 + 24,989, sum: 32,405,707\n\nFor primes up to fifty thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 5,131\n 5 + 7 + 11 + 13 + 17 + 19...49,943 + 49,957 + 49,991 + 49,993 + 49,999, sum: 121,013,303\n\nFor primes up to one hundred thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 9,590\n 2 + 3 + 5 + 7 + 11 + 13...99,907 + 99,923 + 99,929 + 99,961 + 99,971, sum: 454,196,557\n\nFor primes up to two hundred fifty thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 22,041\n 7 + 11 + 13 + 17 + 19 + 23...249,947 + 249,967 + 249,971 + 249,973 + 249,989, sum: 2,623,031,141\n\nFor primes up to five hundred thousand:\nLongest sequence of consecutive primes yielding a prime sum: elements: 41,530\n 2 + 3 + 5 + 7 + 11 + 13...499,801 + 499,819 + 499,853 + 499,879 + 499,883, sum: 9,910,236,647\n```"
}
]
|
[
{
"role": "user",
"content": "Two common conventions for naming of computer program variables are **Snake Case** and\n**Camel Case**.\n\n**Snake case** variables are generally all lower case, with an underscore between words in the variable, as in **snake\\_case\\_variable'**. **Camel case** variables are generally lower case first (except in some Pascal conventions or with class names in many other languages), with captalization of the initial letter of the words within the variable, as in '**camelCaseVariable'**.\n\nLeading underscores are not used in such variables except as part of a different naming convention, usually for special internal or system variables. White space is not permitted as part of camel case or snake case variable names.\n\nTask\n\n: * Write two functions, one to change snake case to camel case and one to change camel case to snake case. If possible, generalize the function enough to apply to strings containing spaces between words or a `-` dash between words, assuming that in those cases a space or hyphen is a also a separator character, like `\\_`, for the purpose of creating a new variable name. Leading or trailing whitespace may be ignored.\n\n: * Show the results on changing to both snake case and camel case for each of the following strings:\n\n```\n\"snakeCase\", \"snake_case\", \"variable_10_case\", \"variable10Case\", \"ɛrgo rE tHis\",\n\"hurry-up-joe!\", \"c://my-docs/happy_Flag-Day/12.doc\", \" spaces \"\n\n```\n\nRelated tasks\n\n* Naming\\_conventions"
},
{
"role": "assistant",
"content": "The specs are a little vague, but taking a wild stab at it... *(May be completely wrong but without any examples of expected output it is hard to judge. This is what **I** would expect at least...)*\n\n```\nmy @tests = qww<\n snakeCase snake_case variable_10_case variable10Case \"ɛrgo rE tHis\"\n hurry-up-joe! c://my-docs/happy_Flag-Day/12.doc \" spaces \"\n>;\n\n\nsub to_snake_case (Str $snake_case_string is copy) {\n $snake_case_string.=trim;\n return $snake_case_string if $snake_case_string.contains: / \\s | '/' /;\n $snake_case_string.=subst: / <after <:Ll>> (<:Lu>|<:digit>+) /, {'_' ~ $0.lc}, :g;\n $snake_case_string.=subst: / <after <:digit>> (<:Lu>) /, {'_' ~ $0.lc}, :g;\n}\n\nsub toCamelCase (Str $CamelCaseString is copy) {\n $CamelCaseString.=trim;\n return $CamelCaseString if $CamelCaseString.contains: / \\s | '/' /;\n $CamelCaseString.=subst: / ('_') (\\w) /, {$1.uc}, :g;\n}\n\nsub to-kebab-case (Str $kebab-case-string is copy) {\n $kebab-case-string.=trim;\n return $kebab-case-string if $kebab-case-string.contains: / \\s | '/' /;\n $kebab-case-string.=subst: / ('_') (\\w) /, {'-' ~ $1.lc}, :g;\n $kebab-case-string.=subst: / <after <:Ll>> (<:Lu>|<:digit>+) /, {'-' ~ $0.lc}, :g;\n $kebab-case-string.=subst: / <after <:digit>> (<:Lu>) /, {'-' ~ $0.lc}, :g;\n}\n\nsay \"{' ' x 30}to_snake_case\";\nprintf \"%33s ==> %s\\n\", $_, .&to_snake_case for @tests;\nsay \"\\n{' ' x 30}toCamelCase\";\nprintf \"%33s ==> %s\\n\", $_, .&toCamelCase for @tests;\nsay \"\\n{' ' x 30}to-kabab-case\";\nprintf \"%33s ==> %s\\n\", $_, .&to-kebab-case for @tests;\n\n```\n\nOutput:\n\n```\n to_snake_case\n snakeCase ==> snake_case\n snake_case ==> snake_case\n variable_10_case ==> variable_10_case\n variable10Case ==> variable_10_case\n ɛrgo rE tHis ==> ɛrgo rE tHis\n hurry-up-joe! ==> hurry-up-joe!\nc://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc\n spaces ==> spaces\n\n toCamelCase\n snakeCase ==> snakeCase\n snake_case ==> snakeCase\n variable_10_case ==> variable10Case\n variable10Case ==> variable10Case\n ɛrgo rE tHis ==> ɛrgo rE tHis\n hurry-up-joe! ==> hurry-up-joe!\nc://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc\n spaces ==> spaces\n\n to-kabab-case\n snakeCase ==> snake-case\n snake_case ==> snake-case\n variable_10_case ==> variable-10-case\n variable10Case ==> variable-10-case\n ɛrgo rE tHis ==> ɛrgo rE tHis\n hurry-up-joe! ==> hurry-up-joe!\nc://my-docs/happy_Flag-Day/12.doc ==> c://my-docs/happy_Flag-Day/12.doc\n spaces ==> spaces\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program that performs so-called canny edge detection on an image.\n\nA possible algorithm consists of the following steps:\n\n1. **Noise reduction.** May be performed by Gaussian filter.\n2. Compute **intensity gradient** (matrices \n\n G\n\n x\n {\\displaystyle {\\displaystyle G\\_{x}}}\n and \n\n G\n\n y\n {\\displaystyle {\\displaystyle G\\_{y}}}\n ) and its **magnitude** \n\n G\n {\\displaystyle {\\displaystyle G}}\n : \n \n\n G\n =\n\n G\n\n x\n\n 2\n +\n\n G\n\n y\n\n 2\n {\\displaystyle {\\displaystyle G={\\sqrt {G\\_{x}^{2}+G\\_{y}^{2}}}}}\n \n May be performed by convolution of an image with Sobel operators.\n3. **Non-maximum suppression.** \n For each pixel compute the orientation of intensity gradient vector: \n\n θ\n =\n\n\n a\n t\n a\n n\n 2\n\n (\n\n\n G\n\n y\n ,\n\n\n G\n\n x\n )\n {\\displaystyle {\\displaystyle \\theta ={\\rm {atan2}}\\left(G\\_{y},\\,G\\_{x}\\right)}}\n . \n Transform angle \n\n θ\n {\\displaystyle {\\displaystyle \\theta }}\n to one of four directions: 0, 45, 90, 135 degrees. \n Compute new array \n\n N\n {\\displaystyle {\\displaystyle N}}\n : if \n\n G\n\n (\n\n p\n\n a\n )\n <\n G\n\n (\n p\n )\n <\n G\n\n (\n\n p\n\n b\n )\n {\\displaystyle {\\displaystyle G\\left(p\\_{a}\\right)<G\\left(p\\right)<G\\left(p\\_{b}\\right)}}\n \n where \n\n p\n {\\displaystyle {\\displaystyle p}}\n is the current pixel, \n\n p\n\n a\n {\\displaystyle {\\displaystyle p\\_{a}}}\n and \n\n p\n\n b\n {\\displaystyle {\\displaystyle p\\_{b}}}\n are the two neighbour pixels in the direction of gradient, \n then \n\n N\n (\n p\n )\n =\n G\n (\n p\n )\n {\\displaystyle {\\displaystyle N(p)=G(p)}}\n , otherwise \n\n N\n (\n p\n )\n =\n 0\n {\\displaystyle {\\displaystyle N(p)=0}}\n . \n Nonzero pixels in resulting array correspond to local maxima of \n\n G\n {\\displaystyle {\\displaystyle G}}\n in direction \n\n θ\n (\n p\n )\n {\\displaystyle {\\displaystyle \\theta (p)}}\n .\n4. **Tracing edges with hysteresis.** \n At this stage two thresholds for the values of \n\n G\n {\\displaystyle {\\displaystyle G}}\n are introduced: \n\n T\n\n m\n i\n n\n {\\displaystyle {\\displaystyle T\\_{min}}}\n and \n\n T\n\n m\n a\n x\n {\\displaystyle {\\displaystyle T\\_{max}}}\n . \n Starting from pixels with \n\n N\n (\n p\n )\n ⩾\n\n T\n\n m\n a\n x\n {\\displaystyle {\\displaystyle N(p)\\geqslant T\\_{max}}}\n , \n find all paths of pixels with \n\n N\n (\n p\n )\n ⩾\n\n T\n\n m\n i\n n\n {\\displaystyle {\\displaystyle N(p)\\geqslant T\\_{min}}}\n and put them to the resulting image."
},
{
"role": "assistant",
"content": "Admittedly laziness always prevails so an off-the-shelf function from ImageMagick is used instead.\n\ncannyedge.c\n\n```\n#include <stdio.h>\n#include <string.h>\n#include <magick/MagickCore.h>\n\nint CannyEdgeDetector(\n const char *infile, const char *outfile,\n double radius, double sigma, double lower, double upper ) {\n\n ExceptionInfo *exception;\n Image *image, *processed_image, *output;\n ImageInfo *input_info;\n\n exception = AcquireExceptionInfo();\n input_info = CloneImageInfo((ImageInfo *) NULL);\n (void) strcpy(input_info->filename, infile);\n image = ReadImage(input_info, exception);\n output = NewImageList();\n processed_image = CannyEdgeImage(image,radius,sigma,lower,upper,exception);\n (void) AppendImageToList(&output, processed_image);\n (void) strcpy(output->filename, outfile);\n WriteImage(input_info, output);\n // after-party clean up \n DestroyImage(image);\n output=DestroyImageList(output);\n input_info=DestroyImageInfo(input_info);\n exception=DestroyExceptionInfo(exception);\n MagickCoreTerminus();\n\n return 0;\n}\n\n```\n\ncannyedge.raku\n\n```\n# 20220103 Raku programming solution\n \nuse NativeCall;\n \nsub CannyEdgeDetector(CArray[uint8], CArray[uint8], num64, num64, num64, num64 \n) returns int32 is native( '/home/hkdtam/LibCannyEdgeDetector.so' ) {*};\n\nCannyEdgeDetector( # imagemagick.org/script/command-line-options.php#canny \n CArray[uint8].new( 'input.jpg'.encode.list, 0), # pbs.org/wgbh/nova/next/wp-content/uploads/2013/09/fingerprint-1024x575.jpg\n CArray[uint8].new( 'output.jpg'.encode.list, 0),\n 0e0, 2e0, 0.05e0, 0.05e0\n)\n\n```\n\nOutput:\n\n```\nexport PKG_CONFIG_PATH=/usr/lib/pkgconfig\ngcc -Wall -fPIC -shared -o LibCannyEdgeDetector.so cannyedge.c `pkg-config --cflags --libs MagickCore`\nraku -c cannyedge.raku && ./cannyedge.raku\n```\n\nOutput: (Offsite image file)"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.\n\nThat is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.\n\nExample\n\nGiven **87.70.141.1/22**, your code should output **87.70.140.0/22**\n\nExplanation\n\nAn Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.\n\nIn general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.\n\nThe example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 → 87.70.140.0.\n\nMore examples for testing\n\n```\n 36.18.154.103/12 → 36.16.0.0/12\n 62.62.197.11/29 → 62.62.197.8/29\n 67.137.119.181/4 → 64.0.0.0/4\n 161.214.74.21/24 → 161.214.74.0/24\n 184.232.176.184/18 → 184.232.128.0/18\n\n```"
},
{
"role": "assistant",
"content": "### Using library\n\n**Library:** raku-IP-Addr\n\n```\nuse IP::Addr;\nfor «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18» -> $cidr {\n say \"$cidr -> $(IP::Addr.new($cidr).network)\";\n}\n\n```\n\n### String manipulation\n\n**Translation of**: Perl\n\n```\n#!/usr/bin/env raku\nunit sub MAIN(*@cidrs);\n\nif !@cidrs {\n # test data\n @cidrs = «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18»;\n}\n\nfor @cidrs -> $cidr {\n say \"$cidr -> $(canonicalize $cidr)\";\n}\n\n# canonicalize a CIDR block: make sure none of the host bits are set\nsub canonicalize($cidr) {\n # dotted-decimal / bits in network part\n my ($dotted, $size) = $cidr.split: '/';\n\n # get network part of the IP as binary string\n my $binary = $dotted.split('.')».fmt('%08b').join.substr(0, $size);\n\n # Add host part with all zeroes\n $binary ~= 0 x (32 - $size);\n\n # Convert back to dotted-decimal\n my $canon = $binary.comb(8)».parse-base(2).join: '.';\n\n # And output\n say \"$canon/$size\";\n}\n\n```\n\nOutput:\n\n```\n87.70.141.1/22 -> 87.70.140.0/22\n36.18.154.103/12 -> 36.16.0.0/12\n62.62.197.11/29 -> 62.62.197.8/29\n67.137.119.181/4 -> 64.0.0.0/4\n161.214.74.21/24 -> 161.214.74.0/24\n184.232.176.184/18 -> 184.232.128.0/18\n```\n\n### Bit mask and shift\n\n```\n# canonicalize a IP4 CIDR block\nsub CIDR-IP4-canonicalize ($address) {\n constant @mask = 24, 16, 8, 0;\n \n # dotted-decimal / subnet size\n my ($dotted, $size) = |$address.split('/'), 32;\n \n # get IP as binary address\n my $binary = sum $dotted.comb(/\\d+/) Z+< @mask;\n \n # mask off subnet\n $binary +&= (2 ** $size - 1) +< (32 - $size);\n \n # Return dotted-decimal notation\n (@mask.map($binary +> * +& 0xFF).join('.'), $size)\n}\n \nmy @tests = <\n 87.70.141.1/22\n 36.18.154.103/12\n 62.62.197.11/29\n 67.137.119.181/4\n 161.214.74.21/24\n 184.232.176.184/18\n 100.68.0.18/18\n 10.4.30.77/30\n 10.207.219.251/32\n 10.207.219.251\n 110.200.21/4\n 10.11.12.13/8\n 10.../8\n>;\n \nprintf \"CIDR: %18s Routing prefix: %s/%s\\n\", $_, |.&CIDR-IP4-canonicalize\n for @*ARGS || @tests;\n\n```\n\nOutput:\n\n```\nCIDR: 87.70.141.1/22 Routing prefix: 87.70.140.0/22\nCIDR: 36.18.154.103/12 Routing prefix: 36.16.0.0/12\nCIDR: 62.62.197.11/29 Routing prefix: 62.62.197.8/29\nCIDR: 67.137.119.181/4 Routing prefix: 64.0.0.0/4\nCIDR: 161.214.74.21/24 Routing prefix: 161.214.74.0/24\nCIDR: 184.232.176.184/18 Routing prefix: 184.232.128.0/18\nCIDR: 100.68.0.18/18 Routing prefix: 100.68.0.0/18\nCIDR: 10.4.30.77/30 Routing prefix: 10.4.30.76/30\nCIDR: 10.207.219.251/32 Routing prefix: 10.207.219.251/32\nCIDR: 10.207.219.251 Routing prefix: 10.207.219.251/32\nCIDR: 110.200.21/4 Routing prefix: 96.0.0.0/4\nCIDR: 10.11.12.13/8 Routing prefix: 10.0.0.0/8\nCIDR: 10.../8 Routing prefix: 10.0.0.0/8\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDraw a Cantor set.\n\nSee details at this Wikipedia webpage: Cantor set"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Kotlin\n\n```\nsub cantor ( Int $height ) {\n my $width = 3 ** ($height - 1);\n\n my @lines = ( \"\\c[FULL BLOCK]\" x $width ) xx $height;\n\n my sub _trim_middle_third ( $len, $start, $index ) {\n my $seg = $len div 3\n or return;\n\n for ( $index ..^ $height ) X ( 0 ..^ $seg ) -> ( $i, $j ) {\n @lines[$i].substr-rw( $start + $seg + $j, 1 ) = ' ';\n }\n\n _trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;\n }\n\n _trim_middle_third( $width, 0, 1 );\n return @lines;\n}\n\n.say for cantor(5);\n\n```\n\nOutput:\n\n```\n█████████████████████████████████████████████████████████████████████████████████\n███████████████████████████ ███████████████████████████\n█████████ █████████ █████████ █████████\n███ ███ ███ ███ ███ ███ ███ ███\n█ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nThere are many techniques that people use to shuffle cards for card games. Some are more effective than others.\n\nTask\n\nImplement the (seemingly) more common techniques of the riffle shuffle and overhand shuffle for *n* iterations.\n\nImplementing playing cards is not necessary if it would be easier to implement these shuffling methods for generic collections.\n\nWhere possible, compare this to a standard/built-in shuffling procedure.\n\nOne iteration of the riffle shuffle is defined as:\n\n1. Split the deck into two piles\n2. Merge the two piles by taking one card from the top of either pile in proportion to the number of cards remaining in the pile. To start with the probability for both piles will be 26/52 (50-50), then 25/51-26/51 etc etc as the riffle progresses.\n3. The merged deck is now the new \"shuffled\" deck\n\nOne iteration of the overhand shuffle is defined as:\n\n1. Take a group of consecutive cards from the top of the deck. For our purposes up to 20% of the deck seems like a good amount.\n2. Place that group on top of a second pile\n3. Repeat these steps until there are no cards remaining in the original deck\n4. The second pile is now the new \"shuffled\" deck\n\nBonus\n\nImplement other methods described in the Wikipedia\narticle: card shuffling.\n\nAllow for \"human errors\" of imperfect cutting and interleaving.\n\nRelated tasks:\n\n* Playing cards\n* Deal cards\\_for\\_FreeCell\n* War Card\\_Game\n* Poker hand\\_analyser\n* Go Fish"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub overhand ( @cards ) {\n my @splits = roll 10, ^( @cards.elems div 5 )+1;\n @cards.rotor( @splits ,:partial ).reverse.flat\n}\n\nsub riffle ( @pile is copy ) {\n my @pile2 = @pile.splice: @pile.elems div 2 ;\n \n roundrobin(\n @pile.rotor( (1 .. 3).roll(7), :partial ),\n @pile2.rotor( (1 .. 3).roll(9), :partial ),\n ).flat\n}\n\nmy @cards = ^20;\n@cards.=&overhand for ^10;\nsay @cards;\n \nmy @cards2 = ^20;\n@cards2.=&riffle for ^10;\nsay @cards2;\n\nsay (^20).pick(*);\n\n```"
}
]
|
[
{
"role": "user",
"content": "A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.\n\nThe Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.\n\nThe purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.\n\nTask\n\nFind Carmichael numbers of the form:\n\n: : : : *Prime*1 × *Prime*2 × *Prime*3\n\nwhere (*Prime*1 < *Prime*2 < *Prime*3) for all *Prime*1 up to **61**.\n \n(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)\n\nPseudocode\n\nFor a given **Prime1**\n\n```\nfor 1 < h3 < Prime1\n for 0 < d < h3+Prime1\n if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3\n then\n Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)\n next d if Prime2 is not prime\n Prime3 = 1 + (Prime1*Prime2/h3)\n next d if Prime3 is not prime\n next d if (Prime2*Prime3) mod (Prime1-1) not equal 1\n Prime1 * Prime2 * Prime3 is a Carmichael Number\n\n```\n\nrelated task\n\nChernick's Carmichael numbers"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nAn almost direct translation of the pseudocode. We take the liberty of going up to 67 to show we aren't limited to 32-bit integers. (Raku uses arbitrary precision in any case.)\n\n```\nfor (2..67).grep: *.is-prime -> \\Prime1 {\n for 1 ^..^ Prime1 -> \\h3 {\n my \\g = h3 + Prime1;\n for 0 ^..^ h3 + Prime1 -> \\d {\n if (h3 + Prime1) * (Prime1 - 1) %% d and -Prime1**2 % h3 == d % h3 {\n my \\Prime2 = floor 1 + (Prime1 - 1) * g / d;\n next unless Prime2.is-prime;\n my \\Prime3 = floor 1 + Prime1 * Prime2 / h3;\n next unless Prime3.is-prime;\n next unless (Prime2 * Prime3) % (Prime1 - 1) == 1;\n say \"{Prime1} × {Prime2} × {Prime3} == {Prime1 * Prime2 * Prime3}\";\n }\n }\n }\n}\n\n```\n\nOutput:\n\n```\n3 × 11 × 17 == 561\n5 × 29 × 73 == 10585\n5 × 17 × 29 == 2465\n5 × 13 × 17 == 1105\n7 × 19 × 67 == 8911\n7 × 31 × 73 == 15841\n7 × 13 × 31 == 2821\n7 × 23 × 41 == 6601\n7 × 73 × 103 == 52633\n7 × 13 × 19 == 1729\n13 × 61 × 397 == 314821\n13 × 37 × 241 == 115921\n13 × 97 × 421 == 530881\n13 × 37 × 97 == 46657\n13 × 37 × 61 == 29341\n17 × 41 × 233 == 162401\n17 × 353 × 1201 == 7207201\n19 × 43 × 409 == 334153\n19 × 199 × 271 == 1024651\n23 × 199 × 353 == 1615681\n29 × 113 × 1093 == 3581761\n29 × 197 × 953 == 5444489\n31 × 991 × 15361 == 471905281\n31 × 61 × 631 == 1193221\n31 × 151 × 1171 == 5481451\n31 × 61 × 271 == 512461\n31 × 61 × 211 == 399001\n31 × 271 × 601 == 5049001\n31 × 181 × 331 == 1857241\n37 × 109 × 2017 == 8134561\n37 × 73 × 541 == 1461241\n37 × 613 × 1621 == 36765901\n37 × 73 × 181 == 488881\n37 × 73 × 109 == 294409\n41 × 1721 × 35281 == 2489462641\n41 × 881 × 12041 == 434932961\n41 × 101 × 461 == 1909001\n41 × 241 × 761 == 7519441\n41 × 241 × 521 == 5148001\n41 × 73 × 137 == 410041\n41 × 61 × 101 == 252601\n43 × 631 × 13567 == 368113411\n43 × 271 × 5827 == 67902031\n43 × 127 × 2731 == 14913991\n43 × 127 × 1093 == 5968873\n43 × 211 × 757 == 6868261\n43 × 631 × 1597 == 43331401\n43 × 127 × 211 == 1152271\n43 × 211 × 337 == 3057601\n43 × 433 × 643 == 11972017\n43 × 547 × 673 == 15829633\n43 × 3361 × 3907 == 564651361\n47 × 3359 × 6073 == 958762729\n47 × 1151 × 1933 == 104569501\n47 × 3727 × 5153 == 902645857\n53 × 157 × 2081 == 17316001\n53 × 79 × 599 == 2508013\n53 × 157 × 521 == 4335241\n59 × 1451 × 2089 == 178837201\n61 × 421 × 12841 == 329769721\n61 × 181 × 5521 == 60957361\n61 × 1301 × 19841 == 1574601601\n61 × 277 × 2113 == 35703361\n61 × 181 × 1381 == 15247621\n61 × 541 × 3001 == 99036001\n61 × 661 × 2521 == 101649241\n61 × 271 × 571 == 9439201\n61 × 241 × 421 == 6189121\n61 × 3361 × 4021 == 824389441\n67 × 2311 × 51613 == 7991602081\n67 × 331 × 7393 == 163954561\n67 × 331 × 463 == 10267951\n```"
}
]
|
[
{
"role": "user",
"content": "Background\n\nThe **Carmichael function**, or **Carmichael lambda function**, is a function in number theory. The Carmichael lambda *λ*(*n*) of a positive integer **n** is the smallest positive integer **m** such that\n\n: a\n\n m\n ≡\n 1\n\n\n (\n mod\n\n n\n )\n {\\displaystyle {\\displaystyle a^{m}\\equiv 1{\\pmod {n}}}}\n\nholds for every integer coprime to **n**.\n\nThe Carmichael lambda function can be iterated, that is, called repeatedly on its result. If this iteration is\nperformed **k** times, this is considered the **k**-iterated Carmichael lambda function. Thus, *λ*(*λ*(*n*))\nwould be the 2-iterated lambda function. With repeated, sufficiently large but finite **k**-iterations, the iterated Carmichael function will eventually compute as 1 for all positive integers **n**.\n\nTask\n\n* Write a function to obtain the Carmichael lambda of a positive integer. If the function is supplied by a core library of the language, this also may be used.\n\n* Write a function to count the number of iterations **k** of the **k**-iterated lambda function needed to get to a value of 1. Show the value of *λ*(*n*) and the number of **k**-iterations for integers from 1 to 25.\n\n* Find the lowest integer for which the value of iterated k is i, for i from 1 to 15.\n\nStretch task (an extension of the third task above)\n\n* Find, additionally, for **i** from 16 to 25, the lowest integer **n** for which the number of iterations **k** of the Carmichael lambda function from **n** to get to 1 is **i**.\n\nSee also\n\n: * Wikipedia entry for Carmichael function\n * OEIS lambda(lambda(n)) function sequence"
},
{
"role": "assistant",
"content": "**Translation of**: Wren\n\n```\n# 20240228 Raku programming solution\n\nuse Prime::Factor;\n\nsub phi(Int $p, Int $r) { return $p**($r - 1) * ($p - 1) }\n\nsub CarmichaelLambda(Int $n) {\n\n state %cache = 1 => 1, 2 => 1, 4 => 2;\n\n sub CarmichaelHelper(Int $p, Int $r) {\n my Int $n = $p ** $r;\n return %cache{$n} if %cache{$n}:exists;\n return %cache{$n} = $p > 2 ?? phi($p, $r) !! phi($p, $r - 1)\n }\n\n if $n < 1 { die \"'n' must be a positive integer.\" }\n return %cache{$n} if %cache{$n}:exists;\n if ( my %pps = prime-factors($n).Bag ).elems == 1 { \n my ($p, $r) = %pps.kv>>.Int;\n return %cache{$n} = $p > 2 ?? phi($p, $r) !! phi($p, $r - 1)\n }\n return [lcm] %pps.kv.map: -> $k, $v { CarmichaelHelper($k.Int, $v) } \n}\n\nsub iteratedToOne($i is copy) {\n my $k = 0;\n while $i > 1 { $i = CarmichaelLambda($i) andthen $k++ } \n return $k\n}\n\nsay \" n λ k\";\nsay \"----------\";\nfor 1..25 -> $n {\n printf \"%2d %2d %2d\\n\", $n, CarmichaelLambda($n), iteratedToOne($n)\n}\n\nsay \"\\nIterations to 1 i lambda(i)\";\nsay \"=====================================\";\nsay \" 0 1 1\";\n\nmy ($maxI, $maxN) = 5e6, 10; # for N=15, takes around 47 minutes with an i5-10500T\nmy @found = True, |( False xx $maxN );\nfor 1 .. $maxI -> $i {\n unless @found[ my $n = iteratedToOne($i) ] {\n printf \"%4d %18d %12d\\n\", $n, $i, CarmichaelLambda($i);\n @found[$n] = True andthen ( last if $n == $maxN )\n }\n}\n\n```\n\nOutput:\n\nSame as Wren example .. and it is probably 30X times slower 😅"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n\n: : {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n\n: : {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n\n: : {1, 2} × {} = {}\n : {} × {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n\n: : {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}\n : {1, 2, 3} × {30} × {500, 100}\n : {1, 2, 3} × {} × {500, 100}"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.06\n\nThe cross meta operator X will return the cartesian product of two lists. To apply the cross meta-operator to a variable number of lists, use the reduce cross meta operator [X].\n\n```\n# cartesian product of two lists using the X cross meta-operator\nsay (1, 2) X (3, 4);\nsay (3, 4) X (1, 2);\nsay (1, 2) X ( );\nsay ( ) X ( 1, 2 );\n\n# cartesian product of variable number of lists using\n# the [X] reduce cross meta-operator\nsay [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);\nsay [X] (1, 2, 3), (30), (500, 100);\nsay [X] (1, 2, 3), (), (500, 100);\n\n```\n\nOutput:\n\n```\n((1 3) (1 4) (2 3) (2 4))\n((3 1) (3 2) (4 1) (4 2))\n()\n()\n((1776 7 4 0) (1776 7 4 1) (1776 7 14 0) (1776 7 14 1) (1776 7 23 0) (1776 7 23 1) (1776 12 4 0) (1776 12 4 1) (1776 12 14 0) (1776 12 14 1) (1776 12 23 0) (1776 12 23 1) (1789 7 4 0) (1789 7 4 1) (1789 7 14 0) (1789 7 14 1) (1789 7 23 0) (1789 7 23 1) (1789 12 4 0) (1789 12 4 1) (1789 12 14 0) (1789 12 14 1) (1789 12 23 0) (1789 12 23 1))\n((1 30 500) (1 30 100) (2 30 500) (2 30 100) (3 30 500) (3 30 100))\n()\n```"
}
]
|
[
{
"role": "user",
"content": "Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:\n\n```\nThe three dogs are named Benjamin, Samba and Bernie.\n\n```\n\nFor a language that is lettercase insensitive, we get the following output:\n\n```\nThere is just one dog named Bernie.\n\n```\n\nRelated task\n\n* Unicode variable names"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $dog = 'Benjamin';\nmy $Dog = 'Samba';\nmy $DOG = 'Bernie';\nsay \"The three dogs are named $dog, $Dog, and $DOG.\"\n\n```\n\nThe only place that Raku pays any attention to the case of identifiers is that, for certain error messages, it will guess that an identifier starting lowercase is probably a function name, while one starting uppercase is probably a type or constant name. But this case distinction is merely a convention in Raku, not mandatory:\n\n```\nconstant dog = 'Benjamin';\nsub Dog() { 'Samba' }\nmy &DOG = { 'Bernie' }\nsay \"The three dogs are named {dog}, {Dog}, and {DOG}.\"\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task (in three parts)\n\nPart 1\n\nWrite a procedure (say \n\nc\no\n9\n(\nx\n)\n{\\displaystyle {\\displaystyle {\\mathit {co9}}(x)}}\n) which implements Casting Out Nines as described by returning the checksum for \n\nx\n{\\displaystyle {\\displaystyle x}}\n. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\nPart 2\n\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: Kaprekar numbers#Casting Out Nines (fast)).\n: note that \n\n 318682\n {\\displaystyle {\\displaystyle 318682}}\n has the same checksum as (\n\n 101558\n +\n 217124\n {\\displaystyle {\\displaystyle 101558+217124}}\n );\n: note that \n\n 101558217124\n {\\displaystyle {\\displaystyle 101558217124}}\n has the same checksum as (\n\n 101558\n +\n 217124\n {\\displaystyle {\\displaystyle 101558+217124}}\n ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of \n\n k\n {\\displaystyle {\\displaystyle k}}\n equals the checksum of \n\n k\n\n 2\n {\\displaystyle {\\displaystyle k^{2}}}\n .\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \n\nc\no\n9\n(\nk\n)\n=\n\n\nc\no\n9\n(\n\nk\n\n2\n)\n{\\displaystyle {\\displaystyle {\\mathit {co9}}(k)={\\mathit {co9}}(k^{2})}}\n and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\nPart 3\n\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n\n: c\n o\n 9\n (\n x\n )\n {\\displaystyle {\\displaystyle {\\mathit {co9}}(x)}}\n is the residual of \n\n x\n {\\displaystyle {\\displaystyle x}}\n mod \n\n 9\n {\\displaystyle {\\displaystyle 9}}\n ;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property \n\nk\n%\n(\n\n\nB\na\ns\ne\n−\n1\n)\n==\n(\n\nk\n\n2\n)\n%\n(\n\n\nB\na\ns\ne\n−\n1\n)\n{\\displaystyle {\\displaystyle k\\%({\\mathit {Base}}-1)==(k^{2})\\%({\\mathit {Base}}-1)}}\n and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\nrelated tasks\n\n* First perfect square in base N with N unique digits\n* Kaprekar numbers"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub cast-out(\\BASE = 10, \\MIN = 1, \\MAX = BASE**2 - 1) {\n my \\B9 = BASE - 1;\n my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9);\n my $x = MIN div B9;\n gather loop {\n for @ran -> \\n {\n my \\k = B9 * $x + n;\n take k if k >= MIN;\n }\n $x++;\n } ...^ * > MAX;\n}\n\nsay cast-out;\nsay cast-out 16;\nsay cast-out 17;\n\n```\n\nOutput:\n\n```\n(1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99)\n(1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255)\n(1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288)\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Catalan numbers. 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\nCatalan numbers are a sequence of numbers which can be defined directly:\n\n: C\n\n n\n =\n\n\n 1\n\n n\n +\n 1\n\n (\n\n\n 2\n n\n n\n\n )\n =\n\n (\n 2\n n\n )\n !\n\n (\n n\n +\n 1\n )\n !\n\n n\n !\n\n for \n n\n ≥\n 0.\n {\\displaystyle {\\displaystyle C\\_{n}={\\frac {1}{n+1}}{2n \\choose n}={\\frac {(2n)!}{(n+1)!\\,n!}}\\qquad {\\mbox{ for }}n\\geq 0.}}\n\nOr recursively:\n\n: C\n\n 0\n =\n 1\n\n and\n\n\n C\n\n n\n +\n 1\n =\n\n ∑\n\n i\n =\n 0\n\n n\n\n C\n\n i\n\n\n C\n\n n\n −\n i\n\n\n for \n n\n ≥\n 0\n ;\n {\\displaystyle {\\displaystyle C\\_{0}=1\\quad {\\mbox{and}}\\quad C\\_{n+1}=\\sum \\_{i=0}^{n}C\\_{i}\\,C\\_{n-i}\\quad {\\text{for }}n\\geq 0;}}\n\nOr alternatively (also recursive):\n\n: C\n\n 0\n =\n 1\n\n and\n\n\n C\n\n n\n =\n\n 2\n (\n 2\n n\n −\n 1\n )\n\n n\n +\n 1\n\n C\n\n n\n −\n 1\n ,\n {\\displaystyle {\\displaystyle C\\_{0}=1\\quad {\\mbox{and}}\\quad C\\_{n}={\\frac {2(2n-1)}{n+1}}C\\_{n-1},}}\n\nTask\n\nImplement at least one of these algorithms and print out the first 15 Catalan numbers with each.\n\nMemoization is not required, but may be worth the effort when using the second method above.\n\nRelated tasks\n\n* Catalan numbers/Pascal's triangle\n* Evaluate binomial coefficients"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nThe recursive formulas are easily written into a constant array, either:\n\n```\nconstant Catalan = 1, { [+] @_ Z* @_.reverse } ... *;\n```\n\nor\n\n```\nconstant Catalan = 1, |[\\*] (2, 6 ... *) Z/ 2 .. *;\n\n\n# In both cases, the sixteen first values can be seen with:\n.say for Catalan[^16];\n```\n\nOutput:\n\n```\n1\n1\n2\n5\n14\n42\n132\n429\n1430\n4862\n16796\n58786\n208012\n742900\n2674440\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nPrint out the first **15** Catalan numbers by extracting them from Pascal's triangle.\n\nSee\n\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\nRelated Tasks\n\nPascal's triangle"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nconstant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;\n\nconstant @catalan = gather for 2, 4 ... * -> $ix {\n my @row := @pascal[$ix];\n my $mid = +@row div 2;\n take [-] @row[$mid, $mid+1]\n}\n\n.say for @catalan[^20];\n\n```\n\nOutput:\n\n```\n1\n2\n5\n14\n42\n132\n429\n1430\n4862\n16796\n58786\n208012\n742900\n2674440\n9694845\n35357670\n129644790\n477638700\n1767263190\n6564120420\n```"
}
]
|
[
{
"role": "user",
"content": "*Reduce* is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.\n\nTask\n\nShow how *reduce* (or *foldl* or *foldr* etc), work (or would be implemented) in your language.\n\nSee also\n\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nAny associative infix operator, either built-in or user-defined, may be turned into a reduce operator by putting it into square brackets (known as \"the reduce metaoperator\") and using it as a list operator. The operations will work left-to-right or right-to-left automatically depending on the natural associativity of the base operator.\n\n```\nmy @list = 1..10;\nsay [+] @list;\nsay [*] @list;\nsay [~] @list;\nsay min @list;\nsay max @list;\nsay [lcm] @list;\n\n```\n\nOutput:\n\n```\n55\n3628800\n12345678910\n1\n10\n2520\n```\n\nIn addition to the reduce metaoperator, a general higher-order function, reduce, can apply any appropriate function. Reproducing the above in this form, using the function names of those operators, we have:\n\n```\nmy @list = 1..10;\nsay reduce &infix:<+>, @list;\nsay reduce &infix:<*>, @list;\nsay reduce &infix:<~>, @list;\nsay reduce &infix:<min>, @list;\nsay reduce &infix:<max>, @list;\nsay reduce &infix:<lcm>, @list;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Write a function which returns the centre and radius of a circle passing through three point in a plane. Demonstrate the function using the points (22.83,2.07) (14.39,30.24) and (33.65,17.31)"
},
{
"role": "assistant",
"content": "Don't bother defining all the intermediate variables.\n\n```\nsub circle( (\\𝒳ᵢ, \\𝒴ᵢ), (\\𝒳ⱼ, \\𝒴ⱼ), (\\𝒳ₖ, \\𝒴ₖ) ) {\n my \\𝒞ₓ = ((𝒳ᵢ² + 𝒴ᵢ²) × (𝒴ₖ - 𝒴ⱼ) + (𝒳ⱼ² + 𝒴ⱼ²) × (𝒴ᵢ - 𝒴ₖ) + (𝒳ₖ² + 𝒴ₖ²) × (𝒴ⱼ - 𝒴ᵢ)) /\n (𝒳ᵢ × (𝒴ₖ - 𝒴ⱼ) + 𝒳ⱼ × (𝒴ᵢ - 𝒴ₖ) + 𝒳ₖ × (𝒴ⱼ - 𝒴ᵢ)) / 2 ;\n my \\𝒞ᵧ = ((𝒳ᵢ² + 𝒴ᵢ²) × (𝒳ₖ - 𝒳ⱼ) + (𝒳ⱼ² + 𝒴ⱼ²) × (𝒳ᵢ - 𝒳ₖ) + (𝒳ₖ² + 𝒴ₖ²) × (𝒳ⱼ - 𝒳ᵢ)) /\n (𝒴ᵢ × (𝒳ₖ - 𝒳ⱼ) + 𝒴ⱼ × (𝒳ᵢ - 𝒳ₖ) + 𝒴ₖ × (𝒳ⱼ - 𝒳ᵢ)) / 2 ;\n center => (𝒞ₓ,𝒞ᵧ), radius => ((𝒞ₓ - 𝒳ᵢ)² + (𝒞ᵧ - 𝒴ᵢ)²).sqrt \n}\n\nsay circle (22.83,2.07), (14.39,30.24), (33.65,17.31);\n\n```\n\nOutput:\n\n```\n(center => (18.97851566 16.2654108) radius => 14.70862397833418)\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "In analytic geometry, the *centroid* of a set of points is a point in the same domain as the set. The centroid point is chosen to show a property which can be calculated for that set.\n\nConsider the centroid defined as the arithmetic mean of a set of points of arbitrary dimension.\n\nTask\n\nCreate a function in your chosen programming language to calculate such a centroid using an arbitrary number of points of arbitrary dimension.\n\nTest your function with the following groups of points\n\n```\none-dimensional: (1), (2), (3)\n\n```\n\n```\ntwo-dimensional: (8, 2), (0, 0)\n\n```\n\n```\nthree-dimensional: the set (5, 5, 0), (10, 10, 0) and the set (1, 3.1, 6.5), (-2, -5, 3.4), (-7, -4, 9), (2, 0, 3)\n\n```\n\n```\nfive-dimensional: (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 1, 0, 0), (0, 1, 0, 0, 0)\n\n```\n\nStretch task\n\n```\n Show a 3D plot image of the second 3-dimensional set and its centroid.\n\n```\n\nSee Also\n\n[Wikipedia page]\n\n[Wolfram Mathworld on Centroid]"
},
{
"role": "assistant",
"content": "```\nsub centroid { ( [»+«] @^LoL ) »/» +@^LoL }\n\nsay .¢roid for\n ( (1,), (2,), (3,) ),\n ( (8, 2), (0, 0) ),\n ( (5, 5, 0), (10, 10, 0) ),\n ( (1, 3.1, 6.5), (-2, -5, 3.4), (-7, -4, 9), (2, 0, 3) ),\n ( (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 1, 0, 0), (0, 1, 0, 0, 0) ),\n;\n\n```\n\nOutput:\n\n```\n(2)\n(4 1)\n(7.5 7.5 0)\n(-1.5 -1.475 5.475)\n(0 0.25 0.25 0.25 0.25)\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nUse the dictionary unixdict.txt\n\nChange letters **e** to **i** in words.\n\nIf the changed word is in the dictionary, show it here on this page.\n\nThe length of any word shown should have a length **> 5****.**\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": "```\nmy %ei = 'unixdict.txt'.IO.words.grep({ .chars > 5 and /<[ie]>/ }).map: { $_ => .subst('e', 'i', :g) };\nput %ei.grep( *.key.contains: 'e' ).grep({ %ei{.value}:exists }).sort.batch(4)».gist».fmt('%-22s').join: \"\\n\";\n\n```\n\nOutput:\n\n```\nanalyses => analysis atlantes => atlantis bellow => billow breton => briton \nclench => clinch convect => convict crises => crisis diagnoses => diagnosis\nenfant => infant enquiry => inquiry frances => francis galatea => galatia \nharden => hardin heckman => hickman inequity => iniquity inflect => inflict \njacobean => jacobian marten => martin module => moduli pegging => pigging \npsychoses => psychosis rabbet => rabbit sterling => stirling synopses => synopsis \nvector => victor welles => willis\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nUsing the dictionary unixdict.txt, change one letter in a word, and if the changed word occurs in the dictionary,\n \nthen display the original word and the changed word here (on this page).\n\nThe length of any word shown should have a length **> 11****.**\n\nNote\n\n* A copy of the specific unixdict.txt linked to should be used for consistency of results.\n* Words **> 11** are required, ie of 12 characters or more.\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\n\nReference\n\n* Levenshtein distance"
},
{
"role": "assistant",
"content": "Sorensen-Dice is very fast to calculate similarities but isn't great for detecting small changes. Levenshtein is great for detecting small changes but isn't very fast.\n\nGet the best of both worlds by doing an initial filter with Sorensen, then get exact results with Levenshtein.\n\n```\nuse Text::Levenshtein;\nuse Text::Sorensen :sorensen;\n\nmy @words = grep {.chars > 11}, 'unixdict.txt'.IO.words;\n\nmy %bi-grams = @words.map: { $_ => .&bi-gram };\n\nmy %skip = @words.map: { $_ => 0 };\n\nsay (++$).fmt('%2d'), |$_ for @words.hyper.map: -> $this {\n next if %skip{$this};\n my ($word, @sorensens) = sorensen($this, %bi-grams);\n next unless @sorensens.=grep: { 1 > .[0] > .8 };\n @sorensens = @sorensens»[1].grep: {$this.chars == .chars};\n my @levenshtein = distance($this, @sorensens).grep: * == 1, :k;\n next unless +@levenshtein;\n %skip{$_}++ for @sorensens[@levenshtein];\n \": {$this.fmt('%14s')} <-> \", @sorensens[@levenshtein].join: ', ';\n}\n\n```\n\nOutput:\n\n```\n 1: aristotelean <-> aristotelian\n 2: claustrophobia <-> claustrophobic\n 3: committeeman <-> committeemen\n 4: committeewoman <-> committeewomen\n 5: complimentary <-> complementary\n 6: confirmation <-> conformation\n 7: congresswoman <-> congresswomen\n 8: councilwoman <-> councilwomen\n 9: draftsperson <-> craftsperson\n10: eavesdropped <-> eavesdropper\n11: frontiersman <-> frontiersmen\n12: handicraftsman <-> handicraftsmen\n13: incommutable <-> incomputable\n14: installation <-> instillation\n15: kaleidescope <-> kaleidoscope\n16: neuroanatomy <-> neuroanotomy\n17: newspaperman <-> newspapermen\n18: nonagenarian <-> nonogenarian\n19: onomatopoeia <-> onomatopoeic\n20: philanthrope <-> philanthropy\n21: proscription <-> prescription\n22: schizophrenia <-> schizophrenic\n23: shakespearean <-> shakespearian\n24: spectroscope <-> spectroscopy\n25: underclassman <-> underclassmen\n26: upperclassman <-> upperclassmen\n```"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.