messages
listlengths
2
2
[ { "role": "user", "content": "Description\n\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\nTask\n\nCode the algorithm in your language and test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nmy @left;\nmy @right;\n\nsub reset {\n @left = <HXUCZVAMDSLKPEFJRIGTWOBNYQ>.comb;\n @right = <PTLNBQDEOYSFAVZKGJRIHWXUMC>.comb;\n}\n\nsub encode ($letter) {\n my $index = @right.first: $letter.uc, :k;\n my $enc = @left[$index];\n $index.&permute;\n $enc\n}\n\nsub decode ($letter) {\n my $index = @left.first: $letter.uc, :k;\n my $dec = @right[$index];\n $index.&permute;\n $dec\n}\n\nsub permute ($index) {\n @left.=rotate: $index;\n @left[1..13].=rotate;\n @right.=rotate: $index + 1;\n @right[2..13].=rotate;\n}\n\nreset;\nsay 'WELLDONEISBETTERTHANWELLSAID'.comb».&encode.join;\nreset;\nsay 'OAHQHCNYNXTSZJRRHJBYHQKSOUJY'.comb».&decode.join;\n\n```\n\nOutput:\n\n```\nOAHQHCNYNXTSZJRRHJBYHQKSOUJY\nWELLDONEISBETTERTHANWELLSAID\n```" } ]
[ { "role": "user", "content": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS).\n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\nTask\n\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\nSee also\n\n* The Game of Chaos" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\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 @vertex = [0, 0], [$w, 0], [$w/2, $h];\n\nmy @xy = [0,0], [0,0], [0,0], [0,0];\n\n# :degree must be equal to or less than @xy elements.\n(^1e5).race(:4degree).map: {\n my $p = ++$ % +@xy;\n @xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };\n $png.set: |@xy[$p], 0, 255, 0;\n}\n\n$png.write: 'Chaos-game-perl6.png';\n\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses).\n\nExample\n\nThe character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode).\n\nConversely, given a code, print out the corresponding character." }, { "role": "assistant", "content": "(formerly Perl 6)\nBoth Perl 5 and Raku have good Unicode support, though Raku attempts to make working with Unicode effortless. Note that even multi-byte emoji and characters outside the BMP are considered single characters. Also note: all of these routines are built into the base compiler. No need to load external libraries. See Wikipedia: Unicode character properties for explanation of Unicode property.\n\n```\nfor 'AΑА𪚥🇺🇸👨‍👩‍👧‍👦'.comb {\n .put for\n [ 'Character',\n 'Character name',\n 'Unicode property',\n 'Unicode script',\n 'Unicode block',\n 'Added in Unicode version',\n 'Ordinal(s)',\n 'Hex ordinal(s)',\n 'UTF-8',\n 'UTF-16LE',\n 'UTF-16BE',\n 'Round trip by name',\n 'Round trip by ordinal'\n ]».fmt('%25s:')\n Z\n [ $_,\n .uninames.join(', '),\n .uniprops.join(', '),\n .uniprops('Script').join(', '),\n .uniprops('Block').join(', '),\n .uniprops('Age').join(', '),\n .ords,\n .ords.fmt('0x%X'),\n .encode('utf8' )».fmt('%02X'),\n .encode('utf16le')».fmt('%02X').join.comb(4),\n .encode('utf16be')».fmt('%02X').join.comb(4),\n .uninames».uniparse.join,\n .ords.chrs\n ];\n say '';\n}\n```\n\nOutput:\n\n```\n Character: A\n Character name: LATIN CAPITAL LETTER A\n Unicode property: Lu\n Unicode script: Latin\n Unicode block: Basic Latin\n Added in Unicode version: 1.1\n Ordinal(s): 65\n Hex ordinal(s): 0x41\n UTF-8: 41\n UTF-16LE: 4100\n UTF-16BE: 0041\n Round trip by name: A\n Round trip by ordinal: A\n\n Character: Α\n Character name: GREEK CAPITAL LETTER ALPHA\n Unicode property: Lu\n Unicode script: Greek\n Unicode block: Greek and Coptic\n Added in Unicode version: 1.1\n Ordinal(s): 913\n Hex ordinal(s): 0x391\n UTF-8: CE 91\n UTF-16LE: 9103\n UTF-16BE: 0391\n Round trip by name: Α\n Round trip by ordinal: Α\n\n Character: А\n Character name: CYRILLIC CAPITAL LETTER A\n Unicode property: Lu\n Unicode script: Cyrillic\n Unicode block: Cyrillic\n Added in Unicode version: 1.1\n Ordinal(s): 1040\n Hex ordinal(s): 0x410\n UTF-8: D0 90\n UTF-16LE: 1004\n UTF-16BE: 0410\n Round trip by name: А\n Round trip by ordinal: А\n\n Character: 𪚥\n Character name: CJK UNIFIED IDEOGRAPH-2A6A5\n Unicode property: Lo\n Unicode script: Han\n Unicode block: CJK Unified Ideographs Extension B\n Added in Unicode version: 3.1\n Ordinal(s): 173733\n Hex ordinal(s): 0x2A6A5\n UTF-8: F0 AA 9A A5\n UTF-16LE: 69D8 A5DE\n UTF-16BE: D869 DEA5\n Round trip by name: 𪚥\n Round trip by ordinal: 𪚥\n\n Character: 🇺🇸\n Character name: REGIONAL INDICATOR SYMBOL LETTER U, REGIONAL INDICATOR SYMBOL LETTER S\n Unicode property: So, So\n Unicode script: Common, Common\n Unicode block: Enclosed Alphanumeric Supplement, Enclosed Alphanumeric Supplement\n Added in Unicode version: 6.0, 6.0\n Ordinal(s): 127482 127480\n Hex ordinal(s): 0x1F1FA 0x1F1F8\n UTF-8: F0 9F 87 BA F0 9F 87 B8\n UTF-16LE: 3CD8 FADD 3CD8 F8DD\n UTF-16BE: D83C DDFA D83C DDF8\n Round trip by name: 🇺🇸\n Round trip by ordinal: 🇺🇸\n\n Character: 👨‍👩‍👧‍👦\n Character name: MAN, ZERO WIDTH JOINER, WOMAN, ZERO WIDTH JOINER, GIRL, ZERO WIDTH JOINER, BOY\n Unicode property: So, Cf, So, Cf, So, Cf, So\n Unicode script: Common, Inherited, Common, Inherited, Common, Inherited, Common\n Unicode block: Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs\n Added in Unicode version: 6.0, 1.1, 6.0, 1.1, 6.0, 1.1, 6.0\n Ordinal(s): 128104 8205 128105 8205 128103 8205 128102\n Hex ordinal(s): 0x1F468 0x200D 0x1F469 0x200D 0x1F467 0x200D 0x1F466\n UTF-8: F0 9F 91 A8 E2 80 8D F0 9F 91 A9 E2 80 8D F0 9F 91 A7 E2 80 8D F0 9F 91 A6\n UTF-16LE: 3DD8 68DC 0D20 3DD8 69DC 0D20 3DD8 67DC 0D20 3DD8 66DC\n UTF-16BE: D83D DC68 200D D83D DC69 200D D83D DC67 200D D83D DC66\n Round trip by name: 👨‍👩‍👧‍👦\n Round trip by ordinal: 👨‍👩‍👧‍👦\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a server for a minimal text based chat.\n\nPeople should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n(or at least started out that way)\n\n**Works with**: Rakudo version 2016.07\n\n```\nreact {\n my %connections;\n \n whenever IO::Socket::Async.listen('localhost', 4004) -> $conn {\n my $name;\n \n $conn.print: \"Please enter your name: \";\n \n whenever $conn.Supply.lines -> $message {\n if !$name {\n if %connections{$message} {\n $conn.print: \"Name already taken, choose another one: \";\n }\n else {\n $name = $message;\n %connections{$name} = $conn;\n broadcast \"+++ %s arrived +++\", $name;\n }\n }\n else {\n broadcast \"%s> %s\", $name, $message;\n }\n LAST {\n broadcast \"--- %s left ---\", $name;\n %connections{$name}:delete;\n $conn.close ;\n }\n QUIT {\n default {\n say \"oh no, $_\";\n }\n }\n }\n }\n \n sub broadcast ($format, $from, *@message) {\n my $text = sprintf $format, $from, |@message;\n say $text;\n for %connections.kv -> $name, $conn {\n $conn.print: \"$text\\n\" if $name ne $from;\n }\n }\n}\n\n```\n\nNotes:\n\n* It operates asynchronously (using IO::Socket::Async), so a slow connection to one client won't affect other clients.\n* It accepts messages encoded in UTF-8.\n* It tokenizes the message streams at newline boundaries (using the Supply.lines method), which I think makes the most sense for a chat application." } ]
[ { "role": "user", "content": "Chebyshev coefficients are the basis of polynomial approximations of functions.\n\nTask\n\nWrite a program to generate Chebyshev coefficients.\n\nCalculate coefficients:   cosine function,   **10**   coefficients,   interval   **0   1**" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: C\n\n```\nsub chebft ( Code $func, Real \\a, Real \\b, Int \\n ) {\n\n my \\bma = ½ × (b - a);\n my \\bpa = ½ × (b + a);\n\n my @pi-n = ( ^n »+» ½ ) »×» (π/n);\n my @f = ( @pi-n».cos »×» bma »+» bpa )».&$func;\n my @sums = (^n).map: { [+] @f »×« ( @pi-n »×» $_ )».cos };\n\n @sums »×» (2/n)\n}\n\nsay chebft(&cos, 0, 1, 10)».fmt: '%+13.7e';\n\n```\n\nOutput:\n\n```\n+1.6471695e+00\n-2.3229937e-01\n-5.3715115e-02\n+2.4582353e-03\n+2.8211906e-04\n-7.7222292e-06\n-5.8985565e-07\n+1.1521427e-08\n+6.5962992e-10\n-1.0021994e-11\n```" } ]
[ { "role": "user", "content": "Self-explanatory: given a polygon (as an array/vector/list of its vertices) and a rectangle (in x, y, width, height format), check if they intersect.\n\nRelated tasks\n\n* Determine if two triangles overlap\n* Check if two polygons overlap" }, { "role": "assistant", "content": "**Translation of**: Go\n\n```\n# 20230810 Raku programming solution\n\nclass Vector2 { has ( $.x, $.y );\n method dot ( \\other ) { self.x * other.x + self.y * other.y }\n}; \n\nclass Rectangle { has ( $.x, $.y, $.w, $.h ) }\n\nclass Projection { has ( $.min, $.max ) };\n\nsub getAxes(\\poly) {\n return poly.append(poly[0]).rotor(2=>-1).map: -> (\\vertex1,\\vertex2) {\n my \\vector1 = Vector2.new: x => vertex1[0], y => vertex1[1];\n my \\vector2 = Vector2.new: x => vertex2[0], y => vertex2[1];\n my \\edge = Vector2.new: x => vector1.x - vector2.x, \n y => vector1.y - vector2.y;\n $_ = Vector2.new: x => -edge.y, y => edge.x\n }\n}\n\nsub projectOntoAxis(\\poly, \\axis) {\n my \\vertex0 = poly[0];\n my \\vector0 = Vector2.new: x => vertex0[0], y => vertex0[1];\n my $max = my $min = axis.dot: vector0;\n for poly -> \\vertex {\n my \\vector = Vector2.new: x => vertex[0], y => vertex[1];\n given axis.dot: vector { when $_ < $min { $min = $_ } \n when $_ > $max { $max = $_ } }\n }\n return Projection.new: min => $min, max => $max\n}\n\nsub projectionsOverlap(\\proj1, \\proj2) {\n return ! ( proj1.max < proj2.min or proj2.max < proj1.min )\n}\n\nsub rectToPolygon( \\r ) {\n return [(r.x, r.y), (r.x, r.y+r.h), (r.x+r.w, r.y+r.h), (r.x+r.w, r.y)]\n}\n\nsub polygonOverlapsRect(\\poly1, \\rect) {\n my \\poly2 = rectToPolygon rect;\n my (\\axes1,\\axes2) := (poly1,poly2).map: { getAxes $_ };\n for (axes1, axes2) -> \\axes {\n for axes -> \\axis {\n my (\\proj1,\\proj2) := (poly1,poly2).map: { projectOntoAxis $_, axis }\n return False unless projectionsOverlap(proj1, proj2) \n }\n }\n return True\n}\n\nmy \\poly = [ <0 0>, <0 2>, <1 4>, <2 2>, <2 0> ]; \nmy \\rect1 = Rectangle.new: :4x, :0y, :2h, :2w;\nmy \\rect2 = Rectangle.new: :1x, :0y, :8h, :2w;\nsay \"poly = \", poly;\nsay \"rect1 = \", rectToPolygon(rect1);\nsay \"rect2 = \", rectToPolygon(rect2);\nsay();\nsay \"poly and rect1 overlap? \", polygonOverlapsRect(poly, rect1);\nsay \"poly and rect2 overlap? \", polygonOverlapsRect(poly, rect2);\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Self-explanatory: given two polygons (as a list of their vertices), check whether they overlap.\n\nRelated tasks\n\n* Determine if two triangles overlap\n* Check if a polygon overlaps with a rectangle" }, { "role": "assistant", "content": "**Translation of**: Go\n\n```\n# 20230810 Raku programming solution\n\nclass Vector2 { has ( $.x, $.y );\n method dot ( \\other ) { self.x * other.x + self.y * other.y }\n}; \n\nclass Projection { has ( $.min, $.max ) };\n\nsub getAxes ( \\poly ) {\n return poly.append(poly[0]).rotor(2=>-1).map: -> (\\vertex1,\\vertex2) {\n my \\vector1 = Vector2.new: x => vertex1[0], y => vertex1[1];\n my \\vector2 = Vector2.new: x => vertex2[0], y => vertex2[1];\n my \\edge = Vector2.new: x => vector1.x - vector2.x, \n y => vector1.y - vector2.y;\n $_ = Vector2.new: x => -edge.y, y => edge.x\n }\n}\n\nsub projectOntoAxis ( \\poly, \\axis ) {\n my \\vertex0 = poly[0];\n my \\vector0 = Vector2.new: x => vertex0[0], y => vertex0[1];\n my $max = my $min = axis.dot: vector0;\n for poly -> \\vertex {\n my \\vector = Vector2.new: x => vertex[0], y => vertex[1];\n given axis.dot: vector { when $_ < $min { $min = $_ } \n when $_ > $max { $max = $_ } }\n }\n return Projection.new: min => $min, max => $max\n}\n\nsub projectionsOverlap ( \\proj1, \\proj2 ) {\n return ! ( proj1.max < proj2.min or proj2.max < proj1.min )\n}\n\nsub polygonsOverlap( \\poly1, \\poly2 ) {\n my (\\axes1,\\axes2) := (poly1,poly2).map: { getAxes $_ };\n for (axes1, axes2) -> \\axes {\n for axes -> \\axis {\n my (\\proj1,\\proj2) := (poly1,poly2).map: { projectOntoAxis $_, axis }\n return False unless projectionsOverlap(proj1, proj2) \n }\n }\n return True\n}\n\nmy \\poly1 = [ <0 0>, <0 2>, <1 4>, <2 2>, <2 0> ];\nmy \\poly2 = [ <4 0>, <4 2>, <5 4>, <6 2>, <6 0> ];\nmy \\poly3 = [ <1 0>, <1 2>, <5 4>, <9 2>, <9 0> ];\n\nsay \"poly1 = \", poly1;\nsay \"poly2 = \", poly2;\nsay \"poly3 = \", poly3;\nsay();\nsay \"poly1 and poly2 overlap? \", polygonsOverlap(poly1, poly2);\nsay \"poly1 and poly3 overlap? \", polygonsOverlap(poly1, poly3);\nsay \"poly2 and poly3 overlap? \", polygonsOverlap(poly2, poly3);\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate how to check whether the input device is a terminal or not.\n\nRelated task\n\n* Check output device is a terminal" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nsay $*IN.t ?? \"Input comes from tty.\" !! \"Input doesn't come from tty.\";\n\n```\n\n```\n$ raku istty.raku\nInput comes from tty.\n$ true | raku istty.raku\nInput doesn't come from tty.\n\n```" } ]
[ { "role": "user", "content": "Machin-like formulas   are useful for efficiently computing numerical approximations for \n\nπ\n{\\displaystyle {\\displaystyle \\pi }}\n\nTask\n\nVerify the following Machin-like formulas are correct by calculating the value of **tan**   (*right hand side)* for each equation using exact arithmetic and showing they equal **1**:\n\n: π\n 4\n =\n arctan\n ⁡\n\n\n 1\n 2\n +\n arctan\n ⁡\n\n\n 1\n 3\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=\\arctan {1 \\over 2}+\\arctan {1 \\over 3}}}\n: π\n 4\n =\n 2\n arctan\n ⁡\n\n\n 1\n 3\n +\n arctan\n ⁡\n\n\n 1\n 7\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=2\\arctan {1 \\over 3}+\\arctan {1 \\over 7}}}\n: π\n 4\n =\n 4\n arctan\n ⁡\n\n\n 1\n 5\n −\n arctan\n ⁡\n\n\n 1\n 239\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=4\\arctan {1 \\over 5}-\\arctan {1 \\over 239}}}\n: π\n 4\n =\n 5\n arctan\n ⁡\n\n\n 1\n 7\n +\n 2\n arctan\n ⁡\n\n\n 3\n 79\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=5\\arctan {1 \\over 7}+2\\arctan {3 \\over 79}}}\n: π\n 4\n =\n 5\n arctan\n ⁡\n\n\n 29\n 278\n +\n 7\n arctan\n ⁡\n\n\n 3\n 79\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=5\\arctan {29 \\over 278}+7\\arctan {3 \\over 79}}}\n: π\n 4\n =\n arctan\n ⁡\n\n\n 1\n 2\n +\n arctan\n ⁡\n\n\n 1\n 5\n +\n arctan\n ⁡\n\n\n 1\n 8\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=\\arctan {1 \\over 2}+\\arctan {1 \\over 5}+\\arctan {1 \\over 8}}}\n: π\n 4\n =\n 4\n arctan\n ⁡\n\n\n 1\n 5\n −\n arctan\n ⁡\n\n\n 1\n 70\n +\n arctan\n ⁡\n\n\n 1\n 99\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=4\\arctan {1 \\over 5}-\\arctan {1 \\over 70}+\\arctan {1 \\over 99}}}\n: π\n 4\n =\n 5\n arctan\n ⁡\n\n\n 1\n 7\n +\n 4\n arctan\n ⁡\n\n\n 1\n 53\n +\n 2\n arctan\n ⁡\n\n\n 1\n 4443\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=5\\arctan {1 \\over 7}+4\\arctan {1 \\over 53}+2\\arctan {1 \\over 4443}}}\n: π\n 4\n =\n 6\n arctan\n ⁡\n\n\n 1\n 8\n +\n 2\n arctan\n ⁡\n\n\n 1\n 57\n +\n arctan\n ⁡\n\n\n 1\n 239\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=6\\arctan {1 \\over 8}+2\\arctan {1 \\over 57}+\\arctan {1 \\over 239}}}\n: π\n 4\n =\n 8\n arctan\n ⁡\n\n\n 1\n 10\n −\n arctan\n ⁡\n\n\n 1\n 239\n −\n 4\n arctan\n ⁡\n\n\n 1\n 515\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=8\\arctan {1 \\over 10}-\\arctan {1 \\over 239}-4\\arctan {1 \\over 515}}}\n: π\n 4\n =\n 12\n arctan\n ⁡\n\n\n 1\n 18\n +\n 8\n arctan\n ⁡\n\n\n 1\n 57\n −\n 5\n arctan\n ⁡\n\n\n 1\n 239\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=12\\arctan {1 \\over 18}+8\\arctan {1 \\over 57}-5\\arctan {1 \\over 239}}}\n: π\n 4\n =\n 16\n arctan\n ⁡\n\n\n 1\n 21\n +\n 3\n arctan\n ⁡\n\n\n 1\n 239\n +\n 4\n arctan\n ⁡\n\n\n 3\n 1042\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=16\\arctan {1 \\over 21}+3\\arctan {1 \\over 239}+4\\arctan {3 \\over 1042}}}\n: π\n 4\n =\n 22\n arctan\n ⁡\n\n\n 1\n 28\n +\n 2\n arctan\n ⁡\n\n\n 1\n 443\n −\n 5\n arctan\n ⁡\n\n\n 1\n 1393\n −\n 10\n arctan\n ⁡\n\n\n 1\n 11018\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=22\\arctan {1 \\over 28}+2\\arctan {1 \\over 443}-5\\arctan {1 \\over 1393}-10\\arctan {1 \\over 11018}}}\n: π\n 4\n =\n 22\n arctan\n ⁡\n\n\n 1\n 38\n +\n 17\n arctan\n ⁡\n\n\n 7\n 601\n +\n 10\n arctan\n ⁡\n\n\n 7\n 8149\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=22\\arctan {1 \\over 38}+17\\arctan {7 \\over 601}+10\\arctan {7 \\over 8149}}}\n: π\n 4\n =\n 44\n arctan\n ⁡\n\n\n 1\n 57\n +\n 7\n arctan\n ⁡\n\n\n 1\n 239\n −\n 12\n arctan\n ⁡\n\n\n 1\n 682\n +\n 24\n arctan\n ⁡\n\n\n 1\n 12943\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=44\\arctan {1 \\over 57}+7\\arctan {1 \\over 239}-12\\arctan {1 \\over 682}+24\\arctan {1 \\over 12943}}}\n: π\n 4\n =\n 88\n arctan\n ⁡\n\n\n 1\n 172\n +\n 51\n arctan\n ⁡\n\n\n 1\n 239\n +\n 32\n arctan\n ⁡\n\n\n 1\n 682\n +\n 44\n arctan\n ⁡\n\n\n 1\n 5357\n +\n 68\n arctan\n ⁡\n\n\n 1\n 12943\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=88\\arctan {1 \\over 172}+51\\arctan {1 \\over 239}+32\\arctan {1 \\over 682}+44\\arctan {1 \\over 5357}+68\\arctan {1 \\over 12943}}}\n\nand confirm that the following formula is *incorrect* by showing   **tan**   (*right hand side)*   is *not*   **1**:\n\n: π\n 4\n =\n 88\n arctan\n ⁡\n\n\n 1\n 172\n +\n 51\n arctan\n ⁡\n\n\n 1\n 239\n +\n 32\n arctan\n ⁡\n\n\n 1\n 682\n +\n 44\n arctan\n ⁡\n\n\n 1\n 5357\n +\n 68\n arctan\n ⁡\n\n\n 1\n 12944\n {\\displaystyle {\\displaystyle {\\pi \\over 4}=88\\arctan {1 \\over 172}+51\\arctan {1 \\over 239}+32\\arctan {1 \\over 682}+44\\arctan {1 \\over 5357}+68\\arctan {1 \\over 12944}}}\n\nThese identities are useful in calculating the values:\n\n: tan\n ⁡\n (\n a\n +\n b\n )\n =\n\n tan\n ⁡\n (\n a\n )\n +\n tan\n ⁡\n (\n b\n )\n\n 1\n −\n tan\n ⁡\n (\n a\n )\n tan\n ⁡\n (\n b\n )\n {\\displaystyle {\\displaystyle \\tan(a+b)={\\tan(a)+\\tan(b) \\over 1-\\tan(a)\\tan(b)}}}\n\n: tan\n ⁡\n\n (\n\n arctan\n ⁡\n\n\n a\n b\n )\n =\n\n\n a\n b\n {\\displaystyle {\\displaystyle \\tan \\left(\\arctan {a \\over b}\\right)={a \\over b}}}\n\n: tan\n ⁡\n (\n −\n a\n )\n =\n −\n tan\n ⁡\n (\n a\n )\n {\\displaystyle {\\displaystyle \\tan(-a)=-\\tan(a)}}\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that *−\n3\nπ\n4\n{\\displaystyle {\\displaystyle {-3\\pi \\over 4}}}\n < right hand side < \n\n5\nπ\n4\n{\\displaystyle {\\displaystyle {5\\pi \\over 4}}}* due to *tan\n⁡\n(\n)\n{\\displaystyle {\\displaystyle \\tan()}}* periodicity." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nThe coercion to FatRat provides for exact computation for all input.\n\n**Translation of**: Perl\n\n```\nsub taneval ($coef, $f) {\n return 0 if $coef == 0;\n return $f if $coef == 1;\n return -taneval(-$coef, $f) if $coef < 0;\n\n my $a = taneval($coef+>1, $f);\n my $b = taneval($coef - $coef+>1, $f);\n ($a+$b)/(1-$a*$b);\n}\n\nsub tans (@xs) {\n return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1;\n\n my $a = tans(@xs[0 .. (-1+@xs+>1)]);\n my $b = tans(@xs[(-1+@xs+>1)+1 .. -1+@xs]);\n ($a+$b)/(1-$a*$b);\n}\n\nsub verify (@eqn) {\n printf \"%5s (%s)\\n\", (tans(@eqn) == 1) ?? \"OK\" !! \"Error\",\n (map { \"[{.[0]} {.[1].nude.join('/')}]\" }, @eqn).join(' ');\n}\n\nverify($_) for\n ([[1,1/2], [1,1/3]],\n [[2,1/3], [1,1/7]],\n [[4,1/5], [-1,1/239]],\n [[5,1/7], [2,3/79]],\n [[5,29/278], [7,3/79]],\n [[1,1/2], [1,1/5], [1,1/8]],\n [[4,1/5], [-1,1/70], [1,1/99]],\n [[5,1/7], [4,1/53], [2,1/4443]],\n [[6,1/8], [2,1/57], [1,1/239]],\n [[8,1/10], [-1,1/239], [-4,1/515]],\n [[12,1/18], [8,1/57], [-5,1/239]],\n [[16,1/21], [3,1/239], [4,3/1042]],\n [[22,1/28], [2,1/443], [-5,1/1393], [-10,1/11018]],\n [[22,1/38], [17,7/601], [10,7/8149]],\n [[44,1/57], [7,1/239], [-12,1/682], [24,1/12943]],\n [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/12943]],\n [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/21944]]\n );\n\n```\n\nOutput:\n\n```\n OK ([1 1/2] [1 1/3])\n OK ([2 1/3] [1 1/7])\n OK ([4 1/5] [-1 1/239])\n OK ([5 1/7] [2 3/79])\n OK ([5 29/278] [7 3/79])\n OK ([1 1/2] [1 1/5] [1 1/8])\n OK ([4 1/5] [-1 1/70] [1 1/99])\n OK ([5 1/7] [4 1/53] [2 1/4443])\n OK ([6 1/8] [2 1/57] [1 1/239])\n OK ([8 1/10] [-1 1/239] [-4 1/515])\n OK ([12 1/18] [8 1/57] [-5 1/239])\n OK ([16 1/21] [3 1/239] [4 3/1042])\n OK ([22 1/28] [2 1/443] [-5 1/1393] [-10 1/11018])\n OK ([22 1/38] [17 7/601] [10 7/8149])\n OK ([44 1/57] [7 1/239] [-12 1/682] [24 1/12943])\n OK ([88 1/172] [51 1/239] [32 1/682] [44 1/5357] [68 1/12943])\nError ([88 1/172] [51 1/239] [32 1/682] [44 1/5357] [68 1/21944])\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate how to check whether the output device is a terminal or not.\n\nRelated task\n\n* Check input device is a terminal" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nThe .t method on a filehandle tells you whether it's going to the terminal. Here we use the note function to emit our result to standard error rather than standard out.\n\n```\n$ raku -e 'note $*OUT.t'\nTrue\n$ raku -e 'note $*OUT.t' >/dev/null\nFalse\n```" } ]
[ { "role": "user", "content": "Task\n\nVerify that a file called     **input.txt**     and   a directory called     **docs**     exist.\n\nThis should be done twice:\n\n: : : * once for the current working directory,   and\n * once for a file and a directory in the filesystem root.\n\nOptional criteria (May 2015):   verify it works with:\n\n: : : * zero-length files\n * an unusual filename:   **`Abdu'l-Bahá.txt**" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $path = \"/etc/passwd\";\nsay $path.IO.e ?? \"Exists\" !! \"Does not exist\";\n\ngiven $path.IO {\n when :d { say \"$path is a directory\"; }\n when :f { say \"$path is a regular file\"; }\n when :e { say \"$path is neither a directory nor a file, but it does exist\"; }\n default { say \"$path does not exist\" }\n}\n\n```\n\n`when` internally uses the smart match operator `~~`, so `when :e` really does `$given ~~ :e` instead of the method call `$given.e`; both test whether the file exists.\n\n```\nrun ('touch', \"♥ Unicode.txt\");\n\nsay \"♥ Unicode.txt\".IO.e; # \"True\"\nsay \"♥ Unicode.txt\".IO ~~ :e; # same\n\n```" } ]
[ { "role": "user", "content": "The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the *checkpoint* at which tasks synchronize themselves before going their paths apart.\n\n**The task**\n\nImplement checkpoint synchronization in your language.\n\nMake sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (*EA* and *EB* correspondingly), then waits for the AND-combination of the events (*EA*&*EB*) and resets its event. Consider the following scenario: A signals *EA* first and gets blocked waiting for *EA*&*EB*. Then B signals *EB* and loses the processor. Then A is released (both events are signaled) and resets *EA*. Now if B returns and enters waiting for *EA*&*EB*, it gets lost.\n\nWhen a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.\n\nIf you can, implement workers joining and leaving." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $TotalWorkers = 3;\nmy $BatchToRun = 3;\nmy @TimeTaken = (5..15); # in seconds\n\nmy $batch_progress = 0;\nmy @batch_lock = map { Semaphore.new(1) } , ^$TotalWorkers;\nmy $lock = Lock.new;\n\nsub assembly_line ($ID) {\n my $wait;\n for ^$BatchToRun -> $j {\n $wait = @TimeTaken.roll;\n say \"Worker \",$ID,\" at batch $j will work for \",$wait,\" seconds ..\";\n sleep($wait);\n $lock.protect: {\n my $k = ++$batch_progress;\n print \"Worker \",$ID,\" is done and update batch $j complete counter \";\n say \"to $k of $TotalWorkers\";\n if ($batch_progress == $TotalWorkers) {\n say \">>>>> batch $j completed.\";\n $batch_progress = 0; # reset for next batch\n for @batch_lock { .release }; # and ready for next batch\n };\n };\n\n @batch_lock[$ID].acquire; # for next batch\n }\n}\n\nfor ^$TotalWorkers -> $i {\n Thread.start(\n sub {\n @batch_lock[$i].acquire;\n assembly_line($i);\n }\n );\n}\n\n```\n\nOutput:\n\n```\nWorker 1 at batch 0 will work for 6 seconds ..\nWorker 2 at batch 0 will work for 32 seconds ..\nWorker 0 at batch 0 will work for 13 seconds ..\nWorker 1 is done and update batch 0 complete counter to 1 of 3\nWorker 0 is done and update batch 0 complete counter to 2 of 3\nWorker 2 is done and update batch 0 complete counter to 3 of 3\n>>>>> batch 0 completed.\nWorker 2 at batch 1 will work for 27 seconds ..\nWorker 0 at batch 1 will work for 18 seconds ..\nWorker 1 at batch 1 will work for 13 seconds ..\nWorker 1 is done and update batch 1 complete counter to 1 of 3\nWorker 0 is done and update batch 1 complete counter to 2 of 3\nWorker 2 is done and update batch 1 complete counter to 3 of 3\n>>>>> batch 1 completed.\nWorker 2 at batch 2 will work for 5 seconds ..\nWorker 0 at batch 2 will work for 28 seconds ..\nWorker 1 at batch 2 will work for 33 seconds ..\nWorker 2 is done and update batch 2 complete counter to 1 of 3\nWorker 0 is done and update batch 2 complete counter to 2 of 3\nWorker 1 is done and update batch 2 complete counter to 3 of 3\n>>>>> batch 2 completed.\n\n```" } ]
[ { "role": "user", "content": "**Context:** In December 2013 a patch was proposed to the coreutils list to add a --color option to the commands md5sum and shaXsum to display the checksums in color to make it easier to visually identify similarities in a list of printed checksums. The patch was not accepted for inclusion and instead it was suggested to create a command line utility which can be used to pipe the output of the md5sum and shaXsum commands similar to the utility colordiff.\n\n**Task:** The task is to create this command line utility that we can use to pipe the output of the md5sum and shaXsum commands and that colors the checksum part of the output. Take each group of 3 or 6 hexadecimal characters and interpret it as if it was a color code and print it with the closest console color. Print with colors if the output is the terminal or print the input unchanged if the output of the utility is a pipe.\n\n**Example:**\n\n```\n$ md5sum coreutils-* | checksumcolor\nab20d840e13adfebf2b6936a2dab071b coreutils-8.29.tar.gz\nb259b2936bb46009be3f5cc06a12c32d coreutils-8.30.tar.gz\n03cf26420de566c306d340df52f6ccd7 coreutils-8.31.tar.gz\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\nTo determine the colors, rather than breaking the md5sum into groups of 3 characters, (which leaves two lonely characters at the end), I elected to replicate the first 5 characters onto the end, then for each character, used it and the 5 characters following as a true-color index. I also added an option to output as HTML code for ease of pasting in here.\n\n```\nunit sub MAIN ($mode = 'ANSI');\n\nif $*OUT.t or $mode eq 'HTML' { # if OUT is a terminal or if in HTML $module\n\n say '<div style=\"background-color:black; font-size:125%; font-family: Monaco, monospace;\">'\n if $mode eq 'HTML';\n\n while my $line = get() {\n my $cs = $line.words[0];\n my $css = $cs ~ $cs.substr(0,5);\n given $mode {\n when 'ANSI' {\n print \"\\e[48;5;232m\";\n .print for $css.comb.rotor(6 => -5)».map({ ($^a, $^b).join })\\\n .map( { sprintf \"\\e[38;2;%d;%d;%dm\", |$_».parse-base(16) } ) Z~ $cs.comb;\n say \"\\e[0m {$line.words[1..*]}\";\n }\n when 'HTML' {\n print \"$_\\</span>\" for $css.comb.rotor(6 => -5)\\\n .map( { \"<span style=\\\"color:#{.join};\\\">\" } ) Z~ $cs.comb;\n say \" <span style=\\\"color:#ffffff\\\"> {$line.words[1..*]}</span>\";\n say '<br>';\n }\n default { say $line; }\n }\n }\n\n say '</div>' if $mode eq 'HTML';\n} else { # just pass the unaltered line through\n .say while $_ = get();\n}\n\n```\n\nCan't really show the ANSI output directly so show the HTML output. Essentially identical.\n\nOutput:\n\n```\nmd5sum *.p6 | raku checksum-color.p6 HTML > checksum-color.html\n```\n\nyields:\n\nf09a3fc8551d8a703d64d8e918ece236 checksum-color (another copy).p6\n \nf09a3fc8551d8a703d64d8e918ece236 checksum-color (copy).p6\n \nf09a3fc8551d8a703d64d8e918ece236 checksum-color.p6\n \nbbd8a92c326c8a35e80d2d71ab8902cd something-completely-different.p6" } ]
[ { "role": "user", "content": "Given a molecule's chemical formula, calculate the   molar mass.\n\nIntroduction\n\n* A molecule consists of atoms.   E.g. water, H2O, has two hydrogen atoms and one oxygen atom\n* The mass of   H2O   is   1.008 \\* 2 + 15.999 = 18.015\n* An atom name consists of one upper-case letter followed by zero, one or two lower-case letters.\n + H       (hydrogen)\n + He     (helium)\n + Uue   (ununennium)\n* The number of atoms is stated behind the atom or atom group\n* An atom group is specified using parenthesis.   E.g. butyric acid, (CH3)2CHCOOH, has two CH3 groups\n* A group may contain other groups, e.g.   COOH(C(CH3)2)3CH3\n\nBackground\n\n* The mass is dimensionless,   it is relative to   1/12   of Carbon-12\n* Carbon-12   has exactly   6 protons,   6 electrons,   and   6 neutrons\n* One mole of   H2O   has the mass 18.015 grams\n* One mole is defined as exactly   6.02214076×1023   particles\n\nThe above number is known as the   Avogadro constant,   which is\nnamed by the International Bureau of Weights and Measures (IBPM);\n \nthe initials are taken from   *Bureau International des Poids et Mesures*,   the official name of the bureau.\n\nAn older name for   *Avogadro constant*   is   *Avogadro number*.\n\nAtom masses\n\nA mapping between some recognized element names and atomic mass is:\n\n```\n H, 1.008\n He, 4.002602\n Li, 6.94\n Be, 9.0121831\n B, 10.81\n C, 12.011\n N, 14.007\n O, 15.999\n F, 18.998403163\n Ne, 20.1797\n Na, 22.98976928\n Mg, 24.305\n Al, 26.9815385\n Si, 28.085\n P, 30.973761998\n S, 32.06\n Cl, 35.45\n K, 39.0983\n Ar, 39.948\n Ca, 40.078\n Sc, 44.955908\n Ti, 47.867\n V, 50.9415\n Cr, 51.9961\n Mn, 54.938044\n Fe, 55.845\n Ni, 58.6934\n Co, 58.933194\n Cu, 63.546\n Zn, 65.38\n Ga, 69.723\n Ge, 72.63\n As, 74.921595\n Se, 78.971\n Br, 79.904\n Kr, 83.798\n Rb, 85.4678\n Sr, 87.62\n Y, 88.90584\n Zr, 91.224\n Nb, 92.90637\n Mo, 95.95\n Ru, 101.07\n Rh, 102.9055\n Pd, 106.42\n Ag, 107.8682\n Cd, 112.414\n In, 114.818\n Sn, 118.71\n Sb, 121.76\n I, 126.90447\n Te, 127.6\n Xe, 131.293\n Cs, 132.90545196\n Ba, 137.327\n La, 138.90547\n Ce, 140.116\n Pr, 140.90766\n Nd, 144.242\n Pm, 145\n Sm, 150.36\n Eu, 151.964\n Gd, 157.25\n Tb, 158.92535\n Dy, 162.5\n Ho, 164.93033\n Er, 167.259\n Tm, 168.93422\n Yb, 173.054\n Lu, 174.9668\n Hf, 178.49\n Ta, 180.94788\n W, 183.84\n Re, 186.207\n Os, 190.23\n Ir, 192.217\n Pt, 195.084\n Au, 196.966569\n Hg, 200.592\n Tl, 204.38\n Pb, 207.2\n Bi, 208.9804\n Po, 209\n At, 210\n Rn, 222\n Fr, 223\n Ra, 226\n Ac, 227\n Pa, 231.03588\n Th, 232.0377\n Np, 237\n U, 238.02891\n Am, 243\n Pu, 244\n Cm, 247\n Bk, 247\n Cf, 251\n Es, 252\n Fm, 257\n Ubn, 299\n Uue, 315\n```\n\nExamples\n\n```\nassert 1.008 == molar_mass('H') # hydrogen\nassert 2.016 == molar_mass('H2') # hydrogen gas\nassert 18.015 == molar_mass('H2O') # water\nassert 34.014 == molar_mass('H2O2') # hydrogen peroxide\nassert 34.014 == molar_mass('(HO)2') # hydrogen peroxide\nassert 142.036 == molar_mass('Na2SO4') # sodium sulfate\nassert 84.162 == molar_mass('C6H12') # cyclohexane\nassert 186.295 == molar_mass('COOH(C(CH3)2)3CH3') # butyric or butanoic acid \nassert 176.124 == molar_mass('C6H4O2(OH)4') # vitamin C\nassert 386.664 == molar_mass('C27H46O') # cholesterol\nassert 315 == molar_mass('Uue') # ununennium\n\n```\n\nReference\n: * Wikipedia article:   Molecular mass" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy %ATOMIC_MASS =\n H => 1.008 , Fe => 55.845 , Te => 127.60 , Ir => 192.217 ,\n He => 4.002602 , Co => 58.933194 , I => 126.90447 , Pt => 195.084 ,\n Li => 6.94 , Ni => 58.6934 , Xe => 131.293 , Au => 196.966569 ,\n Be => 9.0121831 , Cu => 63.546 , Cs => 132.90545196 , Hg => 200.592 ,\n B => 10.81 , Zn => 65.38 , Ba => 137.327 , Tl => 204.38 ,\n C => 12.011 , Ga => 69.723 , La => 138.90547 , Pb => 207.2 ,\n N => 14.007 , Ge => 72.630 , Ce => 140.116 , Bi => 208.98040 ,\n O => 15.999 , As => 74.921595 , Pr => 140.90766 , Po => 209 ,\n F => 18.998403163 , Se => 78.971 , Nd => 144.242 , At => 210 ,\n Ne => 20.1797 , Br => 79.904 , Pm => 145 , Rn => 222 ,\n Na => 22.98976928 , Kr => 83.798 , Sm => 150.36 , Fr => 223 ,\n Mg => 24.305 , Rb => 85.4678 , Eu => 151.964 , Ra => 226 ,\n Al => 26.9815385 , Sr => 87.62 , Gd => 157.25 , Ac => 227 ,\n Si => 28.085 , Y => 88.90584 , Tb => 158.92535 , Th => 232.0377 ,\n P => 30.973761998 , Zr => 91.224 , Dy => 162.500 , Pa => 231.03588 ,\n S => 32.06 , Nb => 92.90637 , Ho => 164.93033 , U => 238.02891 ,\n Cl => 35.45 , Mo => 95.95 , Er => 167.259 , Np => 237 ,\n Ar => 39.948 , Ru => 101.07 , Tm => 168.93422 , Pu => 244 ,\n K => 39.0983 , Rh => 102.90550 , Yb => 173.054 , Am => 243 ,\n Ca => 40.078 , Pd => 106.42 , Lu => 174.9668 , Cm => 247 ,\n Sc => 44.955908 , Ag => 107.8682 , Hf => 178.49 , Bk => 247 ,\n Ti => 47.867 , Cd => 112.414 , Ta => 180.94788 , Cf => 251 ,\n V => 50.9415 , In => 114.818 , W => 183.84 , Es => 252 ,\n Cr => 51.9961 , Sn => 118.710 , Re => 186.207 , Fm => 257 ,\n Mn => 54.938044 , Sb => 121.760 , Os => 190.23 ,\n;\ngrammar Chemical_formula {\n my @ATOMIC_SYMBOLS = %ATOMIC_MASS.keys.sort;\n\n rule TOP { ^ (<lparen>|<rparen>|<element>)+ $ }\n token quantity { \\d+ }\n token lparen { '(' }\n token rparen { ')' <quantity>? }\n token element { $<e>=[@ATOMIC_SYMBOLS] <quantity>? }\n}\nclass Chemical_formula_actions {\n has @stack = 0;\n method TOP ($/) { $/.make: @stack }\n method lparen ($/) { push @stack, 0 }\n method rparen ($/) { my $m = @stack.pop;\n @stack[*-1] += ($<quantity> // 1) * $m }\n method element ($/) { @stack[*-1] += ($<quantity> // 1) * %ATOMIC_MASS{~$<e>} }\n}\nsub molar_mass ( Str $formula --> Real ) {\n Chemical_formula.parse( $formula, :actions(Chemical_formula_actions.new) )\n orelse die \"Chemical formula not recognized: '$formula'\";\n return $/.made.[0];\n}\nsay .&molar_mass.fmt('%7.3f '), $_ for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>;\n\n```\n\nOutput:\n\n```\n 1.008 H\n 2.016 H2\n 18.015 H2O\n142.036 Na2SO4\n 84.162 C6H12\n186.295 COOH(C(CH3)2)3CH3\n```" } ]
[ { "role": "user", "content": "In 1939, Jack Chernick proved that, for **n\n≥\n3\n{\\displaystyle {\\displaystyle n\\geq 3}}** and **m\n≥\n1\n{\\displaystyle {\\displaystyle m\\geq 1}}**:\n\n```\n \n \n \n \n \n \n U\n (\n n\n ,\n m\n )\n =\n (\n 6\n m\n +\n 1\n )\n (\n 12\n m\n +\n 1\n )\n \n ∏\n \n k\n =\n 1\n \n \n n\n −\n 2\n \n \n (\n \n 2\n \n k\n \n \n \n 9\n m\n +\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle U(n,m)=(6m+1)(12m+1)\\prod _{k=1}^{n-2}(2^{k}\\,9m+1)}}\n \n\n\n```\n\nis a Carmichael number if all the factors are primes and, for **n\n>\n4\n{\\displaystyle {\\displaystyle n>4}}**, **m\n{\\displaystyle {\\displaystyle m}}** is a multiple of **2\n\n(\nn\n−\n4\n)\n{\\displaystyle {\\displaystyle 2^{(n-4)}}}**.\n\nExample\n\n```\n \n \n \n \n \n \n U\n (\n 3\n ,\n m\n )\n =\n (\n 6\n m\n +\n 1\n )\n (\n 12\n m\n +\n 1\n )\n (\n 18\n m\n +\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle U(3,m)=(6m+1)(12m+1)(18m+1)}}\n \n\n \n \n \n \n \n \n U\n (\n 4\n ,\n m\n )\n =\n U\n (\n 3\n ,\n m\n )\n (\n \n 2\n \n 2\n \n \n 9\n m\n +\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle U(4,m)=U(3,m)(2^{2}9m+1)}}\n \n\n \n \n \n \n \n \n U\n (\n 5\n ,\n m\n )\n =\n U\n (\n 4\n ,\n m\n )\n (\n \n 2\n \n 3\n \n \n 9\n m\n +\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle U(5,m)=U(4,m)(2^{3}9m+1)}}\n \n\n \n \n \n \n \n \n ⋯\n \n \n \n \n {\\displaystyle {\\displaystyle \\cdots }}\n \n\n \n \n \n \n \n \n U\n (\n n\n ,\n m\n )\n =\n U\n (\n n\n −\n 1\n ,\n m\n )\n (\n \n 2\n \n (\n n\n −\n 2\n )\n \n \n 9\n m\n +\n 1\n )\n \n \n \n \n {\\displaystyle {\\displaystyle U(n,m)=U(n-1,m)(2^{(n-2)}9m+1)}}\n \n\n\n```\n\n* The smallest Chernick's Carmichael number with **3** prime factors, is: U(3, 1) = 1729.\n* The smallest Chernick's Carmichael number with **4** prime factors, is: U(4, 1) = 63973.\n* The smallest Chernick's Carmichael number with **5** prime factors, is: U(5, 380) = 26641259752490421121.\n\nFor **n = 5**, the smallest number **m** that satisfy Chernick's conditions, is **m = 380**, therefore **U(5, 380)** is the smallest Chernick's Carmichael number with **5** prime factors.\n\n**U(5, 380)** is a Chernick's Carmichael number because **m = 380** is a multiple of **2^(n-4)**, where **n = 5**, and the factors { (6\\*380 + 1), (12\\*380 + 1), (18\\*380 + 1), (36\\*380 + 1), (72\\*380 + 1) } are all prime numbers.\n\nTask\n\nFor **n ≥ 3**, let **a(n)** be the smallest Chernick's Carmichael number with **n** prime factors.\n\n* Compute **a(n)** for **n = 3..9**.\n* Optional: find **a(10)**.\n\n**Note**: it's perfectly acceptable to show the terms in factorized form:\n\n```\n a(3) = 7 * 13 * 19\n a(4) = 7 * 13 * 19 * 37\n a(5) = 2281 * 4561 * 6841 * 13681 * 27361\n ...\n\n```\n\nSee also\n\n* Jack Chernick, On Fermat's simple theorem (PDF), equation (8)\n\n* OEIS A318646: The least Chernick's \"universal form\" Carmichael number with n prime factors\n\nRelated tasks\n\n* Carmichael 3 strong pseudoprimes" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUse the ntheory library from Perl for primality testing since it is much, *much* faster than Raku's built-in .is-prime method.\n\n**Translation of**: Perl\n\n**Library:** ntheory\n\n```\nuse Inline::Perl5;\nuse ntheory:from<Perl5> <:all>;\n\nsub chernick-factors ($n, $m) {\n 6×$m + 1, 12×$m + 1, |((1 .. $n-2).map: { (1 +< $_) × 9×$m + 1 } )\n}\n\nsub chernick-carmichael-number ($n) {\n\n my $multiplier = 1 +< (($n-4) max 0);\n my $iterator = $n < 5 ?? (1 .. *) !! (1 .. *).map: * × 5;\n\n $multiplier × $iterator.first: -> $m {\n [&&] chernick-factors($n, $m × $multiplier).map: { is_prime($_) }\n }\n\n}\n\nfor 3 .. 9 -> $n {\n my $m = chernick-carmichael-number($n);\n my @f = chernick-factors($n, $m);\n say \"U($n, $m): {[×] @f} = {@f.join(' ⨉ ')}\";\n}\n\n```\n\nOutput:\n\n```\nU(3, 1): 1729 = 7 ⨉ 13 ⨉ 19\nU(4, 1): 63973 = 7 ⨉ 13 ⨉ 19 ⨉ 37\nU(5, 380): 26641259752490421121 = 2281 ⨉ 4561 ⨉ 6841 ⨉ 13681 ⨉ 27361\nU(6, 380): 1457836374916028334162241 = 2281 ⨉ 4561 ⨉ 6841 ⨉ 13681 ⨉ 27361 ⨉ 54721\nU(7, 780320): 24541683183872873851606952966798288052977151461406721 = 4681921 ⨉ 9363841 ⨉ 14045761 ⨉ 28091521 ⨉ 56183041 ⨉ 112366081 ⨉ 224732161\nU(8, 950560): 53487697914261966820654105730041031613370337776541835775672321 = 5703361 ⨉ 11406721 ⨉ 17110081 ⨉ 34220161 ⨉ 68440321 ⨉ 136880641 ⨉ 273761281 ⨉ 547522561\nU(9, 950560): 58571442634534443082821160508299574798027946748324125518533225605795841 = 5703361 ⨉ 11406721 ⨉ 17110081 ⨉ 34220161 ⨉ 68440321 ⨉ 136880641 ⨉ 273761281 ⨉ 547522561 ⨉ 1095045121\n```" } ]
[ { "role": "user", "content": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n\n```\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\n```\n\nCheryl then tells Albert the   *month*   of birth,   and Bernard the   *day*   (of the month)   of birth.\n\n```\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n```\n\nTask\n\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\nRelated task\n\n* Sum and Product Puzzle\n\nReferences\n\n* Wikipedia article of the same name.\n* Tuple Relational Calculus" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @dates =\n { :15day, :5month },\n { :16day, :5month },\n { :19day, :5month },\n { :17day, :6month },\n { :18day, :6month },\n { :14day, :7month },\n { :16day, :7month },\n { :14day, :8month },\n { :15day, :8month },\n { :17day, :8month }\n;\n\n# Month can't have a unique day\nmy @filtered = @dates.grep(*.<month> != one(@dates.grep(*.<day> == one(@dates».<day>))».<month>));\n\n# Day must be unique and unambiguous in remaining months\nmy $birthday = @filtered.grep(*.<day> == one(@filtered».<day>)).classify({.<month>})\\\n .first(*.value.elems == 1).value[0];\n\n# convenience array\nmy @months = <'' January February March April May June July August September October November December>;\n\nsay \"Cheryl's birthday is { @months[$birthday<month>] } {$birthday<day>}.\";\n\n```\n\nOutput:\n\n```\nCheryl's birthday is July 16.\n```" } ]
[ { "role": "user", "content": "Suppose   \n\nn\n\n1\n{\\displaystyle {\\displaystyle n\\_{1}}}\n,   \n\nn\n\n2\n{\\displaystyle {\\displaystyle n\\_{2}}}\n,   \n\n…\n{\\displaystyle {\\displaystyle \\ldots }}\n,   \n\nn\n\nk\n{\\displaystyle {\\displaystyle n\\_{k}}}\n   are positive integers that are pairwise co-prime.\n\nThen, for any given sequence of integers   \n\na\n\n1\n{\\displaystyle {\\displaystyle a\\_{1}}}\n,   \n\na\n\n2\n{\\displaystyle {\\displaystyle a\\_{2}}}\n,   \n\n…\n{\\displaystyle {\\displaystyle \\dots }}\n,   \n\na\n\nk\n{\\displaystyle {\\displaystyle a\\_{k}}}\n,   there exists an integer   \n\nx\n{\\displaystyle {\\displaystyle x}}\n   solving the following system of simultaneous congruences:\n\n: : : x\n\n\n ≡\n\n a\n\n 1\n\n\n (\n mod\n\n\n n\n\n 1\n )\n\n\n x\n\n\n ≡\n\n a\n\n 2\n\n\n (\n mod\n\n\n n\n\n 2\n )\n\n  \n  \n ⋮\n\n\n x\n\n\n ≡\n\n a\n\n k\n\n\n (\n mod\n\n\n n\n\n k\n )\n {\\displaystyle {\\displaystyle {\\begin{aligned}x&\\equiv a\\_{1}{\\pmod {n\\_{1}}}\\\\x&\\equiv a\\_{2}{\\pmod {n\\_{2}}}\\\\&{}\\ \\ \\vdots \\\\x&\\equiv a\\_{k}{\\pmod {n\\_{k}}}\\end{aligned}}}}\n\nFurthermore, all solutions   \n\nx\n{\\displaystyle {\\displaystyle x}}\n   of this system are congruent modulo the product,   \n\nN\n=\n\nn\n\n1\n\nn\n\n2\n…\n\nn\n\nk\n{\\displaystyle {\\displaystyle N=n\\_{1}n\\_{2}\\ldots n\\_{k}}}\n.\n\nTask\n\nWrite a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem.\n\nIf the system of equations cannot be solved, your program must somehow indicate this.\n\n(It may throw an exception or return a special false value.)\n\nSince there are infinitely many solutions, the program should return the unique solution   \n\ns\n{\\displaystyle {\\displaystyle s}}\n   where   \n\n0\n≤\ns\n≤\n\nn\n\n1\n\nn\n\n2\n…\n\nn\n\nk\n{\\displaystyle {\\displaystyle 0\\leq s\\leq n\\_{1}n\\_{2}\\ldots n\\_{k}}}\n.\n\n*Show the functionality of this program* by printing the result such that the   \n\nn\n{\\displaystyle {\\displaystyle n}}\n's   are   \n\n[\n3\n,\n5\n,\n7\n]\n{\\displaystyle {\\displaystyle [3,5,7]}}\n   and the   \n\na\n{\\displaystyle {\\displaystyle a}}\n's   are   \n\n[\n2\n,\n3\n,\n2\n]\n{\\displaystyle {\\displaystyle [2,3,2]}}\n.\n\n**Algorithm**:   The following algorithm only applies if the   \n\nn\n\ni\n{\\displaystyle {\\displaystyle n\\_{i}}}\n's   are pairwise co-prime.\n\nSuppose, as above, that a solution is required for the system of congruences:\n\n: : : x\n ≡\n\n a\n\n i\n\n\n (\n mod\n\n\n n\n\n i\n )\n\n\n f\n o\n r\n\n i\n =\n 1\n ,\n …\n ,\n k\n {\\displaystyle {\\displaystyle x\\equiv a\\_{i}{\\pmod {n\\_{i}}}\\quad \\mathrm {for} \\;i=1,\\ldots ,k}}\n\nAgain, to begin, the product   \n\nN\n=\n\nn\n\n1\n\nn\n\n2\n…\n\nn\n\nk\n{\\displaystyle {\\displaystyle N=n\\_{1}n\\_{2}\\ldots n\\_{k}}}\n   is defined.\n\nThen a solution   \n\nx\n{\\displaystyle {\\displaystyle x}}\n   can be found as follows:\n\nFor each   \n\ni\n{\\displaystyle {\\displaystyle i}}\n,   the integers   \n\nn\n\ni\n{\\displaystyle {\\displaystyle n\\_{i}}}\n   and   \n\nN\n\n/\n\nn\n\ni\n{\\displaystyle {\\displaystyle N/n\\_{i}}}\n   are co-prime.\n\nUsing the   Extended Euclidean algorithm,   we can find integers   \n\nr\n\ni\n{\\displaystyle {\\displaystyle r\\_{i}}}\n   and   \n\ns\n\ni\n{\\displaystyle {\\displaystyle s\\_{i}}}\n   such that   \n\nr\n\ni\n\nn\n\ni\n+\n\ns\n\ni\nN\n\n/\n\nn\n\ni\n=\n1\n{\\displaystyle {\\displaystyle r\\_{i}n\\_{i}+s\\_{i}N/n\\_{i}=1}}\n.\n\nThen, one solution to the system of simultaneous congruences is:\n\n: : : x\n =\n\n ∑\n\n i\n =\n 1\n\n k\n\n a\n\n i\n\n s\n\n i\n N\n\n /\n\n n\n\n i\n {\\displaystyle {\\displaystyle x=\\sum \\_{i=1}^{k}a\\_{i}s\\_{i}N/n\\_{i}}}\n\nand the minimal solution,\n\n: : : x\n\n\n (\n mod\n\n N\n )\n {\\displaystyle {\\displaystyle x{\\pmod {N}}}}\n ." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: C\n\n**Works with**: Rakudo version 2015.12\n\n```\n# returns x where (a * x) % b == 1\nsub mul-inv($a is copy, $b is copy) {\n return 1 if $b == 1;\n my ($b0, @x) = $b, 0, 1;\n ($a, $b, @x) = (\n\t$b,\n\t$a % $b,\n\t@x[1] - ($a div $b)*@x[0],\n\t@x[0]\n ) while $a > 1;\n @x[1] += $b0 if @x[1] < 0;\n return @x[1];\n}\n\nsub chinese-remainder(*@n) {\n my \\N = [*] @n;\n -> *@a {\n\tN R% [+] map {\n\t my \\p = N div @n[$_];\n\t @a[$_] * mul-inv(p, @n[$_]) * p\n\t}, ^@n\n }\n}\n\nsay chinese-remainder(3, 5, 7)(2, 3, 2);\n\n```\n\nOutput:\n\n```\n23\n```" } ]
[ { "role": "user", "content": "Determine the Chinese zodiac sign and related associations for a given year.\n\nIn the Chinese calendar, years are identified using two lists of labels, one of length 10 – the \"celestial\" (or \"heavenly\") \"stems\" – and one of length 12 – the \"terrestrial\" (or \"earthly\") \"branches\". The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. However, since both lists are of even length, only like-parity pairs occur (A1, A3, A5, but not A2, A4, A6), so only half of the 120 possible pairs are included in the sequence. The result is a repeating 60-year pattern within which each name pair occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Wednesday, January 29, 2025 CE (in the common Gregorian calendar) begins the lunisolar Year of the Snake.\n\nThe stems do not have a one-to-one mapping like that of the branches to animals; however, the five *pairs* of consecutive stems are each associated with one of the traditional *wǔxíng* elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to *yin*, the other to *yang*.\n\nThus, the Chinese year beginning in 2025 CE is also the yin year of Wood. Since 12 is an even number, the association between animals and yin/yang aspect doesn't change; consecutive Years of the Snake will cycle through the five elements, but will always be yin.\n\nTask\n: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\nRequisite information\n\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.\n* Each element gets two consecutive years; a yang followed by a yin.\n* The first year (Wood Rat, yang) of the current 60-year cycle began in 1984 CE.\n\nThe lunisolar year beginning in 2025 CE - which, as already noted, is the year of the Wood Snake (yin) - is the 42nd of the current cycle.\n\nInformation for optional task\n\n* The ten celestial stems are **甲** *jiă*, **乙** *yĭ*, **丙** *bĭng*, **丁** *dīng*, **戊** *wù*, **己** *jĭ*, **庚** *gēng*, **辛** *xīn*, **壬** *rén*, and **癸** *gŭi*. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are **子** *zĭ*, **丑** *chŏu*, **寅** *yín*, **卯** *măo*, **辰** *chén*, **巳** *sì*, **午** *wŭ*, **未** *wèi*, **申** *shēn*, **酉** *yŏu*, **戌** *xū*, **亥** *hài*. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was **甲子** (*jiă-zĭ*, or jia3-zi3), while 2025 is **乙巳** (*yĭ-sì* or yi3-si4)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.01\n\n**Translation of**: Ruby\n\n```\nsub Chinese-zodiac ( Int $year ) {\n my @heaven = <甲 jiă 乙 yĭ 丙 bĭng 丁 dīng 戊 wù 己 jĭ 庚 gēng 辛 xīn 壬 rén 癸 gŭi>.pairup;\n my @earth = <子 zĭ 丑 chŏu 寅 yín 卯 măo 辰 chén 巳 sì 午 wŭ 未 wèi 申 shēn 酉 yŏu 戌 xū 亥 hài>.pairup;\n my @animal = <Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig>;\n my @element = <Wood Fire Earth Metal Water>;\n my @aspect = <yang yin>;\n\n my $cycle_year = ($year - 4) % 60;\n my $i2 = $cycle_year % 2;\n my $i10 = $cycle_year % 10;\n my $i12 = $cycle_year % 12;\n\n  %(\n 'Han' => @heaven[$i10].key ~ @earth[$i12].key,\n 'pinyin' => @heaven[$i10].value ~ @earth[$i12].value,\n 'heaven' => @heaven[$i10],\n 'earth' => @earth[$i12],\n 'element' => @element[$i10 div 2],\n 'animal' => @animal[$i12],\n 'aspect' => @aspect[$i2],\n 'cycle' => $cycle_year + 1\n )\n}\n\n# TESTING\nprintf \"%d: %s (%s, %s %s; %s - year %d in the cycle)\\n\",\n $_, .&Chinese-zodiac<Han pinyin element animal aspect cycle>\n for 1935, 1938, 1968, 1972, 1976, 1984, Date.today.year;\n\n```\n\nOutput:\n\n```\n1935: 乙亥 (yĭhài, Wood Pig; yin - year 12 in the cycle)\n1938: 戊寅 (wùyín, Earth Tiger; yang - year 15 in the cycle)\n1968: 戊申 (wùshēn, Earth Monkey; yang - year 45 in the cycle)\n1972: 壬子 (rénzĭ, Water Rat; yang - year 49 in the cycle)\n1976: 丙辰 (bĭngchén, Fire Dragon; yang - year 53 in the cycle)\n1984: 甲子 (jiăzĭ, Wood Rat; yang - year 1 in the cycle)\n2017: 丁酉 (dīngyŏu, Fire Rooster; yin - year 34 in the cycle)\n```" } ]
[ { "role": "user", "content": "Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:\n\n: A\n =\n L\n\n L\n\n T\n {\\displaystyle {\\displaystyle A=LL^{T}}}\n\nL\n{\\displaystyle {\\displaystyle L}}\n is called the *Cholesky factor* of \n\nA\n{\\displaystyle {\\displaystyle A}}\n, and can be interpreted as a generalized square root of \n\nA\n{\\displaystyle {\\displaystyle A}}\n, as described in Cholesky decomposition.\n\nIn a 3x3 example, we have to solve the following system of equations:\n\n: A\n\n\n =\n\n\n (\n\n a\n\n 11\n\n\n a\n\n 21\n\n\n a\n\n 31\n\n a\n\n 21\n\n\n a\n\n 22\n\n\n a\n\n 32\n\n a\n\n 31\n\n\n a\n\n 32\n\n\n a\n\n 33\n )\n\n =\n\n\n (\n\n l\n\n 11\n\n 0\n\n 0\n\n l\n\n 21\n\n\n l\n\n 22\n\n 0\n\n l\n\n 31\n\n\n l\n\n 32\n\n\n l\n\n 33\n )\n\n\n (\n\n l\n\n 11\n\n\n l\n\n 21\n\n\n l\n\n 31\n\n\n 0\n\n\n l\n\n 22\n\n\n l\n\n 32\n\n\n 0\n\n 0\n\n\n l\n\n 33\n )\n ≡\n L\n\n L\n\n T\n\n =\n\n\n (\n\n l\n\n 11\n\n 2\n\n\n l\n\n 21\n\n l\n\n 11\n\n\n l\n\n 31\n\n l\n\n 11\n\n l\n\n 21\n\n l\n\n 11\n\n\n l\n\n 21\n\n 2\n +\n\n l\n\n 22\n\n 2\n\n\n l\n\n 31\n\n l\n\n 21\n +\n\n l\n\n 32\n\n l\n\n 22\n\n l\n\n 31\n\n l\n\n 11\n\n\n l\n\n 31\n\n l\n\n 21\n +\n\n l\n\n 32\n\n l\n\n 22\n\n\n l\n\n 31\n\n 2\n +\n\n l\n\n 32\n\n 2\n +\n\n l\n\n 33\n\n 2\n )\n {\\displaystyle {\\displaystyle {\\begin{aligned}A&={\\begin{pmatrix}a\\_{11}&a\\_{21}&a\\_{31}\\\\a\\_{21}&a\\_{22}&a\\_{32}\\\\a\\_{31}&a\\_{32}&a\\_{33}\\\\\\end{pmatrix}}\\\\&={\\begin{pmatrix}l\\_{11}&0&0\\\\l\\_{21}&l\\_{22}&0\\\\l\\_{31}&l\\_{32}&l\\_{33}\\\\\\end{pmatrix}}{\\begin{pmatrix}l\\_{11}&l\\_{21}&l\\_{31}\\\\0&l\\_{22}&l\\_{32}\\\\0&0&l\\_{33}\\end{pmatrix}}\\equiv LL^{T}\\\\&={\\begin{pmatrix}l\\_{11}^{2}&l\\_{21}l\\_{11}&l\\_{31}l\\_{11}\\\\l\\_{21}l\\_{11}&l\\_{21}^{2}+l\\_{22}^{2}&l\\_{31}l\\_{21}+l\\_{32}l\\_{22}\\\\l\\_{31}l\\_{11}&l\\_{31}l\\_{21}+l\\_{32}l\\_{22}&l\\_{31}^{2}+l\\_{32}^{2}+l\\_{33}^{2}\\end{pmatrix}}\\end{aligned}}}}\n\nWe can see that for the diagonal elements (\n\nl\n\nk\nk\n{\\displaystyle {\\displaystyle l\\_{kk}}}\n) of \n\nL\n{\\displaystyle {\\displaystyle L}}\n there is a calculation pattern:\n\n: l\n\n 11\n =\n\n a\n\n 11\n {\\displaystyle {\\displaystyle l\\_{11}={\\sqrt {a\\_{11}}}}}\n: l\n\n 22\n =\n\n a\n\n 22\n −\n\n l\n\n 21\n\n 2\n {\\displaystyle {\\displaystyle l\\_{22}={\\sqrt {a\\_{22}-l\\_{21}^{2}}}}}\n: l\n\n 33\n =\n\n a\n\n 33\n −\n (\n\n l\n\n 31\n\n 2\n +\n\n l\n\n 32\n\n 2\n )\n {\\displaystyle {\\displaystyle l\\_{33}={\\sqrt {a\\_{33}-(l\\_{31}^{2}+l\\_{32}^{2})}}}}\n\nor in general:\n\n: l\n\n k\n k\n =\n\n a\n\n k\n k\n −\n\n ∑\n\n j\n =\n 1\n\n k\n −\n 1\n\n l\n\n k\n j\n\n 2\n {\\displaystyle {\\displaystyle l\\_{kk}={\\sqrt {a\\_{kk}-\\sum \\_{j=1}^{k-1}l\\_{kj}^{2}}}}}\n\nFor the elements below the diagonal (\n\nl\n\ni\nk\n{\\displaystyle {\\displaystyle l\\_{ik}}}\n, where \n\ni\n>\nk\n{\\displaystyle {\\displaystyle i>k}}\n) there is also a calculation pattern:\n\n: l\n\n 21\n =\n\n\n 1\n\n l\n\n 11\n\n a\n\n 21\n {\\displaystyle {\\displaystyle l\\_{21}={\\frac {1}{l\\_{11}}}a\\_{21}}}\n: l\n\n 31\n =\n\n\n 1\n\n l\n\n 11\n\n a\n\n 31\n {\\displaystyle {\\displaystyle l\\_{31}={\\frac {1}{l\\_{11}}}a\\_{31}}}\n: l\n\n 32\n =\n\n\n 1\n\n l\n\n 22\n (\n\n a\n\n 32\n −\n\n l\n\n 31\n\n l\n\n 21\n )\n {\\displaystyle {\\displaystyle l\\_{32}={\\frac {1}{l\\_{22}}}(a\\_{32}-l\\_{31}l\\_{21})}}\n\nwhich can also be expressed in a general formula:\n\n: l\n\n i\n k\n =\n\n\n 1\n\n l\n\n k\n k\n\n (\n\n\n a\n\n i\n k\n −\n\n ∑\n\n j\n =\n 1\n\n k\n −\n 1\n\n l\n\n i\n j\n\n l\n\n k\n j\n )\n {\\displaystyle {\\displaystyle l\\_{ik}={\\frac {1}{l\\_{kk}}}\\left(a\\_{ik}-\\sum \\_{j=1}^{k-1}l\\_{ij}l\\_{kj}\\right)}}\n\n**Task description**\n\nThe task is to implement a routine which will return a lower Cholesky factor \n\nL\n{\\displaystyle {\\displaystyle L}}\n for every given symmetric, positive definite nxn matrix \n\nA\n{\\displaystyle {\\displaystyle A}}\n. You should then test it on the following two examples and include your output.\n\nExample 1:\n\n```\n25 15 -5 5 0 0\n15 18 0 --> 3 3 0\n-5 0 11 -1 1 3\n\n```\n\nExample 2:\n\n```\n18 22 54 42 4.24264 0.00000 0.00000 0.00000\n22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000\n54 86 174 134 12.72792 3.04604 1.64974 0.00000\n42 62 134 106 9.89949 1.62455 1.84971 1.39262\n\n```\n\nNote\n\n1. The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.\n2. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub cholesky(@A) {\n my @L = @A »×» 0;\n for ^@A -> \\i {\n for 0..i -> \\j {\n @L[i;j] = (i == j ?? &sqrt !! 1/@L[j;j] × * )\\ # select function\n (@A[i;j] - [+] (@L[i;*] Z× @L[j;*])[^j]) # provide value\n }\n }\n @L\n}\n\n.fmt('%3d').say for cholesky [\n [25],\n [15, 18],\n [-5, 0, 11],\n];\n\nsay '';\n\n.fmt('%6.3f').say for cholesky [\n [18, 22, 54, 42], \n [22, 70, 86, 62],\n [54, 86, 174, 134], \n [42, 62, 134, 106],\n];\n\n```\n\nOutput:\n\n```\n 5\n 3 3\n -1 1 3\n\n 4.243 0.000 0.000 0.000\n 5.185 6.566 0.000 0.000\n12.728 3.046 1.650 0.000\n 9.899 1.625 1.850 1.393\n```" } ]
[ { "role": "user", "content": "Chowla numbers are also known as:\n\n: : * Chowla's function\n * chowla numbers\n * the chowla function\n * the chowla number\n * the chowla sequence\n\nThe chowla number of   **n**   is   (as defined by Chowla's function):\n\n: : * the sum of the divisors of   **n**     excluding unity and   **n**\n * where   **n**   is a positive integer\n\nThe sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995),\n \na London born Indian American mathematician specializing in *number theory*.\n\nGerman mathematician Carl Friedrich Gauss (1777─1855) said:\n\n```\n \"Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics\".\n\n```\n\nDefinitions\n\nChowla numbers can also be expressed as:\n\n```\n \n chowla(n) = sum of divisors of n excluding unity and n\n chowla(n) = sum( divisors(n)) - 1 - n \n chowla(n) = sum( properDivisors(n)) - 1 \n chowla(n) = sum(aliquotDivisors(n)) - 1 \n chowla(n) = aliquot(n) - 1 \n chowla(n) = sigma(n) - 1 - n \n chowla(n) = sigmaProperDivisiors(n) - 1 \n \n chowla(a*b) = a + b,   if a and b are distinct primes\n if chowla(n) = 0,  and n > 1, then n is prime\n if chowla(n) = n - 1, and n > 1, then n is a perfect number\n \n\n```\n\nTask\n: : * create a   **chowla**   function that returns the   **chowla number**   for a positive integer   **n**\n * Find and display   (1 per line)   for the 1st   **37**   integers:\n\n : : * the integer   (the index)\n * the chowla number for that integer\n\n * For finding primes, use the   **chowla**   function to find values of zero\n * Find and display the   *count*   of the primes up to              **100**\n * Find and display the   *count*   of the primes up to           **1,000**\n * Find and display the   *count*   of the primes up to         **10,000**\n * Find and display the   *count*   of the primes up to       **100,000**\n * Find and display the   *count*   of the primes up to    **1,000,000**\n * Find and display the   *count*   of the primes up to  **10,000,000**\n * For finding perfect numbers, use the   **chowla**   function to find values of   **n - 1**\n * Find and display all   perfect numbers   up to   **35,000,000**\n * use commas within appropriate numbers\n * show all output here\n\nRelated tasks\n: * totient function\n * perfect numbers\n * Proper divisors\n * Sieve of Eratosthenes\n\nSee also\n: * the OEIS entry for   A48050 Chowla's function." }, { "role": "assistant", "content": "(formerly Perl 6)\nMuch like in the Totient function task, we are using a thing poorly suited to finding prime numbers, to find large quantities of prime numbers.\n\n: : : (From the task's author):   the object is not in the   *finding*   of prime numbers,   but in   *verifying*   that the Chowla function operates correctly   (and **can be** used for such a purpose, whatever the efficacy).   These types of comments belong in the *discussion* page.   Whether or not this function is poorly suited for finding prime numbers (or anything else) is not part of this task's purpose or objective.\n\n(For a more reasonable test, reduce the orders-of-magnitude range in the \"Primes count\" line from 2..7 to 2..5)\n\n```\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nsub schnitzel (\\Radda, \\radDA = 0) {\n Radda.is-prime ?? !Radda !! ?radDA ?? Radda\n  !! sum flat (2 .. Radda.sqrt.floor).map: -> \\RAdda {\n my \\RADDA = Radda div RAdda;\n next if RADDA * RAdda !== Radda;\n RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA\n }\n}\n\nmy \\chowder = cache (1..Inf).hyper(:8degree).grep( !*.&schnitzel: 'panini' );\n\nmy \\mung-daal = lazy gather for chowder -> \\panini {\n my \\gazpacho = 2**panini - 1;\n take gazpacho * 2**(panini - 1) unless schnitzel gazpacho, panini;\n}\n\nprintf \"chowla(%2d) = %2d\\n\", $_, .&schnitzel for 1..37;\n\nsay '';\n\nprintf \"Count of primes up to %10s: %s\\n\", comma(10**$_),\n comma chowder.first( * > 10**$_, :k) for 2..7;\n\nsay \"\\nPerfect numbers less than 35,000,000\";\n\n.&comma.say for mung-daal[^5];\n\n```\n\nOutput:\n\n```\nchowla( 1) = 0\nchowla( 2) = 0\nchowla( 3) = 0\nchowla( 4) = 2\nchowla( 5) = 0\nchowla( 6) = 5\nchowla( 7) = 0\nchowla( 8) = 6\nchowla( 9) = 3\nchowla(10) = 7\nchowla(11) = 0\nchowla(12) = 15\nchowla(13) = 0\nchowla(14) = 9\nchowla(15) = 8\nchowla(16) = 14\nchowla(17) = 0\nchowla(18) = 20\nchowla(19) = 0\nchowla(20) = 21\nchowla(21) = 10\nchowla(22) = 13\nchowla(23) = 0\nchowla(24) = 35\nchowla(25) = 5\nchowla(26) = 15\nchowla(27) = 12\nchowla(28) = 27\nchowla(29) = 0\nchowla(30) = 41\nchowla(31) = 0\nchowla(32) = 30\nchowla(33) = 14\nchowla(34) = 19\nchowla(35) = 12\nchowla(36) = 54\nchowla(37) = 0\n\nCount of primes up to 100: 25\nCount of primes up to 1,000: 168\nCount of primes up to 10,000: 1,229\nCount of primes up to 100,000: 9,592\nCount of primes up to 1,000,000: 78,498\nCount of primes up to 10,000,000: 664,579\n\nPerfect numbers less than 35,000,000\n6\n28\n496\n8,128\n33,550,336\n\n```" } ]
[ { "role": "user", "content": "Task\n\nIn the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.\n\n* **Church zero** always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.\n* **Church one** applies its first argument f just once to its second argument x, yielding **f(x)**\n* **Church two** applies its first argument f twice to its second argument x, yielding **f(f(x))**\n* and each successive Church numeral applies its first argument one additional time to its second argument, **f(f(f(x)))**, **f(f(f(f(x))))** ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.\n\nArithmetic operations on natural numbers can be similarly represented as functions on Church numerals.\n\nIn your language define:\n\n* Church Zero,\n* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),\n* functions for Addition, Multiplication and Exponentiation over Church numerals,\n* a function to convert integers to corresponding Church numerals,\n* and a function to convert Church numerals to corresponding integers.\n\nYou should:\n\n* Derive Church numerals three and four in terms of Church zero and a Church successor function.\n* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,\n* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,\n* convert each result back to an integer, and return it or print it to the console." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Traditional subs and sigils\n\n**Translation of**: Python\n\n```\nconstant $zero = sub (Code $f) {\n sub ( $x) { $x }}\n\nconstant $succ = sub (Code $n) {\n sub (Code $f) {\n sub ( $x) { $f($n($f)($x)) }}}\n\nconstant $add = sub (Code $n) {\n sub (Code $m) {\n sub (Code $f) {\n sub ( $x) { $m($f)($n($f)($x)) }}}}\n\nconstant $mult = sub (Code $n) {\n sub (Code $m) {\n sub (Code $f) {\n sub ( $x) { $m($n($f))($x) }}}}\n\nconstant $power = sub (Code $b) {\n sub (Code $e) { $e($b) }}\n\nsub to_int (Code $f) {\n sub countup (Int $i) { $i + 1 }\n return $f(&countup).(0)\n}\n\nsub from_int (Int $x) {\n multi sub countdown ( 0) { $zero }\n multi sub countdown (Int $i) { $succ( countdown($i - 1) ) }\n return countdown($x);\n}\n\nconstant $three = $succ($succ($succ($zero)));\nconstant $four = from_int(4);\n\nsay map &to_int,\n $add( $three )( $four ),\n $mult( $three )( $four ),\n $power( $four )( $three ),\n $power( $three )( $four ),\n;\n\n```\n\n### Arrow subs without sigils\n\n**Translation of**: Julia\n\n```\nmy \\zero = -> \\f { -> \\x { x }}\nmy \\succ = -> \\n { -> \\f { -> \\x { f.(n.(f)(x)) }}}\nmy \\add = -> \\n { -> \\m { -> \\f { -> \\x { m.(f)(n.(f)(x)) }}}}\nmy \\mult = -> \\n { -> \\m { -> \\f { -> \\x { m.(n.(f))(x) }}}}\nmy \\power = -> \\b { -> \\e { e.(b) }}\n\nmy \\to_int = -> \\f { f.( -> \\i { i + 1 } ).(0) }\nmy \\from_int = -> \\i { i == 0 ?? zero !! succ.( &?BLOCK(i - 1) ) }\n\nmy \\three = succ.(succ.(succ.(zero)));\nmy \\four = from_int.(4);\n\nsay map -> \\f { to_int.(f) },\n add.( three )( four ),\n mult.( three )( four ),\n power.( four )( three ),\n power.( three )( four ),\n;\n\n```\n\nOutput:\n\n```\n(7 12 64 81)\n```" } ]
[ { "role": "user", "content": "**Cipolla's algorithm**\n\nSolve **x² ≡ n (mod p)**\n\nIn computational number theory, Cipolla's algorithm is a technique for solving an equation of the form **x² ≡ n (mod p)**, where p is an odd prime and x ,n ∊ Fp = {0, 1, ... p-1}.\n\nTo apply the algorithm we need the Legendre symbol, and arithmetic in Fp².\n\nLegendre symbol\n\n* The Legendre symbol ( a | p) denotes the value of a ^ ((p-1)/2) (mod p)\n* (a | p) ≡ 1 if a is a square (mod p)\n* (a | p) ≡ -1 if a is not a square (mod p)\n* (a | p) ≡ 0 is a ≡ 0\n\nArithmetic in Fp²\n\nLet ω a symbol such as ω² is a member of Fp and not a square, x and y members of Fp. The set Fp² is defined as {x + ω y }. The subset { x + 0 ω} of Fp² is Fp. Fp² is somewhat equivalent to the field of complex number, with ω analoguous to i, and i² = -1 . Remembering that all operations are modulo p, addition, multiplication and exponentiation in Fp² are defined as :\n\n* (x1 + ω y1) + (x2 + ω y2) := (x1 + x2 + ω (y1 + y2))\n* (x1 + ω y1) \\* (x2 + ω y2) := (x1\\*x2 + y1\\*y2\\*ω²) + ω (x1\\*y2 + x2\\*y1)\n + (0 + ω) \\* (0 + ω) := (ω² + 0 ω) ≡ ω² in Fp\n* (x1 + ω y1) ^ n := (x + ω y) \\* (x + ω y) \\* ... ( n times) (1)\n\n**Algorithm pseudo-code**\n\n* Input : p an odd prime, and n ≠ 0 in Fp\n* Step 0. Check that n is indeed a square  : (n | p) must be ≡ 1\n* Step 1. Find, by trial and error, an a > 0 such as (a² - n) is **not** a square : (a²-n | p) must be ≡ -1.\n* Step 2. Let ω² = a² - n. Compute, in Fp2 : (a + ω) ^ ((p + 1)/2) (mod p)\n\nTo compute this step, use a pair of numbers, initially [a,1], and use repeated \"multiplication\" which is defined such that [c,d] times [e,f] is (mod p) [ c\\*c + ω²\\*f\\*f, d\\*e + c\\*f ].\n\n* Step 3. Check that the result is ≡ x + 0 \\* ω in Fp2, that is x in Fp.\n* Step 4. Output the two positive solutions, x and p - x (mod p).\n* Step 5. Check that x \\* x ≡ n (mod p)\n\n**Example** from Wikipedia\n\n```\nn := 10 , p := 13\nLegendre(10,13) → 1 // 10 is indeed a square\na := 2 // try\nω² := a*a - 10 // ≡ 7 ≡ -6\nLegendre (ω² , 13) → -1 // ok - not square\n(2 + ω) ^ 7 → 6 + 0 ω // by modular exponentiation (1)\n // 6 and (13 - 6) = 7 are solutions\n(6 * 6) % 13 → 10 // = n . Checked.\n\n```\n\n**Task**\n\nImplement the above.\n\nFind solutions (if any) for\n\n* n = 10 p = 13\n* n = 56 p = 101\n* n = 8218 p = 10007\n* n = 8219 p = 10007\n* n = 331575 p = 1000003\n\n**Extra credit**\n\n* n 665165880 p 1000000007\n* n 881398088036 p 1000000000039\n* n = 34035243914635549601583369544560650254325084643201 p = 10^50 + 151\n\nSee also:\n\n* Modular exponentiation\n* Tonelli-Shanks algorithm" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.10\n\n**Translation of**: Sidef\n\n```\n# Legendre operator (𝑛│𝑝)\nsub infix:<│> (Int \\𝑛, Int \\𝑝 where 𝑝.is-prime && (𝑝 != 2)) {\n given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) {\n when 0 { 0 }\n when 1 { 1 }\n default { -1 }\n }\n}\n\n# a coordinate in a Field of p elements\nclass Fp {\n has Int $.x;\n has Int $.y;\n}\n\nsub cipolla ( Int \\𝑛, Int \\𝑝 ) {\n note \"Invalid parameters ({𝑛}, {𝑝})\"\n and return Nil if (𝑛│𝑝) != 1;\n my $ω2;\n my $a = 0;\n loop {\n last if ($ω2 = ($a² - 𝑛) % 𝑝)│𝑝 < 0;\n $a++;\n }\n\n # define a local multiply operator for Field coordinates\n multi sub infix:<*> ( Fp $a, Fp $b ){\n Fp.new: :x(($a.x * $b.x + $a.y * $b.y * $ω2) % 𝑝),\n  :y(($a.x * $b.y + $b.x * $a.y)  % 𝑝)\n }\n\n my $r = Fp.new: :x(1),  :y(0);\n my $s = Fp.new: :x($a), :y(1);\n\n for (𝑝+1) +> 1, * +> 1 ... 1 {\n $r *= $s if $_ % 2;\n $s *= $s;\n }\n return Nil if $r.y;\n $r.x;\n}\n\nmy @tests = (\n (10, 13),\n (56, 101),\n (8218, 10007),\n (8219, 10007),\n (331575, 1000003),\n (665165880, 1000000007),\n (881398088036, 1000000000039),\n (34035243914635549601583369544560650254325084643201,\n 100000000000000000000000000000000000000000000000151)\n);\n\nfor @tests -> ($n, $p) {\n my $r = cipolla($n, $p);\n say $r ?? \"Roots of $n are ($r, {$p-$r}) mod $p\"\n  !! \"No solution for ($n, $p)\"\n}\n\n```\n\nOutput:\n\n```\nRoots of 10 are (6, 7) mod 13\nRoots of 56 are (37, 64) mod 101\nRoots of 8218 are (9872, 135) mod 10007\nInvalid parameters (8219, 10007)\nNo solution for (8219, 10007)\nRoots of 331575 are (855842, 144161) mod 1000003\nRoots of 665165880 are (475131702, 524868305) mod 1000000007\nRoots of 881398088036 are (791399408049, 208600591990) mod 1000000000039\nRoots of 34035243914635549601583369544560650254325084643201 are (82563118828090362261378993957450213573687113690751, 17436881171909637738621006042549786426312886309400) mod 100000000000000000000000000000000000000000000000151\n\n```" } ]
[ { "role": "user", "content": "2 circles with a given radius through 2 points in 2D space.\n\n2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points.\n\nExceptions\n\n1. r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n2. If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n3. If the points form a diameter then return two identical circles *or* return a single circle, according to which is the most natural mechanism for the implementation language.\n4. If the points are too far apart then no circles can be drawn.\n\nTask detail\n\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, *or some indication of special cases where two, possibly equal, circles cannot be returned*.\n* Show here the output for the following inputs:\n\n```\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n```\n\nRelated task\n\n* Total circles area.\n\nSee also\n\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\n```\nmulti sub circles (@A, @B where ([and] @A Z== @B), 0.0) { 'Degenerate point' }\nmulti sub circles (@A, @B where ([and] @A Z== @B), $) { 'Infinitely many share a point' }\nmulti sub circles (@A, @B, $radius) {\n my @middle = (@A Z+ @B) X/ 2;\n my @diff = @A Z- @B;\n my $q = sqrt [+] @diff X** 2;\n return 'Too far apart' if $q > $radius * 2;\n\n my @orth = -@diff[0], @diff[1] X* sqrt($radius ** 2 - ($q / 2) ** 2) / $q;\n return (@middle Z+ @orth), (@middle Z- @orth);\n}\n\nmy @input =\n ([0.1234, 0.9876], [0.8765, 0.2345], 2.0),\n ([0.0000, 2.0000], [0.0000, 0.0000], 1.0),\n ([0.1234, 0.9876], [0.1234, 0.9876], 2.0),\n ([0.1234, 0.9876], [0.8765, 0.2345], 0.5),\n ([0.1234, 0.9876], [0.1234, 0.9876], 0.0),\n  ;\n\nfor @input {\n say .list.raku, ': ', circles(|$_).join(' and ');\n}\n\n```\n\nOutput:\n\n```\n([0.1234, 0.9876], [0.8765, 0.2345], 2.0): 1.86311180165819 1.97421180165819 and -0.863211801658189 -0.752111801658189\n([0.0, 2.0], [0.0, 0.0], 1.0): 0 1 and 0 1\n([0.1234, 0.9876], [0.1234, 0.9876], 2.0): Infinitely many share a point\n([0.1234, 0.9876], [0.8765, 0.2345], 0.5): Too far apart\n([0.1234, 0.9876], [0.1234, 0.9876], 0.0): Degenerate point\n```\n\nAnother possibility is to use the Complex plane,\nfor it often makes calculations easier with plane geometry:\n\n```\nmulti sub circles ($a, $b where $a == $b, 0.0) { 'Degenerate point' }\nmulti sub circles ($a, $b where $a == $b, $) { 'Infinitely many share a point' }\nmulti sub circles ($a, $b, $r) {\n my $h = ($b - $a) / 2;\n my $l = sqrt($r**2 - $h.abs**2);\n return 'Too far apart' if $l.isNaN;\n return map { $a + $h + $l * $_ * $h / $h.abs }, i, -i;\n}\n\nmy @input =\n (0.1234 + 0.9876i, 0.8765 + 0.2345i, 2.0),\n (0.0000 + 2.0000i, 0.0000 + 0.0000i, 1.0),\n (0.1234 + 0.9876i, 0.1234 + 0.9876i, 2.0),\n (0.1234 + 0.9876i, 0.8765 + 0.2345i, 0.5),\n (0.1234 + 0.9876i, 0.1234 + 0.9876i, 0.0),\n  ;\n\nfor @input {\n say .join(', '), ': ', circles(|$_).join(' and ');\n}\n\n```\n\nOutput:\n\n```\n0.1234+0.9876i, 0.8765+0.2345i, 2: 1.86311180165819+1.97421180165819i and -0.863211801658189-0.752111801658189i\n0+2i, 0+0i, 1: 0+1i and 0+1i\n0.1234+0.9876i, 0.1234+0.9876i, 2: Infinitely many share a point\n0.1234+0.9876i, 0.8765+0.2345i, 0.5: Too far apart\n0.1234+0.9876i, 0.1234+0.9876i, 0: Degenerate point\n```" } ]
[ { "role": "user", "content": "Definitions\n\nA **circular prime** is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.\n\nFor example:\n**1193** is a circular prime, since **1931**, **9311** and **3119** are all also prime.\n\nNote that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So **13** is a circular prime, but **31** is not.\n\nA **repunit** (denoted by R) is a number whose base 10 representation contains only the digit **1**.\n\nFor example:\nR(2) = 11 and R(5) = 11111 are repunits.\n\nTask\n\n* Find the first 19 circular primes.\n\n* If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.\n\n* (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.\n\nSee also\n\n* Wikipedia article - Circular primes.\n* Wikipedia article - Repunit.\n* OEIS sequence A016114 - Circular primes." }, { "role": "assistant", "content": "Most of the repunit testing is relatively speedy using the ntheory library. The really slow ones are R(25031), at ~42 seconds and R(49081) at 922(!!) seconds.\n\n**Library:** ntheory\n\n```\nsub isCircular(\\n) {\n return False unless n.is-prime;\n my @circular = n.comb;\n return False if @circular.min < @circular[0];\n for 1 ..^ @circular -> $i {\n return False unless .is-prime and $_ >= n given @circular.rotate($i).join;\n }\n True\n}\n\nsay \"The first 19 circular primes are:\";\nsay ((2..*).hyper.grep: { isCircular $_ })[^19];\n\nsay \"\\nThe next 4 circular primes, in repunit format, are:\";\nloop ( my $i = 7, my $count = 0; $count < 4; $i++ ) {\n ++$count, say \"R($i)\" if (1 x $i).is-prime\n}\n\nuse ntheory:from<Perl5> qw[is_prime];\n\nsay \"\\nRepunit testing:\";\n\n(5003, 9887, 15073, 25031, 35317, 49081).map: {\n my $now = now;\n say \"R($_): Prime? \", ?is_prime(\"{1 x $_}\"), \" {(now - $now).fmt: '%.2f'}\"\n}\n\n```\n\nOutput:\n\n```\nThe first 19 circular primes are:\n(2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933)\n\nThe next 4 circular primes, in repunit format, are:\nR(19)\nR(23)\nR(317)\nR(1031)\n\nRepunit testing:\nR(5003): Prime? False 0.00\nR(9887): Prime? False 0.01\nR(15073): Prime? False 0.02\nR(25031): Prime? False 41.40\nR(35317): Prime? False 0.32\nR(49081): Prime? True 921.73\n```" } ]
[ { "role": "user", "content": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from **0** to **9999**.\n\nHow they work\n\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number **0**. Then, glyphs representing the digits **1** through **9** are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n: * The **upper-right** quadrant represents the **ones** place.\n * The **upper-left** quadrant represents the **tens** place.\n * The **lower-right** quadrant represents the **hundreds** place.\n * The **lower-left** quadrant represents the **thousands** place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [1]\n\nTask\n\n: * Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n: * Use the routine to show the following Cistercian numerals:\n\n: : * 0\n * 1\n * 20\n * 300\n * 4000\n * 5555\n * 6789\n * And a number of your choice!\n\nNotes\n\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.\n\nSee also\n\n: * **Numberphile - The Forgotten Number System**\n * **dcode.fr - Online Cistercian numeral converter**" }, { "role": "assistant", "content": "Handles 0 through 9999 only. No error trapping. If you feed it an unsupported number it will truncate to maximum 4 digits.\n\n```\nmy @line-segments = (0, 0, 0, 100),\n (0, 0, 35, 0), (0, 35, 35, 35), (0, 0, 35, 35), (0, 35, 35, 0), ( 35, 0, 35, 35),\n (0, 0,-35, 0), (0, 35,-35, 35), (0, 0,-35, 35), (0, 35,-35, 0), (-35, 0,-35, 35),\n (0,100, 35,100), (0, 65, 35, 65), (0,100, 35, 65), (0, 65, 35,100), ( 35, 65, 35,100),\n (0,100,-35,100), (0, 65,-35, 65), (0,100,-35, 65), (0, 65,-35,100), (-35, 65,-35,100);\n\nmy @components = map {@line-segments[$_]}, |((0, 5, 10, 15).map: -> $m {\n |((0,), (1,), (2,), (3,), (4,), (1,4), (5,), (1,5), (2,5), (1,2,5)).map: {$_ »+» $m}\n});\n\nmy $out = 'Cistercian-raku.svg'.IO.open(:w);\n\n$out.say: # insert header\nq|<svg width=\"875\" height=\"470\" style=\"stroke:black;\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"100%\" height=\"100%\" style=\"fill:white;\"/>|;\n\nmy $hs = 50; # horizontal spacing\nmy $vs = 25; # vertical spacing\n\nfor flat ^10, 20, 300, 4000, 5555, 6789, 9394, (^10000).pick(14) -> $cistercian {\n\n $out.say: |@components[0].map: { # draw zero / base vertical bar\n qq|<line x1=\"{.[0] + $hs}\" y1=\"{.[1] + $vs}\" x2=\"{.[2] + $hs}\" y2=\"{.[3] + $vs}\"/>|\n };\n\n my @orders-of-magnitude = $cistercian.polymod(10 xx *);\n\n for @orders-of-magnitude.kv -> $order, $value {\n next unless $value; # skip zeros, already drew zero bar\n last if $order > 3; # truncate too large integers\n\n # draw the component line segments\n $out.say: join \"\\n\", @components[$order * 10 + $value].map: {\n qq|<line x1=\"{.[0] + $hs}\" y1=\"{.[1] + $vs}\" x2=\"{.[2] + $hs}\" y2=\"{.[3] + $vs}\"/>|\n }\n }\n\n # insert the decimal number below\n $out.say: qq|<text x=\"{$hs - 5}\" y=\"{$vs + 120}\">{$cistercian}</text>|;\n\n if ++$ %% 10 { # next row\n $hs = -35;\n $vs += 150;\n }\n\n $hs += 85; # increment horizontal spacing\n\n\n}\n$out.say: q|</svg>|; # insert footer\n\n```\n\nOutput:" } ]
[ { "role": "user", "content": "In object-oriented programming **class** is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.\n\nThe first type T from the class T sometimes is called the **root type** of the class.\n\nA class of types itself, as a type, has the values and operations of its own.\nThe operations of are usually called **methods** of the root type.\nBoth operations and values are called polymorphic.\n\nA polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.\n\nThe action of choice the type-specific implementation of a polymorphic operation is called **dispatch**. Correspondingly, polymorphic operations are often called **dispatching** or **virtual**.\nOperations with multiple arguments and/or the results of the class are called **multi-methods**.\nA further generalization of is the operation with arguments and/or results from different classes.\n\n* single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation *x*.*f*() is used instead of mathematical *f*(*x*).\n* multiple-dispatch languages allow many arguments and/or results to control the dispatch.\n\nA polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.\nThis type is sometimes called **the most specific type** of a [polymorphic] value.\nThe type tag of the value is used in order to resolve the dispatch.\nThe set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.\n\nIn many OO languages\nthe type of the class of T and T itself are considered equivalent.\nIn some languages they are distinct (like in Ada).\nWhen class T and T are equivalent, there is no way to distinguish\npolymorphic and specific values.\n\nTask\n\nCreate a basic class with a method, a constructor, an instance variable and how to instantiate it." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nclass Camel { has Int $.humps = 1; }\n\nmy Camel $a .= new;\nsay $a.humps; # Automatically generated accessor method.\n\nmy Camel $b .= new: humps => 2;\nsay $b.humps;\n```\n\nA more complex example:\n\n```\nclass Butterfly {\n has Int $!age; # With the ! twigil, no public accessor method is generated\n has Str $.name;\n has Str $.color;\n has Bool $.wings;\n\n submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {\n # BUILD is called by bless. Its primary use is to to control\n # object initialization.\n $!wings = $!age > 1;\n }\n\n method flap() {\n say ($.wings\n  ?? 'Watch out for that hurricane!'\n  !! 'No wings to flap.');\n }\n}\n\nmy Butterfly $a .= new: age => 5;\nsay \"Name: {$a.name}, Color: {$a.color}\";\n$a.flap;\n\nmy Butterfly $b .= new(name => 'Osgood', age => 4);\nsay \"Name: {$b.name}, Color: {$b.color}\";\n$b.flap;\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Closest pair of points problem. 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\nProvide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   *planar*   case.\n\nThe straightforward solution is a   O(n2)   algorithm   (which we can call *brute-force algorithm*);   the pseudo-code (using indexes) could be simply:\n\n```\nbruteForceClosestPair of P(1), P(2), ... P(N)\nif N < 2 then\n return ∞\nelse\n minDistance ← |P(1) - P(2)|\n minPoints ← { P(1), P(2) }\n foreach i ∈ [1, N-1]\n foreach j ∈ [i+1, N]\n if |P(i) - P(j)| < minDistance then\n minDistance ← |P(i) - P(j)|\n minPoints ← { P(i), P(j) } \n endif\n endfor\n endfor\n return minDistance, minPoints\n endif\n\n```\n\nA better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(*n* log *n*);   a pseudo-code could be:\n\n```\nclosestPair of (xP, yP)\n where xP is P(1) .. P(N) sorted by x coordinate, and\n yP is P(1) .. P(N) sorted by y coordinate (ascending order)\nif N ≤ 3 then\n return closest points of xP using brute-force algorithm\nelse\n xL ← points of xP from 1 to ⌈N/2⌉\n xR ← points of xP from ⌈N/2⌉+1 to N\n xm ← xP(⌈N/2⌉)x\n yL ← { p ∈ yP : px ≤ xm }\n yR ← { p ∈ yP : px > xm }\n (dL, pairL) ← closestPair of (xL, yL)\n (dR, pairR) ← closestPair of (xR, yR)\n (dmin, pairMin) ← (dR, pairR)\n if dL < dR then\n (dmin, pairMin) ← (dL, pairL)\n endif\n yS ← { p ∈ yP : |xm - px| < dmin }\n nS ← number of points in yS\n (closest, closestPair) ← (dmin, pairMin)\n for i from 1 to nS - 1\n k ← i + 1\n while k ≤ nS and yS(k)y - yS(i)y < dmin\n if |yS(k) - yS(i)| < closest then\n (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})\n endif\n k ← k + 1\n endwhile\n endfor\n return closest, closestPair\nendif\n\n```\n\nReferences and further readings\n\n* Closest pair of points problem\n* Closest Pair (McGill)\n* Closest Pair (UCSB)\n* Closest pair (WUStL)\n* Closest pair (IUPUI)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl 5\n\nUsing concurrency, the 'simple' routine beats the (supposedly) more efficient one for all but the smallest sets of input.\n\n```\nsub MAIN ($N = 5000) {\n my @points = (^$N).map: { [rand × 20 - 10, rand × 20 - 10] }\n\n my @candidates = @points.sort(*.[0]).rotor( 10 => -2, :partial).race.map: { closest-pair-simple(@$_) }\n say 'simple ' ~ (@candidates.sort: *.[2]).head(1).gist;\n @candidates = @points.sort(*.[0]).rotor( 10 => -2, :partial).race.map: { closest-pair(@$_) }\n say 'real ' ~ (@candidates.sort: *.[2]).head(1).gist;\n}\n\nsub dist-squared(@a, @b) { (@a[0] - @b[0])² + (@a[1] - @b[1])² }\n\nsub closest-pair-simple(@points is copy) {\n return ∞ if @points < 2;\n my ($a, $b, $d) = |@points[0,1], dist-squared(|@points[0,1]);\n while @points {\n my \\p = pop @points;\n for @points -> \\l {\n ($a, $b, $d) = p, l, $_ if $_ < $d given dist-squared(p, l);\n }\n }\n $a, $b, $d.sqrt\n}\n\nsub closest-pair(@r) {\n closest-pair-real (@r.sort: *.[0]), (@r.sort: *.[1])\n}\n\nsub closest-pair-real(@rx, @ry) {\n return closest-pair-simple(@rx) if @rx ≤ 3;\n\n my \\N = @rx;\n my \\midx = ceiling(N/2) - 1;\n my @PL := @rx[ 0 .. midx];\n my @PR := @rx[midx+1 ..^ N ];\n my \\xm = @rx[midx;0];\n (.[0] ≤ xm ?? my @yR !! my @yL).push: @$_ for @ry;\n my (\\al, \\bl, \\dL) = closest-pair-real(@PL, @yR);\n my (\\ar, \\br, \\dR) = closest-pair-real(@PR, @yL);\n my ($w1, $w2, $closest) = dR < dL ?? (ar, br, dR) !! (al, bl, dL);\n my @yS = @ry.grep: { (xm - .[0]).abs < $closest }\n\n for 0 ..^ @yS -> \\i {\n for i+1 ..^ @yS -> \\k {\n next unless @yS[k;1] - @yS[i;1] < $closest;\n ($w1, $w2, $closest) = |@yS[k, i], $_ if $_ < $closest given dist-squared(|@yS[k, i]).sqrt;\n }\n }\n $w1, $w2, $closest\n}\n\n```\n\nOutput:\n\n```\nsimple (([-1.1560800527301716 -9.214015073077793] [-1.1570263876019649 -9.213340680530798] 0.0011620477602117762))\n real (([-1.1570263876019649 -9.213340680530798] [-1.1560800527301716 -9.214015073077793] 0.0011620477602117762))\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   ***i***   (you may choose to start   ***i***   from either   **0**   or   **1**),   when run, should return the square of the index,   that is,   ***i*** 2.\n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\nGoal\n\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.\n\nIn imperative languages, one would generally use a loop with a mutable counter variable.\n\nFor each function to maintain the correct number, it has to capture the *value* of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: Multiple distinct objects" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nAll blocks are anonymous closures in Raku, and parameters are lexicals, so it's easy to generate a list of them. We'll use a gather/take generator loop, and call the closures in random order, just to keep things interesting.\n\n```\nmy @c = gather for ^10 -> $i {\n take { $i * $i }\n}\n\n.().say for @c.pick(*); # call them in random order\n```\n\nOutput:\n\n```\n36\n64\n25\n1\n16\n0\n4\n9\n81\n49\n```\n\nOr equivalently, using a more functional notation:\n\n```\nsay .() for pick *, map -> $i { -> {$i * $i} }, ^10\n```" } ]
[ { "role": "user", "content": "First, show the shortest possible program that will emit the nine-character string “Code Golf”, without the quotation marks and without anything after the final “f”. Then show the shortest possible program that does the same thing but without itself containing any string or character literals, and without requiring any input or any environment variables or command-line arguments, though the name of the running program can be used.\n\nExtra credit: how big is the executable required to perform the first task? Skip details about any prior compilation steps that might be involved." }, { "role": "assistant", "content": "Not very interesting, as it's pretty much just standard, non-obscure Raku. The output string is so short, there isn't any easy way to golf it shorter than just printing it directly. 17 bytes.\n\n```\nprint <Code Golf>\n\n```\n\nOutput:\n\n```\nCode Golf\n```\n\nAssuming we can't use the string literal in the source, the shortest I've come up with is:\n\n```\nprint chrs 37,9,2,3,70,33,9,10,0 X+^102 # 39 chars, 39 bytes\n\n```\n\nTry it online!\n\n```\nprint chrs -3,㊶,㉚,㉛,-㊳,1,㊶,㊳,㉜X+㉎ # 33 Chars, 49 bytes\n\n```\n\nTry it online!\n\n```\nprint <Dpef!Hpmg>.ords».pred.chrs # 33 Chars, 34 bytes. Somewhat cheaty as it _does_ contain a string literal, but not the same literal as the output\n\n```\n\nSame output for each. Of course, to actually run any of that code you need the Raku compiler at 18.0Kb, the nqp vm interpreter at 17.9 Kb and the moar virtual machine at 17.9Kb. (Or the Java virtual machine, which is remarkably difficult to come up with a size for...)" } ]
[ { "role": "user", "content": "Some advanced applications, such as memory resident applications, daemons and memory demanding applications unload unrequired parts of the application during use (such as initialization code that will no longer be used again once the application is operational) to free up memory and resources. Demonstrate or explain how to unload an unused section of code from memory.\n\nNote that it is sufficient to flag the memory area as being available for reuse by the memory management system, without the need to demonstrate the zeroing of the bytes and performing a memory shuffle, unless such actions are required to free up the code segment.\n\nLanguages that do not have the facility to free up their code segment (such as scripting languages) can be omitted." }, { "role": "assistant", "content": "(formerly Perl 6)\nIn general, there is no specific mechanism to do a timely destruction of an object, be it code, data, variables, whatever. Raku does automatic garbage collection on objects that are no longer being used. Unlike Perl, from which Raku is loosely derived, it doesn't use reference counting to track when memory may be garbage collected as that tends to be very difficult to get correct and performant in multi-threaded applications. Rather it performs a \"reachability analysis\" to determine when objects can be evicted from memory and safely removed.\n\nRaku objects can provide a \"DESTROY\" method, but you cannot be sure when (if ever) it will be called. Raku tends to not be very memory frugal. If there is lots of memory to be had, it will cheerfully use lots of it. It gets more aggressive about conserving if memory is tight, but usually will trade memory for performance. If and when garbage collection *has* run, the freed memory is then available to to the general OS pool for any process to claim.\n\nThere are some specific details that will allow some finer control of garbage collection in special circumstances, but the average Raku programmer will not need to know about or deal with them." } ]
[ { "role": "user", "content": "Task\n\nCollect and sort square numbers in ascending order from three lists.\n \nlist[1] = [3,4,34,25,9,12,36,56,36]\n \nlist[2] = [2,8,81,169,34,55,76,49,7]\n \nlist[3] = [75,121,75,144,35,16,46,35]" }, { "role": "assistant", "content": "```\nmy $s = cache sort ( my $l = ( cache flat\n\n[3,4,34,25,9,12,36,56,36],\n[2,8,81,169,34,55,76,49,7],\n[75,121,75,144,35,16,46,35]\n\n)).grep: * ∈ cache {$++²}…*>$l.max;\n\nput 'Added - Sorted';\nput ' ' ~ $s.sum ~ ' ' ~ $s.gist;\n\n```\n\n```\nAdded - Sorted\n 690 (4 9 16 25 36 36 49 81 121 144 169)\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\nCollections are abstractions to represent sets of values.\n\nIn statically-typed languages, the values are typically of a common data type.\n\nTask\n\nCreate a collection, and add a few values to it.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nRaku has both mutable and immutable containers of various sorts. Here are some of the most common ones:\n\n### Mutable\n\n```\n# Array\nmy @array = 1,2,3;\[email protected]: 4,5,6;\n\n# Hash\nmy %hash = 'a' => 1, 'b' => 2;\n%hash<c d> = 3,4;\n%hash.push: 'e' => 5, 'f' => 6;\n\n# SetHash\nmy $s = SetHash.new: <a b c>;\n$s ∪= <d e f>;\n\n# BagHash\nmy $b = BagHash.new: <b a k l a v a>;\n$b ⊎= <a b c>;\n```\n\n### Immutable\n\n```\n# List\nmy @list := 1,2,3;\nmy @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists\n\n# Set\nmy $set = set <a b c>;\nmy $newset = $set ∪ <d e f>;\n\n# Bag\nmy $bag = bag <b a k l a v a>;\nmy $newbag = $bag ⊎ <b e e f>;\n```\n\n### Pair list (cons list)\n\n```\nmy $tail = d => e => f => Nil;\nmy $new = a => b => c => $tail;\n```\n\n### P6opaque object (immutable in structure)\n\n```\nclass Something { has $.foo; has $.bar };\nmy $obj = Something.new: foo => 1, bar => 2;\nmy $newobj = $obj but role { has $.baz = 3 } # anonymous mixin\n```" } ]
[ { "role": "user", "content": "## The CIE ΔE2000 color difference formula\n\nThe **ΔE2000 color difference formula** is a widely used metric for comparing two colors in the CIE 1976 color space. It enhances the earlier CIE76 algorithm by integrating additional perceptual factors, resulting in more accurate **color matching**.\n\n### Task\n\nGiven the first six values, obtain the results in column seven, accurate to 10 decimal places.\n\n| L1 | a1 | b1 | L2 | a2 | b2 | ΔE2000 |\n| --- | --- | --- | --- | --- | --- | --- |\n| 73.0 | 49.0 | 39.4 | 73.0 | 49.0 | 39.4 | 0.0 |\n| 30.0 | -41.0 | -119.1 | 30.0 | -41.0 | -119.0 | 0.0134319631 |\n| 79.0 | -117.0 | -100.4 | 79.5 | -117.0 | -100.0 | 0.3572501235 |\n| 15.0 | -55.0 | 6.7 | 14.0 | -55.0 | 7.0 | 0.6731711696 |\n| 83.0 | 98.0 | -59.5 | 85.2 | 98.0 | -59.5 | 1.4597018301 |\n| 59.0 | -11.0 | -95.0 | 56.3 | -11.0 | -95.0 | 2.4566352112 |\n| 74.0 | -1.0 | 68.6 | 81.0 | -1.0 | 69.0 | 4.9755487499 |\n| 46.4 | 125.0 | 6.0 | 40.0 | 125.0 | 6.0 | 5.8974138376 |\n| 18.0 | -5.0 | 68.0 | 20.0 | 5.0 | 82.0 | 6.8542258013 |\n| 35.5 | -99.0 | 109.0 | 25.0 | -99.0 | 109.0 | 8.1462591143 |\n| 59.0 | 77.0 | 41.5 | 63.3 | 77.0 | 12.4 | 13.1325726695 |\n| 40.0 | -92.0 | 7.7 | 58.0 | -92.0 | -8.0 | 19.1411733022 |\n| 49.0 | -9.0 | -74.5 | 51.1 | 31.0 | 16.0 | 48.1082375109 |\n| 88.0 | -124.0 | 56.0 | 97.0 | 62.0 | -28.0 | 63.9449872676 |\n| 98.0 | 75.7 | 11.0 | 3.0 | -62.0 | 11.0 | 126.5088270078 |\n\n* **L1 and L2** nominally ranges from 0 (white) to 100 (black)\n* **a1 and a2** are unbounded and commonly clamped to the range of -128 (green) to 127 (red)\n* **b1 and b2** are unbounded and commonly clamped to the range of -128 (blue) to 127 (yellow)" }, { "role": "assistant", "content": "**Translation of**: Go\n\n```\n# 20250609 Raku programming solution\n\nsub hypot(\\x, \\y) { sqrt(x² + y²) }\n\n# The classic CIE ΔE2000 implementation, which operates on two L*a*b* colors, and returns their difference.\nsub ciede_2000(\\L1, \\A1, \\B1, \\L2, \\A2, \\B2) {\n \n # Kl, Kc, Kh are parametric factors to be adjusted according to\n # different viewing parameters such as textures, backgrounds...\n my (\\Kl, \\Kc, \\Kh) = 1.0 xx 3; \n\n my $n = ((hypot(A1, B1) + hypot(A2, B2)) * 0.5)⁷;\n $n = 1.0 + 0.5 * (1.0 - sqrt($n / ($n + 6103515625.0)));\n \n # hypot calculates the Euclidean distance while avoiding overflow/underflow.\n my (\\C1, \\C2) = ( [A1 * $n, B1], [A2 * $n, B2] ).map: { hypot |$_ }; \n\n # atan2 is preferred over atan because it accurately computes the angle of\n # a point (x, y) in all quadrants, handling the signs of both coordinates.\n my \\H1 = $ = atan2(B1, A1 * $n);\n my \\H2 = $ = atan2(B2, A2 * $n);\n\n if H1 < 0.0 { H1 += 2.0 * π }\n if H2 < 0.0 { H2 += 2.0 * π }\n \n $n = abs(H2 - H1);\n \n # Cross-implementation consistent rounding.\n $n = π if π - 1e-14 < $n && $n < π + 1e-14; \n \n # When the hue angles lie in different quadrants, the straightforward\n # average can produce a mean that incorrectly suggests a hue angle in\n # the wrong quadrant, the next lines handle this issue.\n my \\Hm = $ = (H1 + H2) * 0.5;\n my \\Hd = $ = (H2 - H1) * 0.5;\n \n if π < $n {\n 0.0 < Hd ?? ( Hd -= π ) !! Hd += π;\n Hm += π;\n }\n \n my \\p = 36.0 * Hm - 55.0 * π;\n $n = ((C1 + C2) * 0.5)⁷;\n \n # The hue rotation correction term is designed to account for the\n # non-linear behavior of hue differences in the blue region.\n my \\Rt = -2.0 * sqrt( $n/($n+6103515625.0)) * sin(π/3.0*exp(p²/(-25.0*π²)) );\n $n = ((L1 + L2) * 0.5 - 50.0)²; \n\n # Lightness.\n my \\l = (L2 - L1) / (Kl * (1.0 + 0.015 * $n / sqrt(20.0 + $n)));\n \n # These coefficients adjust the impact of different harmonic\n # components on the hue difference calculation.\n my \\t = 1.0 + 0.24*sin(2.0*Hm + π*0.5) + 0.32*sin(3.0*Hm + 8.0*π/15.0) - \n 0.17*sin(Hm + π/3.0) - 0.20*sin(4.0 * Hm + 3.0*π/20.0);\n $n = C1 + C2;\n \n # Hue.\n my \\h = 2.0 * sqrt(C1 * C2) * sin(Hd) / (Kh * (1.0 + 0.0075 * $n * t));\n \n # Chroma.\n my \\c = (C2 - C1) / (Kc * (1.0 + 0.0225 * $n));\n \n # Returning the square root ensures that the result represents\n # the \"true\" geometric distance in the color space.\n return sqrt(l² + h² + c² + c * h * Rt)\n}\n\nsay \" L1 a1 b1 L2 a2 b2 ΔE2000\";\nsay \"------------------------------------------------------------\";\n\nfor [\n [73.0, 49.0, 39.4, 73.0, 49.0, 39.4],\n [30.0, -41.0, -119.1, 30.0, -41.0, -119.0],\n [79.0, -117.0, -100.4, 79.5, -117.0, -100.0],\n [15.0, -55.0, 6.7, 14.0, -55.0, 7.0],\n [83.0, 98.0, -59.5, 85.2, 98.0, -59.5],\n [59.0, -11.0, -95.0, 56.3, -11.0, -95.0],\n [74.0, -1.0, 68.6, 81.0, -1.0, 69.0],\n [46.4, 125.0, 6.0, 40.0, 125.0, 6.0],\n [18.0, -5.0, 68.0, 20.0, 5.0, 82.0],\n [35.5, -99.0, 109.0, 25.0, -99.0, 109.0],\n [59.0, 77.0, 41.5, 63.3, 77.0, 12.4],\n [40.0, -92.0, 7.7, 58.0, -92.0, -8.0],\n [49.0, -9.0, -74.5, 51.1, 31.0, 16.0],\n [88.0, -124.0, 56.0, 97.0, 62.0, -28.0],\n [98.0, 75.7, 11.0, 3.0, -62.0, 11.0],\n] { printf \"%6.1f \" x 6 ~ \"%14.10f\\n\", $_[^6], ciede_2000 |$_[^6] }\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Task\n\nGet color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.\n\nThe mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis example works with MacOS, customize with the appropriate screencapture utility for other OSes.\n\n```\nuse GD::Raw;\n\nmy $file = '/tmp/one-pixel-screen-capture.png';\n\nqqx/screencapture -R 123,456,1,1 $file/;\n\nmy $fh = fopen($file, \"rb\") or die;\nmy $image = gdImageCreateFromPng($fh);\nmy $pixel = gdImageGetPixel($image, 0, 0);\nmy ($red,$green,$blue) =\n gdImageRed( $image, $pixel),\n gdImageGreen($image, $pixel),\n gdImageBlue( $image, $pixel);\n\nsay \"RGB: $red, $green, $blue\";\n\nfclose($fh);\nunlink $file;\n\n```\n\nOutput:\n\n```\nRGB: 20, 2, 124\n```\n\nAlternately, a version that should work in any X11 environment. Needs X11::xdo and MagickWand installed.\n\n```\nsignal(SIGINT).tap: { sleep .1; cleanup(); print \"\\n\" xx 50, \"\\e[H\\e[J\"; exit(0) }\n\nmulti MAIN () {\n use X11::libxdo;\n my $xdo = Xdo.new;\n my ($lx, $ly) = 0, 0;\n loop {\n sleep .1;\n my ($x, $y, $) = $xdo.get-mouse-location;\n next if $lx == $x and $ly == $y;\n ($lx, $ly) = $x, $y;\n display $x, $y, |get-pixel($x, $y);\n }\n}\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nmulti MAIN (\n Int $x, #= Integer x coordinate to pick\n Int $y, #= Integer y coordinate to pick\n $q = False #= Boolean \"quiet\" mode, set truthy for decimal values, set to h for hex values\n ) {\n my ($red, $green, $blue) = get-pixel($x, $y);\n\n if $q {\n $q.lc eq 'h' ??\n ( printf \"%02X:%02X:%02X\\n\", $red, $green, $blue ) !!\n ( printf \"%03d:%03d:%03d\\n\", $red, $green, $blue );\n } else {\n display($x, $y, $red, $green, $blue);\n cleanup();\n }\n exit(0);\n}\n\nsub get-pixel ($x, $y) {\n my $xcolor =\n qqx/import -window root -crop 1x1+{$x-1 max 0}+{$y-2 max 0} -depth 8 txt:-/\n .comb(/<?after '#'><xdigit> ** 6/);\n\n |$xcolor.comb(2)».parse-base(16);\n}\n\nsub display ($x, $y, $r, $g, $b) {\n print \"\\e[?25l\\e[48;2;0;0;0m\\e[38;2;255;255;255m\\e[H\\e[J\";\n printf \" x: %4d y: $y\\n\", $x;\n printf \" RGB: %03d:%03d:%03d \\n HEX: %02X:%02X:%02X\\n\",\n $r, $g, $b, $r, $g, $b;\n print \"\\e[38;2;{$r};{$g};{$b}m \",\n ('█' x 18 xx 6).join(\"\\n \"), \"\\n\\n\";\n}\n\nsub cleanup { print \"\\e[0m\\e[?25h\" }\n\n```" } ]
[ { "role": "user", "content": "full color\n\nExample: Gimp 16 color\n\nColor quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.\n\n**Task**: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should *not* use a fixed palette such as Web colors or Windows system palette. Dithering is not required.\n\nNote: the funny color bar on top of the frog image is intentional." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\n```\nuse MagickWand;\nuse MagickWand::Enums;\n\nmy $frog = MagickWand.new;\n$frog.read(\"./Quantum_frog.png\");\n$frog.quantize(16, RGBColorspace, 0, True, False);\n$frog.write('./Quantum-frog-16-perl6.png');\n\n```\n\nSee: Quantum-frog-16-perl6.png (offsite .png image)" } ]
[ { "role": "user", "content": "Task\n\nWrite a function to draw a HSV color wheel completely with code.\n\nThis is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.08\n\nFile:Color-wheel-perl6.png\n\n```\nuse Image::PNG::Portable;\n\nmy ($w, $h) = 300, 300;\n\nmy $out = Image::PNG::Portable.new: :width($w), :height($h);\n\nmy $center = $w/2 + $h/2*i;\n\ncolor-wheel($out);\n\n$out.write: 'Color-wheel-perl6.png';\n\nsub color-wheel ( $png ) {\n ^$w .race.map: -> $x {\n for ^$h -> $y {\n my $vector = $center - $x - $y*i;\n my $magnitude = $vector.abs * 2 / $w;\n my $direction = ( π + atan2( |$vector.reals ) ) / τ;\n $png.set: $x, $y, |hsv2rgb( $direction, $magnitude, $magnitude < 1 );\n }\n }\n}\n\nsub hsv2rgb ( $h, $s, $v ){\n my $c = $v * $s;\n my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );\n my $m = $v - $c;\n (do given $h {\n when 0..^1/6 { $c, $x, 0 }\n when 1/6..^1/3 { $x, $c, 0 }\n when 1/3..^1/2 { 0, $c, $x }\n when 1/2..^2/3 { 0, $x, $c }\n when 2/3..^5/6 { $x, 0, $c }\n when 5/6..1 { $c, 0, $x }\n } ).map: ((*+$m) * 255).Int\n}\n\n```" } ]
[ { "role": "user", "content": "A **colorful number** is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.\n\nE.G.\n\n24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840\n\nEvery product is unique.\n\n2346 is **not** a colorful number. 2, 3, 4, **6**, (2×3)**6**, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144\n\nThe product **6** is repeated.\n\nSingle digit numbers **are** considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.\n\nTask\n\n* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.\n* Use that routine to find all of the colorful numbers less than 100.\n* Use that routine to find the largest possible colorful number.\n\nStretch\n\n* Find and display the count of colorful numbers in each order of magnitude.\n* Find and show the total count of **all** colorful numbers.\n\n*Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.*" }, { "role": "assistant", "content": "```\nsub is-colorful (Int $n) {\n return True if 0 <= $n <= 9;\n return False if $n.contains(0) || $n.contains(1) || $n < 0;\n my @digits = $n.comb;\n my %sums = @digits.Bag;\n return False if %sums.values.max > 1;\n for 2..@digits -> $group {\n @digits.rotor($group => 1 - $group).map: { %sums{ [×] $_ }++ }\n return False if %sums.values.max > 1;\n }\n True\n}\n\nput \"Colorful numbers less than 100:\\n\" ~ (^100).hyper.grep( &is-colorful).batch(10)».fmt(\"%2d\").join: \"\\n\";\n\nmy ($start, $total) = 23456789, 10;\n\nprint \"\\nLargest magnitude colorful number: \";\n.put and last if .Int.&is-colorful for $start.flip … $start;\n\n\nput \"\\nCount of colorful numbers for each order of magnitude:\\n\" ~\n \"1 digit colorful number count: $total - 100%\";\n\nfor 2..8 {\n put \"$_ digit colorful number count: \",\n my $c = +(flat $start.comb.combinations($_).map: {.permutations».join».Int}).hyper.grep( &is-colorful ),\n \" - {($c / (exp($_,10) - exp($_-1,10) ) * 100).round(.001)}%\";\n $total += $c;\n}\n\nsay \"\\nTotal colorful numbers: $total\";\n\n```\n\nOutput:\n\n```\nColorful numbers less than 100:\n 0 1 2 3 4 5 6 7 8 9\n23 24 25 26 27 28 29 32 34 35\n36 37 38 39 42 43 45 46 47 48\n49 52 53 54 56 57 58 59 62 63\n64 65 67 68 69 72 73 74 75 76\n78 79 82 83 84 85 86 87 89 92\n93 94 95 96 97 98\n\nLargest magnitude colorful number: 98746253\n\nCount of colorful numbers for each order of magnitude:\n1 digit colorful number count: 10 - 100%\n2 digit colorful number count: 56 - 62.222%\n3 digit colorful number count: 328 - 36.444%\n4 digit colorful number count: 1540 - 17.111%\n5 digit colorful number count: 5514 - 6.127%\n6 digit colorful number count: 13956 - 1.551%\n7 digit colorful number count: 21596 - 0.24%\n8 digit colorful number count: 14256 - 0.016%\n\nTotal colorful numbers: 57256\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay a series of vertical color bars across the width of the display.\n\nThe color bars should either use:\n\n: : : * the system palette,   or\n * the sequence of colors:\n\n : : : * black\n * red\n * green\n * blue\n * magenta\n * cyan\n * yellow\n * white" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\n```\nmy ($x,$y) = 1280, 720;\n\nmy @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },\n 0, 0, 0,\n 255, 0, 0,\n 0, 255, 0,\n 0, 0, 255,\n 255, 0, 255,\n 0, 255, 255,\n 255, 255, 0,\n 255, 255, 255;\n\nmy $img = open \"colorbars.ppm\", :w orelse die \"Can't create colorbars.ppm: $_\";\n\n$img.print: qq:to/EOH/;\n P6\n # colorbars.ppm\n $x $y\n 255\n EOH\n\nfor ^$y {\n for ^@colors -> $h {\n $img.write: @colors[$h];\n }\n}\n\n$img.close;\n\n```" } ]
[ { "role": "user", "content": "The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.\n\nThe pinstripes should either follow the system palette sequence,   or a sequence that includes:\n \nblack,   red,   green,   blue,   magenta,   cyan,   yellow,   and   white:\n\n: : * after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,\n * halfway down the display, switch to 3 pixel wide vertical pinstripe,\n * finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.\n\nSee also\n\n* display black and white\n* print colour" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy ($x,$y) = 1280, 720;\n\nmy @colors = map -> $r, $g, $b { [$r, $g, $b] },\n 0, 0, 0,\n 255, 0, 0,\n 0, 255, 0,\n 0, 0, 255,\n 255, 0, 255,\n 0, 255, 255,\n 255, 255, 0,\n 255, 255, 255;\n\nmy $img = open \"pinstripes.ppm\", :w orelse die \"Can't create pinstripes.ppm: $_\";\n\n$img.print: qq:to/EOH/;\n P3\n # pinstripes.ppm\n $x $y\n 255\n EOH\n\nmy $vzones = $y div 4;\nfor 1..4 -> $width {\n my $stripes = ceiling $x / $width / +@colors;\n my $row = [flat ((@colors Xxx $width) xx $stripes).map: *.values].splice(0,$x);\n $img.put: $row for ^$vzones;\n}\n\n$img.close;\n\n```" } ]
[ { "role": "user", "content": "The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.\n\nAfter the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).\n\nNote that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.\n\nOptionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.01\n\nNote that Raku does not attempt to be a printer driver. This example allows users to specify the dpi and paper size, then generates an image and passes it to the default printer. Defaults to 300 dpi and US letter paper.\n\n```\nunit sub MAIN ($dpi = 300, $size = 'letter');\n\nmy $filename = './Color-pinstripe-printer-perl6.png';\n\nmy %paper = (\n 'letter' => { :width(8.5),  :height(11.0) }\n 'A4' => { :width(8.2677), :height(11.6929)}\n);\n\nmy ($w, $h) = %paper{$size}<width height> »*» $dpi;\n\n# ROYGBIVK\nmy @color = (1,0,0),(1,.598,0),(1,1,0),(0,1,0),(0,0,1),(.294,0,.51),(.58,0,.827),(0,0,0);\n\nmy $gap = floor $w % ($dpi * +@color) / 2;\n\nmy $rows = (1, * * 2 … * > $dpi).elems;\n\nmy $height = $dpi;\n\nuse Cairo;\n\nmy @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };\n\ngiven Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {\n given Cairo::Context.new($image) {\n my Cairo::Pattern::Solid $bg .= create(1,1,1);\n .rectangle(0, 0, $w, $h);\n .pattern($bg);\n .fill;\n $bg.destroy;\n\n my $y = $gap;\n for ^$rows -> $row {\n my $x = $gap;\n my $width = $dpi / (2 ** $row);\n for @colors -> $this {\n my $v = 0;\n while $v++ < (2 ** ($row - 1)) {\n given Cairo::Context.new($image) -> $block {\n $block.rectangle($x, $y, $width, $height);\n $block.pattern($this);\n $block.fill;\n $block.destroy;\n }\n $x += $width;\n $x += $width if $row;\n }\n }\n $y += $height;\n }\n }\n $image.write_png($filename);\n}\n\n# Uncomment next line if you actually want to print it\n#run('lp', $filename)\n\n```\n\nSee Color-pinstripe-printer-perl6.png (offsite png image)" } ]
[ { "role": "user", "content": "Task\n\nGiven non-negative integers   **m**   and   **n**,   generate all size   **m**   combinations   of the integers from   **0**   (zero)   to   **n-1**   in sorted order   (each combination is sorted and the entire table is sorted).\n\nExample\n\n**3**   comb   **5**     is:\n\n```\n0 1 2\n0 1 3\n0 1 4\n0 2 3\n0 2 4\n0 3 4\n1 2 3\n1 2 4\n1 3 4\n2 3 4\n\n```\n\nIf it is more \"natural\" in your language to start counting from   **1**   (unity) instead of   **0**   (zero),\n \nthe combinations can be of the integers from   **1**   to   **n**.\n\nSee also\n\n: : : : The number of samples of size k from n objects.\n \n \n With   combinations and permutations   generation tasks.\n\n | | Order Unimportant | Order Important |\n | --- | --- | --- |\n | Without replacement | ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\\displaystyle {\\displaystyle {\\binom {n}{k}}=^{n}\\operatorname {C} \\_{k}={\\frac {n(n-1)\\ldots (n-k+1)}{k(k-1)\\dots 1}}}} | n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\\displaystyle {\\displaystyle ^{n}\\operatorname {P} \\_{k}=n\\cdot (n-1)\\cdot (n-2)\\cdots (n-k+1)}} |\n | Task: Combinations | Task: Permutations |\n | With replacement | ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\\displaystyle {\\displaystyle {\\binom {n+k-1}{k}}=^{n+k-1}\\operatorname {C} \\_{k}={(n+k-1)! \\over (n-1)!k!}}} | n k {\\displaystyle {\\displaystyle n^{k}}} |\n | Task: Combinations with repetitions | Task: Permutations with repetitions |" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.12\n\nThere actually is a builtin:\n\n```\n.say for combinations(5,3);\n```\n\nOutput:\n\n```\n(0 1 2)\n(0 1 3)\n(0 1 4)\n(0 2 3)\n(0 2 4)\n(0 3 4)\n(1 2 3)\n(1 2 4)\n(1 3 4)\n(2 3 4)\n```\n\nHere is an iterative routine with the same output:\n\n```\nsub combinations(Int $n, Int $k) {\n return ([],) unless $k;\n return if $k > $n || $n <= 0;\n my @c = ^$k;\n gather loop {\n take [@c];\n next if @c[$k-1]++ < $n-1;\n my $i = $k-2;\n $i-- while $i >= 0 && @c[$i] >= $n-($k-$i);\n last if $i < 0;\n @c[$i]++;\n while ++$i < $k { @c[$i] = @c[$i-1] + 1; }\n }\n}\n.say for combinations(5,3);\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Combination. 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| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Permutation. 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\nImplement the combination   (nCk)   and permutation   (nPk)   operators in the target language:\n\n: : : * n\n\n C\n\n k\n =\n\n (\n\n n\n k\n\n )\n =\n\n n\n (\n n\n −\n 1\n )\n …\n (\n n\n −\n k\n +\n 1\n )\n\n k\n (\n k\n −\n 1\n )\n …\n 1\n {\\displaystyle {\\displaystyle ^{n}\\operatorname {C} \\_{k}={\\binom {n}{k}}={\\frac {n(n-1)\\ldots (n-k+1)}{k(k-1)\\dots 1}}}}\n\n: : : * n\n\n P\n\n k\n =\n n\n ⋅\n (\n n\n −\n 1\n )\n ⋅\n (\n n\n −\n 2\n )\n ⋯\n (\n n\n −\n k\n +\n 1\n )\n {\\displaystyle {\\displaystyle ^{n}\\operatorname {P} \\_{k}=n\\cdot (n-1)\\cdot (n-2)\\cdots (n-k+1)}}\n\nSee the Wikipedia articles for a more detailed description.\n\n**To test**, generate and print examples of:\n\n* A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.\n* A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic. \n This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.\n\nRelated task\n\n* Evaluate binomial coefficients\n\n: : : : The number of samples of size k from n objects.\n \n \n With   combinations and permutations   generation tasks.\n\n | | Order Unimportant | Order Important |\n | --- | --- | --- |\n | Without replacement | ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\\displaystyle {\\displaystyle {\\binom {n}{k}}=^{n}\\operatorname {C} \\_{k}={\\frac {n(n-1)\\ldots (n-k+1)}{k(k-1)\\dots 1}}}} | n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\\displaystyle {\\displaystyle ^{n}\\operatorname {P} \\_{k}=n\\cdot (n-1)\\cdot (n-2)\\cdots (n-k+1)}} |\n | Task: Combinations | Task: Permutations |\n | With replacement | ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\\displaystyle {\\displaystyle {\\binom {n+k-1}{k}}=^{n+k-1}\\operatorname {C} \\_{k}={(n+k-1)! \\over (n-1)!k!}}} | n k {\\displaystyle {\\displaystyle n^{k}}} |\n | Task: Combinations with repetitions | Task: Permutations with repetitions |" }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku can't compute arbitrary large floating point values, thus we will use logarithms, as is often needed when dealing with combinations. We'll also use a Stirling method to approximate \n\nln\n⁡\n(\nn\n!\n)\n{\\displaystyle {\\displaystyle \\ln(n!)}}\n:\n\nln\n⁡\nn\n!\n≈\n\n\n1\n2\nln\n⁡\n(\n2\nπ\nn\n)\n+\nn\nln\n⁡\n\n(\n\nn\ne\n+\n\n\n1\n\n12\ne\nn\n)\n{\\displaystyle {\\displaystyle \\ln n!\\approx {\\frac {1}{2}}\\ln(2\\pi n)+n\\ln \\left({\\frac {n}{e}}+{\\frac {1}{12en}}\\right)}}\n\nNotice that Raku can process arbitrary long integers, though. So it's not clear whether using floating points is useful in this case.\n\n```\nmulti P($n, $k) { [*] $n - $k + 1 .. $n }\nmulti C($n, $k) { P($n, $k) / [*] 1 .. $k }\n \nsub lstirling(\\n) {\n n < 10 ?? lstirling(n+1) - log(n+1) !!\n .5*log(2*pi*n)+ n*log(n/e+1/(12*e*n))\n}\n \nrole Logarithm {\n method gist {\n\tmy $e = (self/10.log).Int;\n\tsprintf \"%.8fE%+d\", exp(self - $e*10.log), $e;\n }\n}\nmulti P($n, $k, :$float!) {\n (lstirling($n) - lstirling($n -$k))\n but Logarithm\n}\nmulti C($n, $k, :$float!) {\n (lstirling($n) - lstirling($n -$k) - lstirling($k))\n but Logarithm\n}\n \nsay \"Exact results:\";\nfor 1..12 -> $n {\n my $p = $n div 3;\n say \"P($n, $p) = \", P($n, $p);\n}\n \nfor 10, 20 ... 60 -> $n {\n my $p = $n div 3;\n say \"C($n, $p) = \", C($n, $p);\n}\n \nsay '';\nsay \"Floating point approximations:\";\nfor 5, 50, 500, 1000, 5000, 15000 -> $n {\n my $p = $n div 3;\n say \"P($n, $p) = \", P($n, $p, :float);\n}\n \nfor 100, 200 ... 1000 -> $n {\n my $p = $n div 3;\n say \"C($n, $p) = \", C($n, $p, :float);\n}\n\n```\n\nOutput:\n\n```\nExact results:\nP(1, 0) = 1\nP(2, 0) = 1\nP(3, 1) = 3\nP(4, 1) = 4\nP(5, 1) = 5\nP(6, 2) = 30\nP(7, 2) = 42\nP(8, 2) = 56\nP(9, 3) = 504\nP(10, 3) = 720\nP(11, 3) = 990\nP(12, 4) = 11880\nC(10, 3) = 120\nC(20, 6) = 38760\nC(30, 10) = 30045015\nC(40, 13) = 12033222880\nC(50, 16) = 4923689695575\nC(60, 20) = 4191844505805495\n\nFloating point approximations:\nP(5, 1) = 5.00000000E+0\nP(50, 16) = 1.03017326E+26\nP(500, 166) = 3.53487492E+434\nP(1000, 333) = 5.96932629E+971\nP(5000, 1666) = 6.85674576E+6025\nP(15000, 5000) = 9.64985399E+20469\nC(100, 33) = 2.94692433E+26\nC(200, 66) = 7.26975256E+53\nC(300, 100) = 4.15825147E+81\nC(400, 133) = 1.25794868E+109\nC(500, 166) = 3.92602839E+136\nC(600, 200) = 2.50601778E+164\nC(700, 233) = 8.10320356E+191\nC(800, 266) = 2.64562336E+219\nC(900, 300) = 1.74335637E+247\nC(1000, 333) = 5.77613455E+274\n```" } ]
[ { "role": "user", "content": "The set of combinations with repetitions is computed from a set, \n\nS\n{\\displaystyle {\\displaystyle S}}\n (of cardinality \n\nn\n{\\displaystyle {\\displaystyle n}}\n), and a size of resulting selection, \n\nk\n{\\displaystyle {\\displaystyle k}}\n, by reporting the sets of cardinality \n\nk\n{\\displaystyle {\\displaystyle k}}\n where each member of those sets is chosen from \n\nS\n{\\displaystyle {\\displaystyle S}}\n.\nIn the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.\nFor example:\n\n: Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., \n\n S\n {\\displaystyle {\\displaystyle S}}\n is \n\n {\n\n i\n c\n e\n d\n ,\n\n j\n a\n m\n ,\n\n p\n l\n a\n i\n n\n }\n {\\displaystyle {\\displaystyle \\{\\mathrm {iced} ,\\mathrm {jam} ,\\mathrm {plain} \\}}}\n , \n\n |\n S\n\n |\n =\n 3\n {\\displaystyle {\\displaystyle |S|=3}}\n , and \n\n k\n =\n 2\n {\\displaystyle {\\displaystyle k=2}}\n .)\n\n: A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.\n\nNote that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.\n \nAlso note that *doughnut* can also be spelled *donut*.\n\nTask\n\n* Write a function/program/routine/.. to generate all the combinations with repetitions of \n\n n\n {\\displaystyle {\\displaystyle n}}\n types of things taken \n\n k\n {\\displaystyle {\\displaystyle k}}\n at a time and use it to *show* an answer to the doughnut example above.\n* For extra credit, use the function to compute and show *just the number of ways* of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.\n\nReferences\n\n* k-combination with repetitions\n\nSee also\n\n: : : : The number of samples of size k from n objects.\n \n \n With   combinations and permutations   generation tasks.\n\n | | Order Unimportant | Order Important |\n | --- | --- | --- |\n | Without replacement | ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\\displaystyle {\\displaystyle {\\binom {n}{k}}=^{n}\\operatorname {C} \\_{k}={\\frac {n(n-1)\\ldots (n-k+1)}{k(k-1)\\dots 1}}}} | n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\\displaystyle {\\displaystyle ^{n}\\operatorname {P} \\_{k}=n\\cdot (n-1)\\cdot (n-2)\\cdots (n-k+1)}} |\n | Task: Combinations | Task: Permutations |\n | With replacement | ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\\displaystyle {\\displaystyle {\\binom {n+k-1}{k}}=^{n+k-1}\\operatorname {C} \\_{k}={(n+k-1)! \\over (n-1)!k!}}} | n k {\\displaystyle {\\displaystyle n^{k}}} |\n | Task: Combinations with repetitions | Task: Permutations with repetitions |" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nOne could simply generate all permutations, and then remove \"duplicates\":\n\n**Works with**: Rakudo version 2016.07\n\n```\nmy @S = <iced jam plain>;\nmy $k = 2;\n\n.put for [X](@S xx $k).unique(as => *.sort.cache, with => &[eqv])\n\n```\n\nOutput:\n\n```\niced iced\niced jam\niced plain\njam jam\njam plain\nplain plain\n\n```\n\nAlternatively, a recursive solution:\n\n**Translation of**: Haskell\n\n```\nproto combs_with_rep (UInt, @) {*}\n \nmulti combs_with_rep (0, @) { () }\nmulti combs_with_rep (1, @a) { map { $_, }, @a }\nmulti combs_with_rep ($, []) { () }\nmulti combs_with_rep ($n, [$head, *@tail]) {\n |combs_with_rep($n - 1, ($head, |@tail)).map({ $head, |@_ }),\n |combs_with_rep($n, @tail);\n}\n \n.say for combs_with_rep( 2, [< iced jam plain >] );\n \n# Extra credit:\nsub postfix:<!> { [*] 1..$^n }\nsub combs_with_rep_count ($k, $n) { ($n + $k - 1)! / $k! / ($n - 1)! }\n \nsay combs_with_rep_count( 3, 10 );\n\n```\n\nOutput:\n\n```\n(iced iced)\n(iced jam)\n(iced plain)\n(jam jam)\n(jam plain)\n(plain plain)\n220\n```" } ]
[ { "role": "user", "content": "Iterated digits squaring introduces RC the Project Euler Task #92. Combinations with repetitions introduce RC to the concept of generating all the combinations with repetitions of n types of things taken k at a time.\n\nThe purpose of this task is to combine these tasks as follows:\n\n: The collections of k items will be taken from [0,1,4,9,16,25,36,49,64,81] and must be obtained using code from Combinations with repetitions. The collection of k zeroes is excluded.\n: For each collection of k items determine if it translates to 1 using the rules from Iterated digits squaring\n: For each collection which translates to 1 determine the number of different ways, c say, in which the k items can be uniquely ordered.\n: Keep a running total of all the values of c obtained\n: Answer the Project Euler Task #92 question (k=7).\n: Answer the equivalent question for k=8,11,14.\n: Optionally answer the question for k=17. These numbers will be larger than the basic integer type for many languages, if it is not easy to use larger numbers it is not necessary for this task." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Kotlin\n\n```\nuse v6;\n\nsub endsWithOne($n --> Bool) {\n my $digit;\n my $sum = 0;\n my $nn = $n;\n loop {\n while ($nn > 0) {\n $digit = $nn % 10;\n $sum += $digit²;\n $nn = $nn div 10;\n }\n ($sum == 1) and return True;\n ($sum == 89) and return False;\n $nn = $sum;\n $sum = 0;\n }\n}\n\nmy @ks = (7, 8, 11, 14, 17);\n\nfor @ks -> $k {\n my @sums is default(0) = 1,0;\n my $s;\n for (1 .. $k) -> $n {\n for ($n*81 ... 1) -> $i {\n for (1 .. 9) -> $j {\n $s = $j²;\n if ($s > $i) { last };\n @sums[$i] += @sums[$i-$s];\n }\n }\n }\n my $count1 = 0;\n for (1 .. $k*81) -> $i { if (endsWithOne($i)) {$count1 += @sums[$i]} }\n my $limit = 10**$k - 1;\n say \"For k = $k in the range 1 to $limit\";\n say \"$count1 numbers produce 1 and \",$limit-$count1,\" numbers produce 89\";\n}\n\n```\n\nOutput:\n\n```\nFor k = 7 in the range 1 to 9999999\n1418853 numbers produce 1 and 8581146 numbers produce 89\nFor k = 8 in the range 1 to 99999999\n14255666 numbers produce 1 and 85744333 numbers produce 89\nFor k = 11 in the range 1 to 99999999999\n15091199356 numbers produce 1 and 84908800643 numbers produce 89\nFor k = 14 in the range 1 to 99999999999999\n13770853279684 numbers produce 1 and 86229146720315 numbers produce 89\nFor k = 17 in the range 1 to 99999999999999999\n12024696404768024 numbers produce 1 and 87975303595231975 numbers produce 89\n```" } ]
[ { "role": "user", "content": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\nTask\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n\n1. An input of no words produces the output string of just the two brace characters \"{}\".\n2. An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n3. An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n4. An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\nTest your function with the following series of inputs showing your output here on this page:\n\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub comma-quibbling(@A) {\n <{ }>.join: @A < 2 ?? @A !! \"@A[0..*-2].join(', ') and @A[*-1]\";\n}\n\nsay comma-quibbling($_) for\n [], [<ABC>], [<ABC DEF>], [<ABC DEF G H>];\n\n```\n\nOutput:\n\n```\n{}\n{ABC}\n{ABC and DEF}\n{ABC, DEF, G and H}\n```" } ]
[ { "role": "user", "content": "Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see Scripted main.\n\nSee also Program name.\n\nFor parsing command line arguments intelligently, see Parsing command-line arguments.\n\nExample command line:\n\n```\nmyprogram -c \"alpha beta\" -h \"gamma\"\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\nPerl 5's `@ARGV` is available as `@*ARGS`. Alternatively, if you define a subroutine named `MAIN`, Perl will automatically process `@*ARGS` according to Unix conventions and `MAIN`'s signature (or signatures, if your `MAIN` is a multi sub) and then call `MAIN` with appropriate arguments; for more detailed information see: https://docs.raku.org/language/create-cli\n\n```\n# with arguments supplied\n$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5\n8\n\n# missing argument:\n$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 \nUsage:\n-e '...' x y\n```\n\nIf the program is stored in a file, the file name is printed instead of `-e '...'`." } ]
[ { "role": "user", "content": "*Commatizing*   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.\n\nTask\n\nWrite a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some\nother characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.\n\nSome of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.\n\nThe number may be part of a larger (non-numeric) string such as:\n\n: : : : * «US$1744 millions»       ──or──\n * ±25000 motes.\n\nThe string may possibly *not* have a number suitable for commatizing, so it should be untouched and *no error generated*.\n\nIf any argument (option) is invalid, nothing is changed and no error *need be* generated (quiet execution, no fail execution).   Error message generation is optional.\n\nThe exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000\n\nLeading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882\n\nAny   *period*   (**.**)   in a number is assumed to be a   *decimal point*.\n\nThe original string is never changed   *except*   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all.\n\nTo wit, the following should be preserved:\n\n: : * leading signs (**+**, **-**)       ── even superfluous signs\n * leading/trailing/embedded blanks, tabs, and other whitespace\n * the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002\n\nAny exponent character(s) should be supported:\n\n: : : : : : * 1247e12\n * 57256.1D-4\n * 4444^60\n * 7500**∙**10\\*\\*35\n * 8500x10\\*\\*35\n * 9500↑35\n * +55000↑3\n * 1000\\*\\*100\n * 2048²\n * 409632\n * 10000pow(pi)\n\nNumbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24).\n\nThe character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (**,**) character.\n\nThe   *period length*   can be specified   (sometimes referred to as \"thousands\" or \"thousands separators\").   The   *period length*   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3.\n\n: : : E.G.:   in this example, the   *period length*   is five:   56789,12340,14148\n\nThe location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1.\n\nThe character strings below may be placed in a file (and read) or stored as simple strings within the program.\n\nStrings to be used as a minimum\n\nThe value of   pi   (expressed in base 10)   should be separated with blanks every   **5**   places past the decimal point,\n \nthe Zimbabwe dollar amount should use a decimal point for the \"comma\" separator:\n\n: * pi=3.14159265358979323846264338327950288419716939937510582097494459231\n * The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\n * \"-in Aus$+1411.8millions\"\n * ===US$0017440 millions=== (in 2000 dollars)\n * 123.e8000 is pretty big.\n * The land area of the earth is 57268900(29% of the surface) square miles.\n * Ain't no numbers in this here words, nohow, no way, Jose.\n * James was never known as 0000000007\n * Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\n * ␢␢␢$-140000±100 millions.\n * 6/9/1946 was a good year for some.\n\nwhere the penultimate string has three leading blanks   (real blanks are to be used).\n\nAlso see\n\n* The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nfor ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}),\n ('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}),\n '-in Aus$+1411.8millions',\n '===US$0017440 millions=== (in 2000 dollars)',\n '123.e8000 is pretty big.',\n 'The land area of the earth is 57268900(29% of the surface) square miles.',\n 'Ain\\'t no numbers in this here words, nohow, no way, Jose.',\n 'James was never known as 0000000007',\n 'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.',\n ' $-140000±100 millions.',\n '6/9/1946 was a good year for some.'\n {\n say \"Before: \", .[0];\n say \" After: \", .[1] ?? .[0].&commatize( |.[1] ) !! .&commatize;\n }\n \nsub commatize($s, :$at = 0, :$ins = ',', :$by = 3) {\n $s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /,\n *.flip.comb(/<{ \".**1..$by\" }>/).join($ins).flip;\n}\n\n```\n\nOutput:\n\n```\nBefore: pi=3.14159265358979323846264338327950288419716939937510582097494459231\n After: pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231\nBefore: The author has two Z$100000000000000 Zimbabwe notes (100 trillion).\n After: The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).\nBefore: -in Aus$+1411.8millions\n After: -in Aus$+1,411.8millions\nBefore: ===US$0017440 millions=== (in 2000 dollars)\n After: ===US$0017,440 millions=== (in 2000 dollars)\nBefore: 123.e8000 is pretty big.\n After: 123.e8000 is pretty big.\nBefore: The land area of the earth is 57268900(29% of the surface) square miles.\n After: The land area of the earth is 57,268,900(29% of the surface) square miles.\nBefore: Ain't no numbers in this here words, nohow, no way, Jose.\n After: Ain't no numbers in this here words, nohow, no way, Jose.\nBefore: James was never known as 0000000007\n After: James was never known as 0000000007\nBefore: Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.\n After: Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.\nBefore: $-140000±100 millions.\n After: $-140,000±100 millions.\nBefore: 6/9/1946 was a good year for some.\n After: 6/9/1946 was a good year for some.\n```" } ]
[ { "role": "user", "content": "Task\n\nShow all ways to include text in a language source file\nthat's completely ignored by the compiler or interpreter.\n\nRelated tasks\n\n* Documentation\n* Here\\_document\n\nSee also\n\n* Wikipedia\n* xkcd (Humor: hand gesture denoting `//` for \"commenting out\" people.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Single-line comments**\n\nA single-line comment starts with # and extends to the end of the line.\n\n```\n# the answer to everything\nmy $x = 42;\n```\n\n**Multi-line comments**\n\nA multi-line comment starts with #` and followed by the commented text enclosed by bracketing characters (e.g., (), [], {}, 「」, etc.).\n\n```\n#`( \n Comments beginning with a backtick and one or more opening bracketing characters are embedded comments.\n They can span more than one line…\n)\n\nmy $y = #`{ …or only part of a line. } 3;\n```\n\nMulti-line comments can also be embedded into code.\n\n```\nfor #`(each element in) my @array {\n say #`(or print element) $_ #`(with a newline);\n}\n```\n\nUsing more than one bracketing character lets you include an unmatched close bracket, as shown below.\n\n```\n#`{{\n This close curly brace } won't terminate the comment early.\n}}\n```\n\n**Pod comments**\n\n```\n=begin comment\n\nPod is the successor to Perl 5's POD. This is the simplest way to use it for multi-line comments.\nFor more about Pod, see Pod: https://docs.perl6.org/language/pod\n\n=end comment\n```\n\nPod also provides declarator blocks which are special comments that attach to some source code and can be extracted as documentation. They are either #| or #= and must be immediately followed by either a space or an opening curly brace. In short, blocks starting with #| are attached to the code after them, and blocks starting with #= are attached to the code before them.\n\n```\n#| Compute the distance between two points in the plane.\nsub distance(\n Rat \\x1, #= First point's abscissa,\n Rat \\y1, #= First point's ordinate, \n Rat \\x2, #= Second point's abscissa, \n Rat \\y2, #= Second point's ordinate, \n){\n return sqrt((x2 - x1)**2 + (y2 - y1)**2)\n}\n```" } ]
[ { "role": "user", "content": "Given an integer array **nums**, find the common list elements.\n\nExample\n\n**nums** = [2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9]\n\n**output** = [3,6,9]\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": "```\nput [∩] [2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9,3];\n\n```\n\nOutput:\n\n```\n6 9 3\n```" } ]
[ { "role": "user", "content": "Given an integer array **nums**, the goal is create common sorted list with unique elements.\n\nExample\n\n**nums** = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]\n\n**output** = [1,3,4,5,7,8,9]" }, { "role": "assistant", "content": "```\nput sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];\nput sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9], [<not everything is an integer so why not avoid special cases # ~ 23 4.2>];\n\n```\n\nOutput:\n\n```\n1 3 4 5 7 8 9\n# 1 3 4 4.2 5 7 8 9 23 an avoid cases everything integer is not so special why ~\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven a   list   of arbitrarily many strings, show how to:\n\n* test if they are all lexically **equal**\n* test if every string is lexically **less than** the one after it *(i.e. whether the list is in strict ascending order)*\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an   `if`   statement or similar.\n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is *no* need to provide a complete program and output.\n\nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   `strings`,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers.\n\n*If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature.*\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\nIn Raku, putting square brackets around an infix operator turns it into a listop that effectively works as if the operator had been put in between all of the elements of the argument list *(or in technical terms, it folds/reduces the list using that operator, while taking into account the operator's inherent associativity and identity value)*:\n\n```\n[eq] @strings # All equal\n[lt] @strings # Strictly ascending\n\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.\n\nMeasure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.\n\nExtra credit\n\nGiven more than two strings:\n \nlist = [\"abcd\",\"123456789\",\"abcdef\",\"1234567\"]\n \nShow the strings in descending length order.\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": "So... In what way does this task differ significantly from String length? Other than being horribly under specified?\n\nIn the modern world, string \"length\" is pretty much a useless measurement, especially in the absence of a specified encoding; hence Raku not even having an operator: \"length\" for strings.\n\n```\nsay 'Strings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: \"longest\" first:';\nsay \"$_: characters:{.chars}, Unicode code points:{.codes}, UTF-8 bytes:{.encode('UTF8').bytes}, UTF-16 bytes:{.encode('UTF16').bytes}\" for <👨‍👩‍👧‍👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;\n\n```\n\nOutput:\n\n```\nStrings (👨‍👩‍👧‍👦, 🤔🇺🇸, BOGUS!) sorted: \"longest\" first:\nBOGUS!: characters:6, Unicode code points:6, UTF-8 bytes:6, UTF-16 bytes:12\n🤔🇺🇸: characters:2, Unicode code points:3, UTF-8 bytes:12, UTF-16 bytes:12\n👨‍👩‍👧‍👦: characters:1, Unicode code points:7, UTF-8 bytes:25, UTF-16 bytes:22\n```" } ]
[ { "role": "user", "content": "Measure a relative performance of sorting algorithms implementations.\n\nPlot **execution time vs. input sequence length** dependencies for various implementation of sorting algorithm and different input sequence types (example figures).\n\nConsider three type of input sequences:\n\n: * ones: sequence of all *1'*s.   Example: {1, 1, 1, 1, 1}\n * range: ascending sequence, i.e. already sorted.   Example: {1, 2, 3, 10, 15}\n * shuffled range: sequence with elements randomly distributed.   Example: {5, 3, 9, 6, 8}\n\nConsider at least two different sorting functions (different algorithms or/and different implementation of the same algorithm).\n\nFor example, consider Bubble Sort, Insertion sort, Quicksort or/and implementations of Quicksort with different pivot selection mechanisms.   Where possible, use existing implementations.\n\nPreliminary subtask:\n\n: * Bubble Sort, Insertion sort, Quicksort, Radix sort, Shell sort\n * Query Performance\n * Write float arrays to a text file\n * Plot x, y arrays\n * Polynomial Fitting\n\nGeneral steps:\n\n: 1. Define sorting routines to be considered.\n 2. Define appropriate sequence generators and write timings.\n 3. Plot timings.\n 4. What conclusions about relative performance of the sorting routines could be made based on the plots?" }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\n# 20221114 Raku programming solution\n\nmy ($rounds,$size) = 3, 2000;\nmy @allones = 1 xx $size;\nmy @sequential = 1 .. $size;\nmy @randomized = @sequential.roll xx $size; \n\nsub insertion_sort ( @a is copy ) { # rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#Raku\n for 1 .. @a.end -> \\k {\n loop (my ($j,\\value)=k-1,@a[k];$j>-1&&@a[$j]>value;$j--) {@a[$j+1]=@a[$j]}\n @a[$j+1] = value;\n }\n return @a;\n}\n\nsub merge_sort ( @a ) { # rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Raku\n return @a if @a <= 1;\n\n my $m = @a.elems div 2;\n my @l = merge_sort @a[ 0 ..^ $m ];\n my @r = merge_sort @a[ $m ..^ @a ];\n\n return flat @l, @r if @l[*-1] !after @r[0];\n return flat gather {\n take @l[0] before @r[0] ?? @l.shift !! @r.shift\n while @l and @r;\n take @l, @r;\n }\n}\n\nsub quick-sort(@data) { # andrewshitov.com/2019/06/23/101-quick-sort-in-perl-6/\n return @data if @data.elems <= 1;\n\n my ($pivot,@left, @right) = @data[0];\n\n for @data[1..*] -> $x { $x < $pivot ?? push @left, $x !! push @right, $x }\n\n return flat(quick-sort(@left), $pivot, quick-sort(@right));\n}\n\nsub comparesorts($rounds, @tosort) {\n my ( $iavg, $mavg, $qavg, $t );\n\n for (<i m q> xx $rounds).flat.pick(*) -> \\sort_type {\n given sort_type {\n when 'i' { $t = now ; insertion_sort @tosort ; $iavg += now - $t } \n when 'm' { $t = now ; merge_sort @tosort ; $mavg += now - $t } \n\t when 'q' { $t = now ; quick-sort @tosort ; $qavg += now - $t }\n }\n }\n return $iavg, $mavg, $qavg  »/» $rounds\n}\n\nfor <ones presorted randomized>Z(@allones,@sequential,@randomized) -> ($t,@d) {\n say \"Average sort times for $size $t:\";\n { say \"\\tinsertion sort\\t$_[0]\\n\\tmerge sort\\t$_[1]\\n\\tquick sort\\t$_[2]\" }(comparesorts $rounds,@d)\n}\n\n```\n\nOutput:\n\n```\nAverage sort times for 2000 ones:\n insertion sort 0.112333083\n merge sort 0.506624066\n quick sort 5.899009606666667\nAverage sort times for 2000 presorted:\n insertion sort 0.03596163\n merge sort 0.474839352\n quick sort 5.896118350666666\nAverage sort times for 2000 randomized:\n insertion sort 5.352926729\n merge sort 0.784896982\n quick sort 0.11422247299999999\n```" } ]
[ { "role": "user", "content": "Some programming languages allow calculation of values at compile time.\n\nTask\n\nCalculate   10!   (ten factorial)   at compile time.\n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nconstant $tenfact = [*] 2..10; \nsay $tenfact;\n\n```\n\nLike Perl 5, we also have a BEGIN block, but it also works to introduce a blockless statement,\nthe value of which will be stored up to be used as an expression at run time:\n\n```\n say BEGIN [*] 2..10;\n\n```" } ]
[ { "role": "user", "content": "Code Generator\n\nA code generator translates the output of the syntax analyzer and/or semantic analyzer\ninto lower level code, either assembly, object, or virtual.\n\nTask\n\nTake the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the\nVirtual machine interpreter. The output is in text format, and represents virtual assembly code.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout.\n\nExample - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer solutions\n\n```\nlex < while.t > while.lex\n\n```\n\nRun one of the Syntax analyzer solutions\n\n```\nparse < while.lex > while.ast\n\n```\n\nwhile.ast can be input into the code generator.\n\nThe following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code.\n\n```\nRun as: lex < while.t | parse | gen\n\n```\n\n| Input to lex | Output from lex, input to parse | Output from parse | Output from gen, input to VM |\n| --- | --- | --- | --- |\n| ``` count = 1; while (count < 10) { print(\"count is: \", count, \"\\n\"); count = count + 1; } ``` | **``` 1 1 Identifier count 1 7 Op_assign 1 9 Integer 1 1 10 Semicolon 2 1 Keyword_while 2 7 LeftParen 2 8 Identifier count 2 14 Op_less 2 16 Integer 10 2 18 RightParen 2 20 LeftBrace 3 5 Keyword_print 3 10 LeftParen 3 11 String \"count is: \" 3 23 Comma 3 25 Identifier count 3 30 Comma 3 32 String \"\\n\" 3 36 RightParen 3 37 Semicolon 4 5 Identifier count 4 11 Op_assign 4 13 Identifier count 4 19 Op_add 4 21 Integer 1 4 22 Semicolon 5 1 RightBrace 6 1 End_of_input ```** | **``` Sequence Sequence ; Assign Identifier count Integer 1 While Less Identifier count Integer 10 Sequence Sequence ; Sequence Sequence Sequence ; Prts String \"count is: \" ; Prti Identifier count ; Prts String \"\\n\" ; Assign Identifier count Add Identifier count Integer 1 ```** | **``` Datasize: 1 Strings: 2 \"count is: \" \"\\n\" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt ```** |\n\nInput format\n\nAs shown in the table, above, the output from the syntax analyzer is a flattened AST.\n\nIn the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes.\n\nLoading this data into an internal parse tree should be as simple as:\n\n```\ndef load_ast()\n line = readline()\n # Each line has at least one token\n line_list = tokenize the line, respecting double quotes\n\n text = line_list[0] # first token is always the node type\n\n if text == \";\"\n return None\n\n node_type = text # could convert to internal form if desired\n\n # A line with two tokens is a leaf node\n # Leaf nodes are: Identifier, Integer String\n # The 2nd token is the value\n if len(line_list) > 1\n return make_leaf(node_type, line_list[1])\n\n left = load_ast()\n right = load_ast()\n return make_node(node_type, left, right)\n\n```\n\nOutput format - refer to the table above\n\n* The first line is the header: Size of data, and number of constant strings.\n + size of data is the number of 32-bit unique variables used. In this example, one variable, **count**\n + number of constant strings is just that - how many there are\n* After that, the constant strings\n* Finally, the assembly code\n\nRegisters\n\n* sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array.\n\n* pc: the program counter - points to the current instruction to be performed. The code is an array of bytes.\n\nData\n\n32-bit integers and strings\n\nInstructions\n\nEach instruction is one byte. The following instructions also have a 32-bit integer operand:\n\n```\nfetch [index]\n\n```\n\nwhere index is an index into the data array.\n\n```\nstore [index]\n\n```\n\nwhere index is an index into the data array.\n\n```\npush n\n\n```\n\nwhere value is a 32-bit integer that will be pushed onto the stack.\n\n```\njmp (n) addr\n\n```\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\n```\njz (n) addr\n\n```\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\nThe following instructions do not have an operand. They perform their operation directly\nagainst the stack:\n\nFor the following instructions, the operation is performed against the top two entries in\nthe stack:\n\n```\nadd\nsub\nmul\ndiv\nmod\nlt\ngt\nle\nge\neq\nne\nand\nor\n\n```\n\nFor the following instructions, the operation is performed against the top entry in the\nstack:\n\n```\nneg\nnot\n\n```\n\n```\nprtc\n\n```\n\nPrint the word at stack top as a character.\n\n```\nprti\n\n```\n\nPrint the word at stack top as an integer.\n\n```\nprts\n\n```\n\nStack top points to an index into the string pool. Print that entry.\n\n```\nhalt\n\n```\n\nUnconditional stop.\n\nAdditional examples\n\nYour solution should pass all the test cases above and the additional tests found **Here**.\n\nReference\n\nThe C and Python versions can be considered reference implementations.\n\nRelated Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\nUsing 'while-count' example, input used is here: ast.txt\n\n**Translation of**: Perl\n\n```\nmy %opnames = <\n Less lt LessEqual le Multiply mul Subtract sub NotEqual ne\n Divide div GreaterEqual ge Equal eq Greater gt Negate neg\n>;\n\nmy (@AST, %strings, %names);\nmy $string-count = my $name-count = my $pairsym = my $pc = 0;\n\nsub tree {\n my ($A, $B) = ( '_' ~ ++$pairsym, '_' ~ ++$pairsym );\n my $line = @AST.shift // return '';\n $line ~~ /^ $<instr> = (\\w+|';') [\\s+ $<arg> =(.*)]? / or die \"bad input $line\";\n given $<instr> {\n when 'Identifier' { \"fetch [{%names{$<arg>} //= $name-count++ }]\\n\" }\n when 'Sequence' { tree() ~ tree() }\n when 'Integer' { \"push $<arg>\\n\" }\n when 'String' { \"push { %strings{$<arg>} //= $string-count++ }\\n\" }\n when 'Assign' { join '', reverse (tree().subst( /fetch/, 'store')), tree() }\n when 'While' { \"$A:\\n{ tree() }jz $B\\n{ tree() }jmp $A\\n$B:\\n\" }\n when 'If' { tree() ~ \"jz $A\\n{ [email protected] ~ tree() }jmp $B\\n$A:\\n{ tree() }$B:\\n\" }\n when ';' { '' }\n default { tree() ~ tree() ~ (%opnames{$<instr>} // $<instr>.lc) ~ \"\\n\" }\n }\n}\n\n@AST = slurp('ast.txt').lines;\nmy $code = tree() ~ \"halt\\n\";\n\n$code ~~ s:g/^^ jmp \\s+ (\\S+) \\n ('_'\\d+:\\n) $0:\\n/$1/; # remove jmp next\n$code ~~ s:g/^^ (<[a..z]>\\w* (\\N+)? ) $$/{my $l=$pc.fmt(\"%4d \"); $pc += $0[0] ?? 5 !! 1; $l}$0/; # add locations\nmy %labels = ($code ~~ m:g/^^ ('_' \\d+) ':' \\n \\s* (\\d+)/)».Slip».Str; # pc addr of labels\n$code ~~ s:g/^^ \\s* (\\d+) \\s j[z|mp] \\s* <(('_'\\d+)/ ({%labels{$1} - $0 - 1}) %labels{$1}/; # fix jumps\n$code ~~ s:g/^^ '_'\\d+.*?\\n//; # remove labels\n\nsay \"Datasize: $name-count Strings: $string-count\\n\"\n ~ join('', %strings.keys.sort.reverse «~» \"\\n\")\n ~ $code;\n\n```\n\nOutput:\n\n```\nDatasize: 1 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (43) 65\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-51) 10\n 65 halt\n```" } ]
[ { "role": "user", "content": "Lexical Analyzer\n\nDefinition from Wikipedia:\n\n: *Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified \"meaning\"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though \"scanner\" is also used to refer to the first stage of a lexer).*\n\nCreate a lexical analyzer for the simple programming language specified below. The\nprogram should read input from a file and/or stdin, and write output to a file and/or\nstdout. If the language being used has a lexer module/library/class, it would be great\nif two versions of the solution are provided: One without the lexer module, and one with.\n\nInput Specification\n\nThe simple programming language to be analyzed is more or less a subset of C. It supports the following tokens:\n\nOperators\n\n: : : | Name | Common name | Character sequence |\n | --- | --- | --- |\n | Op\\_multiply | multiply | \\* |\n | Op\\_divide | divide | / |\n | Op\\_mod | mod | % |\n | Op\\_add | plus | + |\n | Op\\_subtract | minus | - |\n | Op\\_negate | unary minus | - |\n | Op\\_less | less than | < |\n | Op\\_lessequal | less than or equal | <= |\n | Op\\_greater | greater than | > |\n | Op\\_greaterequal | greater than or equal | >= |\n | Op\\_equal | equal | == |\n | Op\\_notequal | not equal | != |\n | Op\\_not | unary not | ! |\n | Op\\_assign | assignment | = |\n | Op\\_and | logical and | && |\n | Op\\_or | logical or | ¦¦ |\n\n* The `-` token should always be interpreted as Op\\_subtract by the lexer. Turning some Op\\_subtract into Op\\_negate will be the job of the syntax analyzer, which is not part of this task.\n\nSymbols\n\n: : : | Name | Common name | Character |\n | --- | --- | --- |\n | LeftParen | left parenthesis | ( |\n | RightParen | right parenthesis | ) |\n | LeftBrace | left brace | { |\n | RightBrace | right brace | } |\n | Semicolon | semi-colon | ; |\n | Comma | comma | , |\n\nKeywords\n\n: : : | Name | Character sequence |\n | --- | --- |\n | Keyword\\_if | if |\n | Keyword\\_else | else |\n | Keyword\\_while | while |\n | Keyword\\_print | print |\n | Keyword\\_putc | putc |\n\nIdentifiers and literals\n\nThese differ from the the previous tokens, in that each occurrence of them has a value associated with it.\n\n: : : | Name | Common name | Format description | Format regex | Value |\n | --- | --- | --- | --- | --- |\n | Identifier | identifier | one or more letter/number/underscore characters, but not starting with a number | `[_a-zA-Z][_a-zA-Z0-9]*` | as is |\n | Integer | integer literal | one or more digits | `[0-9]+` | as is, interpreted as a number |\n | Integer | char literal | exactly one character (anything except newline or single quote) or one of the allowed escape sequences, enclosed by single quotes | `'([^'\\n]|\\\\n|\\\\\\\\)'` | the ASCII code point number of the character, e.g. 65 for `'A'` and 10 for `'\\n'` |\n | String | string literal | zero or more characters (anything except newline or double quote), enclosed by double quotes | `\"[^\"\\n]*\"` | the characters without the double quotes and with escape sequences converted |\n\n* For char and string literals, the `\\n` escape sequence is supported to represent a new-line character.\n* For char and string literals, to represent a backslash, use `\\\\`.\n* No other special sequences are supported. This means that:\n + Char literals cannot represent a single quote character (value 39).\n + String literals cannot represent strings containing double quote characters.\n\nZero-width tokens\n\n: : : | Name | Location |\n | --- | --- |\n | End\\_of\\_input | when the end of the input stream is reached |\n\nWhite space\n\n* Zero or more whitespace characters, or comments enclosed in `/* ... */`, are allowed between any two tokens, with the exceptions noted below.\n* \"Longest token matching\" is used to resolve conflicts (e.g., in order to match **<=** as a single token rather than the two tokens **<** and **=**).\n* Whitespace is *required* between two tokens that have an alphanumeric character or underscore at the edge.\n + This means: keywords, identifiers, and integer literals.\n + e.g. `ifprint` is recognized as an identifier, instead of the keywords if and print.\n + e.g. `42fred` is invalid, and neither recognized as a number nor an identifier.\n* Whitespace is *not allowed* inside of tokens (except for chars and strings where they are part of the value).\n + e.g. `& &` is invalid, and not interpreted as the && operator.\n\nFor example, the following two program fragments are equivalent, and should produce the same token stream except for the line and column positions:\n\n* ```\n if ( p /* meaning n is prime */ ) {\n print ( n , \" \" ) ;\n count = count + 1 ; /* number of primes found so far */\n }\n\n ```\n* ```\n if(p){print(n,\" \");count=count+1;}\n\n ```\n\nComplete list of token names\n\n```\nEnd_of_input Op_multiply Op_divide Op_mod Op_add Op_subtract\nOp_negate Op_not Op_less Op_lessequal Op_greater Op_greaterequal\nOp_equal Op_notequal Op_assign Op_and Op_or Keyword_if\nKeyword_else Keyword_while Keyword_print Keyword_putc LeftParen RightParen\nLeftBrace RightBrace Semicolon Comma Identifier Integer\nString\n\n```\n\nOutput Format\n\nThe program output should be a sequence of lines, each consisting of the following whitespace-separated fields:\n\n1. the line number where the token starts\n2. the column number where the token starts\n3. the token name\n4. the token value (only for Identifier, Integer, and String tokens)\n5. the number of spaces between fields is up to you. Neatly aligned is nice, but not a requirement.\n\nThis task is intended to be used as part of a pipeline, with the other compiler tasks - for example:\n \n**lex < hello.t | parse | gen | vm**\n\nOr possibly:\n \n**lex hello.t lex.out**\n \n**parse lex.out parse.out**\n \n**gen parse.out gen.out**\n \n**vm gen.out**\n\nThis implies that the output of this task (the lexical analyzer) should be suitable as input to any of the Syntax Analyzer task programs.\n\nDiagnostics\n\nThe following error conditions should be caught:\n\n: : : | Error | Example |\n | --- | --- |\n | Empty character constant | `''` |\n | Unknown escape sequence. | `\\r` |\n | Multi-character constant. | `'xx'` |\n | End-of-file in comment. Closing comment characters not found. |\n | End-of-file while scanning string literal. Closing string character not found. |\n | End-of-line while scanning string literal. Closing string character not found before end-of-line. |\n | Unrecognized character. | |\n | Invalid number. Starts like a number, but ends in non-numeric characters. | `123abc` |\n\nTest Cases\n\n: | Input | Output |\n | --- | --- |\n | Test Case 1: ``` /* Hello world */ print(\"Hello, World!\\n\"); ``` | **``` 4 1 Keyword_print 4 6 LeftParen 4 7 String \"Hello, World!\\n\" 4 24 RightParen 4 25 Semicolon 5 1 End_of_input ```** |\n | Test Case 2: ``` /* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, \"\\n\"); ``` | **``` 4 1 Identifier phoenix_number 4 16 Op_assign 4 18 Integer 142857 4 24 Semicolon 5 1 Keyword_print 5 6 LeftParen 5 7 Identifier phoenix_number 5 21 Comma 5 23 String \"\\n\" 5 27 RightParen 5 28 Semicolon 6 1 End_of_input ```** |\n | Test Case 3: ``` /* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ \"String literal\" /* Add */ + /* Ident */ variable_name /* character literal */ '\\n' /* character literal */ '\\\\' /* character literal */ ' ' ``` | **``` 5 16 Keyword_print 5 40 Op_subtract 6 16 Keyword_putc 6 40 Op_less 7 16 Keyword_if 7 40 Op_greater 8 16 Keyword_else 8 40 Op_lessequal 9 16 Keyword_while 9 40 Op_greaterequal 10 16 LeftBrace 10 40 Op_equal 11 16 RightBrace 11 40 Op_notequal 12 16 LeftParen 12 40 Op_and 13 16 RightParen 13 40 Op_or 14 16 Op_subtract 14 40 Semicolon 15 16 Op_not 15 40 Comma 16 16 Op_multiply 16 40 Op_assign 17 16 Op_divide 17 40 Integer 42 18 16 Op_mod 18 40 String \"String literal\" 19 16 Op_add 19 40 Identifier variable_name 20 26 Integer 10 21 26 Integer 92 22 26 Integer 32 23 1 End_of_input ```** |\n | Test Case 4: ``` /*** test printing, embedded \\n and comments with lots of '*' ***/ print(42); print(\"\\nHello World\\nGood Bye\\nok\\n\"); print(\"Print a slash n - \\\\n.\\n\"); ``` | **``` 2 1 Keyword_print 2 6 LeftParen 2 7 Integer 42 2 9 RightParen 2 10 Semicolon 3 1 Keyword_print 3 6 LeftParen 3 7 String \"\\nHello World\\nGood Bye\\nok\\n\" 3 38 RightParen 3 39 Semicolon 4 1 Keyword_print 4 6 LeftParen 4 7 String \"Print a slash n - \\\\n.\\n\" 4 33 RightParen 4 34 Semicolon 5 1 End_of_input ```** |\n\nAdditional examples\n\nYour solution should pass all the test cases above and the additional tests found **Here**.\n\nReference\n\nThe C and Python versions can be considered reference implementations.\n\nRelated Tasks\n\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\nThis is more complicated than strictly necessary for this task. It is set up to be easily adapted to do syntax analysis.\n\n(Note: there are several bogus comments added solely to help with syntax highlighting.)\n\n**Works with**: Rakudo version 2016.08\n\n```\ngrammar tiny_C {\n rule TOP { ^ <.whitespace>? <tokens> + % <.whitespace> <.whitespace> <eoi> }\n\n rule whitespace { [ <comment> + % <ws> | <ws> ] }\n\n token comment { '/*' ~ '*/' .*? }\n\n token tokens {\n [\n | <operator> { make $/<operator>.ast }\n | <keyword> { make $/<keyword>.ast }\n | <symbol> { make $/<symbol>.ast }\n | <identifier> { make $/<identifier>.ast }\n | <integer> { make $/<integer>.ast }\n | <char> { make $/<char>.ast }\n | <string> { make $/<string>.ast }\n | <error>\n ]\n }\n\n proto token operator {*}\n token operator:sym<*> { '*' { make 'Op_multiply' } }\n token operator:sym</> { '/'<!before '*'> { make 'Op_divide' } }\n token operator:sym<%> { '%' { make 'Op_mod' } }\n token operator:sym<+> { '+' { make 'Op_add' } }\n token operator:sym<-> { '-' { make 'Op_subtract' } }\n token operator:sym('<='){ '<=' { make 'Op_lessequal' } }\n token operator:sym('<') { '<' { make 'Op_less' } }\n token operator:sym('>='){ '>=' { make 'Op_greaterequal'} }\n token operator:sym('>') { '>' { make 'Op_greater' } }\n token operator:sym<==> { '==' { make 'Op_equal' } }\n token operator:sym<!=> { '!=' { make 'Op_notequal' } }\n token operator:sym<!> { '!' { make 'Op_not' } }\n token operator:sym<=> { '=' { make 'Op_assign' } }\n token operator:sym<&&> { '&&' { make 'Op_and' } }\n token operator:sym<||> { '||' { make 'Op_or' } }\n\n proto token keyword {*}\n token keyword:sym<if> { 'if' { make 'Keyword_if' } }\n token keyword:sym<else> { 'else' { make 'Keyword_else' } }\n token keyword:sym<putc> { 'putc' { make 'Keyword_putc' } }\n token keyword:sym<while> { 'while' { make 'Keyword_while' } }\n token keyword:sym<print> { 'print' { make 'Keyword_print' } }\n\n proto token symbol {*}\n token symbol:sym<(> { '(' { make 'LeftParen' } }\n token symbol:sym<)> { ')' { make 'RightParen' } }\n token symbol:sym<{> { '{' { make 'LeftBrace' } }\n token symbol:sym<}> { '}' { make 'RightBrace' } }\n token symbol:sym<;> { ';' { make 'Semicolon' } }\n token symbol:sym<,> { ',' { make 'Comma' } }\n\n token identifier { <[_A..Za..z]><[_A..Za..z0..9]>* { make 'Identifier ' ~ $/ } }\n token integer { <[0..9]>+ { make 'Integer ' ~ $/ } }\n\n token char {\n '\\'' [<-[']> | '\\n' | '\\\\\\\\'] '\\''\n { make 'Char_Literal ' ~ $/.subst(\"\\\\n\", \"\\n\").substr(1, *-1).ord }\n }\n\n token string {\n '\"' <-[\"\\n]>* '\"' #'\n {\n make 'String ' ~ $/;\n note 'Error: Unknown escape sequence.' and exit if (~$/ ~~ m:r/ <!after <[\\\\]>>[\\\\<-[n\\\\]>]<!before <[\\\\]>> /);\n }\n }\n\n token eoi { $ { make 'End_of_input' } }\n\n token error {\n | '\\'''\\'' { note 'Error: Empty character constant.' and exit }\n | '\\'' <-[']> ** {2..*} '\\'' { note 'Error: Multi-character constant.' and exit }\n | '/*' <-[*]>* $ { note 'Error: End-of-file in comment.' and exit }\n | '\"' <-[\"]>* $ { note 'Error: End-of-file in string.' and exit }\n | '\"' <-[\"]>*? \\n { note 'Error: End of line in string.' and exit } #'\n }\n}\n\nsub parse_it ( $c_code ) {\n my $l;\n my @pos = gather for $c_code.lines>>.chars.kv -> $line, $v {\n take [ $line + 1, $_ ] for 1 .. ($v+1); # v+1 for newline\n $l = $line+2;\n }\n @pos.push: [ $l, 1 ]; # capture eoi\n\n for flat $c_code<tokens>.list, $c_code<eoi> -> $m {\n say join \"\\t\", @pos[$m.from].fmt('%3d'), $m.ast;\n }\n}\n\nmy $tokenizer = tiny_C.parse(@*ARGS[0].IO.slurp);\nparse_it( $tokenizer );\n\n```\n\nOutput  —  test case 3:\n\n```\n 5 16 Keyword_print\n 5 40 Op_subtract\n 6 16 Keyword_putc\n 6 40 Op_less\n 7 16 Keyword_if\n 7 40 Op_greater\n 8 16 Keyword_else\n 8 40 Op_lessequal\n 9 16 Keyword_while\n 9 40 Op_greaterequal\n 10 16 LeftBrace\n 10 40 Op_equal\n 11 16 RightBrace\n 11 40 Op_notequal\n 12 16 LeftParen\n 12 40 Op_and\n 13 16 RightParen\n 13 40 Op_or\n 14 16 Op_subtract\n 14 40 Semicolon\n 15 16 Op_not\n 15 40 Comma\n 16 16 Op_multiply\n 16 40 Op_assign\n 17 16 Op_divide\n 17 40 Integer 42\n 18 16 Op_mod\n 18 40 String \"String literal\"\n 19 16 Op_add\n 19 40\tIdentifier variable_name\n 20 26\tChar_Literal 10\n 21 26\tChar_Literal 92\n 22 26\tChar_Literal 32\n 23 1\tEnd_of_input\n\n```" } ]
[ { "role": "user", "content": "Task\n\n**Introduction**\n \n \nMany programming languages allow file inclusion, so that for example, standard declarations or code-snippets can be stored in a separate source file and be included into the programs that require them at compile-time, without the need for cut-and-paste.\n \n \nProbably the C pre-processor is the most well-known example.\n \n \nThe purpose of this task is to demonstrate how a file inclusion pre-processor could be implemented in your language, for your language. This does not mean to imply that your language needs a file inclusion pre-processor - many languages don't have such a facility.\n \nOther languages, on the other hand do have file inclusion, e.g.: C, COBOL, PL/1.\n \n \nThe distinction between compiled and interpreted languages should be irrelevent - this is a specialised text processing exercise - reading a source file and producing a modified source file that aldo contains the contents of one or more other files.\n \n \nHopefully, the solutions to this task will enable the file inclusion facilities of the languages to be compared, even for languages that don't need such facilities because they have sophisticated equivalents.\n \n \n**The pre-processor**\n \n \nCreate a simple pre-processor that implements file-inclusion for your language.\n \n \nThe pre-processor need not check the validity of the resultant source. The pre-processor's job is purely to insert te specified files into the source at the required points. Whether the result is syntacticly valid or not is a matter for the compiler/interpreter when it is presented with the source.\n \n \nThe syntax accepted for your pre-processor should be as per the standard for your language, should your language have such a facility.\nE.g. for C the pre-processor must recognise and handle \"#include\" directives. For PL/1, %include statements would be processed and for COBOL, COPY statements, and so on.\n \n \nIf your language does not have a standard facility for file-inclusion, implement that used by a popular compiler/interpreter for the language.\n \nIf there is no such feature, either use the C style #include directive or choose something of your own invention, e.g., #include would be problematic for languages where # introduces a comment.\n \n \nState the syntax expected and any limitations, including whether nested includes are supported and if so, how deep the nesting can be.\n \n \n**Minimum requirements**\n \n \nAs a minimum, your pre-procdessor must be able to process a source file (read from a file or standard input, as you prefer) and generate another source file (written to a file or standard output, as you prefer). The file-inclusion directives in the source should be replaced by the contents of the specified files. Implementing nested file inclusion directives (i.e., if an included file contains another file-inclusion directive) is optional.\n \n \nPre-processors for some languages offer additional facilities, such as macro expansion and conditional compilation. Your pre-processor need not implement such things.\n \n \n**Notes**\n\n* implementors: The Task is about implementing a pre-processor for your language, not just describing it's features. Just as the task Calculating the value of e is not about using your language's in-built exp function but showing how e could be calculated, this is about showing how file inclusion could be implemented - even if the compiler/interpreter you are using already has such a facility.\n* the pre-processors on this page are supplied as-is, with no warranty - use at your own peril : )\n\nSee Also\n\n* include a file" }, { "role": "assistant", "content": "A file pre-processor is very nearly pointless for Raku. Raku is nominally an interpreted language; in actuality, it does single pass, just-in-time compilation on the fly as it loads the file. For libraries and constants (or semi constant variables) there is a robust built-in library (module) include system for code that can be pre-compiled and used on demand. `use some-library;` to import any objects exported by the module.\n\nThat's great for code references and constants, but isn't really intended for text inclusion of external files. Since the text file can not be pre-compiled, there isn't much point to having such a system. (For code at least, there are many different templating system modules for text templates; primarily, though not exclusively used for on-the-fly generation of dynamic HTML / XML documents.) One of those could certainly be bent into doing something like what this task is asking for, but are probably both over- and under-powered for the job.\n\n1. they are mostly intended for text, not code.\n2. they tend to be more geared toward inserting the content of a variable rather than the content of a file, although that could be subverted pretty easily.\n\nSo in Raku, there isn't a readily available system to do this, there isn't much point, and it's probably a bad idea...\n\nAh well, that never stopped us before.\n\nA Raku script to do source filtering / preprocessing: save it and call it 'include'\n\n```\nunit sub MAIN ($file-name);\nmy $file = slurp $file-name;\nput $file.=subst(/[^^|['{{' \\s*]] '#include' \\s+ (\\S+) \\s* '}}'?/, {run(«$*EXECUTABLE-NAME $*PROGRAM-NAME $0», :out).out.slurp(:close).trim}, :g);\n\n```\n\nThis will find: any line starting with '#include' followed by a (absolute or relative) path to a file, or #include ./path/to/file.name enclosed in double curly brackets anywhere in the file.\n\nIt will replace the #include notation by the contents of the file referenced, will follow nested #includes arbitrarily deeply, and echo the processed file to STDOUT.\n\nLet's test it out. Here is a test script and a bunch of include files.\n\nTop level named... whatever, let's call it 'preprocess.raku'\n\n```\n# Top level test script file for #include Rosettacode\n# 'Compiler/Simple file inclusion pre processor' task\n\n# some code\n\nsay .³ for ^10;\n\n#include ./include1.file\n\n```\n\ninclude1.file\n\n```\n# included #include1 file >1>\n# test to ensure it only tries to execute #include of the right format\n\n# more code\nsay .³³ for ^10;\n# and more comments\n\n#include ./include2.file # comments ok at end of include line\n# <1<\n```\n\ninclude2.file\n\n```\n# nested #include2.file >2>\nsay \"Test for an nested include inside a line: {{ #include ./include3.file }}\";\n# pointless but why not? <2<\n```\n\ninclude3.file\n\n```\n>3> Yep, it works! <3<\n\n```\n\nInvoke at a command line:\n\n`raku include preprocess.raku`\n\nOutput:\n\n```\n# Top level test script file for #include Rosettacode\n# 'Compiler/Simple file inclusion pre processor' task\n\n# some code\n\nsay .³ for ^10;\n\n# included #include1 file >1>\n# test to ensure it only tries to execute #include of the right format\n\n# more code\nsay .³³ for ^10;\n# and more comments\n\n# nested #include2.file >2>\nsay \"Test for an nested include inside a line: >3> Yep, it works! <3<\";\n# pointless but why not? <2<# comments ok at end of include line\n# <1<\n\n```\n\nYou can either redirect that into a file, or just pass it back into the compiler to execute it:\n\n`raku include preprocess.raku | raku`\n\nOutput:\n\n```\n0\n1\n8\n27\n64\n125\n216\n343\n512\n729\n0\n1\n8589934592\n5559060566555523\n73786976294838206464\n116415321826934814453125\n47751966659678405306351616\n7730993719707444524137094407\n633825300114114700748351602688\n30903154382632612361920641803529\nTest for an nested include inside a line: >3> Yep, it works! <3<\n```\n\nNote that this is not very robust, (it's 3 lines of code, what do you expect?) but it satisfies the task requirements as far as I can tell." } ]
[ { "role": "user", "content": "**Verifying Syntax** \nA Syntax Analyzer that verifies a token stream, \noutputs a string \"true\" if the token stream matches the grammar requirement, \noutputs a string \"false\" if the token stream does not match the grammar.\n\n**Task** \nThe program reads input from a file of token stream, \nreads it and outputs a string \"true\" if the token stream matches the grammar, \noutputs a string \"false\" and error messages if the token stream does not match the grammar, \nbased on the grammar below. The grammar is written in Extended Backus-Naur Form (EBNF).\n\n**Grammar**\n\n```\nstmt = expr ; \n\nexpr = expr_level_2; \nexpr_level_2 = expr_level_3 {\"or\" expr_level_3} ; \nexpr_level_3 = expr_level_4 {\"and\" expr_level_4} ; \nexpr_level_4 = [\"not\"] expr_level_5 [('=' | '<') expr_level_5] ; \nexpr_level_5 = expr_level_6 {('+' | '-') expr_level_6} ; \nexpr_level_6 = primary {('*' | '/') primary} ; \n\nprimary = Identifier\n | Integer\n | '(' expr ')'\n | \"true\"\n | \"false\"\n  ;\nInteger = Digit {Digit};\n\nIdentifier = Letter {Letter | Digit | '_'};\n\nDigit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\" ;\n\nLetter = \"a\" | \"b\" | \"c\" | \"d\" | \"e\" | \"f\" | \"g\" | \"h\" | \"i\" | \"j\" \n | \"k\" | \"l\" | \"m\" | \"n\" | \"o\" | \"p\" | \"q\" | \"r\" | \"s\" | \"t\" \n | \"u\" | \"v\" | \"w\" | \"x\" | \"y\" | \"z\" | \"A\" | \"B\" | \"C\" | \"D\" \n | \"E\" | \"F\" | \"G\" | \"H\" | \"I\" | \"J\" | \"K\" | \"L\" | \"M\" | \"N\" \n | \"O\" | \"P\" | \"Q\" | \"R\" | \"S\" | \"T\" | \"U\" | \"V\" | \"W\" | \"X\" \n | \"Y\" | \"Z\" ;\n\n```" }, { "role": "assistant", "content": "Format of task grammar is changed from EBNF to ABNF to cater for the Grammar::ABNF module and testing data is taken from the Perl entry.\n\n```\n# 20200511 Raku programming solution\n\nuse Grammar::ABNF;\n\ngrammar G is Grammar::ABNF { token CRLF { \"\\n\" } };\n\nmy $g = G.generate(Q:to<RULES>\nstmt = expr\nexpr = expr_level_2\nexpr_level_2 = expr_level_3 *( \" or \" expr_level_3 )\nexpr_level_3 = expr_level_4 *( \" and \" expr_level_4 )\nexpr_level_4 = [\"not \"] expr_level_5 [ [ \" = \" / \" < \" ] expr_level_5 ]\nexpr_level_5 = expr_level_6 *( [ \" + \" / \" - \" ] expr_level_6 )\nexpr_level_6 = primary *( [ \" * \" / \" / \" ] primary )\nInteger = Digit *( Digit )\nIdentifier = Letter *( Letter / Digit / \"_\" )\nprimary = Identifier / Integer / \"(\" expr \")\" / \" true \" / \" false \"\nDigit = \"0\" / \"1\" / \"2\" / \"3\" / \"4\" / \"5\" / \"6\" / \"7\" / \"8\" / \"9\"\nLetter = \"a\" / \"b\" / \"c\" / \"d\" / \"e\" / \"f\" / \"g\" / \"h\" / \"i\" / \"j\" \n / \"k\" / \"l\" / \"m\" / \"n\" / \"o\" / \"p\" / \"q\" / \"r\" / \"s\" / \"t\"\n / \"u\" / \"v\" / \"w\" / \"x\" / \"y\" / \"z\" / \"A\" / \"B\" / \"C\" / \"D\"\n / \"E\" / \"F\" / \"G\" / \"H\" / \"I\" / \"J\" / \"K\" / \"L\" / \"M\" / \"N\"\n / \"O\" / \"P\" / \"Q\" / \"R\" / \"S\" / \"T\" / \"U\" / \"V\" / \"W\" / \"X\" \n / \"Y\" / \"Z\"\nRULES\n);\n\nmy \\DATA = Q:to<DATA>;\n3 + not 5\n3 + (not 5)\n(42 + 3\n(42 + 3 syntax_error\nnot 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true\nand 3 < 2\nnot 7 < 2\n2 < 3 < 4\n2 < foobar - 3 < 4\n2 < foobar and 3 < 4\n4 * (32 - 16) + 9 = 73\n235 76 + 1\na + b = not c and false\na + b = (not c) and false\na + b = (not c and false)\nab_c / bd2 or < e_f7\ng not = h\ni++\nj & k\nl or _m\nUPPER_cAsE_aNd_letter_and_12345_test\nDATA\n\nsay $g.parse($_).Bool, \"\\t\", $_ for DATA.lines\n\n```\n\nOutput:\n\n```\nFalse 3 + not 5\nTrue 3 + (not 5)\nFalse (42 + 3\nFalse (42 + 3 syntax_error\nTrue not 3 < 4 or (true or 3 / 4 + 8 * 5 - 5 * 2 < 56) and 4 * 3 < 12 or not true\nFalse and 3 < 2\nTrue not 7 < 2\nFalse 2 < 3 < 4\nFalse 2 < foobar - 3 < 4\nTrue 2 < foobar and 3 < 4\nTrue 4 * (32 - 16) + 9 = 73\nFalse 235 76 + 1\nFalse a + b = not c and false\nTrue a + b = (not c) and false\nTrue a + b = (not c and false)\nFalse ab_c / bd2 or < e_f7\nFalse g not = h\nFalse i++\nFalse j & k\nFalse l or _m\nTrue UPPER_cAsE_aNd_letter_and_12345_test\n\n```" } ]
[ { "role": "user", "content": "Virtual Machine Interpreter\n\nA virtual machine implements a computer in software.\n\nWrite a virtual machine interpreter. This interpreter should be able to run virtual\nassembly language programs created via the task. This is a\nbyte-coded, 32-bit word stack based virtual machine.\n\nThe program should read input from a file and/or stdin, and write output to a file and/or\nstdout.\n\nInput format\n\nGiven the following program:\n\n```\ncount = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\n\n```\n\nThe output from the Code generator is a virtual assembly code program:\n\n| Output from gen, input to VM |\n| --- |\n| **``` Datasize: 1 Strings: 2 \"count is: \" \"\\n\" 0 push 1 5 store [0] 10 fetch [0] 15 push 10 20 lt 21 jz (43) 65 26 push 0 31 prts 32 fetch [0] 37 prti 38 push 1 43 prts 44 fetch [0] 49 push 1 54 add 55 store [0] 60 jmp (-51) 10 65 halt ```** |\n\nThe first line of the input specifies the datasize required and the number of constant\nstrings, in the order that they are reference via the code.\n\nThe data can be stored in a separate array, or the data can be stored at the beginning of\nthe stack. Data is addressed starting at 0. If there are 3 variables, the 3rd one if\nreferenced at address 2.\n\nIf there are one or more constant strings, they come next. The code refers to these\nstrings by their index. The index starts at 0. So if there are 3 strings, and the code\nwants to reference the 3rd string, 2 will be used.\n\nNext comes the actual virtual assembly code. The first number is the code address of that\ninstruction. After that is the instruction mnemonic, followed by optional operands,\ndepending on the instruction.\n\nRegisters\n\nsp:\n\n```\n the stack pointer - points to the next top of stack. The stack is a 32-bit integer\n array.\n\n```\n\npc:\n\n```\n the program counter - points to the current instruction to be performed. The code is an\n array of bytes.\n\n```\n\nData:\n\n```\n data\n string pool\n\n```\n\nInstructions\n\nEach instruction is one byte. The following instructions also have a 32-bit integer\noperand:\n\n```\nfetch [index]\n\n```\n\nwhere index is an index into the data array.\n\n```\nstore [index]\n\n```\n\nwhere index is an index into the data array.\n\n```\npush n\n\n```\n\nwhere value is a 32-bit integer that will be pushed onto the stack.\n\n```\njmp (n) addr\n\n```\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\n```\njz (n) addr\n\n```\n\nwhere (n) is a 32-bit integer specifying the distance between the current location and the\ndesired location. addr is an unsigned value of the actual code address.\n\nThe following instructions do not have an operand. They perform their operation directly\nagainst the stack:\n\nFor the following instructions, the operation is performed against the top two entries in\nthe stack:\n\n```\nadd\nsub\nmul\ndiv\nmod\nlt\ngt\nle\nge\neq\nne\nand\nor\n\n```\n\nFor the following instructions, the operation is performed against the top entry in the\nstack:\n\n```\nneg\nnot\n\n```\n\nPrint the word at stack top as a character.\n\n```\nprtc\n\n```\n\nPrint the word at stack top as an integer.\n\n```\nprti\n\n```\n\nStack top points to an index into the string pool. Print that entry.\n\n```\nprts\n\n```\n\nUnconditional stop.\n\n```\nhalt\n\n```\n\nA simple example virtual machine\n\n```\ndef run_vm(data_size)\n int stack[data_size + 1000]\n set stack[0..data_size - 1] to 0\n int pc = 0\n while True:\n op = code[pc]\n pc += 1\n\n if op == FETCH:\n stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);\n pc += word_size\n elif op == STORE:\n stack[bytes_to_int(code[pc:pc+word_size])[0]] = stack.pop();\n pc += word_size\n elif op == PUSH:\n stack.append(bytes_to_int(code[pc:pc+word_size])[0]);\n pc += word_size\n elif op == ADD: stack[-2] += stack[-1]; stack.pop()\n elif op == SUB: stack[-2] -= stack[-1]; stack.pop()\n elif op == MUL: stack[-2] *= stack[-1]; stack.pop()\n elif op == DIV: stack[-2] /= stack[-1]; stack.pop()\n elif op == MOD: stack[-2] %= stack[-1]; stack.pop()\n elif op == LT: stack[-2] = stack[-2] < stack[-1]; stack.pop()\n elif op == GT: stack[-2] = stack[-2] > stack[-1]; stack.pop()\n elif op == LE: stack[-2] = stack[-2] <= stack[-1]; stack.pop()\n elif op == GE: stack[-2] = stack[-2] >= stack[-1]; stack.pop()\n elif op == EQ: stack[-2] = stack[-2] == stack[-1]; stack.pop()\n elif op == NE: stack[-2] = stack[-2] != stack[-1]; stack.pop()\n elif op == AND: stack[-2] = stack[-2] and stack[-1]; stack.pop()\n elif op == OR: stack[-2] = stack[-2] or stack[-1]; stack.pop()\n elif op == NEG: stack[-1] = -stack[-1]\n elif op == NOT: stack[-1] = not stack[-1]\n elif op == JMP: pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == JZ: if stack.pop() then pc += word_size else pc += bytes_to_int(code[pc:pc+word_size])[0]\n elif op == PRTC: print stack[-1] as a character; stack.pop()\n elif op == PRTS: print the constant string referred to by stack[-1]; stack.pop()\n elif op == PRTI: print stack[-1] as an integer; stack.pop()\n elif op == HALT: break\n\n```\n\nAdditional examples\n\nYour solution should pass all the test cases above and the additional tests found **Here**.\n\nReference\n\nThe C and Python versions can be considered reference implementations.\n\nRelated Tasks\n\n* Lexical Analyzer task\n* Syntax Analyzer task\n* Code Generator task\n* AST Interpreter task\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\nNon-standard size of instructions (not byte-coded, 'Datasize' is 3 not 1) required adjusting the jump offsets.\n\nNOTE: I don't think you are allowed to change the jump offsets.\nThey come from another program from another company from another planet from another galaxy.\n\nWIP: discovered 'P5pack' module, this may allow for completing the task properly, using correct offsets\n\n**Translation of**: Perl\n\n```\nmy @CODE = q:to/END/.lines;\nDatasize: 3 Strings: 2\n\"count is: \"\n\"\\n\"\n 0 push 1\n 5 store [0]\n 10 fetch [0]\n 15 push 10\n 20 lt\n 21 jz (68) 65 # jump value adjusted\n 26 push 0\n 31 prts\n 32 fetch [0]\n 37 prti\n 38 push 1\n 43 prts\n 44 fetch [0]\n 49 push 1\n 54 add\n 55 store [0]\n 60 jmp (-87) 10 # jump value adjusted\n 65 halt\nEND\n\nmy (@stack, @strings, @data, $memory);\nmy $pc = 0;\n\n(@CODE.shift) ~~ /'Datasize:' \\s+ (\\d+) \\s+ 'Strings:' \\s+ (\\d+)/ or die \"bad header\";\nmy $w = $0; # 'wordsize' of op-codes and 'width' of data values\[email protected]: (my $s = @CODE.shift) eq '\"\\n\"' ?? \"\\n\" !! $s.subst(/'\"'/, '', :g) for 1..$1;\n\nsub value { substr($memory, ($pc += $w) - $w, $w).trim }\n\nmy %ops = (\n 'no-op' => sub { },\n 'add' => sub { @stack[*-2] += @stack.pop },\n 'sub' => sub { @stack[*-2] -= @stack.pop },\n 'mul' => sub { @stack[*-2] *= @stack.pop },\n 'div' => sub { @stack[*-2] /= @stack.pop },\n 'mod' => sub { @stack[*-2]  %= @stack.pop },\n 'neg' => sub { @stack[*-1] = - @stack[*-1] },\n 'and' => sub { @stack[*-2] &&= @stack[*-1]; @stack.pop },\n 'or' => sub { @stack[*-2] ||= @stack[*-1]; @stack.pop },\n 'not' => sub { @stack[*-1] = @stack[*-1]  ?? 0 !! 1 },\n 'lt' => sub { @stack[*-1] = @stack[*-2] < @stack.pop ?? 1 !! 0 },\n 'gt' => sub { @stack[*-1] = @stack[*-2] > @stack.pop ?? 1 !! 0 },\n 'le' => sub { @stack[*-1] = @stack[*-2] <= @stack.pop ?? 1 !! 0 },\n 'ge' => sub { @stack[*-1] = @stack[*-2] >= @stack.pop ?? 1 !! 0 },\n 'ne' => sub { @stack[*-1] = @stack[*-2] != @stack.pop ?? 1 !! 0 },\n 'eq' => sub { @stack[*-1] = @stack[*-2] == @stack.pop ?? 1 !! 0 },\n 'store' => sub { @data[&value] = @stack.pop },\n 'fetch' => sub { @stack.push: @data[&value] // 0 },\n 'push' => sub { @stack.push: value() },\n 'jmp' => sub { $pc += value() - $w },\n 'jz' => sub { $pc += @stack.pop ?? $w !! value() - $w },\n 'prts' => sub { print @strings[@stack.pop] },\n 'prti' => sub { print @stack.pop },\n 'prtc' => sub { print chr @stack.pop },\n 'halt' => sub { exit }\n);\n\nmy %op2n = %ops.keys.sort Z=> 0..*;\nmy %n2op = %op2n.invert;\n%n2op{''} = 'no-op';\n\nfor @CODE -> $_ {\n next unless /\\w/;\n /^ \\s* \\d+ \\s+ (\\w+)/ or die \"bad line $_\";\n $memory ~= %op2n{$0}.fmt(\"%{$w}d\");\n /'(' ('-'?\\d+) ')' | (\\d+) ']'? $/;\n $memory ~= $0 ?? $0.fmt(\"%{$w}d\") !! ' ' x $w;\n}\n\nloop {\n my $opcode = substr($memory, $pc, $w).trim;\n $pc += $w;\n %ops{%n2op{ $opcode }}();\n}\n\n```\n\nOutput:\n\n```\ncount is: 1\ncount is: 2\ncount is: 3\ncount is: 4\ncount is: 5\ncount is: 6\ncount is: 7\ncount is: 8\ncount is: 9\n```" } ]
[ { "role": "user", "content": "Find the composite numbers **k** in base 10, that have no single digit prime factors and whose prime factors are all a substring of **k**.\n\nTask\n\n* Find and show here, on this page, the first ten elements of the sequence.\n\nStretch\n\n* Find and show the next ten elements." }, { "role": "assistant", "content": "```\nuse Prime::Factor;\nuse Lingua::EN::Numbers;\n\nput (2..∞).hyper(:5000batch).map( {\n next if (1 < $_ gcd 210) || .is-prime || any .&prime-factors.map: -> $n { !.contains: $n };\n $_\n} )[^20].batch(10)».&comma».fmt(\"%10s\").join: \"\\n\";\n\n```\n\nOutput:\n\n```\n 15,317 59,177 83,731 119,911 183,347 192,413 1,819,231 2,111,317 2,237,411 3,129,361\n 5,526,173 11,610,313 13,436,683 13,731,373 13,737,841 13,831,103 15,813,251 17,692,313 19,173,071 28,118,827\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a compound data type:\n\n```\n Point(x,y) \n\n```\n\nA compound data type is one that holds multiple independent values.\n\nRelated task\n\n* Enumeration\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #24 \"Seoul\"\n\n### Array\n\n```\nmy @point = 3, 8;\n\nmy Int @point = 3, 8; # or constrain to integer elements\n```\n\n### Hash\n\n```\nmy %point = x => 3, y => 8;\n\nmy Int %point = x => 3, y => 8; # or constrain the hash to have integer values\n```\n\n### Class instance\n\n```\nclass Point { has Real ($.x, $.y) is rw; }\nmy Point $point .= new: x => 3, y => 8;\n```\n\n### Set\n\n```\nmy $s1 = set <a b c d>; # order is not preserved\nmy $s2 = set <c d e f>;\nsay $s1 (&) $s2; # OUTPUT«set(c, e)»\nsay $s1 ∩ $s2; # we also do Unicode\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show here when the concatenation of two primes   (**p1**,  **p2**)   shown in base ten is also prime,   where   **p1,   p2  <  100**." }, { "role": "assistant", "content": "Inefficient, but for a limit of 100, who cares?\n\n```\nmy @p = ^1e2 .grep: *.is-prime;\n\nsay display ( @p X~ @p ).grep( *.is-prime ).unique.sort( +* ); \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```\n128 matching:\n 23 37 53 73 113 137 173 193 197 211\n 223 229 233 241 271 283 293 311 313 317\n 331 337 347 353 359 367 373 379 383 389\n 397 433 523 541 547 571 593 613 617 673\n 677 719 733 743 761 773 797 977 1117 1123\n 1129 1153 1171 1319 1361 1367 1373 1723 1741 1747\n 1753 1759 1783 1789 1913 1931 1973 1979 1997 2311\n 2341 2347 2371 2383 2389 2917 2953 2971 3119 3137\n 3167 3719 3761 3767 3779 3797 4111 4129 4153 4159\n 4337 4373 4397 4723 4729 4759 4783 4789 5323 5347\n 5923 5953 6113 6131 6143 6173 6197 6719 6737 6761\n 6779 7129 7159 7331 7919 7937 8311 8317 8329 8353\n 8389 8923 8929 8941 8971 9719 9743 9767\n```" } ]
[ { "role": "user", "content": "Task\n\nUsing either native language concurrency syntax or freely available libraries, write a program to display the strings \"Enjoy\" \"Rosetta\" \"Code\", one string per line, in random order.\n\nConcurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.9\n\n```\nmy @words = <Enjoy Rosetta Code>;\[email protected](:batch(1)).map: { sleep rand; say $_ };\n\n```\n\nOutput:\n\n```\nCode\nRosetta\nEnjoy\n```" } ]
[ { "role": "user", "content": "Task\n\nList the *conditional structures* offered by a programming language. See Wikipedia: conditionals for descriptions.\n\nCommon conditional structures include **if-then-else** and **switch**.\n\nLess common are **arithmetic if**, **ternary operator** and **Hash-based conditionals**.\n\n***Arithmetic if** allows tight control over computed gotos, which optimizers have a hard time to figure out.*" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### if/else\n\nif, else, elsif, unless, and given work much as they do in Perl 5, with the following differences:\n\n* All the parentheses are now optional.\n* unless no longer permits elsif or else blocks.\n* If the block of an if, elsif, or unless has a nonzero arity, the value of the conditional expression is used as an argument to the block:\n\n ```\n if won() -> $prize {\n say \"You won $prize.\";\n }\n ```\n\n If an else block has a nonzero arity, it receives the value of the condition tested by the last if or elsif.\n\n### given/when\n\nSwitch structures are done by topicalization and by smartmatching in Raku. They are somewhat orthogonal, you can use a given block without when, and vice versa. But the typical use is:\n\n```\ngiven lc prompt(\"Done? \") {\n when 'yes' { return }\n when 'no' { next }\n default { say \"Please answer either yes or no.\" }\n}\n```\n\nwhen blocks are allowed in any block that topicalizes $\\_, including a\nfor loop (assuming one of its loop variables is bound to $\\_)\nor the body of a method (if you have declared the invocant as $\\_).\" See more at: https://docs.raku.org/language/control#index-entry-switch\\_(given)\n\nThere are also statement modifier forms of all of the above.\n\n### Ternary operator\n\nThe ternary operator looks like this:\n\n```\n$expression ?? do_something !! do_fallback\n```\n\n### Other short-circuiting operators\n\nand, or, &&, || and // work as in Perl 5." } ]
[ { "role": "user", "content": "Task\n: Create a program that can take a Latin verb and conjugate it, displaying in the following order:\n\n```\n1st person singular\n2nd person singular\n3rd person singular\n1st person plural\n2nd person plural\n3rd person plural\n\n```\n\n* Each should be on its own line.\n* Have at least one example from each of the 4 conjugations.\n* Irregular verbs are not required.\n* Translation into English is optional.\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\nSee also\n\n* Wikipedia: Latin conjugation." }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\nfor <amāre dare> -> $infinitive {\n say \"\\nPresent active indicative conjugation of infinitive $infinitive.\";\n my $verb = ($infinitive ~~ /^ (\\w+) ['a'|'ā'] 're' $/)[0];\n say $verb ?? (conjugate $verb) !! \"Sorry, don't know how to conjugate $infinitive\"\n}\n\nsub conjugate ($verb) { ($verb X~ <ō ās at āmus ātis ant>).join: \"\\n\" }\n\n```\n\nOutput:\n\n```\nPresent active indicative conjugation of infinitive amāre.\namō\namās\namat\namāmus\namātis\namant\n\nPresent active indicative conjugation of infinitive dare.\ndō\ndās\ndat\ndāmus\ndātis\ndant\n```" } ]
[ { "role": "user", "content": "Suppose that a matrix \n\nM\n{\\displaystyle {\\displaystyle M}}\n contains complex numbers. Then the conjugate transpose of \n\nM\n{\\displaystyle {\\displaystyle M}}\n is a matrix \n\nM\n\nH\n{\\displaystyle {\\displaystyle M^{H}}}\n containing the complex conjugates of the matrix transposition of \n\nM\n{\\displaystyle {\\displaystyle M}}\n.\n\n: : : (\n\n M\n\n H\n\n )\n\n j\n i\n =\n\n M\n\n i\n j\n ¯\n {\\displaystyle {\\displaystyle (M^{H})\\_{ji}={\\overline {M\\_{ij}}}}}\n\nThis means that row \n\nj\n{\\displaystyle {\\displaystyle j}}\n, column \n\ni\n{\\displaystyle {\\displaystyle i}}\n of the conjugate transpose equals the\n \ncomplex conjugate of row \n\ni\n{\\displaystyle {\\displaystyle i}}\n, column \n\nj\n{\\displaystyle {\\displaystyle j}}\n of the original matrix.\n\nIn the next list, \n\nM\n{\\displaystyle {\\displaystyle M}}\n must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: \n\n M\n\n H\n =\n M\n {\\displaystyle {\\displaystyle M^{H}=M}}\n .\n* A normal matrix is commutative in multiplication with its conjugate transpose: \n\n M\n\n H\n M\n =\n M\n\n M\n\n H\n {\\displaystyle {\\displaystyle M^{H}M=MM^{H}}}\n .\n* A unitary matrix has its inverse equal to its conjugate transpose: \n\n M\n\n H\n =\n\n M\n\n −\n 1\n {\\displaystyle {\\displaystyle M^{H}=M^{-1}}}\n . \n This is true iff \n\n M\n\n H\n M\n =\n\n I\n\n n\n {\\displaystyle {\\displaystyle M^{H}M=I\\_{n}}}\n and iff \n\n M\n\n M\n\n H\n =\n\n I\n\n n\n {\\displaystyle {\\displaystyle MM^{H}=I\\_{n}}}\n , where \n\n I\n\n n\n {\\displaystyle {\\displaystyle I\\_{n}}}\n is the identity matrix.\n\nTask\n\nGiven some matrix of complex numbers, find its conjugate transpose.\n\nAlso determine if the matrix is a:\n\n: : * Hermitian matrix,\n * normal matrix, or\n * unitary matrix.\n\nSee also\n\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015-12-13\n\n```\nfor [ # Test Matrices\n [ 1, 1+i, 2i],\n [ 1-i, 5, -3],\n [0-2i, -3, 0]\n ],\n [\n [1, 1, 0],\n [0, 1, 1],\n [1, 0, 1]\n ],\n [\n [0.707 , 0.707, 0],\n [0.707i, 0-0.707i, 0],\n [0 , 0, i]\n ]\n -> @m {\n say \"\\nMatrix:\";\n @m.&say-it;\n my @t = @m».conj.&mat-trans;\n say \"\\nTranspose:\";\n @t.&say-it;\n say \"Is Hermitian?\\t{is-Hermitian(@m, @t)}\";\n say \"Is Normal?\\t{is-Normal(@m, @t)}\";\n say \"Is Unitary?\\t{is-Unitary(@m, @t)}\";\n }\n\nsub is-Hermitian (@m, @t, --> Bool) {\n so @m».Complex eqv @t».Complex\n }\n\nsub is-Normal (@m, @t, --> Bool) {\n so mat-mult(@m, @t)».Complex eqv mat-mult(@t, @m)».Complex\n}\n\nsub is-Unitary (@m, @t, --> Bool) {\n so mat-mult(@m, @t, 1e-3)».Complex eqv mat-ident(+@m)».Complex;\n}\n\nsub mat-trans (@m) { map { [ @m[*;$_] ] }, ^@m[0] }\n\nsub mat-ident ($n) { [ map { [ flat 0 xx $_, 1, 0 xx $n - 1 - $_ ] }, ^$n ] }\n\nsub mat-mult (@a, @b, \\ε = 1e-15) {\n my @p;\n for ^@a X ^@b[0] -> ($r, $c) {\n @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;\n @p[$r][$c].=round(ε); # avoid floating point math errors\n }\n @p\n}\n\nsub say-it (@array) { $_».fmt(\"%9s\").say for @array }\n\n```\n\nOutput:\n\n```\nMatrix:\n[ 1 1+1i 0+2i]\n[ 1-1i 5 -3]\n[ 0-2i -3 0]\n\nTranspose:\n[ 1 1+1i 0+2i]\n[ 1-1i 5 -3]\n[ 0-2i -3 0]\nIs Hermitian?\tTrue\nIs Normal?\tTrue\nIs Unitary?\tFalse\n\nMatrix:\n[ 1 1 0]\n[ 0 1 1]\n[ 1 0 1]\n\nTranspose:\n[ 1 0 1]\n[ 1 1 0]\n[ 0 1 1]\nIs Hermitian?\tFalse\nIs Normal?\tTrue\nIs Unitary?\tFalse\n\nMatrix:\n[ 0.707 0.707 0]\n[ 0+0.707i 0-0.707i 0]\n[ 0 0 0+1i]\n\nTranspose:\n[ 0.707 0-0.707i 0]\n[ 0.707 0+0.707i 0]\n[ 0 0 0-1i]\nIs Hermitian?\tFalse\nIs Normal?\tTrue\nIs Unitary?\tTrue\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. \n \nDo the same for sequences of primes where the differences are strictly descending.\n \n \nIn both cases, show the sequence for primes   <   1,000,000.\n \n \nIf there are multiple sequences of the same length, only the first need be shown." }, { "role": "assistant", "content": "```\nuse Math::Primesieve;\nuse Lingua::EN::Numbers;\n\nmy $sieve = Math::Primesieve.new;\n\nmy $limit = 1000000;\n\nmy @primes = $sieve.primes($limit);\n\nsub runs (&op) {\n my $diff = 1;\n my $run = 1;\n\n my @diff = flat 1, (1..^@primes).map: {\n my $next = @primes[$_] - @primes[$_ - 1];\n if &op($next, $diff) { ++$run } else { $run = 1 }\n $diff = $next;\n $run;\n }\n\n my $max = max @diff;\n my @runs = @diff.grep: * == $max, :k;\n\n @runs.map( {\n my @run = (0..$max).reverse.map: -> $r { @primes[$_ - $r] }\n flat roundrobin(@run».&comma, @run.rotor(2 => -1).map({[R-] $_})».fmt('(%d)'));\n } ).join: \"\\n\"\n}\n\nsay \"Longest run(s) of ascending prime gaps up to {comma $limit}:\\n\" ~ runs(&infix:«>»);\n\nsay \"\\nLongest run(s) of descending prime gaps up to {comma $limit}:\\n\" ~ runs(&infix:«<»);\n\n```\n\nOutput:\n\n```\nLongest run(s) of ascending prime gaps up to 1,000,000:\n128,981 (2) 128,983 (4) 128,987 (6) 128,993 (8) 129,001 (10) 129,011 (12) 129,023 (14) 129,037\n402,581 (2) 402,583 (4) 402,587 (6) 402,593 (8) 402,601 (12) 402,613 (18) 402,631 (60) 402,691\n665,111 (2) 665,113 (4) 665,117 (6) 665,123 (8) 665,131 (10) 665,141 (12) 665,153 (24) 665,177\n\nLongest run(s) of descending prime gaps up to 1,000,000:\n322,171 (22) 322,193 (20) 322,213 (16) 322,229 (8) 322,237 (6) 322,243 (4) 322,247 (2) 322,249\n752,207 (44) 752,251 (12) 752,263 (10) 752,273 (8) 752,281 (6) 752,287 (4) 752,291 (2) 752,293\n```" } ]
[ { "role": "user", "content": "The Consistent Overhead Byte Stuffing (COBS) algorithm is used to demarcate a byte stream into frames. Examples can be found in its Wikipedia article.\n\nTask\n\nTo encode, instances of the byte `0x00` in the unencoded stream are substituted with the number of bytes until the next instance of `0x00` (we'll call this a milestone).\nIf `0x00` does not appear within the next 254 bytes after a milestone the algorithm must emit an extra milestone at the 255th byte.\nOf the encoded output, the first byte is the first milestone, and the final milestone will be the number of bytes until the final byte - `0x00`.\n\nBonus tasks\n\n* Decode an encoded packet\n + Report an error if the final milestone exceeds the length of the end of the packet\n* Support encoding with a non-zero marker" }, { "role": "assistant", "content": "**Translation of**: Wren\n\n```\n# 20231102 Raku programming solution\n\nsub encode($data where $data.Bool, $delim = 0x00) {\n my ($ins,$code,$addLastCode,@enc) = 0,1,True,-1;\n for $data.list -> $byte {\n if $byte != 0 { @enc.push($byte) andthen $code++ }\n $addLastCode = True;\n if $byte == 0 || $code == 255 {\n $addLastCode = False if $code == 255;\n @enc[$ins] = $code;\n $code = 1;\n $ins = @enc.elems;\n @enc.push(-1);\n }\n } \n if $addLastCode {\n @enc[$ins] = $code;\n if $delim != 0 { @enc >>^=>> $delim } \n @enc.push($delim)\n } else {\n if $delim != 0 { @enc >>^=>> $delim }\n @enc[$ins] = $delim\n }\n return @enc;\n}\n\nsub decode($data where $data.Bool, $delim = 0x00) {\n my $length = ( my @enc2 = $data.list[0..*-2] ).elems;\n if $delim != 0 { @enc2 >>^=>> $delim }\n my ($block,$code,@dec) = 0,255;\n for @enc2.kv -> $i,$byte {\n if $block != 0 {\n @dec.push($byte)\n } else {\n die \"marker pointing beyond the end of the packet.\" if $i + $byte > $length;\n @dec.push(0) if $code != 255;\n $block = $code = $byte;\n last if $code == 0\n }\n $block--;\n }\n return @dec;\n}\n\nfor ( [0x00], [0x00,0x00], [0x00,0x11,0x00], [0x11,0x22,0x00,0x33],\n [0x11,0x22,0x33,0x44], [0x11,0x00,0x00,0x00], # 0x01..0xfe, 0x00..0xfe, \n# [0x02..0xff].append(0x00), [0x03..0xff].append(0x00, 0x01),\n) { # https://crccalc.com/bytestuffing.php \n# say encode( $_ )>>.&{.fmt(\"0x%x\")}; \n say decode(encode( $_ ))>>.&{.fmt(\"0x%x\")}\n}\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "**Constrained genericity** or **bounded quantification** means\nthat a parametrized type or function (see parametric polymorphism)\ncan only be instantiated on types fulfilling some conditions,\neven if those conditions are not used in that function.\n\nSay a type is called \"eatable\" if you can call the function eat on it.\nWrite a generic type FoodBox which contains a collection of objects of\na type given as parameter, but can only be instantiated on eatable types.\nThe FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type).\nThe specification of a type being eatable should be as generic as possible\nin your language (i.e. the restrictions on the implementation of eatable types\nshould be as minimal as possible).\nAlso explain the restrictions, if any, on the implementation of eatable types,\nand show at least one example of an eatable type." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsubset Eatable of Any where { .^can('eat') };\n\nclass Cake { method eat() {...} }\n\nrole FoodBox[Eatable] {\n has %.foodbox;\n}\n\nclass Yummy does FoodBox[Cake] { } # composes correctly\n# class Yucky does FoodBox[Int] { } # fails to compose\n\nmy Yummy $foodbox .= new;\nsay $foodbox;\n\n```\n\nOutput:\n\n```\nYummy.new(foodbox => {})\n\n```" } ]
[ { "role": "user", "content": "Task\n\nGenerate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that \n\n10\n≤\n\nx\n\n2\n+\n\ny\n\n2\n≤\n15\n{\\displaystyle {\\displaystyle 10\\leq {\\sqrt {x^{2}+y^{2}}}\\leq 15}}\n. \nThen display/plot them. The outcome should be a \"fuzzy\" circle. The actual number of points plotted may be less than 100, given that some pairs may be generated more than once.\n\nThere are several possible approaches to accomplish this. Here are two possible algorithms.\n\n1) Generate random pairs of integers and filter out those that don't satisfy this condition:\n\n: 10\n ≤\n\n x\n\n 2\n +\n\n y\n\n 2\n ≤\n 15\n {\\displaystyle {\\displaystyle 10\\leq {\\sqrt {x^{2}+y^{2}}}\\leq 15}}\n .\n\n2) Precalculate the set of all possible points (there are 404 of them) and select randomly from this set." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.09\n\n```\nmy @range = -15..16;\n\nmy @points = gather for @range X @range -> ($x, $y) {\n take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15\n}\nmy @samples = @points.roll(100); # or .pick(100) to get distinct points\n\n# format and print\nmy %matrix;\nfor @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' }\n%matrix{.[1]}{.[0]} = '*' for @samples;\n%matrix{$_}{@range}.join(' ').say for @range;\n\n```\n\nOutput:\n\n```\n *\n * *\n * * * * *\n * * * *\n * * * * *\n * *\n * * *\n * * * *\n *\n * * * *\n * * *\n * * * *\n *\n * *\n * * *\n * * * *\n * * *\n *\n * *\n * *\n * * *\n * * *\n * *\n * * *\n * * * * * * *\n * * * * * *\n * * * *\n * *\n * * *\n```\n\nTurning that program completely inside-out and reducing to a single statement with a single non-parameter variable, we get another version that also works.\n\nThis uses, among other things, a 0-based matrix rather than a hash, a given on the first line that allows us to print the final value of the matrix straight from its initial declaration, a for statement feeding a for statement modifier, a lambda that unpacks a single x-y argument into two variables, the functional form of pick rather than the method form, a quasi-list comprehension in the middle loop that filters each given with a when, precalculated squared limits so we don't have to take the square root, use of X- and X\\*\\* to subtract and exponentiate both $x and $y in parallel.\n\nAfter the given do has loaded up @matrix with our circle, the map on the first line substitutes a space for any undefined matrix element, and the extra space between elements is supplied by the stringification of the list value, performed by the prefix ~ operator, the unary equivalent of concatenation in Raku.\n\nAt this point you would be justified in concluding that we are completely mad. :-)\n\n```\n(say ~.map: { $_ // ' ' } for my @matrix) given do\n -> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do\n for ^32 X ^32 -> ($x, $y) {\n [$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2;\n }\n\n```\n\nOutput:\n\n```\n * * *\n * * *\n * * * * * *\n * * * * * *\n * * * * * *\n * * *\n * * * * *\n * * * *\n * *\n * *\n *\n * * *\n\n * *\n* * * * * *\n * *\n\n * * * *\n * * *\n * * * *\n * *\n * *\n * * *\n * * * * * *\n * * * *\n * * * * * *\n * * * *\n * * * * *\n * * *\n```" } ]
[ { "role": "user", "content": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n\n: a\n\n 0\n +\n\n b\n\n 1\n\n a\n\n 1\n +\n\n b\n\n 2\n\n a\n\n 2\n +\n\n b\n\n 3\n\n a\n\n 3\n +\n ⋱\n {\\displaystyle {\\displaystyle a\\_{0}+{\\cfrac {b\\_{1}}{a\\_{1}+{\\cfrac {b\\_{2}}{a\\_{2}+{\\cfrac {b\\_{3}}{a\\_{3}+\\ddots }}}}}}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use \n\na\n\n0\n=\n1\n{\\displaystyle {\\displaystyle a\\_{0}=1}}\n then \n\na\n\nN\n=\n2\n{\\displaystyle {\\displaystyle a\\_{N}=2}}\n. \n\nb\n\nN\n{\\displaystyle {\\displaystyle b\\_{N}}}\n is always \n\n1\n{\\displaystyle {\\displaystyle 1}}\n.\n\n: 2\n =\n 1\n +\n\n 1\n\n 2\n +\n\n 1\n\n 2\n +\n\n 1\n\n 2\n +\n ⋱\n {\\displaystyle {\\displaystyle {\\sqrt {2}}=1+{\\cfrac {1}{2+{\\cfrac {1}{2+{\\cfrac {1}{2+\\ddots }}}}}}}}\n\nFor Napier's Constant, use \n\na\n\n0\n=\n2\n{\\displaystyle {\\displaystyle a\\_{0}=2}}\n, then \n\na\n\nN\n=\nN\n{\\displaystyle {\\displaystyle a\\_{N}=N}}\n. \n\nb\n\n1\n=\n1\n{\\displaystyle {\\displaystyle b\\_{1}=1}}\n then \n\nb\n\nN\n=\nN\n−\n1\n{\\displaystyle {\\displaystyle b\\_{N}=N-1}}\n.\n\n: e\n =\n 2\n +\n\n 1\n\n 1\n +\n\n 1\n\n 2\n +\n\n 2\n\n 3\n +\n\n 3\n\n 4\n +\n ⋱\n {\\displaystyle {\\displaystyle e=2+{\\cfrac {1}{1+{\\cfrac {1}{2+{\\cfrac {2}{3+{\\cfrac {3}{4+\\ddots }}}}}}}}}}\n\nFor Pi, use \n\na\n\n0\n=\n3\n{\\displaystyle {\\displaystyle a\\_{0}=3}}\n then \n\na\n\nN\n=\n6\n{\\displaystyle {\\displaystyle a\\_{N}=6}}\n. \n\nb\n\nN\n=\n(\n2\nN\n−\n1\n\n)\n\n2\n{\\displaystyle {\\displaystyle b\\_{N}=(2N-1)^{2}}}\n.\n\n: π\n =\n 3\n +\n\n 1\n\n 6\n +\n\n 9\n\n 6\n +\n\n 25\n\n 6\n +\n ⋱\n {\\displaystyle {\\displaystyle \\pi =3+{\\cfrac {1}{6+{\\cfrac {9}{6+{\\cfrac {25}{6+\\ddots }}}}}}}}\n\nSee also\n: * Continued fraction/Arithmetic for tasks that do arithmetic over continued fractions." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-10-31\n\n```\nsub continued-fraction(:@a, :@b, Int :$n = 100)\n{\n my $x = @a[$n - 1];\n $x = @a[$_ - 1] + @b[$_] / $x for reverse 1 ..^ $n;\n $x;\n}\n\nprintf \"√2 ≈%.9f\\n\", continued-fraction(:a(1, |(2 xx *)), :b(Nil, |(1 xx *)));\nprintf \"e ≈%.9f\\n\", continued-fraction(:a(2, |(1 .. *)), :b(Nil, 1, |(1 .. *)));\nprintf \"π ≈%.9f\\n\", continued-fraction(:a(3, |(6 xx *)), :b(Nil, |((1, 3, 5 ... *) X** 2)));\n\n```\n\nOutput:\n\n```\n√2 ≈ 1.414213562\ne ≈ 2.718281828\nπ ≈ 3.141592654\n```\n\nA more original and a bit more abstract method would consist in viewing a continued fraction on rank n as a function of a variable x:\n\n: C\n F\n\n 3\n (\n x\n )\n =\n\n a\n\n 0\n +\n\n b\n\n 1\n\n a\n\n 1\n +\n\n b\n\n 2\n\n a\n\n 2\n +\n\n b\n\n 3\n\n a\n\n 3\n +\n x\n {\\displaystyle {\\displaystyle \\mathrm {CF} \\_{3}(x)=a\\_{0}+{\\cfrac {b\\_{1}}{a\\_{1}+{\\cfrac {b\\_{2}}{a\\_{2}+{\\cfrac {b\\_{3}}{a\\_{3}+x}}}}}}}}\n\nOr, more consistently:\n\n: C\n F\n\n 3\n (\n x\n )\n =\n\n a\n\n 0\n +\n\n b\n\n 0\n\n a\n\n 1\n +\n\n b\n\n 1\n\n a\n\n 2\n +\n\n b\n\n 2\n\n a\n\n 3\n +\n\n b\n\n 3\n\n x\n {\\displaystyle {\\displaystyle \\mathrm {CF} \\_{3}(x)=a\\_{0}+{\\cfrac {b\\_{0}}{a\\_{1}+{\\cfrac {b\\_{1}}{a\\_{2}+{\\cfrac {b\\_{2}}{a\\_{3}+{\\cfrac {b\\_{3}}{x}}}}}}}}}}\n\nViewed as such, \n\nC\nF\n\nn\n(\nx\n)\n{\\displaystyle {\\displaystyle \\mathrm {CF} \\_{n}(x)}}\n could be written recursively:\n\n: C\n F\n\n n\n (\n x\n )\n =\n\n\n C\n F\n\n n\n −\n 1\n (\n\n a\n\n n\n +\n\n b\n\n n\n x\n )\n {\\displaystyle {\\displaystyle \\mathrm {CF} \\_{n}(x)=\\mathrm {CF} \\_{n-1}(a\\_{n}+{\\frac {b\\_{n}}{x}})}}\n\nOr in other words:\n\n: C\n F\n\n n\n =\n\n\n C\n F\n\n n\n −\n 1\n ∘\n\n f\n\n n\n =\n\n\n C\n F\n\n n\n −\n 2\n ∘\n\n f\n\n n\n −\n 1\n ∘\n\n f\n\n n\n =\n …\n =\n\n f\n\n 0\n ∘\n\n f\n\n 1\n …\n ∘\n\n f\n\n n\n {\\displaystyle {\\displaystyle \\mathrm {CF} \\_{n}=\\mathrm {CF} \\_{n-1}\\circ f\\_{n}=\\mathrm {CF} \\_{n-2}\\circ f\\_{n-1}\\circ f\\_{n}=\\ldots =f\\_{0}\\circ f\\_{1}\\ldots \\circ f\\_{n}}}\n\nwhere \n\nf\n\nn\n(\nx\n)\n=\n\na\n\nn\n+\n\nb\n\nn\nx\n{\\displaystyle {\\displaystyle f\\_{n}(x)=a\\_{n}+{\\frac {b\\_{n}}{x}}}}\n\nRaku has a builtin composition operator. We can use it with the triangular reduction metaoperator, and evaluate each resulting function at infinity (any value would do actually, but infinite makes it consistent with this particular task).\n\n```\nsub continued-fraction(@a, @b) {\n map { .(Inf) }, [\\o] map { @a[$_] + @b[$_] / * }, ^Inf\n}\n \nprintf \"√2 ≈ %.9f\\n\", continued-fraction((1, |(2 xx *)), (1 xx *))[10];\nprintf \"e ≈ %.9f\\n\", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[10];\nprintf \"π ≈ %.9f\\n\", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100];\n\n```\n\nOutput:\n\n```\n√2 ≈ 1.414213552\ne ≈ 2.718281827\nπ ≈ 3.141592411\n```" } ]
[ { "role": "user", "content": "Given a positive real number, if we truncate its continued fraction representation at a certain depth, we obtain a rational approximation to the real number. The sequence of successively better such approximations is its convergent sequence.\n\nProblem:\n\n* Given a positive rational number \n\n m\n n\n {\\displaystyle {\\displaystyle {\\frac {m}{n}}}}\n , specified by two positive integers \n\n m\n ,\n n\n {\\displaystyle {\\displaystyle m,n}}\n , output its entire sequence of convergents.\n* Given a quadratic real number \n\n b\n\n\n a\n +\n m\n n\n >\n 0\n {\\displaystyle {\\displaystyle {\\frac {b{\\sqrt {a}}+m}{n}}>0}}\n , specified by integers \n\n a\n ,\n b\n ,\n m\n ,\n n\n {\\displaystyle {\\displaystyle a,b,m,n}}\n , where \n\n a\n {\\displaystyle {\\displaystyle a}}\n is not a perfect square, output the first \n\n k\n {\\displaystyle {\\displaystyle k}}\n convergents when given a positive number \n\n k\n {\\displaystyle {\\displaystyle k}}\n .\n\nThe output format can be whatever is necessary to represent rational numbers, but it probably should be a 2-tuple of integers.\n\nFor example, given \n\na\n=\n2\n,\nb\n=\n1\n,\nm\n=\n0\n,\nn\n=\n1\n{\\displaystyle {\\displaystyle a=2,b=1,m=0,n=1}}\n, since\n\n2\n=\n1\n+\n\n1\n\n2\n+\n\n1\n\n2\n+\n\n1\n\n2\n+\n⋱\n{\\displaystyle {\\sqrt {2}}=1+{\\cfrac {1}{2+{\\cfrac {1}{2+{\\cfrac {1}{2+\\ddots }}}}}}}\nthe program should output \n\n(\n1\n,\n1\n)\n,\n(\n3\n,\n2\n)\n,\n(\n7\n,\n5\n)\n,\n(\n17\n\n/\n12\n)\n,\n(\n41\n\n/\n29\n)\n,\n…\n{\\displaystyle {\\displaystyle (1,1),(3,2),(7,5),(17/12),(41/29),\\dots }}\n.\n\nA simple check is to do this for the golden ratio **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response (\"Math extension cannot connect to Restbase.\") from server \"https://wikimedia.org/api/rest\\_v1/\":): {\\displaystyle \\frac{\\sqrt{5}+1}{2}}**\n, that is, **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response (\"Math extension cannot connect to Restbase.\") from server \"https://wikimedia.org/api/rest\\_v1/\":): {\\displaystyle a=5, b=1, m = 1, n = 2 }**\n, which should output \n\n(\n1\n,\n1\n)\n,\n(\n2\n,\n1\n)\n,\n(\n3\n,\n2\n)\n,\n(\n5\n,\n3\n)\n,\n(\n8\n,\n5\n)\n,\n…\n{\\displaystyle {\\displaystyle (1,1),(2,1),(3,2),(5,3),(8,5),\\dots }}\n.\n\nPrint the results for 415/93, 649/200, \n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n, **Failed to parse (SVG (MathML can be enabled via browser plugin): Invalid response (\"Math extension cannot connect to Restbase.\") from server \"https://wikimedia.org/api/rest\\_v1/\":): {\\displaystyle \\sqrt{5}}**\n, and the golden ratio.\n\nReferences and related tasks\n\n* Wikipedia: Continued fraction\n* Continued fraction\n* Continued fraction/Arithmetic\n* Continued fraction/Arithmetic/Construct from rational number\n* Calkin-Wilf sequence" }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\n# 20240210 Raku programming solution\n\nsub convergents(Real $x is copy, Int $maxcount) {\n my @components = gather for ^$maxcount {\n my $fpart = $x - take $x.Int;\n $fpart == 0 ?? ( last ) !! ( $x = 1 / $fpart )\n }\n my ($numa, $denoma, $numb, $denomb) = 1, 0, @components[0], 1;\n return [ Rat.new($numb, $denomb) ].append: gather for @components[1..*] -> $comp {\n ( $numa, $denoma, $numb , $denomb ) \n = $numb, $denomb, $numa + $comp * $numb, $denoma + $comp * $denomb;\n take Rat.new($numb, $denomb);\n }\n}\n\nmy @tests = [ \"415/93\", 415/93, \"649/200\", 649/200, \"sqrt(2)\", sqrt(2),\n \"sqrt(5)\", sqrt(5), \"golden ratio\", (sqrt(5) + 1) / 2 ];\n\nsay \"The continued fraction convergents for the following (maximum 8 terms) are:\";\nfor @tests -> $s, $x {\n say $s.fmt('%15s') ~ \" = { convergents($x, 8).map: *.nude.join('/') } \";\n}\n\n```\n\nOutput:\n\n```\nThe continued fraction convergents for the following (maximum 8 terms) are:\n 415/93 = 4/1 9/2 58/13 415/93 \n 649/200 = 3/1 13/4 159/49 649/200 \n sqrt(2) = 1/1 3/2 7/5 17/12 41/29 99/70 239/169 577/408 \n sqrt(5) = 2/1 9/4 38/17 161/72 682/305 2889/1292 12238/5473 51841/23184 \n golden ratio = 1/1 2/1 3/2 5/3 8/5 13/8 21/13 34/21 \n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "To understand this task in context please see Continued fraction arithmetic\n\nThe purpose of this task is to write a function \n\nr\n2\nc\nf\n(\n\ni\nn\nt\n{\\displaystyle {\\displaystyle {\\mathit {r2cf}}(\\mathrm {int} }}\n \n\nN\n\n1\n,\n\ni\nn\nt\n{\\displaystyle {\\displaystyle N\\_{1},\\mathrm {int} }}\n \n\nN\n\n2\n)\n{\\displaystyle {\\displaystyle N\\_{2})}}\n, or \n\nr\n2\nc\nf\n(\n\nF\nr\na\nc\nt\ni\no\nn\n{\\displaystyle {\\displaystyle {\\mathit {r2cf}}(\\mathrm {Fraction} }}\n \n\nN\n)\n{\\displaystyle {\\displaystyle N)}}\n, which will output a continued fraction assuming:\n\n: N\n\n 1\n {\\displaystyle {\\displaystyle N\\_{1}}}\n is the numerator\n: N\n\n 2\n {\\displaystyle {\\displaystyle N\\_{2}}}\n is the denominator\n\nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of \n\nN\n\n1\n{\\displaystyle {\\displaystyle N\\_{1}}}\n divided by \n\nN\n\n2\n{\\displaystyle {\\displaystyle N\\_{2}}}\n. It then sets \n\nN\n\n1\n{\\displaystyle {\\displaystyle N\\_{1}}}\n to \n\nN\n\n2\n{\\displaystyle {\\displaystyle N\\_{2}}}\n and \n\nN\n\n2\n{\\displaystyle {\\displaystyle N\\_{2}}}\n to the determined remainder part. It then outputs the determined integer part. It does this until \n\na\nb\ns\n(\n\nN\n\n2\n)\n{\\displaystyle {\\displaystyle \\mathrm {abs} (N\\_{2})}}\n is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n should approach \n\n[\n1\n;\n2\n,\n2\n,\n2\n,\n2\n,\n…\n]\n{\\displaystyle {\\displaystyle [1;2,2,2,2,\\ldots ]}}\n try ever closer rational approximations until boredom gets the better of you:\n\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n and convince yourself that, in the same way as \n\n3.7\n{\\displaystyle {\\displaystyle 3.7}}\n may be represented as \n\n3.70\n{\\displaystyle {\\displaystyle 3.70}}\n when an extra decimal place is required, \n\n[\n3\n;\n7\n]\n{\\displaystyle {\\displaystyle [3;7]}}\n may be represented as \n\n[\n3\n;\n7\n,\n∞\n]\n{\\displaystyle {\\displaystyle [3;7,\\infty ]}}\n when an extra term is required." }, { "role": "assistant", "content": "(formerly Perl 6)\nStraightforward implementation:\n\n```\nsub r2cf(Rat $x is copy) {\n gather loop {\n\t$x -= take $x.floor;\n\tlast unless $x > 0;\n\t$x = 1 / $x;\n }\n}\n\nsay r2cf(.Rat) for <1/2 3 23/8 13/11 22/7 1.41 1.4142136>;\n\n```\n\nOutput:\n\n```\n(0 2)\n(3)\n(2 1 7)\n(1 5 2)\n(3 7)\n(1 2 2 3 1 1 2)\n(1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2)\n```\n\nAs a silly one-liner:\n\n```\nsub r2cf(Rat $x is copy) { gather $x [R/]= 1 while ($x -= take $x.floor) > 0 }\n\n```" } ]
[ { "role": "user", "content": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n\n: [\n\n a\n\n 1\n\n a\n\n b\n\n 1\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&a\\\\b\\_{1}&b\\end{bmatrix}}}}\n\nI may perform perform the following operations:\n\n: Input the next term of N1\n: Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \n\na\nb\n{\\displaystyle {\\displaystyle {\\frac {a}{b}}}}\n and \n\na\n\n1\n\nb\n\n1\n{\\displaystyle {\\displaystyle {\\frac {a\\_{1}}{b\\_{1}}}}}\n are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \n\n∞\n{\\displaystyle {\\displaystyle \\infty }}\n.\n\nWhen I input a term t my internal state: \n\n[\n\na\n\n1\n\na\n\nb\n\n1\n\nb\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&a\\\\b\\_{1}&b\\end{bmatrix}}}}\n is transposed thus \n\n[\n\na\n+\n\na\n\n1\n∗\nt\n\n\na\n\n1\n\n\nb\n+\n\nb\n\n1\n∗\nt\n\n\nb\n\n1\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}a+a\\_{1}\\*t&a\\_{1}\\\\b+b\\_{1}\\*t&b\\_{1}\\end{bmatrix}}}}\n\nWhen I output a term t my internal state: \n\n[\n\na\n\n1\n\na\n\nb\n\n1\n\nb\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&a\\\\b\\_{1}&b\\end{bmatrix}}}}\n is transposed thus \n\n[\n\nb\n\n1\n\nb\n\na\n\n1\n−\n\nb\n\n1\n∗\nt\n\na\n−\nb\n∗\nt\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}b\\_{1}&b\\\\a\\_{1}-b\\_{1}\\*t&a-b\\*t\\end{bmatrix}}}}\n\nWhen I need a term t but there are no more my internal state: \n\n[\n\na\n\n1\n\na\n\nb\n\n1\n\nb\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&a\\\\b\\_{1}&b\\end{bmatrix}}}}\n is transposed thus \n\n[\n\na\n\n1\n\n\na\n\n1\n\nb\n\n1\n\n\nb\n\n1\n]\n{\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&a\\_{1}\\\\b\\_{1}&b\\_{1}\\end{bmatrix}}}}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n\n: [1;5,2] + 1/2\n: [3;7] + 1/2\n: [3;7] divided by 4\n\nUsing a generator for \n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n (e.g., from Continued fraction) calculate \n\n1\n\n2\n{\\displaystyle {\\displaystyle {\\frac {1}{\\sqrt {2}}}}}\n. You are now at the starting line for using Continued Fractions to implement Arithmetic-geometric mean without ulps and epsilons.\n\nThe first step in implementing Arithmetic-geometric mean is to calculate \n\n1\n+\n\n\n1\n\n2\n2\n{\\displaystyle {\\displaystyle {\\frac {1+{\\frac {1}{\\sqrt {2}}}}{2}}}}\n do this now to cross the starting line and begin the race." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nAll the important stuff takes place in the NG object. Everything else is helper subs for testing and display. The NG object is capable of working with infinitely long continued fractions, but displaying them can be problematic. You can pass in a limit to the apply method to get a fixed maximum number of terms though. See the last example: 100 terms from the infinite cf (1+√2)/2 and its Rational representation.\n\n```\nclass NG {\n has ( $!a1, $!a, $!b1, $!b );\n submethod BUILD ( :$!a1, :$!a, :$!b1, :$!b ) { }\n\n # Public methods\n method new( $a1, $a, $b1, $b ) { self.bless( :$a1, :$a, :$b1, :$b ) }\n method apply(@cf, :$limit = Inf) {\n (gather {\n map { take self!extract unless self!needterm; self!inject($_) }, @cf;\n take self!drain until self!done;\n })[ ^ $limit ]\n }\n\n # Private methods\n method !inject ($n) {\n sub xform($n, $x, $y) { $x, $n * $x + $y }\n ( $!a, $!a1 ) = xform( $n, $!a1, $!a );\n ( $!b, $!b1 ) = xform( $n, $!b1, $!b );\n }\n method !extract {\n sub xform($n, $x, $y) { $y, $x - $y * $n }\n my $n = $!a div $!b;\n ($!a, $!b ) = xform( $n, $!a, $!b );\n ($!a1, $!b1) = xform( $n, $!a1, $!b1 );\n $n\n }\n method !drain { $!a = $!a1, $!b = $!b1 if self!needterm; self!extract }\n method !needterm { so [||] !$!b, !$!b1, $!a/$!b != $!a1/$!b1 }\n method !done { not [||] $!b, $!b1 }\n}\n\nsub r2cf(Rat $x is copy) { # Rational to continued fraction\n gather loop {\n\t$x -= take $x.floor;\n\tlast if !$x;\n\t$x = 1 / $x;\n }\n}\n\nsub cf2r(@a) { # continued fraction to Rational\n my $x = @a[* - 1]; # Use FatRats for arbitrary precision\n $x = ( @a[$_- 1] + 1 / $x ).FatRat for reverse 1 ..^ @a;\n $x\n}\n\nsub ppcf(@cf) { # format continued fraction for pretty printing \n \"[{ @cf.join(',').subst(',',';') }]\"\n}\n\nsub pprat($a) { # format Rational for pretty printing\n # Use FatRats for arbitrary precision\n $a.FatRat.denominator == 1 ?? $a !! $a.FatRat.nude.join('/')\n}\n\nsub test_NG ($rat, @ng, $op) { \n my @cf = $rat.Rat(1e-18).&r2cf;\n my @op = NG.new( |@ng ).apply( @cf );\n say $rat.raku, ' as a cf: ', @cf.&ppcf, \" $op = \",\n @op.&ppcf, \"\\tor \", @op.&cf2r.&pprat, \"\\n\";\n}\n\n# Testing\ntest_NG(|$_) for (\n [ 13/11, [<2 1 0 2>], '+ 1/2 ' ],\n [ 22/7, [<2 1 0 2>], '+ 1/2 ' ],\n [ 22/7, [<1 0 0 4>], '/ 4 ' ],\n [ 22/7, [<7 0 0 22>], '* 7/22 ' ],\n [ 2**.5, [<1 1 0 2>], \"\\n(1+√2)/2 (approximately)\" ]\n);\n\nsay '100 terms of (1+√2)/2 as a continued fraction and as a rational value:';\n\nmy @continued-fraction = NG.new( 1,1,0,2 ).apply( (lazy flat 1, 2 xx * ), limit => 100 );\nsay @continued-fraction.&ppcf.comb(/ . ** 1..80/).join(\"\\n\");\nsay @continued-fraction.&cf2r.&pprat;\n\n```\n\nOutput:\n\n```\n<13/11> as a cf: [1;5,2] + 1/2 = [1;1,2,7]\tor 37/22\n\n<22/7> as a cf: [3;7] + 1/2 = [3;1,1,1,4]\tor 51/14\n\n<22/7> as a cf: [3;7] / 4 = [0;1,3,1,2]\tor 11/14\n\n<22/7> as a cf: [3;7] * 7/22 = [1]\tor 1\n\n1.4142135623731e0 as a cf: [1;2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] \n(1+√2)/2 (approximately) = [1;4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4]\tor 225058681/186444716\n\n100 terms of (1+√2)/2 and its rational value\n[1;4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4\n,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4\n,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4,1,4]\n161733217200188571081311986634082331709/133984184101103275326877813426364627544\n\n```" } ]
[ { "role": "user", "content": "This task performs the basic mathematical functions on 2 continued fractions. This requires the full version of matrix NG:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n\nI may perform perform the following operations:\n\n: Input the next term of continued fraction N1\n: Input the next term of continued fraction N2\n: Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \n\na\nb\n{\\displaystyle {\\displaystyle {\\frac {a}{b}}}}\n and \n\na\n\n1\n\nb\n\n1\n{\\displaystyle {\\displaystyle {\\frac {a\\_{1}}{b\\_{1}}}}}\n and \n\na\n\n2\n\nb\n\n2\n{\\displaystyle {\\displaystyle {\\frac {a\\_{2}}{b\\_{2}}}}}\n and \n\na\n\n12\n\nb\n\n12\n{\\displaystyle {\\displaystyle {\\frac {a\\_{12}}{b\\_{12}}}}}\n are equal. Otherwise I input a term from continued fraction N1 or continued fraction N2. If I need a term from N but N has no more terms I inject \n\n∞\n{\\displaystyle {\\displaystyle \\infty }}\n.\n\nWhen I input a term t from continued fraction N1 I change my internal state:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n is transposed thus \n\n [\n\n a\n\n 2\n +\n\n a\n\n 12\n ∗\n t\n\n a\n +\n\n a\n\n 1\n ∗\n t\n\n\n a\n\n 12\n\n\n a\n\n 1\n\n b\n\n 2\n +\n\n b\n\n 12\n ∗\n t\n\n b\n +\n\n b\n\n 1\n ∗\n t\n\n\n b\n\n 12\n\n\n b\n\n 1\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{2}+a\\_{12}\\*t&a+a\\_{1}\\*t&a\\_{12}&a\\_{1}\\\\b\\_{2}+b\\_{12}\\*t&b+b\\_{1}\\*t&b\\_{12}&b\\_{1}\\end{bmatrix}}}}\n\nWhen I need a term from exhausted continued fraction N1 I change my internal state:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n is transposed thus \n\n [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 12\n\n\n a\n\n 1\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 12\n\n\n b\n\n 1\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{12}&a\\_{1}\\\\b\\_{12}&b\\_{1}&b\\_{12}&b\\_{1}\\end{bmatrix}}}}\n\nWhen I input a term t from continued fraction N2 I change my internal state:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n is transposed thus \n\n [\n\n a\n\n 1\n +\n\n a\n\n 12\n ∗\n t\n\n\n a\n\n 12\n\n a\n +\n\n a\n\n 2\n ∗\n t\n\n\n a\n\n 2\n\n b\n\n 1\n +\n\n b\n\n 12\n ∗\n t\n\n\n b\n\n 12\n\n b\n +\n\n b\n\n 2\n ∗\n t\n\n\n b\n\n 2\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}+a\\_{12}\\*t&a\\_{12}&a+a\\_{2}\\*t&a\\_{2}\\\\b\\_{1}+b\\_{12}\\*t&b\\_{12}&b+b\\_{2}\\*t&b\\_{2}\\end{bmatrix}}}}\n\nWhen I need a term from exhausted continued fraction N2 I change my internal state:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n is transposed thus \n\n [\n\n a\n\n 12\n\n\n a\n\n 12\n\n\n a\n\n 2\n\n\n a\n\n 2\n\n b\n\n 12\n\n\n b\n\n 12\n\n\n b\n\n 2\n\n\n b\n\n 2\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{12}&a\\_{2}&a\\_{2}\\\\b\\_{12}&b\\_{12}&b\\_{2}&b\\_{2}\\end{bmatrix}}}}\n\nWhen I output a term t I change my internal state:\n\n: [\n\n a\n\n 12\n\n\n a\n\n 1\n\n\n a\n\n 2\n\n a\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{12}&a\\_{1}&a\\_{2}&a\\\\b\\_{12}&b\\_{1}&b\\_{2}&b\\end{bmatrix}}}}\n is transposed thus \n\n [\n\n b\n\n 12\n\n\n b\n\n 1\n\n\n b\n\n 2\n\n b\n\n a\n\n 12\n −\n\n b\n\n 12\n ∗\n t\n\n\n a\n\n 1\n −\n\n b\n\n 1\n ∗\n t\n\n\n a\n\n 2\n −\n\n b\n\n 2\n ∗\n t\n\n a\n −\n b\n ∗\n t\n ]\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}b\\_{12}&b\\_{1}&b\\_{2}&b\\\\a\\_{12}-b\\_{12}\\*t&a\\_{1}-b\\_{1}\\*t&a\\_{2}-b\\_{2}\\*t&a-b\\*t\\end{bmatrix}}}}\n\nWhen I need to choose to input from N1 or N2 I act:\n\n: if b and b2 are zero I choose N1\n: if b is zero I choose N2\n: if b2 is zero I choose N2\n: if abs(\n\n a\n\n 1\n\n b\n\n 1\n −\n\n\n a\n b\n )\n {\\displaystyle {\\displaystyle {\\frac {a\\_{1}}{b\\_{1}}}-{\\frac {a}{b}})}}\n is greater than abs(\n\n a\n\n 2\n\n b\n\n 2\n −\n\n\n a\n b\n )\n {\\displaystyle {\\displaystyle {\\frac {a\\_{2}}{b\\_{2}}}-{\\frac {a}{b}})}}\n I choose N1\n: otherwise I choose N2\n\nWhen performing arithmetic operation on two potentially infinite continued fractions it is possible to generate a rational number. eg \n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n \\* \n\n2\n{\\displaystyle {\\displaystyle {\\sqrt {2}}}}\n should produce 2. This will require either that I determine that my internal state is approaching infinity, or limiting the number of terms I am willing to input without producing any output." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.01\n\nThe NG2 object can work with infinitely long continued fractions, it does lazy evaluation. By default, it is limited to returning the first 30 terms. Pass in a limit value if you want something other than default.\n\n```\nclass NG2 {\n has ( $!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b );\n\n # Public methods\n method operator($!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b ) { self }\n\n method apply(@cf1, @cf2, :$limit = 30) {\n my @cfs = [@cf1], [@cf2];\n gather {\n while @cfs[0] or @cfs[1] {\n my $term;\n (take $term if $term = self!extract) unless self!needterm;\n my $from = self!from;\n $from = @cfs[$from] ?? $from !! $from +^ 1;\n self!inject($from, @cfs[$from].shift);\n }\n take self!drain while $!b;\n }[ ^$limit ].grep: *.defined;\n }\n\n # Private methods\n method !inject ($n, $t) {\n multi sub xform(0, $t, $x12, $x1, $x2, $x) { $x2 + $x12 * $t, $x + $x1 * $t, $x12, $x1 }\n multi sub xform(1, $t, $x12, $x1, $x2, $x) { $x1 + $x12 * $t, $x12, $x + $x2 * $t, $x2 }\n ( $!a12, $!a1, $!a2, $!a ) = xform($n, $t, $!a12, $!a1, $!a2, $!a );\n ( $!b12, $!b1, $!b2, $!b ) = xform($n, $t, $!b12, $!b1, $!b2, $!b );\n }\n method !extract {\n my $t = $!a div $!b;\n ( $!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b ) =\n $!b12, $!b1, $!b2, $!b,\n $!a12 - $!b12 * $t,\n $!a1 - $!b1 * $t,\n $!a2 - $!b2 * $t,\n $!a - $!b * $t;\n $t;\n }\n method !from {\n return $!b == $!b2 == 0 ?? 0 !!\n $!b == 0 || $!b2 == 0 ?? 1 !!\n abs($!a1*$!b*$!b2 - $!a*$!b1*$!b2) > abs($!a2*$!b*$!b1 - $!a*$!b1*$!b2) ?? 0 !! 1;\n }\n method !needterm {\n so !([&&] $!b12, $!b1, $!b2, $!b) or $!a/$!b != $!a1/$!b1 != $!a2/$!b2 != $!a12/$!b1;\n }\n method !noterms($which) {\n $which ?? (($!a1, $!a, $!b1, $!b ) = $!a12, $!a2, $!b12, $!b2)\n  !! (($!a2, $!a, $!b2, $!b ) = $!a12, $!a1, $!b12, $!b1);\n }\n method !drain {\n self!noterms(self!from) if self!needterm;\n self!extract;\n }\n}\n\nsub r2cf(Rat $x is copy) { # Rational to continued fraction\n gather loop {\n $x -= take $x.floor;\n last unless $x;\n $x = 1 / $x;\n }\n}\n\nsub cf2r(@a) { # continued fraction to Rational\n my $x = @a[* - 1].FatRat; # Use FatRats for arbitrary precision\n $x = @a[$_- 1] + 1 / $x for reverse 1 ..^ @a;\n $x\n}\n\n# format continued fraction for pretty printing\nsub ppcf(@cf) { \"[{ @cf.join(',').subst(',',';') }]\" }\n\n# format Rational for pretty printing. Use FatRats for arbitrary precision\nsub pprat($a) { $a.FatRat.denominator == 1 ?? $a !! $a.FatRat.nude.join('/') }\n\nmy %ops = ( # convenience hash of NG matrix operators\n '+' => (0,1,1,0,0,0,0,1),\n '-' => (0,1,-1,0,0,0,0,1),\n '*' => (1,0,0,0,0,0,0,1),\n '/' => (0,1,0,0,0,0,1,0)\n);\n\nsub test_NG2 ($rat1, $op, $rat2) {\n my @cf1 = $rat1.&r2cf;\n my @cf2 = $rat2.&r2cf;\n my @result = NG2.new.operator(|%ops{$op}).apply( @cf1, @cf2 );\n say \"{$rat1.&pprat} $op {$rat2.&pprat} => {@cf1.&ppcf} $op \",\n \"{@cf2.&ppcf} = {@result.&ppcf} => {@result.&cf2r.&pprat}\\n\";\n}\n\n# Testing\ntest_NG2(|$_) for\n [ 22/7, '+', 1/2 ],\n [ 23/11, '*', 22/7 ],\n [ 13/11, '-', 22/7 ],\n [ 484/49, '/', 22/7 ];\n\n\n# Sometimes you may want to limit the terms in the continued fraction to something other than default.\n# Here a lazy infinite continued fraction for √2, then multiply it by itself. We'll limit the result\n# to 6 terms for brevity’s' sake. We'll then convert that continued fraction back to an arbitrary precision\n# FatRat Rational number. (Raku stores FatRats internally as a ratio of two arbitrarily long integers.\n# We need to exercise a little caution because they can eat up all of your memory if allowed to grow unchecked,\n# hence the limit of 6 terms in continued fraction.) We'll then convert that number to a normal precision\n# Rat, which is accurate to the nearest 1 / 2^64, \n\nsay \"√2 expressed as a continued fraction, then squared: \";\nmy @root2 = lazy flat 1, 2 xx *;\nmy @result = NG2.new.operator(|%ops{'*'}).apply( @root2, @root2, limit => 6 );\nsay @root2.&ppcf, \"² = \\n\";\nsay @result.&ppcf;\nsay \"\\nConverted back to an arbitrary (ludicrous) precision Rational: \";\nsay @result.&cf2r.nude.join(\" /\\n\");\nsay \"\\nCoerced to a standard precision Rational: \", @result.&cf2r.Num.Rat;\n\n```\n\nOutput:\n\n```\n22/7 + 1/2 => [3;7] + [0;2] = [3;1,1,1,4] => 51/14\n\n23/11 * 22/7 => [2;11] * [3;7] = [6;1,1,3] => 46/7\n\n13/11 - 22/7 => [1;5,2] - [3;7] = [-2;25,1,2] => -151/77\n\n484/49 / 22/7 => [9;1,7,6] / [3;7] = [3;7] => 22/7\n\n√2 expressed as a continued fraction, then squared: \n[1;2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,...]² = \n\n[1;1,-58451683124983302025,-1927184886226364356176,-65467555105469489418600,-2223969688699736275876224]\n\nConverted back to an arbitrary (ludicrous) precision Rational: \n32802382178012409621354320392819425499699206367450594986122623570838188983519955166754002 /\n16401191089006204810536863200564985394427741343927508600629139291039556821665755787817601\n\nCoerced to a standard precision Rational: 2\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\nThe task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 → 4527027 / 5000000\n* 0.518518 → 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 → 3 / 4" }, { "role": "assistant", "content": "(formerly Perl 6)\nDecimals are natively represented as rationals in Raku, so if the task does not need to handle repeating decimals, it is trivially handled by the .nude method, which returns the numerator and denominator:\n\n```\nsay .nude.join('/') for 0.9054054, 0.518518, 0.75;\n\n```\n\nOutput:\n\n```\n4527027/5000000\n259259/500000\n3/4\n```\n\nHowever, if we want to take repeating decimals into account, then we can get a bit fancier.\n\n```\nsub decimal_to_fraction ( Str $n, Int $rep_digits = 0 ) returns Str {\n my ( $int, $dec ) = ( $n ~~ /^ (\\d+) \\. (\\d+) $/ )».Str or die;\n\n my ( $numer, $denom ) = ( $dec, 10 ** $dec.chars );\n if $rep_digits {\n my $to_move = $dec.chars - $rep_digits;\n $numer -= $dec.substr(0, $to_move);\n $denom -= 10 ** $to_move;\n }\n\n my $rat = Rat.new( $numer.Int, $denom.Int ).nude.join('/');\n return $int > 0 ?? \"$int $rat\" !! $rat;\n}\n\nmy @a = ['0.9054', 3], ['0.518', 3], ['0.75', 0], | (^4).map({['12.34567', $_]});\nfor @a -> [ $n, $d ] {\n say \"$n with $d repeating digits = \", decimal_to_fraction( $n, $d );\n}\n\n```\n\nOutput:\n\n```\n0.9054 with 3 repeating digits = 67/74\n0.518 with 3 repeating digits = 14/27\n0.75 with 0 repeating digits = 3/4\n12.34567 with 0 repeating digits = 12 34567/100000\n12.34567 with 1 repeating digits = 12 31111/90000\n12.34567 with 2 repeating digits = 12 17111/49500\n12.34567 with 3 repeating digits = 12 1279/3700\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a function or program which:\n\n* takes a positive integer representing a duration in seconds as input (e.g., `100`), and\n* returns a string which shows the same duration decomposed into:\n\n: : : * weeks,\n * days,\n * hours,\n * minutes,   and\n * seconds.\n\nThis is detailed below (e.g., \"`2 hr, 59 sec`\").\n\nDemonstrate that it passes the following three test-cases:\n\n***Test Cases***\n\n: : : : : | input number | output string |\n | --- | --- |\n | 7259 | `2 hr, 59 sec` |\n | 86400 | `1 d` |\n | 6000000 | `9 wk, 6 d, 10 hr, 40 min` |\n\n***Details***\n\nThe following five units should be used:\n\n: : : : : | unit | suffix used in output | conversion |\n | --- | --- | --- |\n | week | `wk` | 1 week = 7 days |\n | day | `d` | 1 day = 24 hours |\n | hour | `hr` | 1 hour = 60 minutes |\n | minute | `min` | 1 minute = 60 seconds |\n | second | `sec` | |\n\nHowever, **only** include quantities with non-zero values in the output (e.g., return \"`1 d`\" and not \"`0 wk, 1 d, 0 hr, 0 min, 0 sec`\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return `2 min, 10 sec` and not `1 min, 70 sec` or `130 sec`)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe built-in `polymod` method (which is a generalization of the `divmod` function known from other languages), is a perfect match for a task like this:\n\n```\nsub compound-duration ($seconds) {\n ($seconds.polymod(60, 60, 24, 7) Z <sec min hr d wk>)\n .grep(*[0]).reverse.join(\", \")\n}\n\n# Demonstration:\n\nfor 7259, 86400, 6000000 {\n say \"{.fmt: '%7d'} sec = {compound-duration $_}\";\n}\n\n```\n\nOutput:\n\n```\n 7259 sec = 2 hr, 59 sec\n 86400 sec = 1 d\n6000000 sec = 9 wk, 6 d, 10 hr, 40 min\n\n```" } ]
[ { "role": "user", "content": "Find the points which form a convex hull from a set of arbitrary two dimensional points.\n\nFor example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-9,-3), (-3,-9), (19,-8), (17,5), (12,17), (5,19) and (-3,15).\n\nSee also\n\n* Convex Hull (youtube)\n* http://www.geeksforgeeks.org/convex-hull-set-2-graham-scan/" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\n**Translation of**: zkl\n\nModified the angle sort method as the original could fail if there were multiple points on the same y coordinate as the starting point. Sorts on tangent rather than triangle area. Inexpensive since it still doesn't do any trigonometric math, just calculates the ratio of opposite over adjacent.\n\n```\nclass Point {\n has Real $.x is rw;\n has Real $.y is rw;\n method gist { [~] '(', self.x,', ', self.y, ')' };\n}\n\nsub ccw (Point $a, Point $b, Point $c) {\n ($b.x - $a.x)*($c.y - $a.y) - ($b.y - $a.y)*($c.x - $a.x);\n}\n\nsub tangent (Point $a, Point $b) {\n my $opp = $b.x - $a.x;\n my $adj = $b.y - $a.y;\n $adj != 0 ?? $opp / $adj !! Inf\n}\n\nsub graham-scan (**@coords) {\n # sort points by y, secondary sort on x\n my @sp = @coords.map( { Point.new( :x($_[0]), :y($_[1]) ) } )\n .sort: {.y, .x};\n\n # need at least 3 points to make a hull\n return @sp if +@sp < 3;\n\n # first point on hull is minimum y point\n my @h = @sp.shift;\n\n # re-sort the points by angle, secondary on x\n @sp = @sp.map( { $++ => [tangent(@h[0], $_), $_.x] } )\n .sort( {-$_.value[0], $_.value[1] } )\n .map: { @sp[$_.key] };\n\n # first point of re-sorted list is guaranteed to be on hull\n @h.push: @sp.shift;\n\n # check through the remaining list making sure that\n # there is always a positive angle\n for @sp -> $point {\n if ccw( |@h.tail(2), $point ) > 0 {\n @h.push: $point;\n } else {\n @h.pop;\n @h.push: $point and next if +@h < 2;\n redo;\n }\n }\n @h\n}\n\nmy @hull = graham-scan(\n (16, 3), (12,17), ( 0, 6), (-4,-6), (16, 6), (16,-7), (16,-3),\n (17,-4), ( 5,19), (19,-8), ( 3,16), (12,13), ( 3,-4), (17, 5),\n (-3,15), (-3,-9), ( 0,11), (-9,-3), (-4,-2), (12,10)\n );\n\nsay \"Convex Hull ({+@hull} points): \", @hull;\n\n@hull = graham-scan(\n (16, 3), (12,17), ( 0, 6), (-4,-6), (16, 6), (16,-7), (16,-3),\n (17,-4), ( 5,19), (19,-8), ( 3,16), (12,13), ( 3,-4), (17, 5),\n (-3,15), (-3,-9), ( 0,11), (-9,-3), (-4,-2), (12,10), (20,-9), (1,-9)\n );\n\nsay \"Convex Hull ({+@hull} points): \", @hull;\n\n```\n\nOutput:\n\n```\nConvex Hull (7 points): [(-3, -9) (19, -8) (17, 5) (12, 17) (5, 19) (-3, 15) (-9, -3)]\nConvex Hull (7 points): [(-3, -9) (20, -9) (17, 5) (12, 17) (5, 19) (-3, 15) (-9, -3)]\n```" } ]
[ { "role": "user", "content": "The **Game of Life** is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton.\n\nConway's game of life is described   here:\n\nA cell   **C**   is represented by a   **1**   when alive,   or   **0**   when dead,   in an   m-by-m   (or m×m)   square array of cells.\n\nWe calculate   **N**   - the sum of live cells in C's   eight-location neighbourhood,   then cell   C   is alive or dead in the next generation based on the following table:\n\n```\n C N new C\n 1 0,1 -> 0 # Lonely\n 1 4,5,6,7,8 -> 0 # Overcrowded\n 1 2,3 -> 1 # Lives\n 0 3 -> 1 # It takes three to give birth!\n 0 0,1,2,4,5,6,7,8 -> 0 # Barren\n\n```\n\nAssume cells beyond the boundary are always dead.\n\nThe \"game\" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players.   One interacts with the Game of Life by creating an initial configuration and observing how it evolves.\n\nTask\n\nAlthough you should test your implementation on more complex examples such as the   glider   in a larger universe,   show the action of the blinker   (three adjoining cells in a row all alive),   over three generations, in a 3 by 3 grid.\n\nReferences\n\n* Its creator John Conway, explains   the game of life.   Video from numberphile on youtube.\n* John Conway   Inventing Game of Life   - Numberphile video.\n\nRelated task\n\n* Langton's ant   - another well known cellular automaton." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nclass Automaton {\n subset World of Str where {\n .lines>>.chars.unique == 1 and m/^^<[.#\\n]>+$$/\n }\n has Int ($.width, $.height);\n has @.a;\n\n multi method new (World $s) {\n self.new:\n :width(.pick.chars), :height(.elems),\n :a( .map: { [ .comb ] } )\n given $s.lines.cache;\n }\n\n method gist { join \"\\n\", map { .join }, @!a }\n\n method C (Int $r, Int $c --> Bool) {\n @!a[$r % $!height][$c % $!width] eq '#';\n }\n method N (Int $r, Int $c --> Int) {\n +grep ?*, map { self.C: |@$_ },\n [ $r - 1, $c - 1], [ $r - 1, $c ], [ $r - 1, $c + 1],\n [ $r , $c - 1], [ $r , $c + 1],\n [ $r + 1, $c - 1], [ $r + 1, $c ], [ $r + 1, $c + 1];\n }\n\n method succ {\n self.new: :$!width, :$!height,\n :a(\n gather for ^$.height -> $r {\n take [\n gather for ^$.width -> $c {\n take\n (self.C($r, $c) == 1 && self.N($r, $c) == 2|3)\n || (self.C($r, $c) == 0 && self.N($r, $c) == 3)\n  ?? '#' !! '.'\n }\n ]\n }\n )\n }\n}\n\nmy Automaton $glider .= new: q:to/EOF/;\n ............\n ............\n ............\n .......###..\n .###...#....\n ........#...\n ............\n EOF\n\n\nfor ^10 {\n say $glider++;\n say '--';\n}\n```" } ]
[ { "role": "user", "content": "Task\n\nStarting from the sequence a(1)=1 and a(2)=2 find the next smallest number which is coprime to the last two predecessors and has not yet appeared yet in the sequence.\n \np and q are coprimes if they have no common factors other than 1.\n \n Let **p, q < 50**" }, { "role": "assistant", "content": "```\nmy @coprime-triplets = 1, 2, {\n state %seen = 1, True, 2, True;\n state $min = 3;\n my $g = $^a * $^b;\n my $n = ($min .. *).first: { !%seen{$_} && ($_ gcd $g == 1) }\n %seen{$n} = True;\n if %seen.elems %% 100 { $min = ($min .. *).first: { !%seen{$_} } }\n $n\n} … *;\n\nput \"Coprime triplets before first > 50:\\n\",\n@coprime-triplets[^(@coprime-triplets.first: * > 50, :k)].batch(10)».fmt(\"%4d\").join: \"\\n\";\n\nput \"\\nOr maybe, minimum Coprime triplets that encompass 1 through 50:\\n\",\n@coprime-triplets[0..(@coprime-triplets.first: * == 42, :k)].batch(10)».fmt(\"%4d\").join: \"\\n\";\n\nput \"\\nAnd for the heck of it: 1001st through 1050th Coprime triplet:\\n\",\n@coprime-triplets[1000..1049].batch(10)».fmt(\"%4d\").join: \"\\n\";\n\n```\n\nOutput:\n\n```\nCoprime triplets before first > 50:\n 1 2 3 5 4 7 9 8 11 13\n 6 17 19 10 21 23 16 15 29 14\n 25 27 22 31 35 12 37 41 18 43\n 47 20 33 49 26 45\n\nOr maybe, minimum Coprime triplets that encompass 1 through 50:\n 1 2 3 5 4 7 9 8 11 13\n 6 17 19 10 21 23 16 15 29 14\n 25 27 22 31 35 12 37 41 18 43\n 47 20 33 49 26 45 53 28 39 55\n 32 51 59 38 61 63 34 65 57 44\n 67 69 40 71 73 24 77 79 30 83\n 89 36 85 91 46 75 97 52 81 95\n 56 87 101 50 93 103 58 99 107 62\n 105 109 64 111 113 68 115 117 74 119\n 121 48 125 127 42\n\nAnd for the heck of it: 1001st through 1050th Coprime triplet:\n 682 1293 1361 680 1287 1363 686 1299 1367 688\n1305 1369 692 1311 1373 694 1317 1375 698 1323\n1381 704 1329 1379 706 1335 1387 716 1341 1385\n 712 1347 1391 700 1353 1399 710 1359 1393 718\n1371 1397 722 1365 1403 724 1377 1405 728 1383\n```" } ]
[ { "role": "user", "content": "Task\n\n**p**   and   **q**   are   coprimes   if they have no common factors other than   **1**.\n\nGiven the input pairs:   [21,15],[17,23],[36,12],[18,29],[60,15] display whether they are coprimes." }, { "role": "assistant", "content": "How do you determine if numbers are co-prime? Check to see if the Greatest common divisor is equal to one. Since we're duplicating tasks willy-nilly, lift code from that task, (or in this case, just use the builtin).\n\n```\nsay .raku, ( [gcd] |$_ ) == 1 ?? ' Coprime' !! '' for [21,15],[17,23],[36,12],[18,29],[60,15],[21,22,25,31,143]\n\n```\n\n```\n[21, 15]\n[17, 23] Coprime\n[36, 12]\n[18, 29] Coprime\n[60, 15]\n[21, 22, 25, 31, 143] Coprime\n```" } ]
[ { "role": "user", "content": "This task is about copying a string.\n\nTask\n\nWhere it is relevant, distinguish between copying the contents of a string\nversus making an additional reference to an existing 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\nThere is no special handling needed to copy a string; just assign it to a new variable:\n\n```\nmy $original = 'Hello.';\nmy $copy = $original;\nsay $copy; # prints \"Hello.\"\n$copy = 'Goodbye.';\nsay $copy; # prints \"Goodbye.\"\nsay $original; # prints \"Hello.\"\n```\n\nYou can also bind a new variable to an existing one so that each refers to, and can modify the same string.\n\n```\nmy $original = 'Hello.';\nmy $bound := $original;\nsay $bound; # prints \"Hello.\"\n$bound = 'Goodbye.';\nsay $bound; # prints \"Goodbye.\"\nsay $original; # prints \"Goodbye.\"\n```" } ]
[ { "role": "user", "content": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line." }, { "role": "assistant", "content": "(formerly Perl 6)\nWhen invoked at a command line: Slightly less magical than Perl / sed. The p flag means automatically print each line of output to STDOUT. The e flag means execute what follows inside quotes. \".lines\" reads lines from the assigned pipe (file handle), STDIN by default.\n\n```\nraku -pe'.lines'\n\n```\n\nWhen invoked from a file: Lines are auto-chomped, so need to re-add newlines (hence .say rather than .print)\n\n```\n.say for lines\n\n```" } ]
[ { "role": "user", "content": "Introduction\n\nCORDIC is the name of an algorithm for calculating trigonometric, logarithmic and hyperbolic functions, named after its first application on an airborne computer (COordinate Rotation DIgital Computer) in 1959.\nUnlike a Taylor expansion or polynomial approximation, it converges rapidly on machines with low computing and memory capacities: to calculate a tangent with 10 significant digits, it requires only 6 floating-point constants, and only additions, subtractions and digit shifts in its iterative part.\n\nIt is valid for angle values between 0 and π/2 only, but whatever the value of an angle, the calculation of its tangent can always be reduced to that of an angle between 0 and π/2, using trigonometric identities. Similarly, once you know the tangent, you can easily calculate the sine or cosine.\n\nPseudo code\n\n```\nconstant θ[n] = arctan 10^(-n) // or simply 10^(-n) depending on floating point precision \nconstant epsilon = 10^-12\n\nfunction tan(alpha) // 0 < alpha <= π/2 \n x = 1 ; y = 0 ; k = 0\n while epsilon < alpha\n while alpha < θ[k] \n k++\n end loop\n alpha -= θ[k]\n x2 = x - 10^(-k)*y\n y2 = y + 10^(-k)*x\n x = x2 ; y = y2\n end loop\n return (y/x)\nend function\n\n```\n\nTask\n\n* Implement the CORDIC algorithm, using only the 4 arithmetic operations and right shifts in the main loop if possible.\n* Use your implementation to calculate the cosine of the following angles, expressed in radians: -9, 0, 1.5 and 6\n\nSee also\n\nCORDIC on Wikipedia" }, { "role": "assistant", "content": "**Translation of**: XPL0\n\n```\n# 2023082 Raku programming solution\n\nsub CORDIC ($A is copy) {\n\n my (\\Ten, $K, $X, $Y) = ( 1, * * 1/10 ... * )[^6], 0, 1, 0;\n\n my \\Tbl = < 7.853981633974480e-1 9.966865249116200e-2 9.999666686665240e-3 \n 9.999996666668670e-4 9.999999966666670e-5 9.999999999666670e-6 0.0>;\n\n while $A > 1e-5 { \n $K++ while $A < Tbl[$K];\n $A -= Tbl[$K];\n ($X,$Y) = $X - Ten[$K]*$Y, $Y + Ten[$K]*$X;\n }\n return $X, sqrt($X*$X + $Y*$Y)\n}\n\nsay \"Angle CORDIC Cosine Error\";\nfor <-9 0 1.5 6> { \n my \\result = [/] CORDIC .abs;\n printf \"% 2.1f \"~\"% 2.8f \" x 3~\"\\n\", $_, result, .cos, .cos - result\n}\n\n```\n\nOutput:\n\nSame as XPL0 or you may Attempt This Online!" } ]
[ { "role": "user", "content": "Task\n: Count how many vowels and consonants occur in a 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": "Note that the task **does not** ask for the **total count** of vowels and consonants, but for **how many** occur.\n\n```\nmy @vowels = <a e i o u>;\nmy @consonants = <b c d f g h j k l m n p q r s t v w x y z>;\n\nsub letter-check ($string) {\n my $letters = $string.lc.comb.Set;\n \"{sum $letters{@vowels}} vowels and {sum $letters{@consonants}} consonants occur in the string \\\"$string\\\"\";\n}\n\nsay letter-check \"Forever Ring Programming Language\";\n\n```\n\nOutput:\n\n```\n5 vowels and 8 consonants occur in the string \"Forever Ring Programming Language\"\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program which counts up from   **1**,   displaying each number as the multiplication of its prime factors.\n\nFor the purpose of this task,   **1**   (unity)   may be shown as itself.\n\nExample\n\n**2**   is prime,   so it would be shown as itself.\n \n      **6**   is not prime;   it would be shown as   **2\n×\n3\n{\\displaystyle {\\displaystyle 2\\times 3}}\n.**\n \n**2144**   is not prime;   it would be shown as   **2\n×\n2\n×\n2\n×\n2\n×\n2\n×\n67\n{\\displaystyle {\\displaystyle 2\\times 2\\times 2\\times 2\\times 2\\times 67}}\n.**\n\nRelated tasks\n\n* prime decomposition\n* factors of an integer\n* Sieve of Eratosthenes\n* primality by trial division\n* factors of a Mersenne number\n* trial factoring of a Mersenne number\n* partition an integer X into N primes" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-10-01\n\n```\nconstant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;\n\nmulti factors(1) { 1 }\nmulti factors(Int $remainder is copy) {\n gather for @primes -> $factor {\n\n # if remainder < factor², we're done\n if $factor * $factor > $remainder {\n take $remainder if $remainder > 1;\n last;\n }\n\n # How many times can we divide by this prime?\n while $remainder %% $factor {\n take $factor;\n last if ($remainder div= $factor) === 1;\n }\n }\n}\n\nsay \"$_: \", factors($_).join(\" × \") for 1..*;\n\n```\n\nThe first twenty numbers:\n\n```\n1: 1\n2: 2\n3: 3\n4: 2 × 2\n5: 5\n6: 2 × 3\n7: 7\n8: 2 × 2 × 2\n9: 3 × 3\n10: 2 × 5\n11: 11\n12: 2 × 2 × 3\n13: 13\n14: 2 × 7\n15: 3 × 5\n16: 2 × 2 × 2 × 2\n17: 17\n18: 2 × 3 × 3\n19: 19\n20: 2 × 2 × 5\n```\n\nHere we use a multi declaration with a constant parameter to match the degenerate case. We use copy parameters when we wish to reuse the formal parameter as a mutable variable within the function. (Parameters default to readonly in Raku.) Note the use of gather/take as the final statement in the function, which is a common Raku idiom to set up a coroutine within a function to return a lazy list on demand.\n\nNote also the '×' above is not ASCII 'x', but U+00D7 MULTIPLICATION SIGN. Raku does Unicode natively.\n\nHere is a solution inspired from Almost\\_prime#C. It doesn't use &is-prime.\n\n```\nsub factor($n is copy) {\n $n == 1 ?? 1 !!\n gather {\n\t$n /= take 2 while $n %% 2;\n\t$n /= take 3 while $n %% 3;\n\tloop (my $p = 5; $p*$p <= $n; $p+=2) {\n\t $n /= take $p while $n %% $p;\n\t}\n\ttake $n unless $n == 1;\n }\n}\n\nsay \"$_ == \", join \" \\x00d7 \", factor $_ for 1 .. 20;\n\n```\n\nSame output as above.\n\nAlternately, use a module:\n\n```\nuse Prime::Factor;\n\nsay \"$_ = {(.&prime-factors || 1).join: ' x ' }\" for flat 1 .. 10, 10**20 .. 10**20 + 10;\n\n```\n\nOutput:\n\n```\n1 = 1\n2 = 2\n3 = 3\n4 = 2 x 2\n5 = 5\n6 = 2 x 3\n7 = 7\n8 = 2 x 2 x 2\n9 = 3 x 3\n10 = 2 x 5\n100000000000000000000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5 x 5\n100000000000000000001 = 73 x 137 x 1676321 x 5964848081\n100000000000000000002 = 2 x 3 x 155977777 x 106852828571\n100000000000000000003 = 373 x 155773 x 1721071782307\n100000000000000000004 = 2 x 2 x 13 x 1597 x 240841 x 4999900001\n100000000000000000005 = 3 x 5 x 7 x 7 x 83 x 1663 x 985694468327\n100000000000000000006 = 2 x 31 x 6079 x 265323774602147\n100000000000000000007 = 67 x 166909 x 8942221889969\n100000000000000000008 = 2 x 2 x 2 x 3 x 3 x 3 x 233 x 1986965506278811\n100000000000000000009 = 557 x 72937 x 2461483384901\n100000000000000000010 = 2 x 5 x 11 x 909090909090909091\n```" } ]
[ { "role": "user", "content": "Task\n\nProduce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number.\n\nEach number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached.\n\nRelated task\n\n* Integer sequence   is a similar task without the use of octal numbers." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay .base(8) for ^Inf;\n\n```\n\nOutput:\n\n```\n0\n```\n\nHere we arbitrarily show as many lines of output as there are lines in the program. :-)" } ]
[ { "role": "user", "content": "Task\n\nCreate a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string.\n\nThe function should take two arguments:\n\n: : : * the first argument being the string to search,   and\n * the second a substring to be searched for.\n\nIt should return an integer count.\n\n```\nprint countSubstring(\"the three truths\",\"th\")\n3\n\n// do not count substrings that overlap with previously-counted substrings:\nprint countSubstring(\"ababababab\",\"abab\")\n2\n```\n\nThe matching should yield the highest number of non-overlapping matches.\n\nIn general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page).\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```\nsub count-substring($big, $little) { +$big.comb: / :r $little / }\n \nsay count-substring(\"the three truths\", \"th\"); # 3\nsay count-substring(\"ababababab\", \"abab\"); # 2\n \nsay count-substring(123123123, 12); # 3\n```\n\nThe :r adverb makes the regex \"ratchet forward\" and skip any overlapping matches. .comb - when given a Regex as an argument - returns instances of that substring. Also, prefix + forces numeric context in Raku (it's a no-op in Perl 5). For the built in listy types that is the same as calling .elems method. One other style point: we now tend to prefer hyphenated names over camelCase." } ]
[ { "role": "user", "content": "There are four types of common coins in   US   currency:\n\n: : : 1. quarters   (25 cents)\n 2. dimes   (10 cents)\n 3. nickels   (5 cents),   and\n 4. pennies   (1 cent)\n\nThere are six ways to make change for 15 cents:\n\n: : : 1. A dime and a nickel\n 2. A dime and 5 pennies\n 3. 3 nickels\n 4. 2 nickels and 5 pennies\n 5. A nickel and 10 pennies\n 6. 15 pennies\n\nTask\n\nHow many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents).\n\nOptional\n\nLess common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000?\n\n(Note:   the answer is larger than   232).\n\nReferences\n\n* an algorithm from the book *Structure and Interpretation of Computer Programs*.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.10\n\n**Translation of**: Ruby\n\n```\n# Recursive (cached)\nsub change-r($amount, @coins) {\n my @cache = [1 xx @coins], |([] xx $amount);\n\n multi ways($n where $n >= 0, @now [$coin,*@later]) {\n @cache[$n;+@later] //= ways($n - $coin, @now) + ways($n, @later);\n }\n multi ways($,@) { 0 }\n\n # more efficient to start with coins sorted in descending order\n ways($amount, @coins.sort(-*).list);\n}\n\n# Iterative\nsub change-i(\\n, @coins) {\n my @table = [1 xx @coins], [0 xx @coins] xx n;\n (1..n).map: -> \\i {\n for ^@coins -> \\j {\n my \\c = @coins[j];\n @table[i;j] = [+]\n @table[i - c;j] // 0,\n @table[i;j - 1] // 0;\n }\n }\n @table[*-1][*-1];\n}\n\nsay \"Iterative:\";\nsay change-i 1_00, [1,5,10,25];\nsay change-i 1000_00, [1,5,10,25,50,100];\n\nsay \"\\nRecursive:\";\nsay change-r 1_00, [1,5,10,25];\nsay change-r 1000_00, [1,5,10,25,50,100];\n\n```\n\nOutput:\n\n```\nIterative:\n242\n13398445413854501\n\nRecursive:\n242\n13398445413854501\n```" } ]
[ { "role": "user", "content": "Let say you have some coins in your wallet and you want to have a given sum.\n\nYou can use each coin zero or one time.\n\nHow many ways can you do it ?\n\nThe result should be a number.\n\nFor instance the answer is 10 when coins = [1, 2, 3, 4, 5] and sum = 6.\n\nTask\n\nShow the result for the following examples:\n\n* coins = [1, 2, 3, 4, 5] and sum = 6\n\n* coins = [1, 1, 2, 3, 3, 4, 5] and sum = 6\n\n* coins = [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100] and sum = 40\n\nExtra\n\n* Show the result of the same examples when the order you take the coins doesn't matter. For instance the answer is 3 when coins = [1, 2, 3, 4, 5] and sum = 6.\n\n* Show an example of coins you used to reach the given sum and their indices. See Raku for this case." }, { "role": "assistant", "content": "First part is combinations filtered on a certain property. Second part (extra credit) is permutations of those combinations.\n\nThis is pretty much duplicating other tasks, in process if not wording. Even though I am adding a solution, my vote would be for deletion as it doesn't really add anything to the other tasks; Combinations, Permutations, Subset sum problem and to a large extent 4-rings or 4-squares puzzle.\n\n```\nfor <1 2 3 4 5>, 6\n ,<1 1 2 3 3 4 5>, 6\n ,<1 2 3 4 5 5 5 5 15 15 10 10 10 10 25 100>, 40\n -> @items, $sum {\n\n put \"\\n\\nHow many combinations of [{ @items.join: ', ' }] sum to $sum?\";\n\n given ^@items .combinations.grep: { @items[$_].sum == $sum } {\n .&display;\n display .race.map( { Slip(.permutations) } ), '';\n }\n}\n\nsub display ($list, $un = 'un') {\n put \"\\nOrder {$un}important:\\nCount: { +$list }\\nIndices\" ~ ( +$list > 10 ?? ' (10 random examples):' !! ':' );\n put $list.pick(10).sort».join(', ').join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\nHow many combinations of [1, 2, 3, 4, 5] sum to 6?\n\nOrder unimportant:\nCount: 3\nIndices:\n0, 1, 2\n0, 4\n1, 3\n\nOrder important:\nCount: 10\nIndices:\n0, 1, 2\n0, 2, 1\n0, 4\n1, 0, 2\n1, 2, 0\n1, 3\n2, 0, 1\n2, 1, 0\n3, 1\n4, 0\n\n\nHow many combinations of [1, 1, 2, 3, 3, 4, 5] sum to 6?\n\nOrder unimportant:\nCount: 9\nIndices:\n0, 1, 5\n0, 2, 3\n0, 2, 4\n0, 6\n1, 2, 3\n1, 2, 4\n1, 6\n2, 5\n3, 4\n\nOrder important:\nCount: 38\nIndices (10 random examples):\n0, 4, 2\n1, 2, 3\n1, 2, 4\n1, 5, 0\n1, 6\n2, 1, 3\n2, 1, 4\n2, 4, 0\n3, 2, 0\n6, 0\n\n\nHow many combinations of [1, 2, 3, 4, 5, 5, 5, 5, 15, 15, 10, 10, 10, 10, 25, 100] sum to 40?\n\nOrder unimportant:\nCount: 464\nIndices (10 random examples):\n0, 1, 2, 3, 5, 7, 10, 11\n0, 1, 2, 3, 5, 8, 12\n0, 1, 2, 3, 6, 7, 11, 13\n0, 3, 5, 7, 9, 13\n0, 3, 9, 10, 11\n1, 2, 5, 7, 9, 13\n4, 5, 10, 12, 13\n5, 6, 7, 9, 10\n5, 6, 10, 11, 12\n5, 8, 10, 12\n\nOrder important:\nCount: 3782932\nIndices (10 random examples):\n0, 11, 3, 4, 7, 5, 6, 1, 2\n1, 10, 5, 4, 6, 2, 0, 3, 7\n2, 7, 13, 4, 1, 3, 5, 6, 0\n2, 12, 4, 13, 10, 1\n3, 0, 5, 4, 7, 13, 6, 2, 1\n5, 7, 9, 4, 0, 1, 2, 3\n6, 2, 7, 11, 0, 3, 5, 1, 4\n10, 0, 12, 6, 5, 3, 4\n13, 0, 1, 5, 7, 3, 2, 12\n13, 6, 10, 1, 4, 3, 2, 0\n```" } ]
[ { "role": "user", "content": "It is conjectured that each decimal digit will occur with the same frequency in the mathematical constant e, see: the Wikipedia page on e. \nThis task is to count and display (here on this page) how many times each digit occurs, up to some \"large\" number of fractional digits.\n\nNotes\n\nA B program to calculate the first 4000 fractional digits is on the Wikipedia here: B (programming language) \nThe algorithm shown is from Ken Thompson's *Users' Reference to B* manual and does not require big-integers.\n\nThis Redit article draws a graph of the first 100 digits." }, { "role": "assistant", "content": "```\nconstant 𝑒 = [\\+] flat 1, [\\/] 1.FatRat..*;\n\nsub e-count ($n) {\n my @digits = 𝑒[$n / 2.7].substr(0,$n+1).comb.classify(*).sort.skip(1).map: {.key => .value.elems};\n .say for @digits;\n say 'Total digits: ', @digits».value.sum;\n say '';\n}\n\n.&e-count for 4000, 6000;\n\n```\n\nOutput:\n\n```\n0 => 396\n1 => 395\n2 => 390\n3 => 403\n4 => 387\n5 => 390\n6 => 422\n7 => 408\n8 => 397\n9 => 412\nTotal digits: 4000\n\n0 => 602\n1 => 592\n2 => 604\n3 => 625\n4 => 559\n5 => 586\n6 => 644\n7 => 600\n8 => 597\n9 => 591\nTotal digits: 6000\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven six numbers randomly selected from the list [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 25, 50, 75, 100], calculate using only positive integers and four operations [+, -, \\*, /] a random number between 101 and 999.\n\nExample:\n\nUsing: [3, 6, 25, 50, 75, 100] \nTarget: 952\n\nSolution:\n\n* 100 + 6 = 106\n* 75 \\* 3 = 225\n* 106 \\* 225 = 23850\n* 23850 - 50 = 23800\n* 23800 / 25 = 952\n\nOrigins\n\nThis is originally a 1972 French television game show. The game consists of randomly selecting six of the twenty-four numbers, from a list of: twenty \"small numbers\" (two each from 1 to 10), and four \"large numbers\" of 25, 50, 75 and 100. A random target number between 101 and 999 is generated. The players have 30 seconds to work out a sequence of calculations with the numbers whose final result is as close as possible to the target number. Only the four basic operations: addition, subtraction, multiplication and division can be used to create new numbers and not all six numbers are required. A number can only be used once. Division can only be done if the result has no remainder (fractions are not allowed) and only positive integers can be obtained at any stage of the calculation. (More info on the original game).\n\nExtra challenge\n\nThe brute force algorithm is quite obvious. What is more interesting is to find some optimisation heuristics to reduce the number of calculations. For example, a rather interesting computational challenge is to calculate, as fast as possible, all existing solutions (that means 2'764'800 operations) for all possible games (with all the 13'243 combinations of six numbers out of twenty-four for all 898 possible targets between 101 and 999)." }, { "role": "assistant", "content": "**Translation of**: Wren\n\n```\n# 20221021 Raku programming solution\n\nsub countdown ($target, @numbers) {\n return False if @numbers.elems == 1;\n for @numbers.kv -> \\n0k,\\n0v {\n (my @nums1 = @numbers).splice(n0k,1);\n for @nums1.kv -> \\n1k,\\n1v {\n (my @nums2 = @nums1).splice(n1k,1);\n if n1v >= n0v {\n (my @numsNew = @nums2).append: my $res = n1v + n0v; \n if ($res == $target or countdown($target, @numsNew)) {\n say \"$res = \",n1v,' + ',n0v andthen return True\n }\n\t if n0v != 1 {\n (my @numsNew = @nums2).append: my $res = n1v * n0v;\t\n\t if ($res == $target or countdown($target, @numsNew)) {\n say \"$res = \",n1v,' * ',n0v andthen return True\n\t }\n }\n if n1v != n0v {\n\t (my @numsNew = @nums2).append: my $res = n1v - n0v;\n\t if ($res == $target or countdown($target, @numsNew)) {\n say \"$res = \",n1v,' - ',n0v andthen return True\n }\n }\n if n0v != 1 and n1v %% n0v {\n (my @numsNew = @nums2).append: my $res = n1v div n0v;\n if ($res == $target or countdown($target, @numsNew)) {\n say \"$res = \",n1v,' / ',n0v andthen return True\n }\n }\n }\n }\n }\n return False\n}\n\nmy @allNumbers = < 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 25 50 75 100 >;\nmy @numbersList = <3 6 25 50 75 100> , <100 75 50 25 6 3>, \n <8 4 4 6 8 9> , @allNumbers.pick(6);\nmy @targetList = 952, 952, 594, (101..1000).pick;\n\nfor (0..^+@numbersList) -> \\i {\n say \"Using : \", my @numbers = |@numbersList[i];\n say \"Target: \", my $target = @targetList[i];\n say \"No exact solution found\" unless countdown $target, @numbers;\n say() \n}\n\n```\n\nOutput:\n\n```\nUsing : [3 6 25 50 75 100]\nTarget: 952\n952 = 23800 / 25\n23800 = 23850 - 50\n23850 = 225 * 106\n106 = 100 + 6\n225 = 75 * 3\n\nUsing : [100 75 50 25 6 3]\nTarget: 952\n952 = 23800 / 25\n23800 = 23850 - 50\n23850 = 7950 * 3\n7950 = 106 * 75\n106 = 100 + 6\n\nUsing : [8 4 4 6 8 9]\nTarget: 594\n594 = 66 * 9\n66 = 64 + 2\n64 = 16 * 4\n2 = 6 - 4\n16 = 8 + 8\n\nUsing : [100 9 50 2 9 8]\nTarget: 599\n599 = 590 + 9\n590 = 59 * 10\n10 = 8 + 2\n59 = 109 - 50\n109 = 100 + 9\n```" } ]
[ { "role": "user", "content": "Definitions\n\nIn mathematics, **cousin primes** are prime numbers that differ by four.\n\nFor the purposes of this task a **cousin prime pair** is a pair of non-negative integers of the form [n, n + 4] whose elements are both primes.\n\nTask\n\nWrite a program to determine (and show here) all **cousin prime pairs** whose elements are both less than **1,000**.\n\nOptionally, show the **number** of such pairs.\n\nAlso see\n: * the Wikipedia entry:   cousin prime.\n * the OEIS entry:   A094343.\n * the MathWorld entry:   cousin primes." }, { "role": "assistant", "content": "### Filter\n\nFavoring brevity over efficiency due to the small range of n, the most concise solution is:\n\n```\nsay grep *.all.is-prime, map { $_, $_+4 }, 2..999;\n\n```\n\nOutput:\n\n```\n((3 7) (7 11) (13 17) (19 23) (37 41) (43 47) (67 71) (79 83) (97 101) (103 107) (109 113) (127 131) (163 167) (193 197) (223 227) (229 233) (277 281) (307 311) (313 317) (349 353) (379 383) (397 401) (439 443) (457 461) (463 467) (487 491) (499 503) (613 617) (643 647) (673 677) (739 743) (757 761) (769 773) (823 827) (853 857) (859 863) (877 881) (883 887) (907 911) (937 941) (967 971))\n\n```\n\n### Infinite List\n\nA more efficient and versatile approach is to generate an infinite list of cousin primes, using this info from https://oeis.org/A023200 :\n\n: Apart from the first term, all terms are of the form 6n + 1.\n\n```\nconstant @cousins = (3, 7, *+6 … *).map: -> \\n { (n, n+4) if (n & n+4).is-prime };\n\nmy $count = @cousins.first: :k, *.[0] > 1000;\n\n.say for @cousins.head($count).batch(9);\n\n```\n\nOutput:\n\n```\n((3 7) (7 11) (13 17) (19 23) (37 41) (43 47) (67 71) (79 83) (97 101))\n((103 107) (109 113) (127 131) (163 167) (193 197) (223 227) (229 233) (277 281) (307 311))\n((313 317) (349 353) (379 383) (397 401) (439 443) (457 461) (463 467) (487 491) (499 503))\n((613 617) (643 647) (673 677) (739 743) (757 761) (769 773) (823 827) (853 857) (859 863))\n((877 881) (883 887) (907 911) (937 941) (967 971))\n```" } ]
[ { "role": "user", "content": "In linear algebra, Cramer's rule is an explicit formula for the solution of a system of linear equations with as many equations as unknowns, valid whenever the system has a unique solution. It expresses the solution in terms of the determinants of the (square) coefficient matrix and of matrices obtained from it by replacing one column by the vector of right hand sides of the equations.\n\nGiven\n\n: {\n\n a\n\n 1\n x\n +\n\n b\n\n 1\n y\n +\n\n c\n\n 1\n z\n\n =\n\n d\n\n 1\n\n a\n\n 2\n x\n +\n\n b\n\n 2\n y\n +\n\n c\n\n 2\n z\n\n =\n\n d\n\n 2\n\n a\n\n 3\n x\n +\n\n b\n\n 3\n y\n +\n\n c\n\n 3\n z\n\n =\n\n d\n\n 3\n\n {\\displaystyle {\\displaystyle \\left\\{{\\begin{matrix}a\\_{1}x+b\\_{1}y+c\\_{1}z&={\\color {red}d\\_{1}}\\\\a\\_{2}x+b\\_{2}y+c\\_{2}z&={\\color {red}d\\_{2}}\\\\a\\_{3}x+b\\_{3}y+c\\_{3}z&={\\color {red}d\\_{3}}\\end{matrix}}\\right.}}\n\nwhich in matrix format is\n\n: [\n\n a\n\n 1\n\n\n b\n\n 1\n\n\n c\n\n 1\n\n a\n\n 2\n\n\n b\n\n 2\n\n\n c\n\n 2\n\n a\n\n 3\n\n\n b\n\n 3\n\n\n c\n\n 3\n ]\n\n\n [\n\n x\n\n\n y\n\n\n z\n ]\n =\n\n\n [\n\n d\n\n 1\n\n d\n\n 2\n\n d\n\n 3\n ]\n .\n {\\displaystyle {\\displaystyle {\\begin{bmatrix}a\\_{1}&b\\_{1}&c\\_{1}\\\\a\\_{2}&b\\_{2}&c\\_{2}\\\\a\\_{3}&b\\_{3}&c\\_{3}\\end{bmatrix}}{\\begin{bmatrix}x\\\\y\\\\z\\end{bmatrix}}={\\begin{bmatrix}{\\color {red}d\\_{1}}\\\\{\\color {red}d\\_{2}}\\\\{\\color {red}d\\_{3}}\\end{bmatrix}}.}}\n\nThen the values of \n\nx\n,\ny\n{\\displaystyle {\\displaystyle x,y}}\n and \n\nz\n{\\displaystyle {\\displaystyle z}}\n can be found as follows:\n\n: x\n =\n\n |\n\n d\n\n 1\n\n\n b\n\n 1\n\n\n c\n\n 1\n\n d\n\n 2\n\n\n b\n\n 2\n\n\n c\n\n 2\n\n d\n\n 3\n\n\n b\n\n 3\n\n\n c\n\n 3\n |\n\n |\n\n a\n\n 1\n\n\n b\n\n 1\n\n\n c\n\n 1\n\n a\n\n 2\n\n\n b\n\n 2\n\n\n c\n\n 2\n\n a\n\n 3\n\n\n b\n\n 3\n\n\n c\n\n 3\n |\n ,\n\n y\n =\n\n |\n\n a\n\n 1\n\n d\n\n 1\n\n\n c\n\n 1\n\n a\n\n 2\n\n d\n\n 2\n\n\n c\n\n 2\n\n a\n\n 3\n\n d\n\n 3\n\n\n c\n\n 3\n |\n\n |\n\n a\n\n 1\n\n\n b\n\n 1\n\n\n c\n\n 1\n\n a\n\n 2\n\n\n b\n\n 2\n\n\n c\n\n 2\n\n a\n\n 3\n\n\n b\n\n 3\n\n\n c\n\n 3\n |\n ,\n\n  and \n z\n =\n\n |\n\n a\n\n 1\n\n\n b\n\n 1\n\n d\n\n 1\n\n a\n\n 2\n\n\n b\n\n 2\n\n d\n\n 2\n\n a\n\n 3\n\n\n b\n\n 3\n\n d\n\n 3\n |\n\n |\n\n a\n\n 1\n\n\n b\n\n 1\n\n\n c\n\n 1\n\n a\n\n 2\n\n\n b\n\n 2\n\n\n c\n\n 2\n\n a\n\n 3\n\n\n b\n\n 3\n\n\n c\n\n 3\n |\n .\n {\\displaystyle {\\displaystyle x={\\frac {\\begin{vmatrix}{\\color {red}d\\_{1}}&b\\_{1}&c\\_{1}\\\\{\\color {red}d\\_{2}}&b\\_{2}&c\\_{2}\\\\{\\color {red}d\\_{3}}&b\\_{3}&c\\_{3}\\end{vmatrix}}{\\begin{vmatrix}a\\_{1}&b\\_{1}&c\\_{1}\\\\a\\_{2}&b\\_{2}&c\\_{2}\\\\a\\_{3}&b\\_{3}&c\\_{3}\\end{vmatrix}}},\\quad y={\\frac {\\begin{vmatrix}a\\_{1}&{\\color {red}d\\_{1}}&c\\_{1}\\\\a\\_{2}&{\\color {red}d\\_{2}}&c\\_{2}\\\\a\\_{3}&{\\color {red}d\\_{3}}&c\\_{3}\\end{vmatrix}}{\\begin{vmatrix}a\\_{1}&b\\_{1}&c\\_{1}\\\\a\\_{2}&b\\_{2}&c\\_{2}\\\\a\\_{3}&b\\_{3}&c\\_{3}\\end{vmatrix}}},{\\text{ and }}z={\\frac {\\begin{vmatrix}a\\_{1}&b\\_{1}&{\\color {red}d\\_{1}}\\\\a\\_{2}&b\\_{2}&{\\color {red}d\\_{2}}\\\\a\\_{3}&b\\_{3}&{\\color {red}d\\_{3}}\\end{vmatrix}}{\\begin{vmatrix}a\\_{1}&b\\_{1}&c\\_{1}\\\\a\\_{2}&b\\_{2}&c\\_{2}\\\\a\\_{3}&b\\_{3}&c\\_{3}\\end{vmatrix}}}.}}\n\nTask\n\nGiven the following system of equations:\n\n: {\n\n 2\n w\n −\n x\n +\n 5\n y\n +\n z\n =\n −\n 3\n\n\n 3\n w\n +\n 2\n x\n +\n 2\n y\n −\n 6\n z\n =\n −\n 32\n\n\n w\n +\n 3\n x\n +\n 3\n y\n −\n z\n =\n −\n 47\n\n\n 5\n w\n −\n 2\n x\n −\n 3\n y\n +\n 3\n z\n =\n 49\n\n {\\displaystyle {\\displaystyle {\\begin{cases}2w-x+5y+z=-3\\\\3w+2x+2y-6z=-32\\\\w+3x+3y-z=-47\\\\5w-2x-3y+3z=49\\\\\\end{cases}}}}\n\nsolve for \n\nw\n{\\displaystyle {\\displaystyle w}}\n, \n\nx\n{\\displaystyle {\\displaystyle x}}\n, \n\ny\n{\\displaystyle {\\displaystyle y}}\n and \n\nz\n{\\displaystyle {\\displaystyle z}}\n, using Cramer's rule." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub det(@matrix) {\n my @a = @matrix.map: { [|$_] };\n my $sign = 1;\n my $pivot = 1;\n for ^@a -> \\k {\n my @r = (k+1 ..^ @a);\n my $previous-pivot = $pivot;\n if 0 == ($pivot = @a[k;k]) {\n (my \\s = @r.first: { @a[$_;k] != 0 }) // return 0;\n (@a[s], @a[k]) = (@a[k], @a[s]);\n my $pivot = @a[k;k];\n $sign = -$sign;\n }\n for @r X @r -> (\\i,\\j) {\n ((@a[i;j] ×= $pivot) -= @a[i;k]×@a[k;j]) /= $previous-pivot;\n }\n }\n $sign × $pivot\n}\n\nsub cramers_rule(@A, @terms) {\n gather for ^@A -> \\i {\n my @Ai = @A.map: { [|$_] };\n for ^@terms -> \\j {\n @Ai[j;i] = @terms[j];\n }\n take det(@Ai);\n } »/» det(@A);\n}\n\nmy @matrix = (\n [2, -1, 5, 1],\n [3, 2, 2, -6],\n [1, 3, 3, -1],\n [5, -2, -3, 3],\n);\n\nmy @free_terms = <-3 -32 -47 49>;\nmy ($w, $x, $y, $z) = cramers_rule(@matrix, @free_terms);\n(\"w = $w\", \"x = $x\", \"y = $y\", \"z = $z\").join(\"\\n\").say;\n\n```\n\nOutput:\n\n```\nw = 2\nx = -12\ny = -4\nz = 1\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate a method of deriving the Cyclic Redundancy Check from within the language.\n\nThe result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.\n\nAlgorithms are described on Computation of CRC in Wikipedia.\nThis variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.\n\nFor the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:\n\n: : `The quick brown fox jumps over the lazy dog`" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Call to native function crc32 in zlib\n\n```\nuse NativeCall;\n \nsub crc32(int32 $crc, Buf $buf, int32 $len --> int32) is native('z') { * }\n \nmy $buf = 'The quick brown fox jumps over the lazy dog'.encode;\nsay crc32(0, $buf, $buf.bytes).fmt('%08x');\n\n```\n\nThe libary name \"z\" resolves to /usr/lib/libz.so on a typical Linux system and /usr/lib/libz.dylib on Mac OS X, but may need to be changed for other platforms. Types may be platform-dependent as well. As written, the solution has been tested on Mac OS X 10.5.8 and Arch Linux 2016.08.01 x86\\_64.\n\nOutput:\n\n```\n414fa339\n```\n\n### Pure Raku\n\nA fairly generic implementation with no regard to execution speed:\n\n```\nsub crc(\n Blob $buf,\n # polynomial including leading term, default: ISO 3309/PNG/gzip\n  :@poly = (1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1),\n  :$n = @poly.end, # degree of polynomial\n  :@init = 1 xx $n, # initial XOR bits\n  :@fini = 1 xx $n, # final XOR bits\n  :@bitorder = 0..7, # default: eat bytes LSB-first\n  :@crcorder = 0..$n-1, # default: MSB of checksum is coefficient of x⁰\n) {\n my @bit = flat ($buf.list X+& (1 X+< @bitorder))».so».Int, 0 xx $n;\n\n @bit[0 .. $n-1] «+^=» @init;\n @bit[$_ ..$_+$n] «+^=» @poly if @bit[$_] for [email protected]$n;\n @bit[*-$n.. *-1] «+^=» @fini;\n\n  :2[@bit[@bit.end X- @crcorder]];\n}\n\nsay crc('The quick brown fox jumps over the lazy dog'.encode('ascii')).base(16);\n\n```\n\nOutput:\n\n```\n414FA339\n```" } ]
[ { "role": "user", "content": "In this task, the job is to create a new empty file called \"output.txt\" of size 0 bytes\nand an empty directory called \"docs\". This should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nfor '.', '' -> $prefix {\n mkdir \"$prefix/docs\";\n open \"$prefix/output.txt\", :w;\n}\n```" } ]
[ { "role": "user", "content": "The task is to create a new file called \"TAPE.FILE\" of any size on Magnetic Tape." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $tape = open \"/dev/tape\", :w or die \"Can't open tape: $!\";\n$tape.say: \"I am a tape file now, or hope to be soon.\";\n$tape.close;\n\n```" } ]
[ { "role": "user", "content": "Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-28\n\nLine 1: The input parse doesn't care how you separate the dimensions as long as there are two distinct numbers.\n\nLine 2: The list replication operator xx will automatically thunkify its left side so this produces new subarrays for each replication.\n\nLine 3: Subscripting with a closure automatically passes the size of the dimension to the closure, so we pick an appropriate random index on each level.\n\nLine 4: Print each line of the array.\n\n```\nmy ($major,$minor) = prompt(\"Dimensions? \").comb(/\\d+/);\nmy @array = [ '@' xx $minor ] xx $major;\n@array[ *.rand ][ *.rand ] = ' ';\n.say for @array;\n\n```\n\nTypical run:\n\n```\nDimensions? 5x35\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @]\n\n```\n\nThe most recent versions of Rakudo have preliminary support for 'shaped arrays'. Natively shaped arrays are a flexible feature for declaring typed, potentially multi-dimensional arrays, potentially with pre-defined\ndimensions. They will make memory-efficient matrix storage and matrix operations possible.\n\n```\nmy ($major,$minor) = +«prompt(\"Dimensions? \").comb(/\\d+/);\nmy Int @array[$major;$minor] = (7 xx $minor ) xx $major;\n@array[$major div 2;$minor div 2] = 42;\nsay @array;\n```\n\nTypical run:\n\n```\nDimensions? 3 x 10\n[[7 7 7 7 7 7 7 7 7 7] [7 7 7 7 7 42 7 7 7 7] [7 7 7 7 7 7 7 7 7 7]]\n```" } ]
[ { "role": "user", "content": "Create an HTML table.\n\n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\".\n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.\n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less.\n* The numbers should be aligned in the same fashion for all columns." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe below example is kind of boring, and laughably simple. For more interesting/complicated examples see:\n\nShow\\_Ascii\\_table#Raku - *(simple)* \nMayan\\_numerals#Raku - *(heavy styling)* \nRosetta\\_Code/Count\\_examples/Full\\_list - *(multi-column sortable)* \nRosetta\\_Code/List\\_authors\\_of\\_task\\_descriptions/Full\\_list - *(complex nested tables)*\n\n*Note: the above examples are outputting wikitable formatting, not HTML directly. It's pretty much a one-for-one shorthand notation though and the principles and process are the same.*\n\nThis is certainly not the only or best way to generate HTML tables using Raku; just an example of one possible method.\n\n```\nmy @header = <&nbsp; X Y Z>;\nmy $rows = 5;\n\nsub tag ($tag, $string, $param?) { return \"<$tag\" ~ ($param ?? \" $param\" !! '') ~ \">$string\" ~ \"</$tag>\" };\n\nmy $table = tag('tr', ( tag('th', $_) for @header));\n\nfor 1 .. $rows -> $row { \n $table ~= tag('tr', ( tag('td', $row, 'align=\"right\"')\n ~ (tag('td', (^10000).pick, 'align=\"right\"') for 1..^@header))); \n}\n\nsay tag('table', $table, 'cellspacing=4 style=\"text-align:right; border: 1px solid;\"');\n\n```\n\nOutput:\n\n| | X | Y | Z |\n| --- | --- | --- | --- |\n| 1 | 2179 | 4778 | 2717 |\n| 2 | 2160 | 1592 | 4348 |\n| 3 | 4511 | 540 | 7187 |\n| 4 | 3484 | 5882 | 1273 |\n| 5 | 1310 | 4017 | 410 |" } ]
[ { "role": "user", "content": "In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.\n\nTask\n\nShow how language objects can be allocated at a specific machine addresses.\n\nSince most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).\n\nFor example:\n\n: : * create an integer object\n * print the machine address of the object\n * take the address of the object and create another integer object at this address\n * print the value of this object to verify that it is same as one of the origin\n * change the value of the origin and verify it again" }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku has fairly comprehensive facilities for accessing allocating and accessing memory and also declaring C-style structs, via the NativeCall interface, as this example demonstrates.\n\n```\nuse NativeCall;\nuse NativeCall::Types;\n\n# bind to basic libc memory management\nsub malloc(size_t) returns Pointer[uint8] is native {*};\nsub memset(Pointer, uint32, size_t) is native {*};\nsub free(Pointer[uint8]) is native {*};\n\nmy Pointer[uint8] $base-p = malloc(100);\nmemset($base-p, 0, 100);\n\n# define object as a C struct that contains a short and an int\nclass SampleObject is repr('CStruct') {\n has uint16 $.foo is rw;\n has uint8 $.bar is rw;\n}\n\n# for arguments sake our object is at byte offset 64 in the\n# allocated memory\n\nmy $offset-p = $base-p.clone.add(64);\nmy $object-p := nativecast(Pointer[SampleObject], $offset-p);\nnote \"creating object at address {+$object-p}\";\n\nmy $struct := $object-p.deref;\n\n$struct.foo = 41;\n$struct.bar = 99;\n\n# check we can update\n$struct.foo++; # 42\n\n# Check that we're actually updating the memory\nuse Test;\n\n# look at the bytes directly to verify we've written to memory. Don't be too exact, as\n# the positions may vary on different platforms depending on endianess and field alignment.\n\nmy $rec-size = nativesizeof(SampleObject);\nmy uint8 @bytes-written = (0 ..^ $rec-size).map(-> $i {$base-p[64 + $i]}).grep: * > 0;\n\n# first field 'foo' (amount is small enough to fit in one byte)\nis @bytes-written[0], 42, 'object first field';\n\n# second field 'bar'\nis @bytes-written[1], 99, 'object second field';\n\n# verify that changing the origin changes the object values\nmemset($base-p, 1, 100); # set every byte to 1\n\nis $struct.foo, 256 + 1, 'short updated at origin';\nis $struct.bar, 1, 'byte updated at origin';\n\n# tidy up\nfree($base-p);\ndone-testing;\n\n```\n\nOutput:\n\n```\ncreating object at address 94299589110352\nok 1 - object first field\nok 2 - object second field\nok 3 - short updated at origin\nok 4 - byte updated at origin\n1..4\n\n```" } ]