messages
listlengths
2
2
[ { "role": "user", "content": "Task\n\nFind prime   **n**     for   **0 < n < 500**     which are also primes when the (decimal) digits are reversed.\n \nNearly Emirp Primes, which don't count palindromatic primes like 101." }, { "role": "assistant", "content": "```\nunit sub MAIN ($limit = 500);\nsay \"{+$_} reversible primes < $limit:\\n{$_».fmt(\"%\" ~ $limit.chars ~ \"d\").batch(10).join(\"\\n\")}\",\n with ^$limit .grep: { .is-prime and .flip.is-prime }\n\n```\n\nOutput:\n\n```\n34 reversible primes < 500:\n 2 3 5 7 11 13 17 31 37 71\n 73 79 97 101 107 113 131 149 151 157\n167 179 181 191 199 311 313 337 347 353\n359 373 383 389\n```" } ]
[ { "role": "user", "content": "Task\n: Find prime numbers of the form   n*3*+2,   where 0 < n < 200" }, { "role": "assistant", "content": "```\n# 20210315 Raku programming solution\n\nsay ((1…199)»³ »+»2).grep: *.is-prime\n\n```\n\nOutput:\n\n```\n(3 29 127 24391 91127 250049 274627 328511 357913 571789 1157627 1442899 1860869 2146691 2924209 3581579 5000213 5177719 6751271)\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show on this page the least positive integer number **n**, where difference of **n\\*n** and **(n-1)\\*(n-1)** greater than **1000**.\n \nThe result is **501** because **501\\*501 - 500\\*500 = 251001 - 250000 = 1001 > 1000**." }, { "role": "assistant", "content": "```\nsay first { $_² - ($_-1)² > 1000 }, ^Inf;\n\n```\n\nOutput:\n\n```\n501\n```" } ]
[ { "role": "user", "content": "Task\n\nFind squares **n** where **n+1** is prime and **n<1.000**" }, { "role": "assistant", "content": "Use up to to one thousand (1,000) rather than up to one (1.000) as otherwise it would be a pretty short list...\n\n```\nsay ({$++²}…^*>Ⅿ).grep: (*+1).is-prime\n\n```\n\nOutput:\n\n```\n(1 4 16 36 100 196 256 400 576 676)\n```\n\nAlthough, technically, there is absolutely nothing in the task directions specifying that **n** needs to be the square of an *integer*. So, more accurately...\n\n```\nput (^Ⅿ).grep(*.is-prime).map(*-1).batch(20)».fmt(\"%3d\").join: \"\\n\"\n\n```\n\nOutput:\n\n```\n 1 2 4 6 10 12 16 18 22 28 30 36 40 42 46 52 58 60 66 70\n 72 78 82 88 96 100 102 106 108 112 126 130 136 138 148 150 156 162 166 172\n178 180 190 192 196 198 210 222 226 228 232 238 240 250 256 262 268 270 276 280\n282 292 306 310 312 316 330 336 346 348 352 358 366 372 378 382 388 396 400 408\n418 420 430 432 438 442 448 456 460 462 466 478 486 490 498 502 508 520 522 540\n546 556 562 568 570 576 586 592 598 600 606 612 616 618 630 640 642 646 652 658\n660 672 676 682 690 700 708 718 726 732 738 742 750 756 760 768 772 786 796 808\n810 820 822 826 828 838 852 856 858 862 876 880 882 886 906 910 918 928 936 940\n946 952 966 970 976 982 990 996\n```" } ]
[ { "role": "user", "content": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\nTask\n\nFind the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5]." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.11\n\n**Translation of**: Python\n\n```\nclass Line {\n has $.P0; # point\n has $.u⃗; # ray\n}\nclass Plane {\n has $.V0; # point\n has $.n⃗; # normal\n}\n\nsub infix:<∙> ( @a, @b where +@a == +@b ) { [+] @a «*» @b } # dot product\n\nsub line-plane-intersection ($𝑳, $𝑷) {\n my $cos = $𝑷.n⃗ ∙ $𝑳.u⃗; # cosine between normal & ray\n return 'Vectors are orthogonal; no intersection or line within plane'\n if $cos == 0;\n my $𝑊 = $𝑳.P0 «-» $𝑷.V0; # difference between P0 and V0\n my $S𝐼 = -($𝑷.n⃗ ∙ $𝑊) / $cos; # line segment where it intersects the plane\n $𝑊 «+» $S𝐼 «*» $𝑳.u⃗ «+» $𝑷.V0; # point where line intersects the plane\n }\n\nsay 'Intersection at point: ', line-plane-intersection(\n Line.new( :P0(0,0,10), :u⃗(0,-1,-1) ),\n Plane.new( :V0(0,0, 5), :n⃗(0, 0, 1) )\n );\n\n```\n\nOutput:\n\n```\nIntersection at point: (0 -5 5)\n```\n\n### With a geometric algebra library\n\nSee task geometric algebra\n\n```\nuse Clifford:ver<6.2.1>;\n\n# We pick a (non-degenerate) projective basis and\n# we define the dual and meet operators.\nmy $I = [∧] my ($i, $j, $k, $l) = @e;\nsub prefix:<∗>($M) { $M/$I }\nsub infix:<∨>($A, $B) { ∗((∗$B)∧(∗$A)) }\n\nmy $direction = -$j - $k;\n\n# Homogeneous coordinates of (X, Y, Z) are (X, Y, Z, 1)\nmy $point = 10*$k + $l;\n\n# A projective line is a bivector\nmy $line = $direction ∧ $point;\n\n# A projective plane is a trivector\nmy $plane = (5*$k + $l) ∧ ($k*-$i∧$j∧$k);\n\n# The intersection is the meet\nmy $m = $line ∨ $plane;\n\n# Affine coordinates of (X, Y, Z, W) are (X/W, Y/W, Z/W)\nsay $m/($m·$l) X· ($i, $j, $k);\n\n```\n\nOutput:\n\n```\n(0 -5 5)\n```" } ]
[ { "role": "user", "content": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[1]\n\nTask\n\nFind the point of intersection of two lines in 2D.\n\nThe 1st line passes though   (4,0)   and   (6,10) .\n \nThe 2nd line passes though   (0,3)   and   (10,7) ." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.11\n\n**Translation of**: zkl\n\n```\nsub intersection (Real $ax, Real $ay, Real $bx, Real $by,\n Real $cx, Real $cy, Real $dx, Real $dy ) {\n\n sub term:<|AB|> { determinate($ax, $ay, $bx, $by) }\n sub term:<|CD|> { determinate($cx, $cy, $dx, $dy) }\n\n my $ΔxAB = $ax - $bx;\n my $ΔyAB = $ay - $by;\n my $ΔxCD = $cx - $dx;\n my $ΔyCD = $cy - $dy;\n\n my $x-numerator = determinate( |AB|, $ΔxAB, |CD|, $ΔxCD );\n my $y-numerator = determinate( |AB|, $ΔyAB, |CD|, $ΔyCD );\n my $denominator = determinate( $ΔxAB, $ΔyAB, $ΔxCD, $ΔyCD );\n\n return 'Lines are parallel' if $denominator == 0;\n\n ($x-numerator/$denominator, $y-numerator/$denominator);\n}\n\nsub determinate ( Real $a, Real $b, Real $c, Real $d ) { $a * $d - $b * $c }\n\n# TESTING\nsay 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7 );\nsay 'Intersection point: ', intersection( 4,0, 6,10, 0,3, 10,7.1 );\nsay 'Intersection point: ', intersection( 0,0, 1,1, 1,2, 4,5 );\n\n```\n\nOutput:\n\n```\nIntersection point: (5 5)\nIntersection point: (5.010893 5.054466)\nIntersection point: Lines are parallel\n\n```\n\n### Using a geometric algebra library\n\nSee task geometric algebra.\n\n```\nuse Clifford;\n\n# We pick a projective basis,\n# and we compute its pseudo-scalar and its square.\nmy ($i, $j, $k) = @e;\nmy $I = $i∧$j∧$k;\nmy $I2 = ($I**2).narrow;\n\n# Homogeneous coordinates of point (X,Y) are (X,Y,1)\nmy $A = 4*$i + 0*$j + $k;\nmy $B = 6*$i + 10*$j + $k;\nmy $C = 0*$i + 3*$j + $k;\nmy $D = 10*$i + 7*$j + $k;\n\n# We form lines by joining points\nmy $AB = $A∧$B;\nmy $CD = $C∧$D;\n\n# The intersection is their meet, which we\n# compute by using the De Morgan law\nmy $ab = $AB*$I/$I2;\nmy $cd = $CD*$I/$I2;\nmy $M = ($ab ∧ $cd)*$I/$I2;\n\n# Affine coordinates are (X/Z, Y/Z)\nsay $M/($M·$k) X· $i, $j;\n\n```\n\nOutput:\n\n```\n(5 5)\n```" } ]
[ { "role": "user", "content": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n```\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n```\n\nRelated tasks\n\n* Day of the week\n* Five weekends\n* Last Friday of each month" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nsub MAIN ($year = Date.today.year) {\n for 1..12 -> $month {\n my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month);\n say $month-end - $month-end.day-of-week % 7;\n }\n}\n\n```\n\nOutput  —  for input `2018`:\n\n```\n2018-01-28\n2018-02-25\n2018-03-25\n2018-04-29\n2018-05-27\n2018-06-24\n2018-07-29\n2018-08-26\n2018-09-30\n2018-10-28\n2018-11-25\n2018-12-30\n```" } ]
[ { "role": "user", "content": "```\n ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n```\n\nListed above are   all-but-one   of the permutations of the symbols   **A**,   **B**,   **C**,   and   **D**,   *except*   for one permutation that's   *not*   listed.\n\nTask\n\nFind that missing permutation.\n\nMethods\n\n* Obvious method:\n\n```\n enumerate all permutations of A, B, C, and D, \n and then look for the missing permutation. \n\n```\n\n* alternate method:\n\n```\n Hint: if all permutations were shown above, how many \n times would A appear in each position? \n What is the parity of this number?\n\n```\n\n* another alternate method:\n\n```\n Hint: if you add up the letter values of each column, \n does a missing letter A, B, C, and D from each\n column cause the total value for each column to be unique?\n\n```\n\nRelated task\n\n* Permutations)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @givens = <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;\n\nmy @perms = <A B C D>.permutations.map: *.join;\n\n.say when none(@givens) for @perms;\n\n```\n\nOutput:\n\n```\nDBAC\n```\n\nOf course, all of these solutions are working way too hard,\nwhen you can just xor all the bits,\nand the missing one will just pop right out:\n\n```\nsay [~^] <ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA\n CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB>;\n\n```\n\nOutput:\n\n```\nDBAC\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a function to search plain text for URIs or IRIs.\n\nThe function should return a list of URIs or IRIs found in the text.\n\nThe definition of a URI is given in RFC 3986.\nIRI is defined in RFC 3987.\n\nFor searching URIs in particular \"Appendix C. Delimiting a URI in Context\" is noteworthy.\n\nThe abbreviation IRI isn't as well known as URI and the short description is that an IRI is just an alternate form of a URI that supports Internationalization and hence Unicode. While many specifications support both forms this isn't universal.\n\nConsider the following issues:\n\n: * `. , ; ' ? ( )`   are legal characters in a URI, but they are often used in plain text as a delimiter.\n * IRIs allow most (but not all) unicode characters.\n * URIs can be something else besides http:// or https://\n\nSample text\n\n```\n this URI contains an illegal character, parentheses and a misplaced full stop:\n http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).\n and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)\n \")\" is handled the wrong way by the mediawiki parser.\n ftp://domain.name/path(balanced_brackets)/foo.html\n ftp://domain.name/path(balanced_brackets)/ending.in.dot.\n ftp://domain.name/path(unbalanced_brackets/ending.in.dot.\n leading junk ftp://domain.name/path/embedded?punct/uation.\n leading junk ftp://domain.name/dangling_close_paren)\n if you have other interesting URIs for testing, please add them here: \n\n```\n\nRegular expressions to solve the task are fine, but alternative approaches are welcome too. (otherwise, this task would degrade into 'finding and applying the best regular expression')\n\n**Extra Credit:**   implement the parser to match the IRI specification in RFC 3987." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis needs an installed URI distribution.\n\n**Works with**: Rakudo version 2018.03\n\n```\nuse v6;\nuse IETF::RFC_Grammar::URI;\n\nsay q:to/EOF/.match(/ <IETF::RFC_Grammar::URI::absolute-URI> /, :g).list.join(\"\\n\");\n this URI contains an illegal character, parentheses and a misplaced full stop:\n http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).\n and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)\n \")\" is handled the wrong way by the mediawiki parser.\n ftp://domain.name/path(balanced_brackets)/foo.html\n ftp://domain.name/path(balanced_brackets)/ending.in.dot.\n ftp://domain.name/path(unbalanced_brackets/ending.in.dot.\n leading junk ftp://domain.name/path/embedded?punct/uation.\n leading junk ftp://domain.name/dangling_close_paren)\n EOF\n\nsay $/[*-1];\nsay \"We matched $/[*-1], which is a $/[*-1].^name() at position $/[*-1].from() to $/[*-1].to()\"\n\n```\n\nLike most of the solutions here it does not comply to IRI but only to URI:\n\n```\nstop:\nhttp://en.wikipedia.org/wiki/Erich_K\nhttp://mediawiki.org/).\nparser:\nhttp://en.wikipedia.org/wiki/-)\nftp://domain.name/path(balanced_brackets)/foo.html\nftp://domain.name/path(balanced_brackets)/ending.in.dot.\nftp://domain.name/path(unbalanced_brackets/ending.in.dot.\nftp://domain.name/path/embedded\nftp://domain.name/dangling_close_paren)\n「ftp://domain.name/dangling_close_paren)」\n IETF::RFC_Grammar::URI::absolute_URI => 「ftp://domain.name/dangling_close_paren)」\n scheme => 「ftp」\nWe matched ftp://domain.name/dangling_close_paren), which is a Match, at position 554 to 593\n```\n\nThe last lines show that we get Match objects back that we can query to get all kinds of information.\nWe even get the information what subrules matched, and since these are also Match objects we can obtain\ntheir match position in the text." } ]
[ { "role": "user", "content": "Task\n\nUse the dictionary  unixdict.txt\n\nFind the words which contains all the vowels,   but each vowel should appear only once in a word.\n\nThe length of any word shown should have a length   **>  10****.**\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": "Yet another \"Filter a word list\" task.\n\n```\nput +.words, \" words found:\\n\", $_ with 'unixdict.txt'.IO.words\\\n .grep({ .chars > 10 and all(.comb.Bag<a e i o u>) == 1 })\\\n .batch(5)».fmt('%-13s').join: \"\\n\";\n\n```\n\nOutput:\n\n```\n25 words found:\nambidextrous bimolecular cauliflower communicable communicate \nconsanguine consultative countervail exclusionary grandiloquent\nimportunate incommutable incomputable insupportable loudspeaking \nmalnourished mensuration oneupmanship pandemonium permutation \nperturbation portraiture praseodymium stupefaction sulfonamide \n```" } ]
[ { "role": "user", "content": "Task\n\nUse the dictionary  unixdict.txt\n\nFind the words which contains most consonants,   but each consonant should appear only once in a word.\n\nThe length of any word shown should have a length   **>  10****.**\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": "Hmm. Depends on how you define \"most\".\n\n```\nunit sub MAIN ($min = 11);\nmy @vowel = <a e i o u>;\nmy $vowel = rx/ @vowel /;\nmy @consonant = ('a'..'z').grep: { $_ ∉ @vowel };\nmy $consonant = rx/ @consonant /;\n\nsay \"Minimum characters in a word: $min\";\n\nsay \"Number found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants:\";\nsay +.value, ' @ ', $_ for 'unixdict.txt'.IO.words.grep( {.chars >= $min and so all(.comb.Bag{@consonant}) <= 1} )\n .classify( { +.comb(/$consonant/) } ).sort(-*.key).head(2);\n\nsay \"\\nNumber found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels:\";\nsay +.value, ' @ ', $_ for 'unixdict.txt'.IO.slurp.words.grep( {.chars >= $min and so all(.comb.Bag{@consonant}) <= 1} )\n .classify( { +.comb(/$vowel/) ?? (+.comb(/$consonant/) / +.comb(/$vowel/) ) !! Inf } ).sort(-*.key).head(3);\n\n```\n\nOutput:\n\n```\nMinimum characters in a word: 11\nNumber found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants:\n1 @ 9 => [comprehensible]\n39 @ 8 => [administrable anthropology blameworthy bluestocking boustrophedon bricklaying chemisorption christendom claustrophobia compensatory comprehensive counterexample demonstrable disciplinary discriminable geochemistry hypertensive indecipherable indecomposable indiscoverable lexicography manslaughter misanthropic mockingbird monkeyflower neuropathology paralinguistic pharmacology pitchblende playwriting shipbuilding shortcoming springfield stenography stockholder switchblade switchboard switzerland thunderclap]\n\nNumber found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels:\n14 @ 2.666667 => [blameworthy bricklaying christendom mockingbird pitchblende playwriting shortcoming springfield stenography stockholder switchblade switchboard switzerland thunderclap]\n13 @ 2 => [anthropology bluestocking compensatory demonstrable disciplinary geochemistry hypertensive lexicography manslaughter misanthropic monkeyflower pharmacology shipbuilding]\n1 @ 1.8 => [comprehensible]\n```\n\nCharacter count of 11 minimum is rather arbitrary. If we feed it a character count minimum of 5, the first one returns a pretty similar answer, 8 additional words at 8 consonants (all with 10 characters.)\n\nThe second would actually come up with some infinite ratios (since we somewhat bogusly don't count 'y' as a vowel.):\n\n```\nMinimum characters in a word: 5\nNumber found, consonant count and list of words with the largest absolute number of unique, unrepeated consonants:\n1 @ 9 => [comprehensible]\n47 @ 8 => [administrable anthropology bankruptcy blacksmith blameworthy bluestocking boustrophedon bricklaying chemisorption christendom claustrophobia compensatory comprehensive counterexample crankshaft demonstrable disciplinary discriminable geochemistry hypertensive indecipherable indecomposable indiscoverable lexicography lynchburg manslaughter misanthropic mockingbird monkeyflower neuropathology paralinguistic pharmacology pitchblende playwright playwriting shipbuilding shortcoming sprightly springfield stenography stockholder strickland stronghold switchblade switchboard switzerland thunderclap]\n\nNumber found, ratio and list of words with the highest ratio of unique, unrepeated consonants to vowels:\n6 @ Inf => [crypt glyph lymph lynch nymph psych]\n2 @ 8 => [lynchburg sprightly]\n5 @ 7 => [klystron mcknight schwartz skylight splotchy]\n```" } ]
[ { "role": "user", "content": "Task\n\nUse the dictionary   unixdict.txt\n\nFind words which contains more than three   **e**   vowels   *and*   contains only   **e**   vowels.\n\nShow the output here on this 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": "Hardly even worth saving as a script file; an easily entered one-liner.\n\n```\n.say for \"unixdict.txt\".IO.lines.grep: { !/<[aiou]>/ and /e.*e.*e.*e/ };\n\n```\n\nOutput:\n\n```\nbelvedere\ndereference\nelsewhere\nerlenmeyer\nevergreen\neverywhere\nexegete\nfreewheel\nnevertheless\npersevere\npreference\nreferee\nseventeen\nseventeenth\ntelemeter\ntennessee\n\n```\n\nIn an attempt to be a little less useless, here's an alternate script that allows you to specify a vowel, the minimum count to search for, and the file to search. Counts base vowels case, and combining accent insensitive; works with *any* text file, not just word lists. Defaults to finding words with at least 4 'e's in unixdict.txt. Default output is same as above.\n\n```\nunit sub MAIN ($vowel = 'e', $min = 4, $file = 'unixdict.txt');\n.say for squish sort\n ( $file.IO.slurp.words.grep: { ((my $b = .lc.samemark(' ').comb.Bag){$vowel} >= $min) && $b<a e i o u>.sum == $b{$vowel} } )\\\n  ».subst(/<[\":;,.?!_\\[\\]]>/, '', :g);\n\n```\n\nHow about: find words with at least 4 'a's in the Les Misérables file used for the Word frequency task?\n\nCommand line `> raku monovowel a 4 lemiz.txt`\n\nOutput:\n\n```\nCaracalla\nCaracara\nSalamanca\nVâsaphantâ\n```" } ]
[ { "role": "user", "content": "Task\n\nUsing the dictionary  unixdict.txt\n \n \nfind the words whose first and last three letters are equal.\n\nThe length of any word shown should have a length   **>  5****.**\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "```\n# 20210210 Raku programming solution\n\nmy ( \\L, \\N, \\IN ) = 5, 3, 'unixdict.txt';\n\nfor IN.IO.lines { .say if .chars > L and .substr(0,N) eq .substr(*-N,*) }\n\n```\n\nOutput:\n\n```\nantiperspirant\ncalendrical\neinstein\nhotshot\nmurmur\noshkosh\ntartar\ntestes\n\n```" } ]
[ { "role": "user", "content": "Task\n\nUsing the dictionary   unixdict.txt,   find words which odd letters are consonants and even letters are vowels or vice versa.\n \nDisplay the words here (on this page).\n\nThe length of any word shown should have a length   **> 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": "Sigh. Yet another \"Filter a word list\" task. In a effort to make it a *little* more interesting, rather than just doing a one-liner, build a grammar and use that to filter.\n\n```\ngrammar VOWCON {\n token TOP { <|w> <vowel>? ( <consonant> <vowel> )* <consonant>? <|w> }\n token vowel { <[aeiou]> }\n token consonant { <[a..z] - [aeiou]> }\n}\n\nsay ( grep { VOWCON.parse: .lc }, grep { .chars > 9 }, 'unixdict.txt'.IO.words ).batch(6)».fmt('%-15s').join: \"\\n\";\n\n```\n\nOutput:\n\n```\naboriginal apologetic bimolecular borosilicate calorimeter capacitate \ncapacitive capitoline capitulate caricature colatitude coloratura \ncolorimeter debilitate decelerate decolonize definitive degenerate \ndeliberate demodulate denominate denotative deregulate desiderata \ndesideratum dilapidate diminutive epigenetic facilitate hemosiderin \nheretofore hexadecimal homogenate inoperative judicature latitudinal \nlegitimate lepidolite literature locomotive manipulate metabolite \nnicotinamide oratorical paragonite pejorative peridotite peripatetic \npolarimeter recitative recuperate rehabilitate rejuvenate remunerate \nrepetitive reticulate savonarola similitude solicitude tananarive \ntelekinesis teratogenic topologize unilateral unimodular uninominal \nverisimilitude\n```" } ]
[ { "role": "user", "content": "A Finite state machine (FSM) is computational abstraction which maps a finite number of states to other states within the same set, via transitions. An FSM can only be in one state at any given moment. Transitions can either be explicit or implicit; explicit transitions are triggered by an input signal and implicit transitions by the internal state of the system (that is, the current state). Implicit transitions thus represent \"automatic\" or sequenced states that are generally processed between explicit transitions (although they can also be used to provide an optional path when no valid transition exists for a given input signal).\n\nExample\n\nConsider the model of a simple vending machine. The machine is initially in the \"ready\" state, which maps to exactly two states in the following way:\n\n: ready -> **deposit** -> waiting\n\n: ready -> **quit** -> exit\n\nThe variables in bold-face represent transitions. Any input signal not corresponding to one of those transitions can either trigger an error or be ignored. Otherwise, the current state is updated and the process is repeated. If, for example, a **deposit** input signal is encountered, the FSM will move to the \"waiting\" state, which defines these transitions:\n\n: waiting -> **select** -> dispense\n\n: waiting -> **refund** -> refunding\n\nThe \"dispense\" state defines only one transition:\n\n: dispense -> **remove** -> ready\n\nNote, however, that in this example the \"refunding\" state doesn't actually require input in order to move to the \"ready\" state, so an implicit transition is defined as such:\n\n: refunding -> ready\n\nTask\n\nImplement a finite state machine which handles both explicit and implicit transitions. Then demonstrate an example which models some real-world process.\n\nSee also\n\n* Computers Without Memory (Finite State Automata), A Computerphile Video." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\n#===== The state machine =====#\n\nclass StateMachine {\n class State {...}\n class Transition {...}\n\n has State %!state;\n has &.choose-transition is rw;\n\n method add-state(Str $id, &action)\n {\n %!state{$id} = State.new(:$id, :&action);\n }\n\n multi method add-transition(Str $from, Str $to)\n {\n %!state{$from}.implicit-next = %!state{$to};\n }\n\n multi method add-transition(Str $from, $id, Str $to)\n {\n %!state{$from}.explicit-next.push: Transition.new(:$id, to => %!state{$to});\n }\n\n method run(Str $initial-state)\n {\n my $state = %!state{$initial-state};\n \n loop {\n $state.action.();\n if $state.implicit-next -> $_ { $state = $_; }\n elsif $state.explicit-next -> $_ { $state = &.choose-transition.(|$_).to; }\n else { last; }\n }\n }\n\n class Transition {\n has $.id;\n has State $.to;\n }\n class State {\n has $.id;\n has &.action;\n has State $.implicit-next is rw;\n has Transition @.explicit-next;\n }\n}\n\n\n#===== Usage example: Console-based vending machine =====#\n\nmy StateMachine $machine .= new;\n\n$machine.choose-transition = sub (*@transitions) {\n say \"[{.key + 1}] {.value.id}\" for @transitions.pairs;\n loop {\n my $n = val get;\n return @transitions[$n - 1] if $n ~~ Int && $n ~~ 1..@transitions;\n say \"Invalid input; try again.\";\n }\n}\n\n$machine.add-state(\"ready\", { say \"Please deposit coins.\"; });\n$machine.add-state(\"waiting\", { say \"Please select a product.\"; });\n$machine.add-state(\"dispense\", { sleep 2; say \"Please remove product from tray.\"; });\n$machine.add-state(\"refunding\", { sleep 1; say \"Refunding money...\"; });\n$machine.add-state(\"exit\", { say \"Shutting down...\"; });\n\n$machine.add-transition(\"ready\", \"quit\", \"exit\");\n$machine.add-transition(\"ready\", \"deposit\", \"waiting\");\n$machine.add-transition(\"waiting\", \"select\", \"dispense\");\n$machine.add-transition(\"waiting\", \"refund\", \"refunding\");\n$machine.add-transition(\"dispense\", \"remove\", \"ready\");\n$machine.add-transition(\"refunding\", \"ready\");\n\n$machine.run(\"ready\");\n\n```" } ]
[ { "role": "user", "content": "Task\n\nShow on this page the first 9 prime Fibonacci numbers." }, { "role": "assistant", "content": "```\nput ++$ .fmt(\"%2d: \") ~ $_ for (0, 1, * + * … *).grep( &is-prime )[^20];\n\n```\n\nOutput:\n\n```\n 1: 2\n 2: 3\n 3: 5\n 4: 13\n 5: 89\n 6: 233\n 7: 1597\n 8: 28657\n 9: 514229\n10: 433494437\n11: 2971215073\n12: 99194853094755497\n13: 1066340417491710595814572169\n14: 19134702400093278081449423917\n15: 475420437734698220747368027166749382927701417016557193662268716376935476241\n16: 529892711006095621792039556787784670197112759029534506620905162834769955134424689676262369\n17: 1387277127804783827114186103186246392258450358171783690079918032136025225954602593712568353\n18: 3061719992484545030554313848083717208111285432353738497131674799321571238149015933442805665949\n19: 10597999265301490732599643671505003412515860435409421932560009680142974347195483140293254396195769876129909\n20: 36684474316080978061473613646275630451100586901195229815270242868417768061193560857904335017879540515228143777781065869\n```" } ]
[ { "role": "user", "content": "According to Wikipedia, \"In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable\".\n\nOften this term is used in the context of \"first class functions\". In an analogous way, a programming language may support \"first class environments\".\n\nThe environment is minimally, the set of variables accessible to a statement being executed. Change the environments and the same statement could produce different results when executed.\n\nOften an environment is captured in a closure, which encapsulates a function together with an environment. That environment, however, is **not** first-class, as it cannot be created, passed etc. independently from the function's code.\n\nTherefore, a first class environment is a set of variable bindings which can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable. It is like a closure without code. A statement must be able to be executed within a stored first class environment and act according to the environment variable values stored within.\n\nTask\n\nBuild a dozen environments, and a single piece of code to be run repeatedly in each of these environments.\n\nEach environment contains the bindings for two variables:\n\n: * a value in the Hailstone sequence, and\n * a count which is incremented until the value drops to 1.\n\nThe initial hailstone values are 1 through 12, and the count in each environment is zero.\n\nWhen the code runs, it calculates the next hailstone step in the current environment (unless the value is already 1) and counts the steps. Then it prints the current value in a tabular form.\n\nWhen all hailstone values dropped to 1, processing stops, and the total number of hailstone steps for each environment is printed." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nSet up an array of hashes containing the current values and iteration counts then pass each hash in turn with a code reference to a routine to calculate the next iteration.\n\n```\nmy $calculator = sub ($n is rw) {\n $n == 1 ?? 1 !! $n %% 2 ?? $n div 2 !! $n * 3 + 1\n}\n\nsub next (%this, &get_next) {\n return %this if %this.<value> == 1;\n %this.<value> .= &get_next;\n %this.<count>++;\n %this;\n}\n\nmy @hailstones = map { %(value => $_, count => 0) }, 1 .. 12;\n\nwhile not all( map { $_.<value> }, @hailstones ) == 1 {\n say [~] map { $_.<value>.fmt: '%4s' }, @hailstones;\n @hailstones[$_] .= &next($calculator) for ^@hailstones;\n}\n\nsay \"\\nCounts\\n\" ~ [~] map { $_.<count>.fmt: '%4s' }, @hailstones;\n\n```\n\nOutput:\n\n```\n 1 2 3 4 5 6 7 8 9 10 11 12\n 1 1 10 2 16 3 22 4 28 5 34 6\n 1 1 5 1 8 10 11 2 14 16 17 3\n 1 1 16 1 4 5 34 1 7 8 52 10\n 1 1 8 1 2 16 17 1 22 4 26 5\n 1 1 4 1 1 8 52 1 11 2 13 16\n 1 1 2 1 1 4 26 1 34 1 40 8\n 1 1 1 1 1 2 13 1 17 1 20 4\n 1 1 1 1 1 1 40 1 52 1 10 2\n 1 1 1 1 1 1 20 1 26 1 5 1\n 1 1 1 1 1 1 10 1 13 1 16 1\n 1 1 1 1 1 1 5 1 40 1 8 1\n 1 1 1 1 1 1 16 1 20 1 4 1\n 1 1 1 1 1 1 8 1 10 1 2 1\n 1 1 1 1 1 1 4 1 5 1 1 1\n 1 1 1 1 1 1 2 1 16 1 1 1\n 1 1 1 1 1 1 1 1 8 1 1 1\n 1 1 1 1 1 1 1 1 4 1 1 1\n 1 1 1 1 1 1 1 1 2 1 1 1\nCounts\n 0 1 7 2 5 8 16 3 19 6 14 9\n```" } ]
[ { "role": "user", "content": "Find the first perfect square in a given base **N** that has at least **N** digits and\nexactly **N** *significant unique* digits when expressed in base **N**.\n\nE.G. In base **10**, the first perfect square with at least **10** unique digits is **1026753849** (**32043²**).\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\nTask\n\n* Find and display here, on this page, the first perfect square in base **N**, with **N** significant unique digits when expressed in base **N**, for each of base **2** through **12**. Display each number in the base **N** for which it was calculated.\n\n* (optional) Do the same for bases **13** through **16**.\n\n* (stretch goal) Continue on for bases **17** - **??** (Big Integer math)\n\nSee also\n\n* OEIS A260182: smallest square that is pandigital in base n.\n\nRelated task\n\n* Casting out nines" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\nAs long as you have the patience, this will work for bases 2 through 36.\n\nBases 2 through 19 finish quickly, (about 10 seconds on my system), 20 takes a while, 21 is pretty fast, 22 is glacial. 23 through 26 takes several hours.\n\nUse analytical start value filtering based on observations by Hout++\nand Nigel Galloway++ on the\ndiscussion page.\n\nTry it online!\n\n```\n#`[\n\nOnly search square numbers that have at least N digits;\nsmaller could not possibly match.\n\nOnly bother to use analytics for large N. Finesse takes longer than brute force for small N.\n\n]\n\nunit sub MAIN ($timer = False);\n\nsub first-square (Int $n) {\n my @start = flat '1', '0', (2 ..^ $n)».base: $n;\n\n if $n > 10 { # analytics\n my $root = digital-root( @start.join, :base($n) );\n my @roots = (2..$n).map(*²).map: { digital-root($_.base($n), :base($n) ) };\n if $root ∉ @roots {\n my $offset = min(@roots.grep: * > $root ) - $root;\n @start[1+$offset] = $offset ~ @start[1+$offset];\n }\n }\n\n my $start = @start.join.parse-base($n).sqrt.ceiling;\n my @digits = reverse (^$n)».base: $n;\n my $sq;\n my $now = now;\n my $time = 0;\n my $sr;\n for $start .. * {\n $sq = .²;\n my $s = $sq.base($n);\n my $f;\n $f = 1 and last unless $s.contains: $_ for @digits;\n if $timer && $n > 19 && $_ %% 1_000_000 {\n $time += now - $now;\n say \"N $n: {$_}² = $sq <$s> : {(now - $now).round(.001)}s\" ~\n \" : {$time.round(.001)} elapsed\";\n $now = now;\n }\n next if $f;\n $sr = $_;\n last\n }\n sprintf( \"Base %2d: %13s² == %-30s\", $n, $sr.base($n), $sq.base($n) ) ~\n ($timer ?? ($time + now - $now).round(.001) !! '');\n}\n\nsub digital-root ($root is copy, :$base = 10) {\n $root = $root.comb.map({:36($_)}).sum.base($base) while $root.chars > 1;\n $root.parse-base($base);\n}\n\nsay \"First perfect square with N unique digits in base N: \";\nsay .&first-square for flat\n 2 .. 12, # required\n 13 .. 16, # optional\n 17 .. 19, # stretch\n 20, # slow\n 21, # pretty fast\n 22, # very slow\n 23, # don't hold your breath\n 24, # slow but not too terrible\n 25, # very slow\n 26, # \"\n;\n\n```\n\nOutput:\n\n```\nFirst perfect square with N unique digits in base N:\nBase 2: 10² == 100\nBase 3: 22² == 2101\nBase 4: 33² == 3201\nBase 5: 243² == 132304\nBase 6: 523² == 452013\nBase 7: 1431² == 2450361\nBase 8: 3344² == 13675420\nBase 9: 11642² == 136802574\nBase 10: 32043² == 1026753849\nBase 11: 111453² == 1240A536789\nBase 12: 3966B9² == 124A7B538609\nBase 13: 3828943² == 10254773CA86B9\nBase 14: 3A9DB7C² == 10269B8C57D3A4\nBase 15: 1012B857² == 102597BACE836D4\nBase 16: 404A9D9B² == 1025648CFEA37BD9\nBase 17: 423F82GA9² == 101246A89CGFB357ED\nBase 18: 44B482CAD² == 10236B5F8EG4AD9CH7\nBase 19: 1011B55E9A² == 10234DHBG7CI8F6A9E5\nBase 20: 49DGIH5D3G² == 1024E7CDI3HB695FJA8G\nBase 21: 4C9HE5FE27F² == 1023457DG9HI8J6B6KCEAF\nBase 22: 4F94788GJ0F² == 102369FBGDEJ48CHI7LKA5\nBase 23: 1011D3EL56MC² == 10234ACEDKG9HM8FBJIL756\nBase 24: 4LJ0HDGF0HD3² == 102345B87HFECKJNIGMDLA69\nBase 25: 1011E145FHGHM² == 102345DOECKJ6GFB8LIAM7NH9\nBase 26: 52K8N53BDM99K² == 1023458LO6IEMKG79FPCHNJDBA\n```" } ]
[ { "role": "user", "content": "(This task is taken from a   *Project Euler*   problem.)\n\n(All numbers herein are expressed in base ten.)\n\n**27   =   128**   and   **7**   is\nthe first power of   **2**   whose leading decimal digits are   **12**.\n\nThe next power of   **2**   whose leading decimal digits\nare   **12**   is   **80**,\n \n**280   =   1208925819614629174706176**.\n\nDefine     ***p*(*L,n*)**     to be the ***n*th**-smallest\nvalue of   ***j***   such that the base ten representation\nof   **2*j***   begins with the digits of   ***L*** .\n\n```\n So p(12, 1) = 7 and\n p(12, 2) = 80\n\n```\n\nYou are also given that:\n\n```\n p(123, 45)   =   12710\n\n```\n\nTask\n: : * find:\n\n : : : * ***p*(12, 1)**\n * ***p*(12, 2)**\n * ***p*(123, 45)**\n * ***p*(123, 12345)**\n * ***p*(123, 678910)**\n\n * display the results here, on this page." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\nUses logs similar to Go and Pascal entries. Takes advantage of patterns in the powers to cut out a bunch of calculations.\n\n```\nuse Lingua::EN::Numbers;\n\nconstant $ln2ln10 = log(2) / log(10);\n\nmy @startswith12 = ^∞ .grep: { ( 10 ** ($_ * $ln2ln10 % 1) ).substr(0,3) eq '1.2' };\n\nmy @startswith123 = lazy gather loop {\n state $pre = '1.23';\n state $count = 0;\n state $this = 0;\n given $this {\n when 196 {\n $this = 289;\n my \\n = $count + $this;\n $this = 485 unless ( 10 ** (n * $ln2ln10 % 1) ).substr(0,4) eq $pre;\n }\n when 485 {\n $this = 196;\n my \\n = $count + $this;\n $this = 485 unless ( 10 ** (n * $ln2ln10 % 1) ).substr(0,4) eq $pre;\n }\n when 289 { $this = 196 }\n when 90 { $this = 289 }\n when 0 { $this = 90 }\n }\n take $count += $this;\n}\n\nmulti p ($prefix where *.chars == 2, $nth) { @startswith12[$nth-1] }\nmulti p ($prefix where *.chars == 3, $nth) { @startswith123[$nth-1] }\n\n# The Task\nfor < 12 1 12 2 123 45 123 12345 123 678910 > -> $prefix, $nth {\n printf \"%-15s %9s power of two (2^n) that starts with %5s is at n = %s\\n\", \"p($prefix, $nth):\",\n comma($nth) ~ ordinal-digit($nth).substr(*-2), \"'$prefix'\", comma p($prefix, $nth);\n}\n\n```\n\nOutput:\n\n```\np(12, 1): 1st power of two (2^n) that starts with '12' is at n = 7\np(12, 2): 2nd power of two (2^n) that starts with '12' is at n = 80\np(123, 45): 45th power of two (2^n) that starts with '123' is at n = 12,710\np(123, 12345): 12,345th power of two (2^n) that starts with '123' is at n = 3,510,491\np(123, 678910): 678,910th power of two (2^n) that starts with '123' is at n = 193,060,223\n```" } ]
[ { "role": "user", "content": "A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:\n\n* Create new functions from preexisting functions at run-time\n* Store functions in collections\n* Use functions as arguments to other functions\n* Use functions as return values of other functions\n\nTask\n\nWrite a program to create an ordered collection *A* of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection *B* with the inverse of each function in *A*. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in *A* and its inverse in *B* to a value, is the original value. (Within the limits of computational accuracy).\n\n(A solution need not actually call the collections \"A\" and \"B\". These names are only used in the preceding paragraph for clarity.)\n\nRelated task\n\nFirst-class Numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\nHere we use the Z (\"zipwith\") metaoperator to zip the 𝐴 and 𝐵 lists with builtin composition operator, ∘ (or just o). The .() construct invokes the function contained in the $\\_ (current topic) variable.\n\n```\nmy \\𝐴 = &sin, &cos, { $_ ** <3/1> }\nmy \\𝐵 = &asin, &acos, { $_ ** <1/3> }\n\nsay .(.5) for 𝐴 Z∘ 𝐵\n\n```\n\nOutput:\n\n```\n0.5\n0.4999999999999999\n0.5000000000000001\n\n```\n\nIt is not clear why we don't get exactly 0.5, here.\n\nOperators, both builtin and user-defined, are first class too.\n\n```\nmy @a = 1,2,3;\nmy @op = &infix:<+>, &infix:<->, &infix:<*>;\nfor flat @a Z @op -> $v, &op { say 42.&op($v) }\n\n```\n\nOutput:\n\n```\n43\n40\n126\n```" } ]
[ { "role": "user", "content": "In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n\n```\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\n```\n\nCreate a function *multiplier*, that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n\n```\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\n```\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. \n**Compare and contrast the resultant program with the corresponding entry in First-class functions.** They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015-09-10\n\n```\nsub multiplied ($g, $f) { return { $g * $f * $^x } }\n \nmy $x = 2.0;\nmy $xi = 0.5;\nmy $y = 4.0;\nmy $yi = 0.25;\nmy $z = $x + $y;\nmy $zi = 1.0 / ( $x + $y );\n\nmy @numbers = $x, $y, $z;\nmy @inverses = $xi, $yi, $zi;\n \nfor flat @numbers Z @inverses { say multiplied($^g, $^f)(.5) }\n\n```\n\nOutput:\n\n```\n0.5\n0.5\n0.5\n```\n\nThe structure of this is identical to first-class function task." } ]
[ { "role": "user", "content": "The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.\n\nTask\n\n1. Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar).\n2. Show the *number* of months with this property (there should be 201).\n3. Show at least the first and last five dates, in order.\n\n**Algorithm suggestions**\n\n* Count the number of Fridays, Saturdays, and Sundays in every month.\n* Find all of the 31-day months that begin on Friday.\n\n**Extra credit**\n\nCount and/or show all of the years which do not have at least one five-weekend month (there should be 29).\n\nRelated tasks\n\n* Day of the week\n* Last Friday of each month\n* Find last sunday of each month" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015-09-10\n\n```\n# A month has 5 weekends iff it has 31 days and starts on Friday.\n\nmy @years = 1900 .. 2100;\nmy @has31 = 1, 3, 5, 7, 8, 10, 12;\nmy @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));\n\nsay 'Happy month count: ', +@happy;\nsay 'First happy months: ' ~ @happy[^5];\nsay 'Last happy months: ' ~ @happy[*-5 .. *];\nsay 'Dreary years count: ', @years - @happy».year.squish;\n\n```\n\nOutput:\n\n```\nHappy month count: 201\nFirst happy months: 1901-03-01 1902-08-01 1903-05-01 1904-01-01 1904-07-01\nLast happy months: 2097-03-01 2098-08-01 2099-05-01 2100-01-01 2100-10-01\nDreary years count: 29\n```" } ]
[ { "role": "user", "content": "Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the   **R**   programming language implements Tukey's five-number summary as the **fivenum** function.\n\nTask\n\nGiven an array of numbers, compute the five-number summary.\n\nNote\n\nWhile these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data.\n\nMoreover, while there is a consensus about the \"box\" of the boxplot,   there are variations among statistical packages for the whiskers." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub fourths ( Int $end ) {\n my $end_22 = $end div 2 / 2;\n\n return 0, $end_22, $end/2, $end - $end_22, $end;\n}\nsub fivenum ( @nums ) {\n my @x = @nums.sort(+*)\n or die 'Input must have at least one element';\n\n my @d = fourths(@x.end);\n\n return ( @x[@d».floor] Z+ @x[@d».ceiling] ) »/» 2;\n}\n\nsay .&fivenum for [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43],\n [36, 40, 7, 39, 41, 15], [\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594,\n 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772,\n 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469,\n 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578,\n];\n\n```\n\nOutput:\n\n```\n(6 25.5 40 42.5 49)\n(7 15 37.5 40 41)\n(-1.95059594 -0.676741205 0.23324706 0.746070945 1.73131507)\n```" } ]
[ { "role": "user", "content": "Fixed length read/write\n\nBefore terminals, computers commonly used punch card readers or paper tape input.\n\nA common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code.\n\nThese input devices handled 80 columns per card and had a limited character set, encoded by punching holes in one or more rows of the card for each column.\n\nThese devices assumed/demanded a fixed line width of 80 characters, newlines were not required (and could not even be encoded in some systems).\n\nTask\n\nWrite a program to read 80 column fixed length records (no newline terminators (but newline characters allowed in the data)) and then write out the reverse of each line as fixed length 80 column records.\n\nSamples here use printable characters, but that is not a given with fixed length data. Filenames used are sample.txt, infile.dat, outfile.dat.\n\n**Note:** There are no newlines, inputs and outputs are fixed at 80 columns, no more, no less, space padded. Fixed length data is 8 bit complete. NUL bytes of zero are allowed.\n\nThese fixed length formats are still in wide use on mainframes, with JCL and with COBOL (which commonly use EBCDIC encoding and not ASCII). Most of the large players in day to day financial transactions know all about fixed length records and the expression *logical record length*.\n\nSample data\n\nTo create the sample input file, use an editor that supports fixed length records or use a conversion utility. For instance, most GNU/Linux versions of **dd** support blocking and unblocking records with a conversion byte size.\n\n```\nLine 1...1.........2.........3.........4.........5.........6.........7.........8\nLine 2\nLine 3\nLine 4\n\nLine 6\nLine 7\n Indented line 8............................................................\nLine 9 RT MARGIN\n```\n\n```\nprompt$ dd if=sample.txt of=infile.dat cbs=80 conv=block\n```\n\nwill create a fixed length record file of 80 bytes given newline delimited text input.\n\n```\nprompt$ dd if=infile.dat cbs=80 conv=unblock\n```\n\nwill display a file with 80 byte logical record lengths to standard out as standard text with newlines.\n\nBonus round\n\nForth systems often include BLOCK words. A block is 1024 bytes. Source code is stored as 16 lines of 64 characters each (again, no newline character or sequence to mark the end of a line).\n\nWrite a program to convert a block file to text (using newlines). Trailing spaces should be excluded from the output.\n\nAlso demonstrate how to convert from a normal text file to block form. All lines either truncated or padded to 64 characters with no newline terminators. The last block filled to be exactly 1024 characters by adding blanks if needed. Assume a full range of 8 bit byte values for each character.\n\nThe COBOL example uses forth.txt and forth.blk filenames." }, { "role": "assistant", "content": "(formerly Perl 6)\nLink to a copy of the input file used: flr-infile.dat\n\nEssentially the same as task Selective\\_File\\_Copy except more boring.\n\n```\n$*OUT = './flr-outfile.dat'.IO.open(:w, :bin) orelse .die; # open a file in binary mode for writing\nwhile my $record = $*IN.read(80) { # read in fixed sized binary chunks\n $*OUT.write: $record.=reverse; # write reversed records out to $outfile\n $*ERR.say: $record.decode('ASCII'); # display decoded records on STDERR\n}\nclose $*OUT;\n\n```\n\nOutput:\n\n```\n8.........7.........6.........5.........4.........3.........2.........1...1 eniL\n 2 eniL\n 3 eniL\n 4 eniL\n \n 6 eniL\n 7 eniL\n............................................................8 enil detnednI \nNIGRAM TR 9 eniL\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program that prints the integers from   **1**   to   **100**   (inclusive).\n\nBut:\n\n: * for multiples of three,   print   **Fizz**     instead of the number;\n * for multiples of five,   print   **Buzz**     instead of the number;\n * for multiples of both three and five,   print   **FizzBuzz**     instead of the number.\n\nThe   *FizzBuzz*   problem was presented as the lowest level of comprehension required to illustrate adequacy.\n\nAlso see\n\n* (a blog)   dont-overthink-fizzbuzz\n* (a blog)   fizzbuzz-the-programmers-stairway-to-heaven" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2015-09-10\n\nMost straightforwardly:\n\n```\nfor 1 .. 100 {\n when $_ %% (3 & 5) { say 'FizzBuzz'; }\n when $_ %% 3 { say 'Fizz'; }\n when $_ %% 5 { say 'Buzz'; }\n default { .say; }\n}\n```\n\nOr abusing multi subs:\n\n```\nmulti sub fizzbuzz(Int $ where * %% 15) { 'FizzBuzz' }\nmulti sub fizzbuzz(Int $ where * %% 5) { 'Buzz' }\nmulti sub fizzbuzz(Int $ where * %% 3) { 'Fizz' }\nmulti sub fizzbuzz(Int $number ) { $number }\n(1 .. 100)».&fizzbuzz.say;\n```\n\nOr abusing list metaoperators:\n\n```\n[1..100].map({[~] ($_%%3, $_%%5) »||» \"\" Z&& <fizz buzz> or $_ })».say\n```\n\nConcisely (readable):\n\n```\nsay 'Fizz' x $_ %% 3 ~ 'Buzz' x $_ %% 5 || $_ for 1 .. 100;\n```\n\nShortest FizzBuzz to date:\n\n```\nsay \"Fizz\"x$_%%3~\"Buzz\"x$_%%5||$_ for 1..100\n```\n\nAnd here's an implementation that never checks for divisibility:\n\n```\n.say for\n (\n (flat ('' xx 2, 'Fizz') xx *)\n Z~\n (flat ('' xx 4, 'Buzz') xx *)\n )\n Z||\n 1 .. 100;\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a function to flatten the nesting in an arbitrary list of values.\n\nYour program should work on the equivalent of this list:\n\n```\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\n\n```\n\nWhere the correct result would be the list:\n\n```\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n```\n\nRelated task\n\n* Tree traversal" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2018.03\n\n```\nmy @l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []];\n\nsay .perl given gather @l.deepmap(*.take); # lazy recursive version\n\n# Another way to do it is with a recursive function (here actually a Block calling itself with the &?BLOCK dynamic variable):\n\nsay { |(@$_ > 1 ?? map(&?BLOCK, @$_) !! $_) }(@l)\n```" } ]
[ { "role": "user", "content": "The game\n\nGiven an   **N×N**   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones.\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered\ncolumns at once   (as one move).\n\nIn an inversion.   any  **1**  becomes  **0**,   and any  **0**  becomes  **1**  for that whole row or column.\n\nTask\n\nCreate a program to score for the Flipping bits game.\n\n1. The game should create an original random target configuration and a starting configuration.\n2. Ensure that the starting position is *never* the target position.\n3. The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position).\n4. The number of moves taken so far should be shown.\n\nShow an example of a short game here, on this page, for a   **3×3**   array of bits." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.11\n\nPass in a parameter to set the square size for the puzzle. (Defaults to 4.) Arbitrarily limited to between 1 and 26. Yes, you can choose to solve a 1 element square puzzle, but it won't be very challenging. Accepts upper or lower case letters for columns. Disregards any out-of-range indices. Enter a blank or 0 (zero) to exit.\n\n```\nsub MAIN ($square = 4) {\n say \"{$square}? Seriously?\" and exit if $square < 1 or $square > 26;\n my %bits = map { $_ => %( map { $_ => 0 }, ('A' .. *)[^ $square] ) },\n (1 .. *)[^ $square];\n scramble %bits;\n my $target = build %bits;\n scramble %bits until build(%bits) ne $target;\n display($target, %bits);\n my $turns = 0;\n while my $flip = prompt \"Turn {++$turns}: Flip which row / column? \" {\n flip $flip.match(/\\w/).uc, %bits;\n if display($target, %bits) {\n say \"Hurray! You solved it in $turns turns.\";\n last;\n }\n }\n}\n\nsub display($goal, %hash) {\n shell('clear');\n say \"Goal\\n$goal\\nYou\";\n my $this = build %hash;\n say $this;\n return ($goal eq $this);\n}\n\nsub flip ($a, %hash) {\n given $a {\n when any(keys %hash) {\n %hash{$a}{$_} = %hash{$a}{$_} +^ 1 for %hash{$a}.keys\n };\n when any(keys %hash{'1'}) {\n %hash{$_}{$a} = %hash{$_}{$a} +^ 1 for %hash.keys\n };\n }\n}\n\nsub build (%hash) {\n my $string = ' ';\n $string ~= sprintf \"%2s \", $_ for sort keys %hash{'1'};\n $string ~= \"\\n\";\n for %hash.keys.sort: +* -> $key {\n $string ~= sprintf \"%2s \", $key;\n $string ~= sprintf \"%2s \", %hash{$key}{$_} for sort keys %hash{$key};\n $string ~= \"\\n\";\n };\n $string\n}\n\nsub scramble(%hash) {\n my @keys = keys %hash;\n @keys.push: | keys %hash{'1'};\n flip $_, %hash for @keys.pick( @keys/2 );\n}\n\n```\n\nA sample 3 x 3 game might look like this:\n\n```\nGoal\n A B C \n 1 1 1 0 \n 2 0 0 1 \n 3 1 1 0 \n\nYou\n A B C \n 1 0 0 0 \n 2 1 1 1 \n 3 1 1 1 \n\nTurn 1: Flip which row / column? 2\n\nGoal\n A B C \n 1 1 1 0 \n 2 0 0 1 \n 3 1 1 0 \n\nYou\n A B C \n 1 0 0 0 \n 2 0 0 0 \n 3 1 1 1 \n\nTurn 2: Flip which row / column? 1\n\nGoal\n A B C \n 1 1 1 0 \n 2 0 0 1 \n 3 1 1 0 \n\nYou\n A B C \n 1 1 1 1 \n 2 0 0 0 \n 3 1 1 1 \n\nTurn 3: Flip which row / column? c\n\nGoal\n A B C \n 1 1 1 0 \n 2 0 0 1 \n 3 1 1 0 \n\nYou\n A B C \n 1 1 1 0 \n 2 0 0 1 \n 3 1 1 0 \n\nHurray! You solved it in 3 turns.\n```" } ]
[ { "role": "user", "content": "Task\n\nDocument common flow-control structures.\n\nOne common example of a flow-control structure is the   `goto`   construct.\n\nNote that   Conditional Structures   and   Loop Structures   have their own articles/categories.\n\nRelated tasks\n\n* Conditional Structures\n* Loop Structures" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Control exceptions\n\nControl flow is extensible in Raku; most abnormal control flow (including the standard loop and switch exits) is managed by throwing control exceptions that are caught by the code implementing the construct in question. Warnings are also handled via control exceptions, and turn into control flow if the dynamic context chooses not to resume after the warning. See [S04/Control exceptions] for more information.\n\n### Phasers\n\nPhasers are blocks that are transparent to the normal control flow but that are automatically called at an appropriate phase of compilation or execution. The current list of phasers may be found in [S04/Phasers].\n\n### goto\n\n```\nTOWN: goto TOWN;\n\n```\n\nLabels that have not been defined yet must be enclosed in quotes." } ]
[ { "role": "user", "content": "Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where\n\n* the first row is   **1**     (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\nThe first few lines of a Floyd triangle looks like this:\n\n```\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n```\n\nTask\n: 1. Write a program to generate and display here the first   n   lines of a Floyd triangle. \n (Use   n=5   and   n=14   rows).\n 2. Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row." }, { "role": "assistant", "content": "(formerly Perl 6)\nHere's two ways of doing it.\n\n```\nconstant @floyd1 = (1..*).rotor(1..*);\nconstant @floyd2 = gather for 1..* -> $s { take [++$ xx $s] }\n\nsub format-rows(@f) {\n my @table;\n my @formats = @f[@f-1].map: {\"%{.chars}s\"}\n for @f -> @row {\n @table.push: (@row Z @formats).map: -> ($i, $f) { $i.fmt($f) }\n }\n join \"\\n\", @table;\n}\n\nsay format-rows(@floyd1[^5]);\nsay '';\nsay format-rows(@floyd2[^14]);\n\n```\n\nOutput:\n\n```\n 1 \n 2 3 \n 4 5 6 \n 7 8 9 10 \n11 12 13 14 15\n \n 1 \n 2 3 \n 4 5 6 \n 7 8 9 10 \n11 12 13 14 15 \n16 17 18 19 20 21 \n22 23 24 25 26 27 28 \n29 30 31 32 33 34 35 36 \n37 38 39 40 41 42 43 44 45 \n46 47 48 49 50 51 52 53 54 55 \n56 57 58 59 60 61 62 63 64 65 66 \n67 68 69 70 71 72 73 74 75 76 77 78 \n79 80 81 82 83 84 85 86 87 88 89 90 91 \n92 93 94 95 96 97 98 99 100 101 102 103 104 105\n```" } ]
[ { "role": "user", "content": "The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights.\n\nTask\n\nFind the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel edges and negative cycles.\n\nPrint the pair, the distance and (optionally) the path.\n\nExample\n\n```\npair dist path\n1 -> 2 -1 1 -> 3 -> 4 -> 2\n1 -> 3 -2 1 -> 3\n1 -> 4 0 1 -> 3 -> 4\n2 -> 1 4 2 -> 1\n2 -> 3 2 2 -> 1 -> 3\n2 -> 4 4 2 -> 1 -> 3 -> 4\n3 -> 1 5 3 -> 4 -> 2 -> 1\n3 -> 2 1 3 -> 4 -> 2\n3 -> 4 2 3 -> 4\n4 -> 1 3 4 -> 2 -> 1\n4 -> 2 -1 4 -> 2\n4 -> 3 1 4 -> 2 -> 1 -> 3\n```\n\nSee also\n\n* Floyd-Warshall Algorithm - step by step guide (youtube)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.12\n\n**Translation of**: Ruby\n\n```\nsub Floyd-Warshall (Int $n, @edge) {\n my @dist = [0, |(Inf xx $n-1)], *.Array.rotate(-1) … !*[*-1];\n my @next = [0 xx $n] xx $n;\n\n for @edge -> ($u, $v, $w) {\n @dist[$u-1;$v-1] = $w;\n @next[$u-1;$v-1] = $v-1;\n }\n\n for [X] ^$n xx 3 -> ($k, $i, $j) {\n if @dist[$i;$j] > my $sum = @dist[$i;$k] + @dist[$k;$j] {\n @dist[$i;$j] = $sum;\n @next[$i;$j] = @next[$i;$k];\n }\n }\n\n say ' Pair Distance Path';\n for [X] ^$n xx 2 -> ($i, $j){\n next if $i == $j;\n my @path = $i;\n @path.push: @next[@path[*-1];$j] until @path[*-1] == $j;\n printf(\"%d → %d %4d %s\\n\", $i+1, $j+1, @dist[$i;$j],\n @path.map( *+1 ).join(' → '));\n }\n}\n\nFloyd-Warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]]);\n\n```\n\nOutput:\n\n```\n Pair Distance Path\n1 → 2 -1 1 → 3 → 4 → 2\n1 → 3 -2 1 → 3\n1 → 4 0 1 → 3 → 4\n2 → 1 4 2 → 1\n2 → 3 2 2 → 1 → 3\n2 → 4 4 2 → 1 → 3 → 4\n3 → 1 5 3 → 4 → 2 → 1\n3 → 2 1 3 → 4 → 2\n3 → 4 2 3 → 4\n4 → 1 3 4 → 2 → 1\n4 → 2 -1 4 → 2\n4 → 3 1 4 → 2 → 1 → 3\n\n```" } ]
[ { "role": "user", "content": "Lagrange's theorem tells us that every positive integer can be written as a sum of at most four squares.\n\nMany, (square numbers) can be written as a \"sum\" of a single square. **E.G.:** `4 == 22`.\n\nSome numbers require at least two squares to be summed. `5 == 22 + 12`\n\nOthers require at least three squares. `6 == 22 + 12 + 12`\n\nFinally, some, (the focus of this task) require the sum at least four squares. `7 == 22 + 12 + 12 + 12`. There is no way to reach 7 summing fewer than four squares.\n\nThese numbers show up in crystallography; x-ray diffraction patterns of cubic crystals depend on a length squared plus a width squared plus a height squared. Some configurations that require at least four squares are impossible to index and are colloquially known as **forbidden numbers**.\n\nNote that some numbers *can* be made from the sum of four squares: `16 == 22 + 22 + 22 + 22`, but since it can also be formed from fewer than four, `16 == 42`, it does not count as a forbidden number.\n\nTask\n\n* Find and show the first fifty forbidden numbers.\n\n* Find and show the **count** of forbidden numbers up to 500, 5,000.\n\nStretch\n\n* Find and show the **count** of forbidden numbers up to 50,000, 500,000.\n\nSee also\n\n* Wikipedia: Lagrange's theorem * OEIS A004215 - Numbers that are the sum of 4 but no fewer nonzero squares" }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\nuse List::Divvy;\n\nmy @f = (1..*).map: *×8-1;\n\nmy @forbidden = lazy flat @f[0], gather for ^∞ {\n state ($p0, $p1) = 1, 0;\n take (@f[$p0] < @forbidden[$p1]×4) ?? @f[$p0++] !! @forbidden[$p1++]×4;\n}\n\nput \"First fifty forbidden numbers: \\n\" ~\n @forbidden[^50].batch(10)».fmt(\"%3d\").join: \"\\n\";\n\nput \"\\nForbidden number count up to {.Int.&cardinal}: \" ~\n comma +@forbidden.&upto: $_ for 5e2, 5e3, 5e4, 5e5, 5e6;\n\n```\n\nOutput:\n\n```\nFirst fifty forbidden numbers: \n 7 15 23 28 31 39 47 55 60 63\n 71 79 87 92 95 103 111 112 119 124\n127 135 143 151 156 159 167 175 183 188\n191 199 207 215 220 223 231 239 240 247\n252 255 263 271 279 284 287 295 303 311\n\nForbidden number count up to five hundred: 82\n\nForbidden number count up to five thousand: 831\n\nForbidden number count up to fifty thousand: 8,330\n\nForbidden number count up to five hundred thousand: 83,331\n\nForbidden number count up to five million: 833,329\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Forest-fire model. 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 Drossel and Schwabl definition of the forest-fire model.\n\nIt is basically a 2D   cellular automaton   where each cell can be in three distinct states (*empty*, *tree* and *burning*) and evolves according to the following rules (as given by Wikipedia)\n\n1. A burning cell turns into an empty cell\n2. A tree will burn if at least one neighbor is burning\n3. A tree ignites with probability   *f*   even if no neighbor is burning\n4. An empty space fills with a tree with probability   *p*\n\nNeighborhood is the   Moore neighborhood;   boundary conditions are so that on the boundary the cells are always empty (\"fixed\" boundary condition).\n\nAt the beginning, populate the lattice with empty and tree cells according to a specific probability (e.g. a cell has the probability 0.5 to be a tree). Then, let the system evolve.\n\nTask's requirements do not include graphical display or the ability to change parameters (probabilities   *p*   and   *f* )   through a graphical or command line interface.\n\nRelated tasks\n\n* See   Conway's Game of Life\n* See   Wireworld." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### ANSI graphics\n\n**Works with**: rakudo version 2015-10-04\n\nThis version saves a lot of looking around by using four states instead of three; the Heating state does a lookahead to track trees that are being heated up by burning trees, so we only ever have to traverse the neighbors of burning trees, not all trees. Also, by only checking the list of burning trees, we can avoid copying the entire forest each iteration, since real forests are mutable.\n\n```\nconstant $RED = \"\\e[1;31m\";\nconstant $YELLOW = \"\\e[1;33m\";\nconstant $GREEN = \"\\e[1;32m\";\nconstant $CLEAR = \"\\e[0m\";\n# make sure we clear colors at the end\nEND print $CLEAR;\n \nenum Cell-State <Empty Tree Heating Burning>;\nmy @pix = ' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木';\n \nclass Forest {\n has Rat $.p = 0.01;\n has Rat $.f = 0.001;\n has Int $!height;\n has Int $!width;\n has @!coords;\n has @!spot;\n has @!neighbors;\n\n method BUILD (Int :$!height, Int :$!width) {\n\t@!coords = ^$!height X ^$!width;\n\t@!spot = [ (Bool.pick ?? Tree !! Empty) xx $!width ] xx $!height;\n self!init-neighbors;\n }\n \n method !init-neighbors {\n for @!coords -> ($i, $j) {\n @!neighbors[$i][$j] = eager gather for\n [-1,-1],[+0,-1],[+1,-1],\n [-1,+0], [+1,+0],\n [-1,+1],[+0,+1],[+1,+1]\n\t {\n\t\ttake-rw @!spot[$i + .[0]][$j + .[1]] // next;\n\t }\n\t}\n }\n \n method step {\n\tmy @heat;\n for @!coords -> ($i, $j) {\n given @!spot[$i][$j] {\n when Empty { $_ = Tree if rand < $!p }\n when Tree { $_ = Heating if rand < $!f }\n when Heating { $_ = Burning; push @heat, ($i, $j); }\n when Burning { $_ = Empty }\n }\n }\n\tfor @heat -> ($i,$j) {\n\t $_ = Heating for @!neighbors[$i][$j].grep(Tree);\n\t}\n }\n \n method show {\n for ^$!height -> $i {\n say @pix[@!spot[$i].list].join;\n }\n }\n}\n\nmy ($ROWS, $COLS) = qx/stty size/.words;\n\nsignal(SIGINT).act: { print \"\\e[H\\e[2J\"; exit }\n\nsub MAIN (Int $height = $ROWS - 2, Int $width = +$COLS div 2 - 1) {\n my Forest $forest .= new(:$height, :$width);\n print \"\\e[2J\"; # ANSI clear screen\n loop {\n\tprint \"\\e[H\"; # ANSI home\n\tsay $++;\n\t$forest.show;\n\t$forest.step;\n }\n}\n\n```\n\n### SDL2 Animation\n\nAn alternate version implemented in SDL2.\n\n```\nuse NativeCall;\nuse SDL2::Raw;\n\nmy ($width, $height) = 900, 900;\n\nSDL_Init(VIDEO);\nmy SDL_Window $window = SDL_CreateWindow(\n \"Forest Fire - Raku\",\n SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,\n $width, $height,\n RESIZABLE\n);\nmy SDL_Renderer $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| PRESENTVSYNC );\n\nSDL_ClearError();\n\nmy int ($w, $h) = 200, 200;\n\nmy $forest_texture = SDL_CreateTexture($renderer, %PIXELFORMAT<RGB332>, STREAMING, $w, $h);\n\nmy $pixdatabuf = CArray[int64].new(0, $w, $h, $w);\nmy $work-buffer = CArray[int64].new(0, $w, $h, $w);\n\nmy int $bare = 0; # Black\nmy int $tree = 8; # Green\nmy int $heating = -120; # Orange ( 132 but it's being passed into an int8 )\nmy int $burning = 128; # Red\nmy int $buf = $w * $h;\nmy $humidity = .7; # Chance that a tree next to a burning tree will resist catching fire\nmy $tree-spawn = .75; # Initial probability that a space will contain a tree. Probability\n # will be adjusted (way down) once rendering starts.\n\nsub render {\n\n # work-around to pass the pointer-pointer.\n my $pixdata = nativecast(Pointer[int64], $pixdatabuf);\n SDL_LockTexture($forest_texture, SDL_Rect, $pixdata, my int $pitch);\n\n $pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));\n\n loop (my int $row; $row < $h; $row = $row + 1) {\n my int $rs = $row * $w; # row start\n my int $re = $rs + $w; # row end\n loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {\n # Skip it if it is a tree\n next if $pixdata[$idx] == $tree;\n if $pixdata[$idx] == $bare {\n # Maybe spawn a tree on bare ground\n $work-buffer[$idx] = rand < $tree-spawn ?? $tree !! $bare;\n } elsif $pixdata[$idx] == $heating {\n # Check if there are trees around a hot spot and light them if humidity is low enough\n $work-buffer[$idx - $w - 1] = $heating if rand > $humidity && $pixdata[$idx - $w - 1] && $row > 0;\n $work-buffer[$idx - $w ] = $heating if rand > $humidity && $pixdata[$idx - $w ] && $row > 0;\n $work-buffer[$idx - $w + 1] = $heating if rand > $humidity && $pixdata[$idx - $w + 1] && $row > 0;\n $work-buffer[$idx - 1 ] = $heating if rand > $humidity && $pixdata[$idx - 1 ];\n $work-buffer[$idx + $w - 1] = $heating if rand > $humidity && $pixdata[$idx + $w - 1];\n $work-buffer[$idx + $w ] = $heating if rand > $humidity && $pixdata[$idx + $w ];\n $work-buffer[$idx + $w + 1] = $heating if rand > $humidity && $pixdata[$idx + $w + 1];\n $work-buffer[$idx + 1 ] = $heating if rand > $humidity && $pixdata[$idx + 1 ];\n\n # Hotspot becomes a flame\n $work-buffer[$idx] = $burning\n } else {\n # Extinguish a flame after fuel is gone\n $work-buffer[$idx] = $bare;\n }\n }\n }\n # copy working buffer to main texture buffer\n loop (my int $i; $i < $buf; $i = $i + 1) { $pixdata[$i] = $work-buffer[$i] }\n\n # start a fire maybe\n $pixdata[$buf.rand] = $heating if rand < .1;\n\n SDL_UnlockTexture($forest_texture);\n\n SDL_RenderCopy($renderer, $forest_texture, SDL_Rect, SDL_Rect.new(:x(0), :y(0), :w($width), :h($height)));\n SDL_RenderPresent($renderer);\n once $tree-spawn = .005;\n}\n\nmy $event = SDL_Event.new;\n\nenum KEY_CODES ( K_Q => 20 );\n\nmain: loop {\n\n while SDL_PollEvent($event) {\n my $casted_event = SDL_CastEvent($event);\n\n given $casted_event {\n when *.type == QUIT {\n last main;\n }\n when *.type == KEYDOWN {\n if KEY_CODES(.scancode) -> $comm {\n given $comm {\n when 'K_Q' { last main }\n }\n }\n }\n when *.type == WINDOWEVENT {\n if .event == RESIZED {\n $width = .data1;\n $height = .data2;\n }\n }\n }\n }\n render();\n print fps;\n}\nsay '';\n\nsub fps {\n state $fps-frames = 0;\n state $fps-now = now;\n state $fps = '';\n $fps-frames++;\n if now - $fps-now >= 1 {\n $fps = [~] \"\\b\" x 40, ' ' x 20, \"\\b\" x 20 ,\n sprintf \"FPS: %5.2f \", ($fps-frames / (now - $fps-now)).round(.01);\n $fps-frames = 0;\n $fps-now = now;\n }\n $fps\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nSpawn a new process which can run simultaneously with, and independently of, the original parent process." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.06\n\n```\nuse NativeCall;\nsub fork() returns int32 is native { ... }\n\nif fork() -> $pid {\n print \"I am the proud parent of $pid.\\n\";\n}\nelse {\n print \"I am a child. Have you seen my mommy?\\n\";\n}\n\n```\n\nOutput:\n\n```\nI am the proud parent of 17691.\nI am a child. Have you seen my mommy?\n```" } ]
[ { "role": "user", "content": "A *power series* is an infinite sum of the form\n\na\n\n0\n+\n\na\n\n1\n⋅\nx\n+\n\na\n\n2\n⋅\n\nx\n\n2\n+\n\na\n\n3\n⋅\n\nx\n\n3\n+\n⋯\n{\\displaystyle {\\displaystyle a\\_{0}+a\\_{1}\\cdot x+a\\_{2}\\cdot x^{2}+a\\_{3}\\cdot x^{3}+\\cdots }}\n\nThe *ai* are called the *coefficients* of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of *x* are calculated according to the usual rules.\n\nIf one is not interested in evaluating such a series for particular values of *x*, or in other words, if convergence doesn't play a role, then such a collection of coefficients is called *formal power series*. It can be treated like a new kind of number.\n\n**Task**: Implement formal power series as a numeric type. Operations should at least include *addition*, *multiplication*, *division* and additionally non-numeric operations like *differentiation* and *integration* (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.\n\nAs an example, define the power series of sine and cosine in terms of each other using integration, as in\n\nsin\n⁡\nx\n=\n\n∫\n\n0\n\nx\ncos\n⁡\nt\n\nd\nt\n{\\displaystyle {\\displaystyle \\sin x=\\int \\_{0}^{x}\\cos t\\,dt}}\n\ncos\n⁡\nx\n=\n1\n−\n\n∫\n\n0\n\nx\nsin\n⁡\nt\n\nd\nt\n{\\displaystyle {\\displaystyle \\cos x=1-\\int \\_{0}^{x}\\sin t\\,dt}}\n\n**Goals**: Demonstrate how the language handles new numeric types and delayed (or *lazy*) evaluation." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nclass DerFPS { ... }\nclass IntFPS { ... }\n\nrole FPS {\n method coeffs { ... }\n method differentiate { DerFPS.new(:x(self)) }\n method integrate { IntFPS.new(:x(self)) }\n\n method pretty($n) {\n sub super($i) { $i.trans('0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹') }\n my $str = $.coeffs[0];\n for flat 1..$n Z $.coeffs[1..$n] -> $p, $c {\n when $c > 0 { $str ~= \" + { $c .nude.join: '/'}∙x{super($p)}\" }\n when $c < 0 { $str ~= \" - {-$c .nude.join: '/'}∙x{super($p)}\" }\n }\n $str;\n }\n}\n\nclass ExplicitFPS does FPS { has @.coeffs }\n\nclass SumFPS does FPS {\n has FPS ($.x, $.y);\n method coeffs { $.x.coeffs Z+ $.y.coeffs }\n}\n\nclass DifFPS does FPS {\n has FPS ($.x, $.y);\n method coeffs { $.x.coeffs Z- $.y.coeffs }\n}\n\nclass ProFPS does FPS {\n has FPS ($.x, $.y);\n method coeffs { (0..*).map: { [+] ($.x.coeffs[0..$_] Z* $.y.coeffs[$_...0]) } }\n}\n\nclass InvFPS does FPS {\n has FPS $.x;\n method coeffs {\n # see http://en.wikipedia.org/wiki/Formal_power_series#Inverting_series\n flat gather {\n my @a = $.x.coeffs;\n @a[0] != 0 or fail \"Cannot invert power series with zero constant term.\";\n take my @b = (1 / @a[0]);\n take @b[$_] = -@b[0] * [+] (@a[1..$_] Z* @b[$_-1...0]) for 1..*;\n }\n }\n}\n\nclass DerFPS does FPS {\n has FPS $.x;\n method coeffs { (1..*).map: { $_ * $.x.coeffs[$_] } }\n}\n\nclass IntFPS does FPS {\n has FPS $.x;\n method coeffs { 0, |(0..*).map: { $.x.coeffs[$_] / ($_+1) } }\n}\n\nclass DeferredFPS does FPS {\n has FPS $.realized is rw;\n method coeffs { $.realized.coeffs }\n}\n\n# some arithmetic operations for formal power series\nmulti infix:<+>(FPS $x, FPS $y) { SumFPS.new(:$x, :$y) }\nmulti infix:<->(FPS $x, FPS $y) { DifFPS.new(:$x, :$y) }\nmulti infix:<*>(FPS $x, FPS $y) { ProFPS.new(:$x, :$y) }\nmulti infix:</>(FPS $x, FPS $y) { $x * InvFPS.new(:x($y)) }\n\n# an example of a mixed-type operator:\nmulti infix:<->(Numeric $x, FPS $y) { ExplicitFPS.new(:coeffs(lazy flat $x, 0 xx *)) - $y }\n\n# define sine and cosine in terms of each other\nmy $sin = DeferredFPS.new;\nmy $cos = 1 - $sin.integrate;\n$sin.realized = $cos.integrate;\n\n# define tangent in terms of sine and cosine\nmy $tan = $sin / $cos;\n\nsay 'sin(x) ≈ ' ~ $sin.pretty(10);\nsay 'cos(x) ≈ ' ~ $cos.pretty(10);\nsay 'tan(x) ≈ ' ~ $tan.pretty(10);\n\n```\n\nOutput:\n\n```\nsin(x) ≈ 0 + 1/1∙x¹ - 1/6∙x³ + 1/120∙x⁵ - 1/5040∙x⁷ + 1/362880∙x⁹\ncos(x) ≈ 1 - 1/2∙x² + 1/24∙x⁴ - 1/720∙x⁶ + 1/40320∙x⁸ - 1/3628800∙x¹⁰\ntan(x) ≈ 0 + 1/1∙x¹ + 1/3∙x³ + 2/15∙x⁵ + 17/315∙x⁷ + 62/2835∙x⁹\n```" } ]
[ { "role": "user", "content": "Task\n\nExpress a number in decimal as a fixed-length string with leading zeros.\n\nFor example, the number   **7.125**   could be expressed as   **00007.125**." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay 7.125.fmt('%09.3f');\n\n```" } ]
[ { "role": "user", "content": "Definition\n\nA Fortunate number is the smallest integer **m > 1** such that for a given positive integer **n**, **primorial(n) + m** is a prime number, where **primorial(n)** is the product of the first **n** prime numbers.\n\nFor example the first fortunate number is 3 because primorial(1) is 2 and 2 + 3 = 5 which is prime whereas 2 + 2 = 4 is composite.\n\nTask\n\nAfter sorting and removal of any duplicates, compute and show on this page the first **8** Fortunate numbers or, if your language supports *big integers*, the first **50** Fortunate numbers.\n\nRelated task\n\n* Primorial numbers\n\nSee also\n\n* oeis:A005235 Fortunate numbers\n* oeis:A046066 Fortunate numbers, sorted with duplicates removed" }, { "role": "assistant", "content": "Limit of 75 primorials to get first 50 unique fortunates is arbitrary, found through trial and error.\n\n```\nmy @primorials = [\\*] grep *.is-prime, ^∞;\n\nsay display :title(\"First 50 distinct fortunate numbers:\\n\"),\n (squish sort @primorials[^75].hyper.map: -> $primorial {\n (2..∞).first: (* + $primorial).is-prime\n })[^50];\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```\nFirst 50 distinct fortunate numbers:\n 3 5 7 13 17 19 23 37 47 59\n 61 67 71 79 89 101 103 107 109 127\n 151 157 163 167 191 197 199 223 229 233\n 239 271 277 283 293 307 311 313 331 353\n 373 379 383 397 401 409 419 421 439 443\n```" } ]
[ { "role": "user", "content": "Task\n\nProvide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers.\n\nThe first-order forward difference of a list of numbers   **A**   is a new list   **B**,   where   **B**n = **A**n+1 - **A**n.\n\nList   **B**   should have one fewer element as a result.\n\nThe second-order forward difference of   **A**   will be:\n\n```\ntdefmodule Diff do\n\tdef forward(arr,i\\\\1) do\n\t\tforward(arr,[],i)\n\tend\n\n\tdef forward([_|[]],diffs,i) do\n\t\tif i == 1 do\n\t\t\tIO.inspect diffs\n\t\telse \n\t\t\tforward(diffs,[],i-1)\n\t\tend\n\tend\n\n\tdef forward([val1|[val2|vals]],diffs,i) do\n\t\tforward([val2|vals],diffs++[val2-val1],i) \n\tend\nend \n\n```\n\nThe same as the first-order forward difference of   **B**.\n\nThat new list will have two fewer elements than   **A**   and one less than   **B**.\n\nThe goal of this task is to repeat this process up to the desired order.\n\nFor a more formal description, see the related   Mathworld article.\n\nAlgorithmic options\n\n* Iterate through all previous forward differences and re-calculate a new array each time.\n* Use this formula (from Wikipedia):\n\n: : : Δ\n\n n\n [\n f\n ]\n (\n x\n )\n =\n\n ∑\n\n k\n =\n 0\n\n n\n\n (\n\n n\n k\n\n )\n (\n −\n 1\n\n )\n\n n\n −\n k\n f\n (\n x\n +\n k\n )\n {\\displaystyle {\\displaystyle \\Delta ^{n}[f](x)=\\sum \\_{k=0}^{n}{n \\choose k}(-1)^{n-k}f(x+k)}}\n\n: : : (Pascal's Triangle   may be useful for this option.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2010-07\n\nHere we use signature matching to bind both an entire array and a version missing the head.\nThe Z- operator is a zip metaoperator with a minus to subtract the two lists pairwise.\nIt's almost a shame to define difn, since the series and subscript are hardly longer than the call itself would be, and arguably more self-documenting than the name of the function would be.\n\n```\nsub dif(@array [$, *@tail]) { @tail Z- @array }\nsub difn($array, $n) { ($array, &dif ... *)[$n] }\n\n```" } ]
[ { "role": "user", "content": "Task\n\n\"*Simulate*\" a four-bit adder.\n\nThis design can be realized using four 1-bit full adders.\nEach of these 1-bit full adders can be built with two half adders and an   *or*   gate. ;\n\nFinally a half adder can be made using an   *xor*   gate and an   *and*   gate.\n\nThe   *xor*   gate can be made using two   *not*s,   two   *and*s   and one   *or*.\n\n**Not**,   **or**   and   **and**,   the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language.\n\nIf there is not a *bit type* in your language, to be sure that the   *not*   does not \"invert\" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   *nand*   (*and*   then   *not*)   with the constant   **1**   on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   *connecting* the other \"constructive blocks\",   in turn made of \"simpler\" and \"smaller\" ones.\n\nSchematics of the \"constructive blocks\"\n\n| (Xor gate with ANDs, ORs and NOTs) | (A half adder) | (A full adder) | (A 4-bit adder) |\n| --- | --- | --- | --- |\n| | | | |\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\".\n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a *block* in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub xor ($a, $b) { (($a and not $b) or (not $a and $b)) ?? 1 !! 0 }\n\nsub half-adder ($a, $b) {\n return xor($a, $b), ($a and $b);\n}\n\nsub full-adder ($a, $b, $c0) {\n my ($ha0_s, $ha0_c) = half-adder($c0, $a);\n my ($ha1_s, $ha1_c) = half-adder($ha0_s, $b);\n return $ha1_s, ($ha0_c or $ha1_c);\n}\n\nsub four-bit-adder ($a0, $a1, $a2, $a3, $b0, $b1, $b2, $b3) {\n my ($fa0_s, $fa0_c) = full-adder($a0, $b0, 0);\n my ($fa1_s, $fa1_c) = full-adder($a1, $b1, $fa0_c);\n my ($fa2_s, $fa2_c) = full-adder($a2, $b2, $fa1_c);\n my ($fa3_s, $fa3_c) = full-adder($a3, $b3, $fa2_c);\n\n return $fa0_s, $fa1_s, $fa2_s, $fa3_s, $fa3_c;\n}\n\n{\n use Test;\n\n is four-bit-adder(1, 0, 0, 0, 1, 0, 0, 0), (0, 1, 0, 0, 0), '1 + 1 == 2';\n is four-bit-adder(1, 0, 1, 0, 1, 0, 1, 0), (0, 1, 0, 1, 0), '5 + 5 == 10';\n is four-bit-adder(1, 0, 0, 1, 1, 1, 1, 0)[4], 1, '7 + 9 == overflow';\n}\n\n```\n\nOutput:\n\n```\nok 1 - 1 + 1 == 2\nok 2 - 5 + 5 == 10\nok 3 - 7 + 9 == overflow\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in *that* word.\n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer **3**. Convert **3** to **Three**, add **is** , then the cardinal character count of three, or **five**, with a comma to separate if from the next phrase. Continue the sequence **five is four,** (five has four letters), and finally, **four is magic.**\n\n```\n Three is five, five is four, four is magic.\n\n```\n\nFor reference, here are outputs for 0 through 9.\n\n```\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n```\n\nSome task guidelines\n: * You may assume the input will only contain integer numbers.\n * Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. (**23** is **twenty three** or **twenty-three** not **twentythree**.)\n * Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n * Cardinal numbers should not include commas. (**20140** is **twenty thousand one hundred forty** not **twenty thousand, one hundred forty**.)\n * When converted to a string, **100** should be **one hundred**, not **a hundred** or **hundred**, **1000** should be **one thousand**, not **a thousand** or **thousand**.\n * When converted to a string, there should be no **and** in the cardinal string. **130** should be **one hundred thirty** not **one hundred and thirty**.\n * When counting characters, count *all* of the characters in the cardinal number including spaces and hyphens. **One hundred fifty-one** should be **21** not **18**.\n * The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n * The output can either be the return value from the function, or be displayed from within the function.\n * You are encouraged, though not mandated to use proper sentence capitalization.\n * You may optionally support negative numbers. **-7** is **negative seven**.\n * Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.\n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. **This is not code golf.** Write legible, idiomatic and well formatted code.\n\nRelated tasks\n: * Four is the number of\\_letters in the ...\n * Look-and-say sequence\n * Number names\n * Self-describing numbers\n * Summarize and say sequence\n * Spelling of ordinal numbers\n * De Bruijn sequences" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nLingua::EN::Numbers module available from the Raku ecosystem.\n\n```\nuse Lingua::EN::Numbers; # Version 2.4.0 or higher\n\nsub card ($n) { cardinal($n).subst(/','/, '', :g) }\n\nsub magic (Int $int is copy) {\n my $string;\n loop {\n $string ~= \"{ card($int) } is \";\n if $int = ($int == 4) ?? 0 !! card($int).chars {\n $string ~= \"{ card($int) }, \"\n } else {\n $string ~= \"magic.\\n\";\n last\n }\n }\n $string.tc\n}\n\n.&magic.say for 0, 4, 6, 11, 13, 75, 337, -164, 9876543209, 2**256;\n\n```\n\nOutput:\n\n```\nZero is four, four is magic.\n\nFour is magic.\n\nSix is three, three is five, five is four, four is magic.\n\nEleven is six, six is three, three is five, five is four, four is magic.\n\nThirteen is eight, eight is five, five is four, four is magic.\n\nSeventy-five is twelve, twelve is six, six is three, three is five, five is four, four is magic.\n\nThree hundred thirty-seven is twenty-six, twenty-six is ten, ten is three, three is five, five is four, four is magic.\n\nNegative one hundred sixty-four is thirty-one, thirty-one is ten, ten is three, three is five, five is four, four is magic.\n\nNine billion eight hundred seventy-six million five hundred forty-three thousand two hundred nine is ninety-seven, ninety-seven is twelve, twelve is six, six is three, three is five, five is four, four is magic.\n\nOne hundred fifteen quattuorvigintillion seven hundred ninety-two trevigintillion eighty-nine duovigintillion two hundred thirty-seven unvigintillion three hundred sixteen vigintillion one hundred ninety-five novemdecillion four hundred twenty-three octodecillion five hundred seventy septendecillion nine hundred eighty-five sexdecillion eight quindecillion six hundred eighty-seven quattuordecillion nine hundred seven tredecillion eight hundred fifty-three duodecillion two hundred sixty-nine undecillion nine hundred eighty-four decillion six hundred sixty-five nonillion six hundred forty octillion five hundred sixty-four septillion thirty-nine sextillion four hundred fifty-seven quintillion five hundred eighty-four quadrillion seven trillion nine hundred thirteen billion one hundred twenty-nine million six hundred thirty-nine thousand nine hundred thirty-six is eight hundred sixty-nine, eight hundred sixty-nine is twenty-four, twenty-four is eleven, eleven is six, six is three, three is five, five is four, four is magic.\n```" } ]
[ { "role": "user", "content": "The     **Four is ...**     sequence is based on the counting of the number of\nletters in the words of the (never─ending) sentence:\n\n```\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, ··· \n\n```\n\nDefinitions and directives\n: * English is to be used in spelling numbers.\n * **Letters**   are defined as the upper─ and lowercase letters in the Latin alphabet   (**A──►Z**   and   **a──►z**).\n * Commas are not counted,   nor are hyphens (dashes or minus signs).\n * **twenty─three**   has eleven letters.\n * **twenty─three**   is considered one word   (which is hyphenated).\n * no   ***and***   words are to be used when spelling a (English) word for a number.\n * The short scale numbering system (i.e. 2,000,000,000 is two billion) will be used here. wp:Long and short scales\n\n```\n 2,000,000,000   is two billion,   not   two milliard.\n\n```\n\nTask\n: * Write a driver (invoking routine) and a function (subroutine/routine···) that returns the sequence (for any positive integer) of the number of letters in the first   **N**   words in the never─ending sentence.   For instance, the portion of the never─ending sentence shown above (2nd sentence of this task's preamble),   the sequence would be:\n\n```\n 4 2 3 6 2 7\n\n```\n\n: * Only construct as much as is needed for the never─ending sentence.\n * Write a driver (invoking routine) to show the number of letters in the   Nth   word,   *as well as*   showing the   Nth   word itself.\n * After each test case, show the total number of characters   (including blanks, commas, and punctuation)   of the sentence that was constructed.\n * Show all output here.\n\nTest cases\n\n```\n Display the first 201 numbers in the sequence   (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n```\n\nRelated tasks\n: * Four is magic\n * Look-and-say sequence\n * Number names\n * Self-describing numbers\n * Self-referential sequence\n * Spelling of ordinal numbers\n\nAlso see\n: * See the OEIS sequence A72425 \"Four is the number of letters...\".\n * See the OEIS sequence A72424 \"Five's the number of letters...\"" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses the Lingua::EN::Numbers module to generate both cardinal and ordinal numbers. This module places commas in number words between 3-orders-of-magnitude clusters. E.G. `12345678.&ordinal` becomes: twelve million, three hundred forty-five thousand, six hundred seventy-eighth. Uses a custom 'no-commas' routine to filter them out for accurate character counts. Generates the 'sentence' lazily so only the words needed are ever calculated and reified.\n\n```\nuse Lingua::EN::Numbers;\nno-commas(True);\n\nmy $index = 1;\nmy @sentence = flat 'Four is the number of letters in the first word of this sentence, '.words,\n { @sentence[$index++].&alpha.&cardinal, 'in', 'the', |($index.&ordinal ~ ',').words } ... * ;\n\nsub alpha ( $str ) { $str.subst(/\\W/, '', :g).chars }\nsub count ( $index ) { @sentence[^$index].join(' ').chars ~ \" characters in the sentence, up to and including this word.\\n\" }\n\nsay 'First 201 word lengths in the sequence:';\nput ' ', map { @sentence[$_].&alpha.fmt(\"%2d\") ~ (((1+$_) %% 25) ?? \"\\n\" !! '') }, ^201;\nsay 201.&count;\n\nfor 1e3, 1e4, 1e5, 1e6, 1e7 {\n say \"{.&ordinal.tc} word, '{@sentence[$_ - 1]}', has {@sentence[$_ - 1].&alpha} characters. \", .&count\n}\n\n```\n\nOutput:\n\n```\nFirst 201 word lengths in the sequence:\n 4 2 3 6 2 7 2 3 5 4 2 4 8 3 2 3 6 5 2 3 5 3 2 3 6\n 3 2 3 5 5 2 3 5 3 2 3 7 5 2 3 6 4 2 3 5 4 2 3 5 3\n 2 3 8 4 2 3 7 5 2 3 10 5 2 3 10 3 2 3 9 5 2 3 9 3 2\n 3 11 4 2 3 10 3 2 3 10 5 2 3 9 4 2 3 11 5 2 3 12 3 2 3\n 11 5 2 3 12 3 2 3 11 5 2 3 11 3 2 3 13 5 2 3 12 4 2 3 11\n 4 2 3 9 3 2 3 11 5 2 3 12 4 2 3 11 5 2 3 12 3 2 3 11 5\n 2 3 11 5 2 3 13 4 2 3 12 3 2 3 11 5 2 3 8 3 2 3 10 4 2\n 3 11 3 2 3 10 5 2 3 11 4 2 3 10 4 2 3 10 3 2 3 12 5 2 3\n 11\n1203 characters in the sentence, up to and including this word.\n\nOne thousandth word, 'in', has 2 characters. 6249 characters in the sentence, up to and including this word.\n\nTen thousandth word, 'in', has 2 characters. 64097 characters in the sentence, up to and including this word.\n\nOne hundred thousandth word, 'one', has 3 characters. 659455 characters in the sentence, up to and including this word.\n\nOne millionth word, 'the', has 3 characters. 7113560 characters in the sentence, up to and including this word.\n\nTen millionth word, 'thousand', has 8 characters. 70995729 characters in the sentence, up to and including this word.\n```" } ]
[ { "role": "user", "content": "Task\n\nFill with 1's the four sides of square. The rest of the square should be filled with 0's.\n \nIf you can please use GUI\n \nFour sides of square - image\n\n### See also\n\n* Matrix with two diagonals\n* Mosaic matrix" }, { "role": "assistant", "content": "This isn't a matrix, especially if it is supposed to be graphical; it's a very small (or extremely low resolution) bitmap.\n\n```\nsub hollow ($n) { [1 xx $n], |(0 ^..^ $n).map( { [flat 1, 0 xx $n - 2, 1] } ), [1 xx $n] }\n\n.put for hollow 7;\nput '';\n.put for hollow 10;\n\n```\n\nOutput:\n\n```\n1 1 1 1 1 1 1\n1 0 0 0 0 0 1\n1 0 0 0 0 0 1\n1 0 0 0 0 0 1\n1 0 0 0 0 0 1\n1 0 0 0 0 0 1\n1 0 0 0 0 0 1\n1 1 1 1 1 1 1\n\n1 1 1 1 1 1 1 1 1 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 0 0 0 0 0 0 0 0 1\n1 1 1 1 1 1 1 1 1 1\n```" } ]
[ { "role": "user", "content": "Generate and draw a fractal tree.\n\n1. Draw the trunk\n2. At the end of the trunk, split by some angle and draw two branches\n3. Repeat at the end of each branch until a sufficient level of branching is reached\n\nRelated tasks\n\n* Pythagoras Tree" }, { "role": "assistant", "content": "(formerly Perl 6)\nImage is created in SVG format.\n\n```\nmy ($width, $height) = (1000,1000); # image dimension\nmy $scale = 6/10; # branch scale relative to trunk\nmy $length = 400; # trunk size\n\nsay \"<?xml version='1.0' encoding='utf-8' standalone='no'?>\n<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' \n'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n<svg width='100%' height='100%' version='1.1'\nxmlns='http://www.w3.org/2000/svg'>\";\n\ntree($width/2, $height, $length, 3*pi/2);\n\nsay \"</svg>\";\n\nmulti tree($, $, $length where { $length < 1}, $) {}\nmulti tree($x, $y, $length, $angle)\n{\n\tmy ($x2, $y2) = ( $x + $length * $angle.cos, $y + $length * $angle.sin);\n\tsay \"<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'/>\";\n\ttree($x2, $y2, $length*$scale, $angle + pi/5);\n\ttree($x2, $y2, $length*$scale, $angle - pi/5);\n}\n\n```" } ]
[ { "role": "user", "content": "```\n There is a fine line between numerator and denominator.       ─── anonymous\n\n```\n\nA method to   \"reduce\"   some reducible fractions is to   *cross out*   a digit from the\nnumerator and the denominator.   An example is:\n\n```\n 16 16\n ──── and then (simply) cross─out the sixes: ────\n 64 64\n\n```\n\nresulting in:\n\n```\n 1\n ─── \n 4\n\n```\n\nNaturally,   this \"method\" of reduction must reduce to the proper value   (shown as a fraction).\n\nThis \"method\" is also known as   *anomalous cancellation*   and also   *accidental cancellation*.\n\n(Of course,   this \"method\" shouldn't be taught to impressionable or gullible minds.)       😇\n\nTask\n\nFind and show some fractions that can be reduced by the above \"method\".\n\n: * show 2-digit fractions found   (like the example shown above)\n * show 3-digit fractions\n * show 4-digit fractions\n * show 5-digit fractions   (and higher)       *(optional)*\n * show each (above) n-digit fractions separately from other different n-sized fractions, don't mix different \"sizes\" together\n * for each \"size\" fraction,   only show a dozen examples   (the 1st twelve found)\n * (it's recognized that not every programming solution will have the same generation algorithm)\n * for each \"size\" fraction:\n\n : : * show a count of how many reducible fractions were found.   The example (above) is size **2**\n * show a count of which digits were crossed out   (one line for each different digit)\n\n * for each \"size\" fraction,   show a count of how many were found.   The example (above) is size **2**\n * show each n-digit example   (to be shown on one line):\n\n : : * show each n-digit fraction\n * show each reduced n-digit fraction\n * show what digit was crossed out for the numerator and the denominator\n\nTask requirements/restrictions\n: * only proper fractions and their reductions   (the result)   are to be used   (no vulgar fractions)\n * only positive fractions are to be used   (no negative signs anywhere)\n * only base ten integers are to be used for the numerator and denominator\n * no zeros   (decimal digit)   can be used within the numerator or the denominator\n * the numerator and denominator should be composed of the same number of digits\n * no digit can be repeated in the numerator\n * no digit can be repeated in the denominator\n * (naturally)   there should be a shared decimal digit in the numerator   *and*   the denominator\n * fractions can be shown as   16/64   (for example)\n\nShow all output here, on this page.\n\nSomewhat related task\n: * Farey sequence       (It concerns fractions.)\n\nReferences\n: * Wikipedia entry:   proper and improper fractions.\n * Wikipedia entry:   anomalous cancellation and/or accidental cancellation." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nAnomalous Cancellation\n\n```\nmy %reduced;\nmy $digits = 2..4;\n\nfor $digits.map: * - 1 -> $exp {\n my $start = sum (0..$exp).map( { 10 ** $_ * ($exp - $_ + 1) });\n my $end = 10**($exp+1) - sum (^$exp).map( { 10 ** $_ * ($exp - $_) } ) - 1;\n\n ($start ..^ $end).race(:8degree, :3batch).map: -> $den {\n next if $den.contains: '0';\n next if $den.comb.unique <= $exp;\n\n for $start ..^ $den -> $num {\n next if $num.contains: '0';\n next if $num.comb.unique <= $exp;\n\n my $set = ($den.comb.head(* - 1).Set ∩ $num.comb.skip(1).Set);\n next if $set.elems < 1;\n\n for $set.keys {\n my $ne = $num.trans: $_ => '', :delete;\n my $de = $den.trans: $_ => '', :delete;\n if $ne / $de == $num / $den {\n print \"\\b\" x 40, \"$num/$den:$_ => $ne/$de\";\n %reduced{\"$num/$den:$_\"} = \"$ne/$de\";\n }\n }\n }\n }\n\n\n print \"\\b\" x 40, ' ' x 40, \"\\b\" x 40;\n\n my $digit = $exp +1;\n my %d = %reduced.pairs.grep: { .key.chars == ($digit * 2 + 3) };\n say \"\\n({+%d}) $digit digit reduceable fractions:\";\n for 1..9 {\n my $cnt = +%d.pairs.grep( *.key.contains: \":$_\" );\n next unless $cnt;\n say \" $cnt with removed $_\";\n }\n say \"\\n 12 Random (or all, if less) $digit digit reduceable fractions:\";\n say \" {.key.substr(0, $digit * 2 + 1)} => {.value} removed {.key.substr(* - 1)}\"\n for %d.pairs.pick(12).sort;\n}\n\n```\n\nSample output:\n\n```\n(4) 2 digit reduceable fractions:\n 2 with removed 6\n 2 with removed 9\n\n 12 Random (or all, if less) 2 digit reduceable fractions:\n 16/64 => 1/4 removed 6\n 19/95 => 1/5 removed 9\n 26/65 => 2/5 removed 6\n 49/98 => 4/8 removed 9\n\n(122) 3 digit reduceable fractions:\n 9 with removed 3\n 1 with removed 4\n 6 with removed 5\n 15 with removed 6\n 16 with removed 7\n 15 with removed 8\n 60 with removed 9\n\n 12 Random (or all, if less) 3 digit reduceable fractions:\n 149/298 => 14/28 removed 9\n 154/352 => 14/32 removed 5\n 165/264 => 15/24 removed 6\n 176/275 => 16/25 removed 7\n 187/286 => 17/26 removed 8\n 194/291 => 14/21 removed 9\n 286/385 => 26/35 removed 8\n 286/682 => 26/62 removed 8\n 374/572 => 34/52 removed 7\n 473/572 => 43/52 removed 7\n 492/984 => 42/84 removed 9\n 594/693 => 54/63 removed 9\n\n(660) 4 digit reduceable fractions:\n 14 with removed 1\n 25 with removed 2\n 92 with removed 3\n 14 with removed 4\n 29 with removed 5\n 63 with removed 6\n 16 with removed 7\n 17 with removed 8\n 390 with removed 9\n\n 12 Random (or all, if less) 4 digit reduceable fractions:\n 1348/4381 => 148/481 removed 3\n 1598/3196 => 158/316 removed 9\n 1783/7132 => 178/712 removed 3\n 1978/5934 => 178/534 removed 9\n 2971/5942 => 271/542 removed 9\n 2974/5948 => 274/548 removed 9\n 3584/4592 => 384/492 removed 5\n 3791/5798 => 391/598 removed 7\n 3968/7936 => 368/736 removed 9\n 4329/9324 => 429/924 removed 3\n 4936/9872 => 436/872 removed 9\n 6327/8325 => 627/825 removed 3\n```" } ]
[ { "role": "user", "content": "**FRACTRAN** is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.\n\nA FRACTRAN program is an ordered list of positive fractions \n\nP\n=\n(\n\nf\n\n1\n,\n\nf\n\n2\n,\n…\n,\n\nf\n\nm\n)\n{\\displaystyle {\\displaystyle P=(f\\_{1},f\\_{2},\\ldots ,f\\_{m})}}\n, together with an initial positive integer input \n\nn\n{\\displaystyle {\\displaystyle n}}\n.\n\nThe program is run by updating the integer \n\nn\n{\\displaystyle {\\displaystyle n}}\n as follows:\n\n* for the first fraction, \n\n f\n\n i\n {\\displaystyle {\\displaystyle f\\_{i}}}\n , in the list for which \n\n n\n\n f\n\n i\n {\\displaystyle {\\displaystyle nf\\_{i}}}\n is an integer, replace \n\n n\n {\\displaystyle {\\displaystyle n}}\n with \n\n n\n\n f\n\n i\n {\\displaystyle {\\displaystyle nf\\_{i}}}\n  ;\n* repeat this rule until no fraction in the list produces an integer when multiplied by \n\n n\n {\\displaystyle {\\displaystyle n}}\n , then halt.\n\nConway gave a program for primes in FRACTRAN:\n\n: 17\n\n /\n 91\n {\\displaystyle {\\displaystyle 17/91}}\n , \n\n 78\n\n /\n 85\n {\\displaystyle {\\displaystyle 78/85}}\n , \n\n 19\n\n /\n 51\n {\\displaystyle {\\displaystyle 19/51}}\n , \n\n 23\n\n /\n 38\n {\\displaystyle {\\displaystyle 23/38}}\n , \n\n 29\n\n /\n 33\n {\\displaystyle {\\displaystyle 29/33}}\n , \n\n 77\n\n /\n 29\n {\\displaystyle {\\displaystyle 77/29}}\n , \n\n 95\n\n /\n 23\n {\\displaystyle {\\displaystyle 95/23}}\n , \n\n 77\n\n /\n 19\n {\\displaystyle {\\displaystyle 77/19}}\n , \n\n 1\n\n /\n 17\n {\\displaystyle {\\displaystyle 1/17}}\n , \n\n 11\n\n /\n 13\n {\\displaystyle {\\displaystyle 11/13}}\n , \n\n 13\n\n /\n 11\n {\\displaystyle {\\displaystyle 13/11}}\n , \n\n 15\n\n /\n 14\n {\\displaystyle {\\displaystyle 15/14}}\n , \n\n 15\n\n /\n 2\n {\\displaystyle {\\displaystyle 15/2}}\n , \n\n 55\n\n /\n 1\n {\\displaystyle {\\displaystyle 55/1}}\n\nStarting with \n\nn\n=\n2\n{\\displaystyle {\\displaystyle n=2}}\n, this FRACTRAN program will change \n\nn\n{\\displaystyle {\\displaystyle n}}\n to \n\n15\n=\n2\n×\n(\n15\n\n/\n2\n)\n{\\displaystyle {\\displaystyle 15=2\\times (15/2)}}\n, then \n\n825\n=\n15\n×\n(\n55\n\n/\n1\n)\n{\\displaystyle {\\displaystyle 825=15\\times (55/1)}}\n, generating the following sequence of integers:\n\n: 2\n {\\displaystyle {\\displaystyle 2}}\n , \n\n 15\n {\\displaystyle {\\displaystyle 15}}\n , \n\n 825\n {\\displaystyle {\\displaystyle 825}}\n , \n\n 725\n {\\displaystyle {\\displaystyle 725}}\n , \n\n 1925\n {\\displaystyle {\\displaystyle 1925}}\n , \n\n 2275\n {\\displaystyle {\\displaystyle 2275}}\n , \n\n 425\n {\\displaystyle {\\displaystyle 425}}\n , \n\n 390\n {\\displaystyle {\\displaystyle 390}}\n , \n\n 330\n {\\displaystyle {\\displaystyle 330}}\n , \n\n 290\n {\\displaystyle {\\displaystyle 290}}\n , \n\n 770\n {\\displaystyle {\\displaystyle 770}}\n , \n\n …\n {\\displaystyle {\\displaystyle \\ldots }}\n\nAfter 2, this sequence contains the following powers of 2:\n\n: 2\n\n 2\n =\n 4\n {\\displaystyle {\\displaystyle 2^{2}=4}}\n , \n\n 2\n\n 3\n =\n 8\n {\\displaystyle {\\displaystyle 2^{3}=8}}\n , \n\n 2\n\n 5\n =\n 32\n {\\displaystyle {\\displaystyle 2^{5}=32}}\n , \n\n 2\n\n 7\n =\n 128\n {\\displaystyle {\\displaystyle 2^{7}=128}}\n , \n\n 2\n\n 11\n =\n 2048\n {\\displaystyle {\\displaystyle 2^{11}=2048}}\n , \n\n 2\n\n 13\n =\n 8192\n {\\displaystyle {\\displaystyle 2^{13}=8192}}\n , \n\n 2\n\n 17\n =\n 131072\n {\\displaystyle {\\displaystyle 2^{17}=131072}}\n , \n\n 2\n\n 19\n =\n 524288\n {\\displaystyle {\\displaystyle 2^{19}=524288}}\n , \n\n …\n {\\displaystyle {\\displaystyle \\ldots }}\n\nwhich are the prime powers of 2.\n\nTask\n\nWrite a program that reads a list of fractions in a *natural* format from the keyboard or from a string,\nto parse it into a sequence of fractions (*i.e.* two integers),\nand runs the FRACTRAN starting from a provided integer, writing the result at each step.\nIt is also required that the number of steps is limited (by a parameter easy to find).\n\nExtra credit\n\nUse this program to derive the first **20** or so prime numbers.\n\nSee also\n\nFor more on how to program FRACTRAN as a universal programming language, see:\n\n* J. H. Conway (1987). Fractran: A Simple Universal Programming Language for Arithmetic. In: Open Problems in Communication and Computation, pages 4–26. Springer.\n\n* J. H. Conway (2010). \"FRACTRAN: A simple universal programming language for arithmetic\". In Jeffrey C. Lagarias. The Ultimate Challenge: the 3x+1 problem. American Mathematical Society. pp. 249–264. ISBN 978-0-8218-4940-8. Zbl 1216.68068.\n\n* Number Pathology: Fractran by Mark C. Chu-Carroll; October 27, 2006." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-03\n\nA Fractran program potentially returns an infinite list, and infinite lists are a common data structure in Raku. The limit is therefore enforced only by slicing the infinite list.\n\n```\nsub fractran(@program) {\n 2, { first Int, map (* * $_).narrow, @program } ... 0\n}\nsay fractran(<17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11\n 15/14 15/2 55/1>)[^100];\n\n```\n\nOutput:\n\n```\n(2 15 825 725 1925 2275 425 390 330 290 770 910 170 156 132 116 308 364 68 4 30 225 12375 10875 28875 25375 67375 79625 14875 13650 2550 2340 1980 1740 4620 4060 10780 12740 2380 2184 408 152 92 380 230 950 575 2375 9625 11375 2125 1950 1650 1450 3850 4550 850 780 660 580 1540 1820 340 312 264 232 616 728 136 8 60 450 3375 185625 163125 433125 380625 1010625 888125 2358125 2786875 520625 477750 89250 81900 15300 14040 11880 10440 27720 24360 64680 56840 150920 178360 33320 30576 5712 2128 1288)\n```\n\n**Extra credit:**\nWe can weed out all the powers of two into another infinite constant list based on the first list. In this case the sequence is limited only by our patience, and a ^C from the terminal. The .msb method finds the most significant bit of an integer, which conveniently is the base-2 log of the power-of-two in question.\n\n```\nsub fractran(@program) {\n 2, { first Int, map (* * $_).narrow, @program } ... 0\n}\nfor fractran <17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11\n 15/14 15/2 55/1> {\n say $++, \"\\t\", .msb, \"\\t\", $_ if 1 +< .msb == $_;\n}\n\n```\n\nOutput:\n\n```\n0 1 2\n1\t2\t4\n2\t3\t8\n3\t5\t32\n4\t7\t128\n5\t11\t2048\n6\t13\t8192\n7\t17\t131072\n8\t19\t524288\n9\t23\t8388608\n^C\n```" } ]
[ { "role": "user", "content": "Write a program to convert dates between the Gregorian calendar and the French Republican calendar.\n\nThe year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendémiaire, Brumaire, Frimaire, Nivôse, Pluviôse, Ventôse, Germinal, Floréal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or *Sansculottides* (*Fête de la vertu* / Virtue Day, *Fête du génie* / Talent Day, *Fête du travail* / Labour Day, *Fête de l'opinion* / Opinion Day, and *Fête des récompenses* / Honours Day). In leap years (the years 3, 7, and 11) a sixth *Sansculottide* was added: *Fête de la Révolution* / Revolution Day.\n\nAs a minimum, your program should give correct results for dates in the range from 1 Vendémiaire 1 = 22 September 1792 to 10 Nivôse 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)\n\nTest your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:\n\n• 1 Vendémiaire 1 = 22 September 1792\n\n• 1 Prairial 3 = 20 May 1795\n\n• 27 Messidor 7 = 15 July 1799 *(Rosetta Stone discovered)*\n\n• Fête de la Révolution 11 = 23 September 1803\n\n• 10 Nivôse 14 = 31 December 1805" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse v6;\nconstant @month_names = <\n Vendémiaire Brumaire Frimaire Nivôse Pluviôse Ventôse\n Germinal Floréal Prairial Messidor Thermidor Fructidor\n>;\nconstant @intercalary =\n 'Fête de la vertu', 'Fête du génie', 'Fête du travail',\n \"Fête de l'opinion\", 'Fête des récompenses', 'Fête de la Révolution',\n;\nconstant %month_nums = %( @month_names Z=> 1..12 );\nconstant %i_cal_nums = %( @intercalary Z=> 1.. 6 );\nconstant $i_cal_month = 13;\nconstant $epoch = Date.new: '1792-09-22';\n\nsub is_republican_leap_year ( Int:D $year --> Bool ) {\n my $y := $year + 1;\n return ?( $y %% 4 and ($y !%% 100 or $y %% 400) );\n}\n\nsub Republican_to_Gregorian ( Str:D $rep_date --> Date ) {\n grammar Republican_date_text {\n token day { \\d+ }\n token year { \\d+ }\n token ic { @intercalary }\n token month { @month_names }\n rule TOP { ^ [ <ic> | <day> <month> ] <year> $ }\n }\n \n Republican_date_text.parse($rep_date)\n orelse die \"Republican date not recognized: '$rep_date'\";\n\n my $day1  := $/<ic>  ?? %i_cal_nums{~$/<ic>}  !! +$/<day>;\n my $month1 := $/<month> ?? %month_nums{~$/<month>} !! $i_cal_month;\n\n my @ymd0 := ($/<year>, $month1, $day1) »-» 1;\n my $days_since_epoch := [+] @ymd0 Z* (365, 30, 1);\n\n my $leap_days := +grep &is_republican_leap_year, 1 ..^ $/<year>;\n return $epoch + $days_since_epoch + $leap_days;\n}\n\nsub Gregorian_to_Republican ( Date:D $greg_date --> Str ) {\n my $days_since_epoch := $greg_date - $epoch;\n die if $days_since_epoch < 0;\n\n my ( $year, $days ) = 1, $days_since_epoch;\n loop {\n my $year_length = 365 + (1 if $year.&is_republican_leap_year);\n last if $days < $year_length;\n $days -= $year_length;\n $year += 1;\n }\n\n my ( $day0, $month0 ) = $days.polymod( 30 );\n my ( $day1, $month1 ) = ($day0, $month0) X+ 1;\n\n return $month1 == $i_cal_month\n  ?? \"@intercalary[$day0 ] $year\"\n  !! \"$day1 @month_names[$month0] $year\";\n}\n\nmy @test_data =\n ( '1792-09-22', '1 Vendémiaire 1' ),\n ( '1795-05-20', '1 Prairial 3' ),\n ( '1799-07-15', '27 Messidor 7' ),\n ( '1803-09-23', 'Fête de la Révolution 11' ),\n ( '1805-12-31', '10 Nivôse 14' ),\n\n ( '1871-03-18', '27 Ventôse 79' ),\n ( '1944-08-25', '7 Fructidor 152' ),\n ( '2016-09-19', 'Fête du travail 224' ),\n\n ( '1871-05-06', '16 Floréal 79' ), # Paris Commune begins\n ( '1871-05-23', '3 Prairial 79' ), # Paris Commune ends\n ( '1799-11-09', '18 Brumaire 8' ), # Revolution ends by Napoléon coup\n ( '1804-12-02', '11 Frimaire 13' ), # Republic ends by Napoléon coronation\n ( '1794-10-30', '9 Brumaire 3' ), # École Normale Supérieure established\n ( '1794-07-27', '9 Thermidor 2' ), # Robespierre falls\n ( '1799-05-27', '8 Prairial 7' ), # Fromental Halévy born\n\n ( '1792-09-22', '1 Vendémiaire 1' ),\n ( '1793-09-22', '1 Vendémiaire 2' ),\n ( '1794-09-22', '1 Vendémiaire 3' ),\n ( '1795-09-23', '1 Vendémiaire 4' ),\n ( '1796-09-22', '1 Vendémiaire 5' ),\n ( '1797-09-22', '1 Vendémiaire 6' ),\n ( '1798-09-22', '1 Vendémiaire 7' ),\n ( '1799-09-23', '1 Vendémiaire 8' ),\n ( '1800-09-23', '1 Vendémiaire 9' ),\n ( '1801-09-23', '1 Vendémiaire 10' ),\n ( '1802-09-23', '1 Vendémiaire 11' ),\n ( '1803-09-24', '1 Vendémiaire 12' ),\n ( '1804-09-23', '1 Vendémiaire 13' ),\n ( '1805-09-23', '1 Vendémiaire 14' ),\n ( '1806-09-23', '1 Vendémiaire 15' ),\n ( '1807-09-24', '1 Vendémiaire 16' ),\n ( '1808-09-23', '1 Vendémiaire 17' ),\n ( '1809-09-23', '1 Vendémiaire 18' ),\n ( '1810-09-23', '1 Vendémiaire 19' ),\n ( '1811-09-24', '1 Vendémiaire 20' ),\n ( '2015-09-23', '1 Vendémiaire 224' ),\n ( '2016-09-22', '1 Vendémiaire 225' ),\n ( '2017-09-22', '1 Vendémiaire 226' ),\n;\n\nfor @test_data -> ( $g_text, $r ) {\n my $g = Date.new: $g_text;\n\n die if Republican_to_Gregorian($r) != $g\n or Gregorian_to_Republican($g) ne $r;\n\n die if Gregorian_to_Republican(Republican_to_Gregorian($r)) ne $r\n or Republican_to_Gregorian(Gregorian_to_Republican($g)) != $g;\n}\nsay 'All tests successful.';\n\n```\n\nOutput:\n\n```\nAll tests successful.\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and display here on this page the Frobenius numbers that are   <   10,000.\n\nThe series is defined by:\n\n```\n FrobeniusNumber(n) = prime(n) * prime(n+1) - prime(n) - prime(n+1)\n\n```\n\nwhere:\n\n: : : : prime(1)   =   2\n : prime(2)   =   3\n : prime(3)   =   5\n : prime(4)   =   7\n\n : •\n : •\n : •" }, { "role": "assistant", "content": "```\nsay \"{+$_} matching numbers\\n{.batch(10)».fmt('%4d').join: \"\\n\"}\\n\"\n given (^1000).grep( *.is-prime ).rotor(2 => -1)\n .map( { (.[0] * .[1] - .[0] - .[1]) } ).grep(* < 10000);\n\n```\n\nOutput:\n\n```\n25 matching numbers\n 1 7 23 59 119 191 287 395 615 839\n1079 1439 1679 1931 2391 3015 3479 3959 4619 5039\n5615 6395 7215 8447 9599\n```" } ]
[ { "role": "user", "content": "Task\n\nConnect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.04\n\n```\nuse Net::FTP;\n\nmy $host = 'speedtest.tele2.net';\nmy $user = 'anonymous';\nmy $password = '';\n\nmy $ftp = Net::FTP.new( host => $host, :passive );\n\n$ftp.login( user => $user, pass => $password );\n\n$ftp.cwd( 'upload' );\n\n$ftp.cwd( '/' );\n\nsay $_<name> for $ftp.ls;\n\n$ftp.get( '1KB.zip', :binary );\n\n```\n\nOutput:\n\n```\n1000GB.zip\n100GB.zip\n100KB.zip\n100MB.zip\n10GB.zip\n10MB.zip\n1GB.zip\n1KB.zip\n1MB.zip\n200MB.zip\n20MB.zip\n2MB.zip\n3MB.zip\n500MB.zip\n50MB.zip\n512KB.zip\n5MB.zip\nupload\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a function, compose,   whose two arguments   *f*   and   *g*,   are both functions with one argument.\n\nThe result of compose is to be a function of one argument, (lets call the argument   *x*),   which works like applying function   *f*   to the result of applying function   *g*   to   *x*.\n\nExample\n\n```\n compose(f, g) (x) = f(g(x))\n\n```\n\nReference: Function composition\n\nHint: In some languages, implementing compose correctly requires creating a closure." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nThe function composition operator is ∘, U+2218 RING OPERATOR (with a \"Texas\" version o for the Unicode challenged). Here we compose a routine, an operator, and a lambda:\n\n```\nsub triple($n) { 3 * $n }\nmy &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 };\nsay &f(5); # prints \"-21\".\n```" } ]
[ { "role": "user", "content": "A function is a body of code that returns a value.\n\nThe value returned may depend on arguments provided to the function.\n\nTask\n\nWrite a definition of a function called \"multiply\" that takes two arguments and returns their product.\n\n(Argument types should be chosen so as not to distract from showing how functions are created and values returned).\n\nRelated task\n\n* Function prototype" }, { "role": "assistant", "content": "(formerly Perl 6)\nWithout a signature:\n\n```\nsub multiply { return @_[0] * @_[1]; }\n```\n\nThe return is optional on the final statement, since the last expression would return its value anyway. The final semicolon in a block is also optional.\n(Beware that a subroutine without an explicit signature, like this one, magically becomes variadic (rather than nullary) only if `@_` or `%_` appear in the body.) In fact, we can define the variadic version explicitly, which still works for two arguments:\n\n```\nsub multiply { [*] @_ }\n```\n\nWith formal parameters and a return type:\n\n```\nsub multiply (Rat $a, Rat $b --> Rat) { $a * $b }\n```\n\nSame thing:\n\n```\nmy Rat sub multiply (Rat $a, Rat $b) { $a * $b }\n```\n\nIt is possible to define a function in \"lambda\" notation and then bind that into a scope, in which case it works like any function:\n\n```\nmy &multiply := -> $a, $b { $a * $b };\n```\n\nAnother way to write a lambda is with internal placeholder parameters:\n\n```\nmy &multiply := { $^a * $^b };\n```\n\n(And, in fact, our original @\\_ above is just a variadic self-declaring placeholder argument. And the famous Perl \"topic\", $\\_, is just a self-declared parameter to a unary block.)\n\nYou may also curry both built-in and user-defined operators by supplying a \\* (known as \"whatever\") in place of the argument that is *not* to be curried:\n\n```\nmy &multiply := * * *;\n```\n\nThis is not terribly readable in this case due to the visual confusion between the whatever star and the multiplication operator, but Perl knows when it's expecting terms instead of infixes, so only the middle star is multiplication.\nIt tends to work out much better with other operators. In particular, you may\ncurry a cascade of methods with only the original invocant missing:\n\n```\[email protected]( *.substr(0,1).lc.match(/<[0..9 a..f]>/) )\n```\n\nThis is equivalent to:\n\n```\[email protected]( -> $obj { $obj.substr(0,1).lc.match(/<[0..9 a..f]>/) } )\n```" } ]
[ { "role": "user", "content": "Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred).\n\nThis is a static analysis: The question is not how often each function is\nactually executed at runtime, but how often it is used by the programmer.\n\nBesides its practical usefulness, the intent of this task is to show how to do self-inspection within the language." }, { "role": "assistant", "content": "(formerly Perl 6)\nHere we just examine the ast of the Raku compiler (which is written in Raku) to look for function calls.\n\n```\nmy $text = qqx[raku --target=ast @*ARGS[]];\nmy %fun;\nfor $text.lines {\n %fun{$0}++ if / '(call &' (.*?) ')' /\n}\n\nfor %fun.invert.sort.reverse[^10] { .value.say }\n\n```\n\nOutput:\n\nHere we run it on the strand sort RC entry. Note how Raku considers various operators to really be function calls underneath.\n\n```\n$ ./morefun strand\npop\npostcircumfix:<[ ]>\nunshift\nsucceed\nsplice\nprefix:<->\npush\ninfix:<,>\ninfix:<..>\ninfix:<->\n```" } ]
[ { "role": "user", "content": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping.\n\nTask\n\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\nLanguages that do not provide function prototyping facilities should be omitted from this task." }, { "role": "assistant", "content": "(formerly Perl 6)\nThere is no restriction on placement of prototype declarations. (Actually, we call them \"stub declarations\".) In fact, stub declarations are rarely needed in Raku because post-declaration of functions is allowed, and normal function declarations do not bend the syntax the way they sometimes do in Perl 5.\n\nNote that the ... in all of these stub bodies is literally part of the declaration syntax.\n\nA prototype declaration for a function that does not require arguments (and returns an Int):\n\n```\nsub foo ( --> Int) {...}\n\n```\n\nA prototype declaration for a function that requires two arguments.\nNote that we can omit the variable name and just use the sigil in the stub, since we don't need to reference the argument until the actual definition of the routine. Also, unlike in Perl 5, a sigil like @ defaults to binding a single positional argument.\n\n```\nsub foo (@, $ --> Int) {...}\n\n```\n\nA prototype declaration for a function that utilizes varargs after one required argument.\nNote the \"slurpy\" star turns the @ sigil into a parameter that accepts all the rest of the positional arguments.\n\n```\nsub foo ($, *@ --> Int) {...}\n\n```\n\nA prototype declaration for a function that utilizes optional arguments after one required argument. Optionality is conferred by either a question mark or a default:\n\n```\nsub foo ($, $?, $ = 42 --> Int) {...}\n\n```\n\nA prototype declaration for a function that utilizes named parameters:\n\n```\nsub foo ($, :$faster, :$cheaper --> Int) {...}\n\n```\n\nExample of prototype declarations for subroutines or procedures, which in Raku is done simply by noting that nothing is returned:\n\n```\nsub foo ($, $ --> Nil) {...}\n\n```\n\nA routine may also slurp up all the named arguments that were not bound earlier in the signature:\n\n```\nsub foo ($, :$option, *% --> Int) {...}\n\n```\n\nA routine may make a named parameter mandatory using exclamation mark. (This is more useful in multi subs than in stubs though.)\n\n```\nsub foo ($, :$option! --> Int) {...}\n\n```\n\nA routine may unpack an Array automaticly. Here the first element is stored in a scalar and the rest in an Array. Other buildin types can be unpacked as well.\n\n```\nsub foo ([$, @]) {...}\n\n```\n\nA routine may ask for a closure parameter to implement higher order functions. Typed or untyped signatures can be supplied.\n\n```\nsub foo (@, &:(Str --> Int)) {...}\n\n```" } ]
[ { "role": "user", "content": "Functional coverage is a measure of how much a particular function of a system\nhas been verified as correct. It is used heavily in tracking the completeness\nof the verification of complex System on Chip (SoC) integrated circuits, where\nit can also be used to track how well the functional *requirements* of the\nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking\nfunctional coverage but uses a more familiar(?) scenario.\n\nTask Description\n\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when\nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on\neach house who return with a breakdown of how they will report on progress in\neach house.\n\nThe overall hierarchy of (sub)tasks is as follows,\n\n```\ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n```\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\n\n```\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n```\n\nCalculation\n\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n**The task is to** calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\nExtra Credit\n\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained \n\n1\n−\nc\no\nv\ne\nr\na\ng\ne\n{\\displaystyle {\\displaystyle 1-coverage}}\n for any node, by the product of the `powers` of its parent nodes from the top down to the node. \nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n```\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\n```\n\nFollowed by a call to:\n\n```\n top.delta_calculation(power=1)\n\n```\n\n**Note:** to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub walktree ($data) {\n my (@parts, $cnt);\n\n while ($data ~~ m:nth(++$cnt)/$<head>=[(\\s*) \\N+\\n ] # split off one level as 'head' (or terminal 'leaf')\n $<body>=[[$0 \\s+ \\N+\\n]*]/ ) { # next sub-level is 'body' (defined by extra depth of indentation)\n\n my ($head, $body) = ($<head>, $<body>);\n $head ~~ /'|' $<weight>=[\\S*] \\s* '|' $<coverage>=[\\S*]/; # save values of weight and coverage (if any) for later\n\n my ($w, $wsum) = (0, 0);\n $head ~= .[0],\n $w += .[1],\n $wsum += .[1] * .[2]\n for walktree $body;\n\n my $weight = (~$<weight> or 1).fmt('%-8s');\n my $coverage = $w == 0\n  ?? (~$<coverage> or 0).fmt('%-10s')\n  !! ($wsum/$w) .fmt('%-10.2g');\n @parts.push: [$head.subst(/'|' \\N+/, \"|$weight|$coverage|\"), $weight, $coverage ];\n }\n return @parts;\n}\n\n(say .[0] for walktree $_) given \n\n q:to/END/\n NAME_HIERARCHY |WEIGHT |COVERAGE |\n cleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n END\n\n```\n\nOutput:\n\n```\nNAME_HIERARCHY |WEIGHT |COVERAGE |\n\ncleaning |1 |0.41 |\n house1 |40 |0.33 |\n bedrooms |1 |0.25 |\n bathrooms |1 |0.5 |\n bathroom1 |1 |0.5 |\n bathroom2 |1 |0 |\n outside_lavatory |1 |1 |\n attic |1 |0.75 |\n kitchen |1 |0.1 |\n living_rooms |1 |0.25 |\n lounge |1 |0 |\n dining_room |1 |0 |\n conservatory |1 |0 |\n playroom |1 |1 |\n basement |1 |0 |\n garage |1 |0 |\n garden |1 |0.8 |\n house2 |60 |0.46 |\n upstairs |1 |0.15 |\n bedrooms |1 |0 |\n suite_1 |1 |0 |\n suite_2 |1 |0 |\n bedroom_3 |1 |0 |\n bedroom_4 |1 |0 |\n bathroom |1 |0 |\n toilet |1 |0 |\n attics |1 |0.6 |\n groundfloor |1 |0.32 |\n kitchen |1 |0 |\n living_rooms |1 |0 |\n lounge |1 |0 |\n dining_room |1 |0 |\n conservatory |1 |0 |\n playroom |1 |0 |\n wet_room_&_toilet |1 |0 |\n garage |1 |0 |\n garden |1 |0.9 |\n hot_tub_suite |1 |1 |\n basement |1 |0.92 |\n cellars |1 |1 |\n wine_cellar |1 |1 |\n cinema |1 |0.75 |\n```" } ]
[ { "role": "user", "content": "Definitions\n\nThe   **fusc**   integer sequence is defined as:\n\n: : * fusc(0) = 0\n * fusc(1) = 1\n * for **n**>1,   the   **n**th   term is defined as:\n\n : : * if   **n**   is even;     fusc(n) = fusc(n/2)\n * if   **n**   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2)\n\nNote that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above).\n\nAn observation\n: : : : : * fusc(A) = fusc(B)\n\nwhere   **A**   is some non-negative integer expressed in binary,   and\nwhere   **B**   is the binary value of   **A**   reversed.\n\nFusc numbers are also known as:\n\n: : * fusc function   (named by Dijkstra, 1982)\n * Stern's Diatomic series   (although it starts with unity, not zero)\n * Stern-Brocot sequence   (although it starts with unity, not zero)\n\nTask\n: : * show the first   **61**   fusc numbers (starting at zero) in a horizontal format.\n * show the fusc number (and its index) whose length is greater than any previous fusc number length.\n\n : : * (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n\n * show all numbers with commas   (if appropriate).\n * show all output here.\n\nRelated task\n: * Stern-Brocot sequence\n * Calkin-Wilf sequence.\n\nAlso see\n: : * the MathWorld entry:   Stern's Diatomic Series.\n * the OEIS entry:   A2487." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Recurrence\n\n```\nmy @Fusc = 0, 1, 1, { |(@Fusc[$_ - 1] + @Fusc[$_], @Fusc[$_]) given ++$+1 } ... *;\n\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nput \"First 61 terms of the Fusc sequence:\\n{@Fusc[^61]}\" ~\n \"\\n\\nIndex and value for first term longer than any previous:\";\n\nfor flat 'Index', 'Value', 0, 0, (1..4).map({\n my $l = 10**$_;\n @Fusc.first(* > $l, :kv).map: &comma\n }) -> $i, $v {\n printf \"%15s : %s\\n\", $i, $v\n}\n\n```\n\nOutput:\n\n```\nFirst 61 terms of the Fusc sequence:\n0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4\n\nIndex and value for first term longer than any previous:\n Index : Value\n 0 : 0\n 37 : 11\n 1,173 : 108\n 35,499 : 1,076\n 699,051 : 10,946\n\n```\n\n### Recursive\n\nAlternative version using Raku's multiple-dispatch feature. This version is significantly slower than the one above, but it's definitely prettier.\n\n```\nmulti fusc( 0 ) { 0 }\nmulti fusc( 1 ) { 1 }\nmulti fusc( $n where $n %% 2 ) { fusc $n div 2 }\nmulti fusc( $n ) { [+] map *.&fusc, ( $n - 1 ) div 2, ( $n + 1 ) div 2 }\nput map *.&fusc, 0..60;\n\n```\n\nOutput:\n\n```\n0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4\n```" } ]
[ { "role": "user", "content": "Problem Statement\n\nGabow's algorithm is an algorithm used to find strongly connected components (SCCs) in a digraph.\n\nGiven a directed graph (digraph) with *V* vertices and *E* edges, where vertices are represented as integers from 0 to *V-1* and edges are directed from one vertex to another, design an algorithm to identify all **strongly connected components (SCCs)**. A strongly connected component is a maximal subset of vertices in the digraph such that for every pair of vertices *v* and *w* in the subset, there exists a directed path from *v* to *w* and from *w* to *v*. The algorithm should:\n\n1. Compute the number of SCCs in the digraph.\n2. Assign each vertex to its corresponding SCC.\n3. Provide a way to query whether two vertices belong to the same SCC.\n4. Return the component identifier for any given vertex.\n\nInput\n\n* A directed graph *G* represented as an adjacency list, where:\n + *V* is the number of vertices (non-negative integer).\n + Edges are provided as pairs *(v, w)*, indicating a directed edge from vertex *v* to vertex *w*.\n* The vertices are integers in the range [0, *V-1*].\n\nOutput\n\n* The total number of strongly connected components in the digraph.\n* An assignment of each vertex to a unique component identifier (an integer ≥ 0).\n* A mechanism to check if two vertices *v* and *w* are strongly connected (i.e., belong to the same SCC).\n* The ability to retrieve the component ID of any vertex *v*.\n\nConstraints\n\n* *V* ≥ 0 (the graph can be empty).\n* Edges *(v, w)* must satisfy 0 ≤ *v*, *w* < *V*.\n* The graph may contain cycles, self-loops, or parallel edges (though parallel edges are effectively ignored in this implementation as duplicates in adjacency lists are allowed but not explicitly handled).\n\nExample\n\nConsider a digraph with *V = 13* vertices and the following edges:\n\n```\n(4, 2), (2, 3), (3, 2), (6, 0), (0, 1), (2, 0), (11, 12), (12, 9), (9, 10), \n(9, 11), (8, 9), (10, 12), (0, 5), (5, 4), (3, 5), (6, 4), (6, 9), (7, 6), \n(7, 8), (8, 7), (5, 3), (0, 6)\n\n```\n\n* Compute the SCCs.\n* Determine how many SCCs exist.\n* List the vertices in each SCC.\n* Check if specific pairs of vertices (e.g., 0 and 3, 0 and 7) are strongly connected." }, { "role": "assistant", "content": "**Translation of**: Rust\n\n```\n# 20250415 Raku programming solution\n\nmy subset Vertex of UInt;\nmy subset ComponentId of UInt;\n\nclass Digraph {\n has Int $.vertex-count is readonly;\n has Int $.edge-count is rw = 0;\n has @.adjacency-lists;\n\n method new(Int $vertex-count where * >= 0) { # Constructor\n self.bless( vertex-count => $vertex-count,\n adjacency-lists => [ [] xx $vertex-count ] )\n }\n\n method add-edge(Vertex $from, Vertex $to) { # Add a directed edge\n self!validate-vertex($from);\n self!validate-vertex($to);\n @!adjacency-lists[$from].push($to);\n $!edge-count++;\n }\n\n method adjacency-list(Vertex $vertex) { # Get adjacency list for a vertex\n self!validate-vertex($vertex);\n @!adjacency-lists[$vertex];\n }\n\n method !validate-vertex(Vertex $vertex) { # Validate vertex index\n if $vertex >= $!vertex-count {\n die \"Vertex $vertex is not between 0 and {$!vertex-count - 1}\";\n }\n }\n\n method gist { # String representation\n return [~] [ \n \"Digraph has $!vertex-count vertices and $!edge-count edges\\n\",\n \"Adjacency lists:\\n\"\n ].append( gather for ^$!vertex-count -> $vertex {\n take sprintf(\"%2d: \", $vertex);\n take @!adjacency-lists[$vertex].sort.Str ~ \"\\n\"\n })\n }\n}\n\nclass GabowSCC {\n has Bool @.visited;\n has Int @.component-ids; # Using Int with -1 as None equivalent\n has Int @.preorders; # Using Int with -1 as None equivalent\n has Int $.preorder-count is rw = 0;\n has Int $.scc-count is rw = 0;\n has Vertex @.visited-vertices-stack;\n has Vertex @.auxiliary-stack;\n\n method new(Digraph $digraph) { # Constructor\n my $n = $digraph.vertex-count;\n my $self = self.bless(\n visited => False xx $n,\n component-ids => (-1) xx $n,\n preorders => (-1) xx $n,\n visited-vertices-stack => [],\n auxiliary-stack => []\n );\n\n for ^$n -> $vertex {\n $self!depth-first-search($digraph, $vertex) unless $self.visited[$vertex]\n }\n $self;\n }\n\n # Depth-first search for Gabow's algorithm\n method !depth-first-search(Digraph $digraph, Vertex $vertex) {\n @!visited[$vertex] = True;\n @!preorders[$vertex] = $!preorder-count++;\n @!visited-vertices-stack.push($vertex);\n @!auxiliary-stack.push($vertex);\n\n for $digraph.adjacency-list($vertex).List -> $adjacent {\n if !@!visited[$adjacent] {\n self!depth-first-search($digraph, $adjacent)\n } else {\n if @!component-ids[$adjacent] == -1 {\n my $adjacent-preorder = @!preorders[$adjacent];\n while @!auxiliary-stack && @!preorders[@!auxiliary-stack[*-1]] > $adjacent-preorder {\n @!auxiliary-stack.pop;\n }\n }\n }\n }\n\n if @!auxiliary-stack && @!auxiliary-stack[*-1] == $vertex {\n @!auxiliary-stack.pop;\n loop {\n my $scc-member = @!visited-vertices-stack.pop // die \"Visited stack empty\";\n @!component-ids[$scc-member] = $!scc-count;\n last if $scc-member == $vertex;\n }\n $!scc-count++;\n }\n }\n\n method get-component-id(Vertex $vertex) { # Get component ID for a vertex\n self!validate-vertex($vertex);\n @!component-ids[$vertex] == -1 ?? Nil !! @!component-ids[$vertex];\n }\n\n # Check if two vertices are strongly connected\n method is-strongly-connected(Vertex $v, Vertex $w) {\n self!validate-vertex($v);\n self!validate-vertex($w);\n @!component-ids[$v] != -1 && @!component-ids[$w] != -1 && @!component-ids[$v] == @!component-ids[$w];\n }\n\n method get-components() { # Get all components\n my @components = [] xx $!scc-count;\n for @!component-ids.kv -> $vertex, $id {\n if $id != -1 {\n $id < $!scc-count\n  ?? @components[$id].push($vertex)\n  !! note \"Warning: Vertex $vertex has invalid SCC ID $id\"\n }\n }\n @components.map: *.sort \n }\n\n method !validate-vertex(Vertex $vertex) { # Validate vertex index\n given my $n = @!visited.elems {\n die \"Vertex $vertex is not between 0 and {$n - 1}\" if $vertex >= $n\n }\n }\n}\n\nmy @edges = [ <4 2>, <2 3>, <3 2>, <6 0>, <0 1>, <2 0>, <11 12>, <12 9>, \n <9 10>, <9 11>, <8 9>, <10 12>, <0 5>, <5 4>, <3 5>, <6 4>, \n <6 9>, <7 6>, <7 8>, <8 7>, <5 3>, <0 6>\n ].map: { ( from => .[0], to => .[1] ).Hash };\nmy $vertex-count = 13;\nmy $digraph = Digraph.new($vertex-count);\n\nfor @edges -> $edge { $digraph.add-edge($edge<from>, $edge<to>) }\n\nprint \"Constructed digraph:\" ~ $digraph.gist;\n\nmy $gabow-scc = GabowSCC.new($digraph);\nsay \"It has $gabow-scc.scc-count() strongly connected components.\";\n\nmy @components = $gabow-scc.get-components();\nsay \"\\nComponents:\";\nfor @components.kv -> $i, @component {\n say \"Component $i: \" ~ @component.Str if @component.Bool;\n}\n\nsay \"\\nExample connectivity checks:\";\nfor ( <0 3>, <0 7>, <9 12> ) -> ($i,$j) {\n say \"Vertices $i and $j strongly connected? {$gabow-scc.is-strongly-connected($i, $j)}\"\n}\n\nsay \"Component ID of vertex 5: {$gabow-scc.get-component-id(5) // 'None'}\";\nsay \"Component ID of vertex 8: {$gabow-scc.get-component-id(8) // 'None'}\";\n\n(my $id = $gabow-scc.get-component-id(5)).defined\n  ?? say \"Component ID of vertex 5 (explicit handling): $id\"\n  !! say \"Vertex 5 has no assigned component ID.\";\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Example of a Galton Box at the end of animation.\n\nA   **Galton device**   Sir Francis Galton's device   is also known as a   **bean machine**,   a   **Galton Board**,   or a   **quincunx**.\n\nDescription of operation\n\nIn a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.\n\nEventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin.\n\nTask\n\nGenerate an animated simulation of a Galton device.\n\nTask requirements\n: : * The box should have at least 5 pins on the bottom row.\n * A solution can use graphics or ASCII animation.\n * Provide a sample of the output/display such as a screenshot.\n * There can be one or more balls in flight at the same time.\n * If multiple balls are in flight, ensure they don't interfere with each other.\n * A solution should allow users to specify the number of balls, or it should run until full or a preset limit.\n * Optionally,   display the number of balls." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUPPER HALF BLOCK and LOWER HALF BLOCK alternate to give a somewhat smooth animation.\n\n**Works with**: rakudo version 2015-09-12\n\n```\nmy $row-count = 6;\n \nconstant $peg = \"*\";\nconstant @coin-icons = \"\\c[UPPER HALF BLOCK]\", \"\\c[LOWER HALF BLOCK]\";\n \nsub display-board(@positions, @stats is copy, $halfstep) {\n my $coin = @coin-icons[$halfstep.Int];\n \n state @board-tmpl = {\n # precompute a board\n my @tmpl;\n sub out(*@stuff) {\n @tmpl.push: $[@stuff.join>>.ords.flat];\n }\n # three lines of space above\n for 1..3 {\n out \" \", \" \" x (2 * $row-count);\n }\n # $row-count lines of pegs\n for flat ($row-count...1) Z (1...$row-count) -> $spaces, $pegs {\n out \" \", \" \" x $spaces, ($peg xx $pegs).join(\" \"), \" \" x $spaces;\n }\n # four lines of space below\n for 1..4 {\n out \" \", \" \" x (2 * $row-count);\n }\n @tmpl\n }();\n \n my $midpos = $row-count + 2;\n \n my @output;\n {\n # collect all the output and output it all at once at the end\n sub say(Str $foo) {\n @output.push: $foo, \"\\n\";\n }\n sub print(Str $foo) {\n @output.push: $foo;\n }\n \n # make some space above the picture\n say \"\" for ^10;\n \n my @output-lines = map { [ @$_ ] }, @board-tmpl;\n # place the coins\n for @positions.kv -> $line, $pos {\n next unless $pos.defined;\n @output-lines[$line][$pos + $midpos] = $coin.ord;\n }\n # output the board with its coins\n for @output-lines -> @line {\n say @line.chrs;\n }\n \n # show the statistics\n my $padding = 0;\n while any(@stats) > 0 {\n $padding++;\n print \" \";\n @stats = do for @stats -> $stat {\n given $stat {\n when 1 {\n print \"\\c[UPPER HALF BLOCK]\";\n $stat - 1;\n }\n when * <= 0 {\n print \" \";\n 0\n }\n default {\n print \"\\c[FULL BLOCK]\";\n $stat - 2;\n }\n }\n }\n say \"\";\n }\n say \"\" for $padding...^10;\n }\n say @output.join(\"\");\n}\n \nsub simulate($coins is copy) {\n my $alive = True;\n \n sub hits-peg($x, $y) {\n if 3 <= $y < 3 + $row-count and -($y - 2) <= $x <= $y - 2 {\n return not ($x - $y) %% 2;\n }\n return False;\n }\n \n my @coins = Int xx (3 + $row-count + 4);\n my @stats = 0 xx ($row-count * 2);\n # this line will dispense coins until turned off.\n @coins[0] = 0;\n while $alive {\n $alive = False;\n # if a coin falls through the bottom, count it\n given @coins[*-1] {\n when *.defined {\n @stats[$_ + $row-count]++;\n }\n }\n \n # move every coin down one row\n for ( 3 + $row-count + 3 )...1 -> $line {\n my $coinpos = @coins[$line - 1];\n \n @coins[$line] = do if not $coinpos.defined {\n Nil\n } elsif hits-peg($coinpos, $line) {\n # when a coin from above hits a peg, it will bounce to either side.\n $alive = True;\n ($coinpos - 1, $coinpos + 1).pick;\n } else {\n # if there was a coin above, it will fall to this position.\n $alive = True;\n $coinpos;\n }\n }\n # let the coin dispenser blink and turn it off if we run out of coins\n if @coins[0].defined {\n @coins[0] = Nil\n } elsif --$coins > 0 {\n @coins[0] = 0 \n }\n \n # smooth out the two halfsteps of the animation\n my $start-time;\n ENTER { $start-time = now }\n my $wait-time = now - $start-time;\n \n sleep 0.1 - $wait-time if $wait-time < 0.1;\n for @coin-icons.keys {\n sleep $wait-time max 0.1;\n display-board(@coins, @stats, $_);\n }\n }\n}\n \nsub MAIN($coins = 20, $peg-lines = 6) {\n $row-count = $peg-lines;\n simulate($coins);\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement one algorithm (or more) to compute the Gamma (\n\nΓ\n{\\displaystyle {\\displaystyle \\Gamma }}\n) function (in the real field only).\n\nIf your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function.\n\nThe Gamma function can be defined as:\n\n: : : : : : Γ\n (\n x\n )\n =\n\n\n ∫\n\n 0\n\n ∞\n\n t\n\n x\n −\n 1\n\n e\n\n −\n t\n d\n t\n {\\displaystyle {\\displaystyle \\Gamma (x)=\\displaystyle \\int \\_{0}^{\\infty }t^{x-1}e^{-t}dt}}\n\nThis suggests a straightforward (but inefficient) way of computing the \n\nΓ\n{\\displaystyle {\\displaystyle \\Gamma }}\n through numerical integration.\n\nBetter suggested methods:\n\n* Lanczos approximation\n* Stirling's approximation" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub Γ(\\z) {\n constant g = 9;\n z < .5 ?? pi/ sin(pi * z) / Γ(1 - z) !!\n sqrt(2*pi) *\n (z + g - 1/2)**(z - 1/2) *\n exp(-(z + g - 1/2)) *\n [+] <\n 1.000000000000000174663\n 5716.400188274341379136\n -14815.30426768413909044\n 14291.49277657478554025\n -6348.160217641458813289\n 1301.608286058321874105\n -108.1767053514369634679\n 2.605696505611755827729\n -0.7423452510201416151527e-2\n 0.5384136432509564062961e-7\n -0.4023533141268236372067e-8\n > Z* 1, |map 1/(z + *), 0..*\n}\n\nsay Γ($_) for 1/3, 2/3 ... 10/3;\n\n```\n\nOutput:\n\n```\n2.67893853470775\n1.3541179394264\n1\n0.892979511569248\n0.902745292950934\n1\n1.190639348759\n1.50457548825155\n2\n2.77815848043766\n```" } ]
[ { "role": "user", "content": "Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the\nfirst and last digit are known as   **gapful numbers**.\n\n*Evenly divisible*   means divisible with   no   remainder.\n\nAll   one─   and two─digit   numbers have this property and are trivially excluded.   Only\nnumbers   ≥ **100**   will be considered for this Rosetta Code task.\n\nExample\n\n**187**   is a   **gapful**   number because it is evenly divisible by the\nnumber   **17**   which is formed by the first and last decimal digits\nof   **187**.\n\nAbout   7.46%   of positive integers are   *gapful*.\n\nTask\n: * Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page\n * Show the first   **30**   gapful numbers\n * Show the first   **15**   gapful numbers   ≥          **1,000,000**\n * Show the first   **10**   gapful numbers   ≥   **1,000,000,000**\n\nRelated tasks\n: * Harshad or Niven series.\n * palindromic gapful numbers.\n * largest number divisible by its digits.\n\nAlso see\n: * The OEIS entry:   A108343 gapful numbers.\n * numbersaplenty gapful numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nAlso test starting on a number that *doesn't* start with 1. Required to have titles, may as well make 'em noble. :-)\n\n```\nuse Lingua::EN::Numbers;\n\nfor (1e2, 30, 1e6, 15, 1e9, 10, 7123, 25)».Int -> $start, $count {\n put \"\\nFirst $count gapful numbers starting at {comma $start}:\\n\" ~\n <Sir Lord Duke King>.pick ~ \": \", ~\n ($start..*).grep( { $_ %% .comb[0, *-1].join } )[^$count];\n}\n\n```\n\nOutput:\n\n```\nFirst 30 gapful numbers starting at 100:\nSir: 100 105 108 110 120 121 130 132 135 140 143 150 154 160 165 170 176 180 187 190 192 195 198 200 220 225 231 240 242 253\n\nFirst 15 gapful numbers starting at 1,000,000:\nDuke: 1000000 1000005 1000008 1000010 1000016 1000020 1000021 1000030 1000032 1000034 1000035 1000040 1000050 1000060 1000065\n\nFirst 10 gapful numbers starting at 1,000,000,000:\nKing: 1000000000 1000000001 1000000005 1000000008 1000000010 1000000016 1000000020 1000000027 1000000030 1000000032\n\nFirst 25 gapful numbers starting at 7,123:\nKing: 7125 7140 7171 7189 7210 7272 7275 7280 7296 7350 7373 7420 7425 7474 7488 7490 7560 7575 7630 7632 7676 7700 7725 7770 7777\n```" } ]
[ { "role": "user", "content": "Task\n\nInvert matrix   **A**   using Gauss-Jordan method.\n\n**A**   being an   **n** × **n**   matrix." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUses bits and pieces from other tasks, Reduced row echelon form primarily.\n\n```\nsub gauss-jordan-invert (@m where &is-square) {\n ^@m .map: { @m[$_].append: identity(+@m)[$_] };\n @m.&rref[*]»[+@m .. *];\n}\n\nsub is-square (@m) { so @m == all @m[*] }\n\nsub identity ($n) { [ 1, |(0 xx $n-1) ], *.rotate(-1).Array ... *.tail }\n\n# reduced row echelon form (from 'Gauss-Jordan elimination' task)\nsub rref (@m) {\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n\n for ^$rows -> $r {\n $lead < $cols or return @m;\n my $i = $r;\n until @m[$i;$lead] {\n ++$i == $rows or next;\n $i = $r;\n ++$lead == $cols and return @m;\n }\n @m[$i, $r] = @m[$r, $i] if $r != $i;\n @m[$r] »/=» $ = @m[$r;$lead];\n for ^$rows -> $n {\n next if $n == $r;\n @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0);\n }\n ++$lead;\n }\n @m\n}\nsub rat-or-int ($num) {\n return $num unless $num ~~ Rat|FatRat;\n return $num.narrow if $num.narrow ~~ Int;\n $num.nude.join: '/';\n}\n\nsub say_it ($message, @array) {\n my $max;\n @array.map: {$max max= max $_».&rat-or-int.comb(/\\S+/)».chars};\n say \"\\n$message\";\n $_».&rat-or-int.fmt(\" %{$max}s\").put for @array;\n}\n\nmulti to-matrix ($str) { [$str.split(';').map(*.words.Array)] }\nmulti to-matrix (@array) { @array }\n\nsub hilbert-matrix ($h) {\n [ (1..$h).map( -> $n { [ ($n ..^ $n + $h).map: { (1/$_).FatRat } ] } ) ]\n}\n\nmy @tests =\n '1 2 3; 4 1 6; 7 8 9',\n '2 -1 0; -1 2 -1; 0 -1 2',\n '-1 -2 3 2; -4 -1 6 2; 7 -8 9 1; 1 -2 1 3',\n '1 2 3 4; 5 6 7 8; 9 33 11 12; 13 14 15 17',\n '3 1 8 9 6; 6 2 8 10 1; 5 7 2 10 3; 3 2 7 7 9; 3 5 6 1 1',\n\n # Test with a Hilbert matrix\n hilbert-matrix 10;\n\[email protected]: {\n my @matrix = .&to-matrix;\n say_it( \" {'=' x 20} Original Matrix: {'=' x 20}\", @matrix );\n say_it( ' Gauss-Jordan Inverted:', my @invert = gauss-jordan-invert @matrix );\n say_it( ' Re-inverted:', gauss-jordan-invert @invert».Array );\n}\n\n```\n\nOutput:\n\n```\n ==================== Original Matrix: ====================\n 1 2 3\n 4 1 6\n 7 8 9\n\n Gauss-Jordan Inverted:\n -13/16 1/8 3/16\n 1/8 -1/4 1/8\n 25/48 1/8 -7/48\n\n Re-inverted:\n 1 2 3\n 4 1 6\n 7 8 9\n\n ==================== Original Matrix: ====================\n 2 -1 0\n -1 2 -1\n 0 -1 2\n\n Gauss-Jordan Inverted:\n 3/4 1/2 1/4\n 1/2 1 1/2\n 1/4 1/2 3/4\n\n Re-inverted:\n 2 -1 0\n -1 2 -1\n 0 -1 2\n\n ==================== Original Matrix: ====================\n -1 -2 3 2\n -4 -1 6 2\n 7 -8 9 1\n 1 -2 1 3\n\n Gauss-Jordan Inverted:\n -21/23 17/69 13/138 19/46\n -38/23 15/23 1/23 15/23\n -16/23 25/69 11/138 9/46\n -13/23 16/69 -2/69 13/23\n\n Re-inverted:\n -1 -2 3 2\n -4 -1 6 2\n 7 -8 9 1\n 1 -2 1 3\n\n ==================== Original Matrix: ====================\n 1 2 3 4\n 5 6 7 8\n 9 33 11 12\n 13 14 15 17\n\n Gauss-Jordan Inverted:\n 19/184 -199/184 -1/46 1/2\n 1/23 -2/23 1/23 0\n -441/184 813/184 -1/46 -3/2\n 2 -3 0 1\n\n Re-inverted:\n 1 2 3 4\n 5 6 7 8\n 9 33 11 12\n 13 14 15 17\n\n ==================== Original Matrix: ====================\n 3 1 8 9 6\n 6 2 8 10 1\n 5 7 2 10 3\n 3 2 7 7 9\n 3 5 6 1 1\n\n Gauss-Jordan Inverted:\n -4525/6238 2529/6238 -233/3119 1481/3119 -639/6238\n 1033/6238 -1075/6238 342/3119 -447/3119 871/6238\n 1299/6238 -289/6238 -204/3119 -390/3119 739/6238\n 782/3119 -222/3119 237/3119 -556/3119 -177/3119\n -474/3119 -17/3119 -24/3119 688/3119 -140/3119\n\n Re-inverted:\n 3 1 8 9 6\n 6 2 8 10 1\n 5 7 2 10 3\n 3 2 7 7 9\n 3 5 6 1 1\n\n ==================== Original Matrix: ====================\n 1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10\n 1/2 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11\n 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12\n 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13\n 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14\n 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15\n 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16\n 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17\n 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17 1/18\n 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17 1/18 1/19\n\n Gauss-Jordan Inverted:\n 100 -4950 79200 -600600 2522520 -6306300 9609600 -8751600 4375800 -923780\n -4950 326700 -5880600 47567520 -208107900 535134600 -832431600 770140800 -389883780 83140200\n 79200 -5880600 112907520 -951350400 4281076800 -11237826600 17758540800 -16635041280 8506555200 -1829084400\n -600600 47567520 -951350400 8245036800 -37875637800 101001700800 -161602721280 152907955200 -78843164400 17071454400\n 2522520 -208107900 4281076800 -37875637800 176752976400 -477233036280 771285715200 -735869534400 382086104400 -83223340200\n -6306300 535134600 -11237826600 101001700800 -477233036280 1301544644400 -2121035716800 2037792556800 -1064382719400 233025352560\n 9609600 -832431600 17758540800 -161602721280 771285715200 -2121035716800 3480673996800 -3363975014400 1766086882560 -388375587600\n -8751600 770140800 -16635041280 152907955200 -735869534400 2037792556800 -3363975014400 3267861442560 -1723286307600 380449555200\n 4375800 -389883780 8506555200 -78843164400 382086104400 -1064382719400 1766086882560 -1723286307600 912328045200 -202113826200\n -923780 83140200 -1829084400 17071454400 -83223340200 233025352560 -388375587600 380449555200 -202113826200 44914183600\n\n Re-inverted:\n 1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10\n 1/2 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11\n 1/3 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12\n 1/4 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13\n 1/5 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14\n 1/6 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15\n 1/7 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16\n 1/8 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17\n 1/9 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17 1/18\n 1/10 1/11 1/12 1/13 1/14 1/15 1/16 1/17 1/18 1/19\n```" } ]
[ { "role": "user", "content": "Task\n\nSolve   **Ax=b**   using Gaussian elimination then backwards substitution.\n\n**A**   being an   **n** by **n**   matrix.\n\nAlso,   **x** and **b**   are   **n** by **1**   vectors.\n\nTo improve accuracy, please use partial pivoting and scaling.\n\nSee also\n: * the Wikipedia entry:   Gaussian elimination" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nGaussian elimination results in a matrix in row echelon form. Gaussian elimination with back-substitution (also known as Gauss-Jordan elimination) results in a matrix in reduced row echelon form. That being the case, we can reuse much of the code from the Reduced row echelon form task. Raku stores and does calculations on decimal numbers within its limit of precision using Rational numbers by default, meaning the calculations are exact.\n\n```\nsub gauss-jordan-solve (@a, @b) {\n @b.kv.map: { @a[$^k].append: $^v };\n @a.&rref[*]»[*-1];\n}\n\n# reduced row echelon form\nsub rref (@m) {\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n\n for ^$rows -> $r {\n $lead < $cols or return @m;\n my $i = $r;\n until @m[$i;$lead] {\n ++$i == $rows or next;\n $i = $r;\n ++$lead == $cols and return @m;\n }\n @m[$i, $r] = @m[$r, $i] if $r != $i;\n @m[$r] »/=» $ = @m[$r;$lead];\n for ^$rows -> $n {\n next if $n == $r;\n @m[$n] »-=» @m[$r] »×» (@m[$n;$lead] // 0);\n }\n ++$lead;\n }\n @m\n}\n\nsub rat-or-int ($num) {\n return $num unless $num ~~ Rat;\n return $num.narrow if $num.narrow ~~ Int;\n $num.nude.join: '/';\n}\n\nsub say-it ($message, @array, $fmt = \" %8s\") {\n say \"\\n$message\";\n $_».&rat-or-int.fmt($fmt).put for @array;\n}\n\nmy @a = (\n [ 1.00, 0.00, 0.00, 0.00, 0.00, 0.00 ],\n [ 1.00, 0.63, 0.39, 0.25, 0.16, 0.10 ],\n [ 1.00, 1.26, 1.58, 1.98, 2.49, 3.13 ],\n [ 1.00, 1.88, 3.55, 6.70, 12.62, 23.80 ],\n [ 1.00, 2.51, 6.32, 15.88, 39.90, 100.28 ],\n [ 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 ],\n);\nmy @b = ( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 );\n\nsay-it 'A matrix:', @a, \"%6.2f\";\nsay-it 'or, A in exact rationals:', @a;\nsay-it 'B matrix:', @b, \"%6.2f\";\nsay-it 'or, B in exact rationals:', @b;\nsay-it 'x matrix:', (my @gj = gauss-jordan-solve @a, @b), \"%16.12f\";\nsay-it 'or, x in exact rationals:', @gj, \"%28s\";\n\n```\n\nOutput:\n\n```\nA matrix:\n 1.00 0.00 0.00 0.00 0.00 0.00\n 1.00 0.63 0.39 0.25 0.16 0.10\n 1.00 1.26 1.58 1.98 2.49 3.13\n 1.00 1.88 3.55 6.70 12.62 23.80\n 1.00 2.51 6.32 15.88 39.90 100.28\n 1.00 3.14 9.87 31.01 97.41 306.02\n\nor, A in exact rationals:\n 1 0 0 0 0 0\n 1 63/100 39/100 1/4 4/25 1/10\n 1 63/50 79/50 99/50 249/100 313/100\n 1 47/25 71/20 67/10 631/50 119/5\n 1 251/100 158/25 397/25 399/10 2507/25\n 1 157/50 987/100 3101/100 9741/100 15301/50\n\nB matrix:\n -0.01\n 0.61\n 0.91\n 0.99\n 0.60\n 0.02\n\nor, B in exact rationals:\n -1/100\n 61/100\n 91/100\n 99/100\n 3/5\n 1/50\n\nx matrix:\n -0.010000000000\n 1.602790394502\n -1.613203059906\n 1.245494121371\n -0.490989719585\n 0.065760696175\n\nor, x in exact rationals:\n -1/100\n 655870882787/409205648497\n -660131804286/409205648497\n 509663229635/409205648497\n -200915766608/409205648497\n 26909648324/409205648497\n\n```" } ]
[ { "role": "user", "content": "A Gaussian Integer is a complex number such that its real and imaginary parts are both integers.\n\n```\n a + bi where a and b are integers and i is √-1.\n\n```\n\nThe norm of a Gaussian integer is its product with its conjugate.\n\n```\n N(a + bi) = (a + bi)(a − bi) = a² + b²\n\n```\n\nA Gaussian integer is a Gaussian prime if and only if either: both **a** and **b** are non-zero and its **norm** is a prime number, or, one of **a** or **b** is zero and it is the product of a unit **(±1, ±i)** and a prime integer of the form **4n + 3**.\n\nPrime integers that are *not* of the form **4n + 3** can be factored into a Gaussian integer and its complex conjugate so are not a Gaussian prime.\n\n```\n E.G. 5 = (2 + i)(2 − i) So 5 is not a Gaussian prime\n\n```\n\nGaussian primes are octogonally symmetrical on a real / imaginary Cartesian field. If a particular complex norm **a² + b²** is prime, since addition is commutative, **b² + a²** is also prime, as are the complex conjugates and negated instances of both.\n\nTask\n\nFind and show, here on this page, the Gaussian primes with a norm of less than 100, (within a radius of 10 from the origin **0 + 0i** on a complex plane.)\n\nPlot the points corresponding to the Gaussian primes on a Cartesian real / imaginary plane at least up to a radius of 50.\n\nSee also\n\n* Wikipedia: Gaussian integers * Wikipedia: Gaussian primes * OEIS: Gaussian primes" }, { "role": "assistant", "content": "Plotting the points up to a radius of 150.\n\n```\nuse List::Divvy;\n\nmy @next = { :1x, :1y, :2n },;\n\nsub next-interval (Int $int) {\n @next.append: (^$int).map: { %( :x($int), :y($_), :n($int² + .²) ) };\n @next = |@next.sort: *.<n>;\n}\n\nmy @gaussian = lazy gather {\n my $interval = 1;\n loop {\n my @this = @next.shift;\n @this.push: @next.shift while @next and @next[0]<n> == @this[0]<n>;\n for @this {\n .take if .<n>.is-prime || (!.<y> && .<x>.is-prime && (.<x> - 3) %% 4);\n next-interval(++$interval) if $interval == .<x>\n }\n }\n}\n\n# Primes within a radius of 10 from origin\nsay \"Gaussian primes with a norm less than 100 sorted by norm:\";\nsay @gaussian.&before(*.<n> > 10²).map( {\n my (\\i, \\j) = .<x y>;\n flat ((i,j),(-i,j),(-i,-j),(i,-j),(j,i),(-j,i),(-j,-i),(j,-i)).map: {\n .[0] ?? .[1] ?? (sprintf \"%d%s%di\", .[0], (.[1] ≥ 0 ?? '+' !! ''), .[1]) !! .[0] !! \"{.[1]}i\"\n }} )».subst('1i', 'i', :g)».fmt(\"%6s\")».unique.flat.batch(10).join: \"\\n\" ;\n\n\n# Plot points within a 150 radius\nuse SVG;\n\nmy @points = unique flat @gaussian.&before(*.<n> > 150²).map: {\n my (\\i, \\j) = .<x y>;\n do for (i,j),(-i,j),(-i,-j),(i,-j),(j,i),(-j,i),(-j,-i),(j,-i) {\n  :use['xlink:href'=>'#point', 'transform'=>\"translate({500 + 3 × .[0]},{500 + 3 × .[1]})\"]\n }\n}\n\n'gaussian-primes-raku.svg'.IO.spurt: SVG.serialize(\n svg => [\n  :width<1000>, :height<1000>,\n  :rect[:width<100%>, :height<100%>, :style<fill:black;>],\n  :defs[:g[:id<point>, :circle[:0cx, :0cy, :2r, :fill('gold')]]],\n |@points\n ],\n);\n\n```\n\nOutput:\n\n```\nGaussian primes with a norm less than 100 sorted by norm:\n 1+i -1+i -1-i 1-i 2+i -2+i -2-i 2-i 1+2i -1+2i\n -1-2i 1-2i 3 -3 3i -3i 3+2i -3+2i -3-2i 3-2i\n 2+3i -2+3i -2-3i 2-3i 4+i -4+i -4-i 4-i 1+4i -1+4i\n -1-4i 1-4i 5+2i -5+2i -5-2i 5-2i 2+5i -2+5i -2-5i 2-5i\n 6+i -6+i -6-i 6-i 1+6i -1+6i -1-6i 1-6i 5+4i -5+4i\n -5-4i 5-4i 4+5i -4+5i -4-5i 4-5i 7 -7 7i -7i\n 7+2i -7+2i -7-2i 7-2i 2+7i -2+7i -2-7i 2-7i 6+5i -6+5i\n -6-5i 6-5i 5+6i -5+6i -5-6i 5-6i 8+3i -8+3i -8-3i 8-3i\n 3+8i -3+8i -3-8i 3-8i 8+5i -8+5i -8-5i 8-5i 5+8i -5+8i\n -5-8i 5-8i 9+4i -9+4i -9-4i 9-4i 4+9i -4+9i -4-9i 4-9i\n```\n\nOff-site SVG image: gaussian-primes-raku.svg" } ]
[ { "role": "user", "content": "Task\n\nWrite a generalized version of FizzBuzz that works for any list of factors, along with their words.\n\nThis is basically a \"fizzbuzz\" implementation where the user supplies the parameters.\n\nThe user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be printed.\n\nFor simplicity's sake, assume the user will input an integer as the max number and 3 factors, each with a word associated with them.\n\nFor example, given:\n\n```\n>20 #This is the maximum number, supplied by the user\n>3 Fizz #The user now enters the starting factor (3) and the word they want associated with it (Fizz)\n>5 Buzz #The user now enters the next factor (5) and the word they want associated with it (Buzz)\n>7 Baxx #The user now enters the next factor (7) and the word they want associated with it (Baxx)\n\n```\n\nIn other words: For this example, print the numbers **1** through **20**, replacing every multiple of **3** with \"Fizz\", every multiple of **5** with \"Buzz\", and every multiple of **7** with \"Baxx\".\n\nIn the case where a number is a multiple of at least two factors, print each of the words associated with those factors in the order of least to greatest factor.\n\nFor instance, the number **15** is a multiple of both **3** and **5**; print \"FizzBuzz\".\n\nIf the max number was **105** instead of **20**, you would print \"FizzBuzzBaxx\" because it's a multiple of **3**, **5**, and **7**.\n\nOutput:\n\n```\n1\n2\nFizz\n4\nBuzz\nFizz\nBaxx\n8\nFizz\nBuzz\n11\nFizz\n13\nBaxx\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-09-20\n\n```\n# General case implementation of a \"FizzBuzz\" class.\n# Defaults to standard FizzBuzz unless a new schema is passed in.\nclass FizzBuzz {\n has $.schema is rw = < 3 Fizz 5 Buzz >.hash;\n method filter (Int $this) {\n my $fb;\n for $.schema.sort: { +.key } -> $p { $fb ~= $this %% +$p.key ?? $p.value !! ''};\n return $fb || $this;\n }\n}\n\n\n# Sub implementing the specific requirements of the task.\nsub GeneralFizzBuzz (Int $upto, @schema?) {\n my $ping = FizzBuzz.new;\n $ping.schema = @schema.hash if @schema;\n map { $ping.filter: $_ }, 1 .. $upto;\n}\n\n# The task\nsay 'Using: 20 ' ~ <3 Fizz 5 Buzz 7 Baxx>;\n.say for GeneralFizzBuzz(20, <3 Fizz 5 Buzz 7 Baxx>);\n\nsay '';\n\n# And for fun\nsay 'Using: 21 ' ~ <2 Pip 4 Squack 5 Pocketa 7 Queep>;\nsay join ', ', GeneralFizzBuzz(21, <2 Pip 4 Squack 5 Pocketa 7 Queep>);\n\n```\n\nOutput:\n\n```\nUsing: 20 3 Fizz 5 Buzz 7 Baxx\n1\n2\nFizz\n4\nBuzz\nFizz\nBaxx\n8\nFizz\nBuzz\n11\nFizz\n13\nBaxx\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n\nUsing: 21 2 Pip 4 Squack 5 Pocketa 7 Queep\n1, Pip, 3, PipSquack, Pocketa, Pip, Queep, PipSquack, 9, PipPocketa, 11, PipSquack, 13, PipQueep, Pocketa, PipSquack, 17, Pip, 19, PipSquackPocketa, Queep\n```\n\nHere's the same program in a more functional idiom:\n\n```\nsub genfizzbuzz($n, +@fb) {\n [Z~](\n do for @fb || <3 fizz 5 buzz> -> $i, $s {\n flat ('' xx $i-1, $s) xx *;\n }\n ) Z|| 1..$n\n}\n\n.say for genfizzbuzz(20, <3 Fizz 5 Buzz 7 Baxx>);\n\n```" } ]
[ { "role": "user", "content": "It is possible to implement floating point arithmetic in many different ways; though the standard IEEE arithmetic implementation on modern hardware usually uses a fixed-width binary implementation (using a total of 32 bits for single-precision floats — `float` in a number of languages — and 64 bits for double-precision floats — `double`) many other schemes can be used. For example, the base need not be binary (alternatives include decimal, binary-coded decimal, and even balanced ternary) and there is no requirement that a fixed number of digits be used.\n\nDefine addition for floating point numbers where the digits are stored in an arbitrary base; e.g. the digits can be stored as binary, decimal, binary-coded decimal, or even balanced ternary.\nYou should implement the code in a generalised form (such as a Template, Module or Mixin etc) that permits reusing of the code for different Bases.\n\nIf it is not possible to implement code by providing an implementation that uses the *syntax* of the specific language then:\n\n* Note the reason why this is.\n* Demonstrate that the language still supports the semantics of generalised floating point by implementing the *test case* using built-in code or a library.\n\n**Test case:**\n\nDefine arbitrary precision addition on floating point numbers (e.g., encoding those numbers using Binary Coded Decimal, or using an arbitrary precision integer arithmetic library). Calculate the terms for -7 to 21 in this sequence of calculations:\n\nCalculate the terms for -7 to 21 in this sequence of calculations\n\n| Number | Term calculation | Result |\n| --- | --- | --- |\n| -7 | 12345679e63 × 81 + 1e63 | 1e72 |\n| -6 | 12345679012345679e54 × 81 + 1e54 | 1e72 |\n| -5 | 12345679012345679012345679e45 × 81 + 1e45 | 1e72 |\n| -4 | 12345679012345679012345679012345679e36 × 81 + 1e36 | 1e72 |\n| etc. | The final calculation will be over 256 digits wide | 1e72 |\n\nYou will either need to implement multiplication, or perform the multiplication by 81 by using repeated additions. The results will always be 1e72.\n\nBonus\n\nMake the template (module, class, mixing, etc.) able to successfully handle using other bases to perform the above test case. Demonstrate using balanced ternary." }, { "role": "assistant", "content": "(formerly Perl 6)\nAs long as all values are kept as rationals (type `Rat`) calculations are done full precision.\n\n```\nmy $e = 63;\nfor -7..21 -> $n {\n my $num = '12345679' ~ '012345679' x ($n+7);\n my $sum = $_ + ($num * $_) * 81 given $e > -20 ?? 10**$e !! Rat.new(1,10**abs $e);\n printf \"$n:%s \", 10**72 == $sum ?? 'Y' !! 'N';\n $e -= 9;\n}\n\n```\n\nOutput:\n\n```\n-7:Y -6:Y -5:Y -4:Y -3:Y -2:Y -1:Y 0:Y 1:Y 2:Y 3:Y 4:Y 5:Y 6:Y 7:Y 8:Y 9:Y 10:Y 11:Y 12:Y 13:Y 14:Y 15:Y 16:Y 17:Y 18:Y 19:Y 20:Y 21:Y\n\n```" } ]
[ { "role": "user", "content": "**Chess960** is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n + the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n + the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\nWith those constraints there are **960** possible starting positions, thus the name of the variant.\n\nTask\n\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed using either the chess symbols in Unicode (♔♕♖♗♘), the letters **K**ing **Q**ueen **R**ook **B**ishop k**N**ight, or the corresponding letters in a language other than English." }, { "role": "assistant", "content": "(formerly Perl 6)\nFirst, using a list with three rooks and no king, we keep generating a random piece order until the two bishops are on opposite colors. Then we sneakily promote the second of the three rooks to a king.\n\n```\nrepeat until m/ '♗' [..]* '♗' / { $_ = < ♖ ♖ ♖ ♕ ♗ ♗ ♘ ♘ >.pick(*).join }\ns:2nd['♖'] = '♔';\nsay .comb;\n\n```\n\nOutput:\n\n```\n♕ ♗ ♖ ♘ ♔ ♖ ♗ ♘\n```\n\nHere's a more \"functional\" solution that avoids side effects\n\n```\nsub chess960 {\n .subst(:nth(2), /'♜'/, '♚') given\n first rx/ '♝' [..]* '♝' /,\n < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.pick(*).join xx *;\n}\n\nsay chess960;\n\n```\n\nOutput:\n\n```\n♛♝♜♚♝♞♞♜\n```\n\nWe can also pregenerate the list of 960 positions, though the method we use below is a bit wasteful, since it\ngenerates 40320 candidates only to throw most of them away. This is essentially the same filtering algorithm\nbut written in the form of a list comprehension rather than nested map and grep. (The list comprehension is actually faster currently.) Note that the constant is calculated at compile time, because, well, it's a constant. Just a big fancy one.\n\n```\nconstant chess960 =\n < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚');\n\n.say for chess960;\n\n```\n\nHere's a much faster way (about 30x) to generate all 960 variants by construction. No need to filter for uniqueness, since it produces exactly 960 entries.\n\n```\nconstant chess960 = gather for 0..3 -> $q {\n (my @q = <♜ ♚ ♜>).splice($q, 0, '♛');\n for 0 .. @q -> $n1 {\n (my @n1 = @q).splice($n1, 0, '♞');\n for $n1 ^.. @n1 -> $n2 {\n (my @n2 = @n1).splice($n2, 0, '♞');\n for 0 .. @n2 -> $b1 {\n (my @b1 = @n2).splice($b1, 0, '♝');\n for $b1+1, $b1+3 ...^ * > @b1 -> $b2 {\n (my @b2 = @b1).splice($b2, 0, '♝');\n take @b2.join;\n }\n }\n }\n }\n}\n\nCHECK { note \"done compiling\" }\nnote +chess960;\nsay chess960.pick;\n\n```\n\nOutput:\n\n```\ndone compiling\n960\n♜♚♝♜♞♛♞♝\n```\n\nIf you run this you'll see that most of the time is spent in compilation, so in the case of separate precompilation the table of 960 entries merely needs to be deserialized back into memory. Picking from those entries guarantees uniform distribution over all possible boards.\n\n```\n♛♝♜♚♝♞♞♜\n```\n\n### Raku: Generate from SP-ID\n\nThere is a standard numbering scheme for Chess960 positions, assigning each an index in the range 0..959. This function will generate the corresponding position from a given index number (or fall back to a random one if no index is specified, making it yet another solution to the general problem).\n\n```\nsubset Pos960 of Int where { $_ ~~ ^960 };\nsub chess960(Pos960 $position = (^960).pick) {\n\n # We remember the remainder used to place first bishop in order to place the\n # second\n my $b1;\n \n # And likewise remember the chosen combination for knights between those\n # placements\n my @n;\n \n # Piece symbols and positioning rules in order. Start with the position\n # number. At each step, divide by the divisor; the quotient becomes the\n # dividend for the next step. Feed the remainder into the specified code block\n # to get a space number N, then place the piece in the Nth empty space left in\n # the array.\n my @rules = (\n #divisor, mapping function, piece\n ( 4, { $b1 = $_; 2 * $_ + 1 }, '♝' ),\n ( 4, { 2 * $_ - ($_ > $b1 ?? 1 !! 0) }, '♝' ),\n ( 6, { $_ }, '♛' ),\n (10, { @n = combinations(5,2)[$_]; @n[0] }, '♞' ),\n ( 1, { @n[1]-1 }, '♞' ),\n ( 1, { 0 }, '♜' ),\n ( 1, { 0 }, '♚' ),\n ( 1, { 0 }, '♜' )\n \n );\n \n # Initial array, using '-' to represent empty spaces\n my @array = «-» xx 8;\n \n # Working value that starts as the position number but is divided by the\n # divisor at each placement step.\n my $p = $position;\n \n # Loop over the placement rules\n for @rules -> ($divisor, $block, $piece) {\n \n # get remainder when divided by divisor\n (my $remainder, $p) = $p.polymod($divisor);\n \n # apply mapping function\n my $space = $block($remainder);\n \n # find index of the $space'th element of the array that's still empty\n my $index = @array.kv.grep(-> $i,$v { $v eq '-' })[$space][0];\n \n # and place the piece\n @array[$index] = $piece;\n }\n return @array;\n}\n\n# demo code\nsay chess960(518); #standard optning position\nsay chess960; # (it happened to pick #300)\n\n```\n\nOutput:\n\n```\n♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜\n♛ ♝ ♞ ♜ ♚ ♜ ♝ ♞\n```" } ]
[ { "role": "user", "content": "Task\n\nGenerate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence.\n\nFor this basic task use a reliable style of coding, a style fit for a very large program, and use strong typing if available. It's bug prone to enumerate all the lowercase characters manually in the code.\n\nDuring code review it's not immediate obvious to spot the bug in a Tcl line like this contained in a page of code:\n\n```\nset alpha {a b c d e f g h i j k m n o p q r s t u v w x y z}\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-10-21\n\n```\nsay my @letters = 'a'..'z';\n```\n\n* `'a'..'z'` is a range literal, it constructs an immutable `Range` object.\n* Assigning to an `@` variable flattens it into an `Array`." } ]
[ { "role": "user", "content": "Task\n\nGenerate a random chess position in FEN format.\n\nThe position does not have to be realistic or even balanced,  but it must comply to the following rules:\n\n: * there is one and only one king of each color  (one black king and one white king);\n * the kings must not be placed on adjacent squares;\n * there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank);\n * including the kings, up to 32 pieces of either color can be placed.\n * There is no requirement for material balance between sides.\n * The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.\n * it is white's turn.\n * It's assumed that both sides have lost castling rights and that there is no possibility for   *en passant*   (the FEN should thus end in w - - 0 1).\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub pick-FEN {\n # First we chose how many pieces to place\n my $n = (2..32).pick;\n\n # Then we pick $n squares\n my @n = (^64).pick($n);\n\n # We try to find suitable king positions on non-adjacent squares.\n # If we could not find any, we return recursively\n return pick-FEN() unless\n my @kings[2] = first -> [$a, $b] {\n $a !== $b && abs($a div 8 - $b div 8) | abs($a mod 8 - $b mod 8) > 1\n }, (@n X @n);\n\n # We make a list of pieces we can pick (apart from the kings)\n my @pieces = <p P n N b B r R q Q>;\n\n # We make a list of two king symbols to pick randomly a black or white king\n my @k = <K k>.pick(*);\n\n return (gather for ^64 -> $sq {\n if $sq == @kings.any { take @k.shift }\n elsif $sq == @n.any {\n my $row = 7 - $sq div 8;\n take\n $row == 7 ?? @pieces.grep(none('P')).pick !!\n $row == 0 ?? @pieces.grep(none('p')).pick !!\n @pieces.pick;\n }\n else { take 'ø' }\n }).rotor(8)».join».subst(/ø+/,{ .chars }, :g).join('/') ~ ' w - - 0 1';\n}\n\nsay pick-FEN();\n\n```\n\nOutput:\n\n```\nq2n1n2/1Qpk3Q/1r3bP1/1b1b4/2pRBR2/4P1bN/2R3K1/N1r2rPB w - - 0 1\n```" } ]
[ { "role": "user", "content": "Many puzzle games such as the 15 puzzle game need a way to randomize the order of the pieces. One way to do this is to create an array and fill it with random values, with each element's index in that array being its position. Unfortunately, most random number generators can produce the same value more than once, which in this case isn't what we want.\n\nTask\n\nCreate a random number generator and have it output the numbers 1 through 20 (inclusive), in a random order. It cannot produce the same value more than once.\n\nOr\n\nGiven the output of an existing random number generator that *does* produce repeated output, create a function that constrains the output to numbers 1 through 20 (inclusive), and no number is output more than once. (Technically it stops being \"random\" at that point, but that's beyond the scope of this task.) Try your best not to make the process take too long at runtime.\n\nFor the second version of the task, the random number generator itself need not be implemented; however you must specify its possible range of values before your constraint function is applied. (e.g \"Assume the random number generator creates a value from 0 to 255, and values are allowed to repeat\")\n\nRelated Tasks\n: * 15 Puzzle Solver\n * 16 Puzzle Game\n * Random numbers" }, { "role": "assistant", "content": "Raku has three distinct \"random\" functions built in. rand() for when you want some fraction between 0 and 1. roll() when you want to select elements from a collection with replacement (rolls of a die). And pick() for when you want to select some elements from a collection *without* replacement. (pick a card, any card, or two cards or 10 cards...). If you want to select *all* the elements in random order, just pick 'whatever'. Here we'll pick all from 1 to 20, 5 times using the repetition operator.\n\nPick random elements *without* replacement\n\n```\n.put for (1..20).pick(*) xx 5\n\n```\n\nSample output:\n\n```\n20 4 5 7 15 19 2 16 8 6 3 12 14 13 10 18 9 17 1 11\n4 5 18 10 13 3 1 11 6 2 19 8 12 7 16 17 14 20 15 9\n14 8 15 11 17 4 3 10 18 7 16 13 1 20 12 9 6 5 19 2\n7 5 15 11 12 18 17 3 20 6 13 19 14 2 16 10 4 9 8 1\n19 12 4 7 3 20 13 17 5 8 6 15 10 18 1 11 2 14 16 9\n```\n\nPick random elements *with* replacement\n\n```\n.put for (1..20).roll(20) xx 5\n\n```\n\nSample output:\n\n```\n16 20 15 17 13 4 19 1 3 8 4 12 13 4 4 5 14 17 10 14\n12 6 8 8 9 6 2 4 16 8 4 3 14 8 19 20 5 12 7 15\n20 4 20 16 14 6 15 15 16 18 5 19 20 3 14 11 2 7 13 12\n3 19 11 13 9 4 5 11 2 20 16 17 14 18 12 10 4 1 13 2\n17 20 12 17 19 4 20 20 14 8 2 19 2 12 18 14 4 14 10 8\n```" } ]
[ { "role": "user", "content": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n\nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”.\n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\nTask\n\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n\n: : : * Squares.\n * Cubes.\n\n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\nNote that this task *requires* the use of generators in the calculation of the result.\n\nAlso see\n\n* Generator" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nAs with Haskell, generators are disguised as lazy lists in Raku.\n\n```\nsub powers($m) { 0..* X** $m }\n\nmy @squares = powers(2);\nmy @cubes = powers(3);\n\nsub infix:<with-out> (@orig, @veto) {\n gather for @veto -> $veto {\n take @orig.shift while @orig[0] before $veto;\n @orig.shift if @orig[0] eqv $veto;\n }\n}\n\nsay (@squares with-out @cubes)[20 ..^ 20+10].join(', ');\n\n```\n\nOutput:\n\n```\n529, 576, 625, 676, 784, 841, 900, 961, 1024, 1089\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.\n\nIf your solution language is statically typed please describe the way your language provides genericity.\n\nIf variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation.\nThat is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.\n\nGeneric swap is a task which brings together a few separate issues in programming language semantics.\n\nDynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.\n\nFunctional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.\n\nSome static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).\n\nDo your best!" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nSimilar to Perl 5. Raku supports type constraints for variables and subroutines, unlike Perl 5, but the default is still to permit all values.\n\nAlternatively, you can write it like this:\n\n```\n($x, $y) .= reverse;\n```" } ]
[ { "role": "user", "content": "Geohashes are used to represent standard latitude and longitude coordinates as single values in the form of a simple string -- using the digits (0-9) and the letters (B-Z excluding I, L, O). They can vary in length, with more characters in the string representing more precision.\n\nTask\n\nGenerate a Geohash with a desired precision from a coordinate represented as an array of two floating point numbers, latitude and longitude. (Ideally double precision).\n\n**Example 1:**\n: print (encodeGeohash (for: [51.433718, -0.214126], withPrecision: 2))\n: // Result: \"gc\" (all of Ireland, most of England and Wales, small part of Scotland)\n\n**Example 2:**\n: print (encodeGeohash (for: [51.433718, -0.214126], withPrecision: 9))\n: // Result: \"gcpue5hp4\" (the umpire's chair on Center Court at Wimbledon)\n\nFrom the Wikipedia page, geohashes can be \"useful in database systems where queries on a single index are much easier or faster than multiple-index queries.\"\n\nExtra credit\n\nProvide a decode function to convert a geohash code back to latitude and longitude, expressed either as ranges or in median +/- deviation format.\n\nReference\n\n* Wikipedia article - Geohash." }, { "role": "assistant", "content": "### Module based\n\nReference: Used this for verification.\n\n```\n#20200615 Raku programming solution\n\nuse Geo::Hash;\n\n# task example 1 : Ireland, most of England and Wales, small part of Scotland\nsay geo-encode(51.433718e0, -0.214126e0, 2);\n\n# task example 2 : the umpire's chair on Center Court at Wimbledon\nsay geo-encode(51.433718e0, -0.214126e0, 9);\n\n# Lake Raku is an artificial lake in Tallinn, Estonia\n# https://goo.gl/maps/MEBXXhiFbN8WMo5z8\nsay geo-encode(59.358639e0, 24.744778e0, 4);\n\n# Village Raku is a development committee in north-western Nepal\n# https://goo.gl/maps/33s7k2h3UrHCg8Tb6\nsay geo-encode(29.2021188e0, 81.5324561e0, 4);\n\n```\n\nOutput:\n\n```\ngc\ngcpue5hp4\nud99\ntv1y\n\n```\n\n### Roll your own\n\nAlternately, a roll-your-own version that will work with any Real coordinate, not just floating point values, and thus can return ridiculous precision.\nThe geo-decode routine returns the range in which the actual value will be found; converted here to the mid-point with the interval size. Probably better\nto specify an odd precision so the error interval ends up the same for both latitude and longitude.\n\n```\nmy @Geo32 = <0 1 2 3 4 5 6 7 8 9 b c d e f g h j k m n p q r s t u v w x y z>;\n\nsub geo-encode ( Rat(Real) $latitude, Rat(Real) $longitude, Int $precision = 9 ) {\n my @coord = $latitude, $longitude;\n my @range = [-90, 90], [-180, 180];\n my $which = 1;\n my $value = '';\n while $value.chars < $precision * 5 {\n my $mid = @range[$which].sum / 2;\n $value ~= my $upper = +(@coord[$which] > $mid);\n @range[$which][not $upper] = $mid;\n $which = not $which;\n }\n @Geo32[$value.comb(5)».parse-base(2)].join;\n}\n\nsub geo-decode ( Str $geo ) {\n my @range = [-90, 90], [-180, 180];\n my $which = 1;\n my %Geo32 = @Geo32.antipairs;\n for %Geo32{$geo.comb}».fmt('%05b').join.comb {\n @range[$which][$_] = @range[$which].sum / 2;\n $which = not $which;\n }\n @range\n}\n\n# TESTING\n\nfor 51.433718, -0.214126, 2, # Ireland, most of England and Wales, small part of Scotland\n 51.433718, -0.214126, 9, # the umpire's chair on Center Court at Wimbledon\n 51.433718, -0.214126, 17, # likely an individual molecule of the chair\n 57.649110, 10.407440, 11, # Wikipedia test value - Råbjerg Mile in Denmark\n 59.358639, 24.744778, 7, # Lake Raku in Estonia\n 29.2021188, 81.5324561, 7 # Village Raku in Nepal\n -> $lat, $long, $precision {\n say \"$lat, $long, $precision:\\ngeo-encoded: \",\n my $enc = geo-encode $lat, $long, $precision;\n say 'geo-decoded: ', geo-decode($enc).map( {-.sum/2 ~ ' ± ' ~\n (abs(.[0]-.[1])/2).Num.fmt('%.3e')} ).join(', ') ~ \"\\n\";\n}\n\n```\n\n```\n51.433718, -0.214126, 2:\ngeo-encoded: gc\ngeo-decoded: 53.4375 ± 2.813e+00, -5.625 ± 5.625e+00\n\n51.433718, -0.214126, 9:\ngeo-encoded: gcpue5hp4\ngeo-decoded: 51.4337182 ± 2.146e-05, -0.21412611 ± 2.146e-05\n\n51.433718, -0.214126, 17:\ngeo-encoded: gcpue5hp4ebnf8unc\ngeo-decoded: 51.43371800000523 ± 2.046e-11, -0.21412600000303 ± 2.046e-11\n\n57.64911, 10.40744, 11:\ngeo-encoded: u4pruydqqvj\ngeo-decoded: 57.64911063 ± 6.706e-07, 10.407439694 ± 6.706e-07\n\n59.358639, 24.744778, 7:\ngeo-encoded: ud99ejf\ngeo-decoded: 59.358444 ± 6.866e-04, 24.744644 ± 6.866e-04\n\n29.2021188, 81.5324561, 7:\ngeo-encoded: tv1ypk4\ngeo-decoded: 29.202347 ± 6.866e-04, 81.532974 ± 6.866e-04\n\n```" } ]
[ { "role": "user", "content": "**Geometric algebra** is another name for Clifford algebras and it's basically an algebra containing a vector space \n\nV\n{\\displaystyle {\\displaystyle {\\mathcal {V}}}}\n and obeying the following axioms:\n\n: (\n a\n b\n )\n c\n =\n a\n (\n b\n c\n )\n\n\n a\n (\n b\n +\n c\n )\n =\n a\n b\n +\n a\n c\n\n\n (\n a\n +\n b\n )\n c\n =\n a\n c\n +\n b\n c\n\n\n ∀\n\n x\n ∈\n\n\n V\n ,\n\n x\n\n 2\n ∈\n\n R\n {\\displaystyle {\\displaystyle {\\begin{array}{c}(ab)c=a(bc)\\\\a(b+c)=ab+ac\\\\(a+b)c=ac+bc\\\\\\forall \\mathbf {x} \\in {\\mathcal {V}},\\,\\mathbf {x} ^{2}\\in \\mathbb {R} \\end{array}}}}\n\nThe product operation in such algebra is called the *geometric product*. Elements are called *multivectors*, while multivectors in \n\nV\n{\\displaystyle {\\displaystyle {\\mathcal {V}}}}\n are just called *vectors*.\n\nThere are a few simple examples of geometric algebras. A trivial one for instance is simply \n\nR\n{\\displaystyle {\\displaystyle \\mathbb {R} }}\n, where \n\nV\n=\n\nR\n{\\displaystyle {\\displaystyle {\\mathcal {V}}=\\mathbb {R} }}\n. The complex numbers also form a geometric algebra, where the vector space is the one-dimensional space of all purely imaginary numbers. Another example is the space of quaternions, where the vector space is the three-dimensional space of all linear combinations of \n\n(\ni\n,\nj\n,\nk\n)\n{\\displaystyle {\\displaystyle (i,j,k)}}\n.\n\nThe purpose of this task is to implement a geometric algebra with a vector space \n\nV\n{\\displaystyle {\\displaystyle {\\mathcal {V}}}}\n of dimension *n* of at least five, but for extra-credit you can implement a version with *n* arbitrary large. Using a dimension five is useful as it is the dimension required for the so-called *conformal model* which will be the subject of a derived task.\n\nTo ensure the unicity of the solution (that is, up to some isomorphism), we will also restrict ourselves to the so-called euclidean case, where the square of a non-zero vector is positive:\n\n∀\n\nx\n∈\n\n\nV\n,\n\n\nx\n≠\n0\n\n⟹\n\nx\n\n2\n>\n0\n{\\displaystyle {\\displaystyle \\forall \\mathbf {x} \\in {\\mathcal {V}},\\,\\mathbf {x} \\neq 0\\implies \\mathbf {x} ^{2}>0}}\n.\n\nYou can of course, for extra credit, implement the general case. This would require the definition of a parameter for the *signature* of the metric.\n\nIn order to show that your solution uses a vector space of dimension at least five, you will create a function n -> e(n) such that the vectors e(0), e(1), e(2), e(3), e(4) are linearly independent. To do so you will make them orthonormal with the following scalar product:\n\nx\n⋅\n\ny\n=\n(\n\nx\n\ny\n+\n\ny\n\nx\n)\n\n/\n2\n{\\displaystyle {\\displaystyle \\mathbf {x} \\cdot \\mathbf {y} =(\\mathbf {x} \\mathbf {y} +\\mathbf {y} \\mathbf {x} )/2}}\n\nThe fact that this so-called *inner product* defines a scalar product is a consequence of the fourth axiom. To see it one just needs to notice the relation:\n\nx\n\ny\n+\n\ny\n\nx\n=\n(\n\nx\n+\n\ny\n\n)\n\n2\n−\n\n\nx\n\n2\n−\n\n\ny\n\n2\n{\\displaystyle {\\displaystyle \\mathbf {x} \\mathbf {y} +\\mathbf {y} \\mathbf {x} =(\\mathbf {x} +\\mathbf {y} )^{2}-\\mathbf {x} ^{2}-\\mathbf {y} ^{2}}}\n\nOnce you'll have shown that your vector space is at least of dimension five, you will show that the axioms are satisfied. For this purpose you will pick three random multivectors *a*, *b* and *c*, along with a random vector \n\nx\n{\\displaystyle {\\displaystyle \\mathbf {x} }}\n.\n\nProducing a random vector is easy. Just use a pseudo-random generation function rand and create a vector:\n\nr\na\nn\nd\no\nm\nV\ne\nc\nt\no\nr\n(\n)\n=\n\n∑\n\ni\n=\n0\n\n4\n\nr\na\nn\nd\n(\n)\n\n\ne\n\ni\n{\\displaystyle {\\displaystyle \\mathrm {randomVector} ()=\\sum \\_{i=0}^{4}\\mathrm {rand} ()\\mathbf {e} \\_{i}}}\n\nProducing a random multivector is slightly more involved. It is known that when the dimension of \n\nV\n{\\displaystyle {\\displaystyle {\\mathcal {V}}}}\n is *n*, then the dimension of the algebra (seen as a vector space with its natural scalar multiplication) is 2n. This means that for n=5 there is a basis of 25 = 32 basis multivectors from which any multivector can be written as a linear combination. Create such a basis \n\nm\n\n0\n,\n\nm\n\n1\n,\n…\n,\n\nm\n\n31\n{\\displaystyle {\\displaystyle m\\_{0},m\\_{1},\\ldots ,m\\_{31}}}\n along with a function producting a random multivector:\n\nr\na\nn\nd\no\nm\nM\nu\nl\nt\ni\nv\ne\nc\nt\no\nr\n(\n)\n=\n\n∑\n\ni\n=\n0\n\n31\n\nr\na\nn\nd\n(\n)\n\nm\n\ni\n{\\displaystyle {\\displaystyle \\mathrm {randomMultivector} ()=\\sum \\_{i=0}^{31}\\mathrm {rand} ()m\\_{i}}}\n\nTo summarize, to solve this task you will:\n\n* define the inner product of two vectors : \n\n x\n ⋅\n\n y\n =\n (\n\n x\n y\n +\n\n y\n x\n )\n\n /\n 2\n {\\displaystyle {\\displaystyle \\mathbf {x} \\cdot \\mathbf {y} =(\\mathbf {xy} +\\mathbf {yx} )/2}}\n .\n* define the function e\n* verify the orthonormality \n\n e\n\n i\n ⋅\n\n\n e\n\n j\n =\n\n δ\n\n i\n ,\n j\n {\\displaystyle {\\displaystyle \\mathbf {e} \\_{i}\\cdot \\mathbf {e} \\_{j}=\\delta \\_{i,j}}}\n for i, j in \n\n {\n 0\n ,\n 1\n ,\n 2\n ,\n 3\n ,\n 4\n }\n {\\displaystyle {\\displaystyle \\{0,1,2,3,4\\}}}\n .\n* create a function returning a random multivector\n* create a function returning a random vector\n* verify the axioms for three rarndom multivectors *a*, *b*, *c* and a random vector **x**.\n\nOptionally, you will repeat the last step a large number of times, in order to increase confidence in the result." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nHere we write a simplified version of the Clifford module. It is very general as it is of infinite dimension and also contains an anti-euclidean basis @ē in addition to the euclidean basis @e.\n\n```\nclass MultiVector is Mix {\n subset Vector of ::?CLASS is export where *.grades.all == 1;\n\n method narrow { self.keys.any > 0 ?? self !! (self{0} // 0) }\n method grades { self.keys.map: *.base(2).comb.sum }\n\n multi method new(Real $x) returns ::?CLASS { self.new-from-pairs: 0 => $x }\n multi method new(Str $ where /^^e(\\d+)$$/) { self.new-from-pairs: (1 +< (2*$0)) => 1 }\n\n our @e is export = map { ::?CLASS.new: \"e$_\" }, ^Inf;\n\n my sub order(UInt:D $i is copy, UInt:D $j) {\n (state %){$i}{$j} //= do {\n my $n = 0;\n repeat {\n\t$i +>= 1;\n\t$n += [+] ($i +& $j).polymod(2 xx *);\n } until $i == 0;\n $n +& 1 ?? -1 !! 1;\n }\n }\n\n sub infix:<·>(Vector $x, Vector $y) returns Real is export { (($x*$y + $y*$x)/2){0} }\n \n multi infix:<+>(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export {\n return ::?CLASS.new-from-pairs: |$A.pairs, |$B.pairs;\n }\n multi infix:<+>(Real $s, ::?CLASS $B) returns ::?CLASS is export {\n samewith $B.new($s), $B\n }\n multi infix:<+>(::?CLASS $A, Real $s) returns ::?CLASS is export {\n samewith $s, $A\n }\n\n multi infix:<*>(::?CLASS $, 0) is export { 0 }\n multi infix:<*>(::?CLASS $A, 1) returns ::?CLASS is export { $A }\n multi infix:<*>(::?CLASS $A, Real $s) returns ::?CLASS is export {\n  ::?CLASS.new-from-pairs: $A.pairs.map({Pair.new: .key, $s*.value})\n }\n multi infix:<*>(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export {\n ::?CLASS.new-from-pairs: gather\n for $A.pairs -> $a {\n\tfor $B.pairs -> $b {\n\t take ($a.key +^ $b.key) => [*]\n\t $a.value, $b.value,\n\t order($a.key, $b.key),\n\t |grep +*, (\n\t\t|(1, -1) xx * Z*\n\t\t($a.key +& $b.key).polymod(2 xx *)\n\t )\n\t}\n }\n }\n multi infix:<**>(::?CLASS $ , 0) returns ::?CLASS is export { ::?CLASS.new: (0 => 1).Mix }\n multi infix:<**>(::?CLASS $A, 1) returns ::?CLASS is export { $A }\n multi infix:<**>(::?CLASS $A, 2) returns ::?CLASS is export { $A * $A }\n multi infix:<**>(::?CLASS $A, UInt $n where $n %% 2) returns ::?CLASS is export { ($A ** ($n div 2)) ** 2 }\n multi infix:<**>(::?CLASS $A, UInt $n) returns ::?CLASS is export { $A * ($A ** ($n div 2)) ** 2 }\n\n multi infix:<*>(Real $s, ::?CLASS $A) returns ::?CLASS is export { $A * $s }\n multi infix:</>(::?CLASS $A, Real $s) returns ::?CLASS is export { $A * (1/$s) }\n multi prefix:<->(::?CLASS $A) returns ::?CLASS is export { return -1 * $A }\n multi infix:<->(::?CLASS $A, ::?CLASS $B) returns ::?CLASS is export { $A + -$B }\n multi infix:<->(::?CLASS $A, Real $s) returns ::?CLASS is export { $A + -$s }\n multi infix:<->(Real $s, ::?CLASS $A) returns ::?CLASS is export { $s + -$A }\n\n multi infix:<==>(::?CLASS $A, 0) returns Bool is export { $A.elems == 0 }\n multi infix:<==>(::?CLASS $A, ::?CLASS $B) returns Bool is export { samewith $A - $B, 0 }\n multi infix:<==>(Real $x, ::?CLASS $A) returns Bool is export { samewith $A, $x }\n multi infix:<==>(::?CLASS $A, Real $x) returns Bool is export { samewith $A, $A.new($x); }\n\n sub random is export {\n [+] map {\n\t ::?CLASS.new-from-pairs: $_ => rand.round(.01)\n }, ^32;\n }\n}\n\n#########################################\n## Test code to verify the solution: ##\n#########################################\n\nimport MultiVector;\nuse Test;\n \nconstant N = 10;\nplan 5;\n \nsubtest \"Orthonormality\", {\n for ^N X ^N -> ($i, $j) {\n my $s = $i == $j ?? 1 !! 0;\n ok @e[$i]·@e[$j] == $s, \"e$i·e$j = $s\";\n }\n}\n \nmy ($a, $b, $c) = random() xx 3;\n \nok ($a*$b)*$c == $a*($b*$c), 'associativity';\nok $a*($b + $c) == $a*$b + $a*$c, 'left distributivity';\nok ($a + $b)*$c == $a*$c + $b*$c, 'right distributivity';\nmy @coeff = (.5 - rand) xx 5;\nmy $v = [+] @coeff Z* @e[^5];\nok ($v**2).narrow ~~ Real, 'contraction';\n\n```" } ]
[ { "role": "user", "content": "Task\n\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).\n\nRelated task\n\n* Execute a system command" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nIf you don't want to execute it in shell (and you probably don't), then use this:\n\n```\nsay run($command, $arg1, $arg2, :out).out.slurp;\n\n```\n\nUnfortunately, it is very long to type, but that is the only way to pass your variables as arguments safely.\n\nYou might be tempted to start using shell when you have to pipe something, but even in that case there is no need to do so. See this code:\n\n```\nmy $p1 = run 'echo', 'Hello, world', :out;\nmy $p2 = run 'cat', '-n', :in($p1.out), :out;\nsay $p2.out.slurp-rest;\n\n```\n\nSee docs for more info.\n\nIf you really want to run something in shell and you understand potential security problems, then you can use `qx//` (interpolates environment variables) or `qqx//` (interpolates normally). See the docs for more info.\n\n```\nsay qx[dir]\n\n```\n\nOutput:\n\n```\nFind_URI_in_text.p6 History_variables.p6 K-d_tree.pl\nFractran.pl\t History_variables.pl XML_Input.p6\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program (function) to get the number of decimal places in a given number.\n\nExamples\n: * for num = 12.345         decimals = 3,     and\n * for num = 12.3450       decimals = 4\n\n(Note that the reference implementation – in the **Ring** language – shows a function over a given **number** rather than a given numeric string, and that the sample values shown above are not enclosed in quotes)." }, { "role": "assistant", "content": "**Works with**: Rakudo version 2020.07\n\nRaku does not specifically have a \"decimal\" number type, however we can\neasily determine the fractional precision of a rational number. It is somewhat\ntouchy-feely for floating point numbers; (what is the fractional precision for\n2.45e-12?), it's pretty pointless for Integers; (zero, aalllways zero...), but\nRats (rationals) are doable. Note that these are (mostly) actual numerics, not\nnumeric strings. The exception is '12.3450'. That is a numeric string since\nactual numerics automatically truncate non-significant trailing zeros. If you\nwant to retain them, you need to pass the value as a string. (As below.)\n\n```\nuse Rat::Precise;\n\nprintf \"Fractional precision: %-2s || Number: %s\\n\", (.split('.')[1] // '').chars, $_\n for 9, 12.345, '12.3450', 0.1234567890987654321, (1.5**63).precise;\n\n```\n\nOutput:\n\n```\nFractional precision: 0 || Number: 9\nFractional precision: 3 || Number: 12.345\nFractional precision: 4 || Number: 12.3450\nFractional precision: 19 || Number: 0.1234567890987654321\nFractional precision: 63 || Number: 124093581919.648947697827373650380188008224280338254175148904323577880859375\n```" } ]
[ { "role": "user", "content": "Definition\n\nA **Giuga number** is a composite number **n** which is such that each of its distinct prime factors\n**f** divide (n/f - 1) exactly.\n\nAll known Giuga numbers are even though it is not known for certain that there are no odd examples.\n\nExample\n\n30 is a Giuga number because its distinct prime factors are 2, 3 and 5 and:\n\n* 30/2 - 1 = 14 is divisible by 2\n* 30/3 - 1 = 9 is divisible by 3\n* 30/5 - 1 = 5 is divisible by 5\n\nTask\n\nDetermine and show here the first four Giuga numbers.\n\nStretch\n\nDetermine the fifth Giuga number and any more you have the patience for.\n\nReferences\n\n* Wikipedia: Giuga number\n* OEIS:A007850 - Giuga numbers" }, { "role": "assistant", "content": "```\nmy @primes = (3..60).grep: &is-prime;\n\nprint 'First four Giuga numbers: ';\n\nput sort flat (2..4).map: -> $c {\n @primes.combinations($c).map: {\n my $n = [×] 2,|$_;\n $n if all .map: { ($n / $_ - 1) %% $_ };\n }\n}\n\n```\n\nOutput:\n\n```\nFirst 4 Giuga numbers: 30 858 1722 66198\n```" } ]
[ { "role": "user", "content": "Task\n\nReplace every occurring instance of a piece of text in a group of text files with another one.\n\nFor this task we want to replace the text   \"**Goodbye London!**\"   with   \"**Hello New York!**\"   for a list of files." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nCurrent Raku implementations do not yet support the -i flag for editing files in place, so we roll our own (rather unsafe) version:\n\n```\nslurp($_).subst('Goodbye London!', 'Hello New York!', :g) ==> spurt($_)\n for <a.txt b.txt c.txt>;\n\n```" } ]
[ { "role": "user", "content": "Write a program to let the user play Go Fish against a computer opponent. Use the following rules:\n\n* Each player is dealt nine cards to start with.\n* On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more.\n + If the opponent has any cards of the named rank, they must hand over all such cards, and the requester can ask again.\n + If the opponent has no cards of the named rank, the requester draws a card and ends their turn.\n* A *book* is a collection of every card of a given rank. Whenever a player completes a book, they may remove it from their hand.\n* If at any time a player's hand is empty, they may immediately draw a new card, so long as any new cards remain in the deck.\n* The game ends when every book is complete. The player with the most books wins.\n\nThe game's AI need not be terribly smart, but it should use at least some strategy. That is, it shouldn't choose legal moves entirely at random.\n\nYou may want to use code from Playing Cards.\n\nRelated tasks:\n\n* Playing cards\n* Card shuffles\n* Deal cards\\_for\\_FreeCell\n* War Card\\_Game\n* Poker hand\\_analyser" }, { "role": "assistant", "content": "(formerly Perl 6)\nSee Go Fish/Raku" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Goldbach's comet. 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**Goldbach's comet** is the name given to a plot of the function **g(E)**, the so-called **Goldbach function**.\n\nThe Goldbach function is studied in relation to Goldbach's conjecture. The function **g(E)** is defined for all *even* integers **E>2** to be the number of different ways in which E can be expressed as the sum of two primes.\n\nExamples\n\n* G(4) = 1, since 4 can only be expressed as the sum of one distinct pair of primes (4 = 2 + 2)\n* G(22) = 3, since 22 can be expressed as the sum of 3 distinct pairs of primes (22 = 11 + 11 = 5 + 17 = 3 + 19)\n\nTask\n\n* Find and show (preferably, in a neat 10x10 table) the first 100 G numbers (that is: the result of the G function described above, for the first 100 even numbers >= 4)\n* Find and display the value of G(1000000)\n\nStretch\n\n* Calculate the values of G up to 2000 (inclusive) and display the results in a scatter 2d-chart, aka the Goldbach's Comet\n\nSee also\n\n* Wikipedia: Goldbach's conjecture * OEIS: A045917 - From Goldbach problem: number of decompositions of 2n into unordered sums of two primes" }, { "role": "assistant", "content": "For the stretch, actually generates a plot, doesn't just calculate values to be plotted by a third party application. Deviates slightly from the stretch goal, plots the first two thousand defined values rather than the values up to two thousand that happen to be defined. (More closely matches the wikipedia example image.)\n\n```\nsub G (Int $n) { +(2..$n/2).grep: { .is-prime && ($n - $_).is-prime } }\n\n# Task\nput \"The first 100 G values:\\n\", (^100).map({ G 2 × $_ + 4 }).batch(10)».fmt(\"%2d\").join: \"\\n\";\n\nput \"\\nG 1_000_000 = \", G 1_000_000;\n\n# Stretch\nuse SVG;\nuse SVG::Plot;\n\nmy @x = map 2 × * + 4, ^2000;\nmy @y = @x.map: &G;\n\n'Goldbachs-Comet-Raku.svg'.IO.spurt: SVG.serialize: SVG::Plot.new(\n width => 1000,\n height => 500,\n background => 'white',\n title => \"Goldbach's Comet\",\n x => @x,\n values => [@y,],\n).plot: :points;\n\n```\n\nOutput:\n\n```\nThe first 100 G values:\n 1 1 1 2 1 2 2 2 2 3\n 3 3 2 3 2 4 4 2 3 4\n 3 4 5 4 3 5 3 4 6 3\n 5 6 2 5 6 5 5 7 4 5\n 8 5 4 9 4 5 7 3 6 8\n 5 6 8 6 7 10 6 6 12 4\n 5 10 3 7 9 6 5 8 7 8\n11 6 5 12 4 8 11 5 8 10\n 5 6 13 9 6 11 7 7 14 6\n 8 13 5 8 11 7 9 13 8 9\n\nG 1_000_000 = 5402\n```\n\n**Stretch goal:** (offsite SVG image) Goldbachs-Comet-Raku.svg" } ]
[ { "role": "user", "content": "The golden ratio can be defined as the continued fraction\n\n: ϕ\n =\n 1\n +\n\n\n 1\n\n 1\n +\n\n\n 1\n\n 1\n +\n\n\n 1\n\n 1\n +\n ⋯\n {\\displaystyle {\\displaystyle \\phi =1+{1 \\over {1+{1 \\over {1+{1 \\over {1+\\cdots }}}}}}}}\n\nThus \n\nϕ\n=\n1\n+\n\n1\n\n/\nϕ\n{\\displaystyle {\\displaystyle \\phi =1+{1/\\phi }}}\n. Multiplying both sides by \n\nϕ\n{\\displaystyle {\\displaystyle \\phi }}\n and solving the resulting quadratic equation for its positive solution, one gets \n\nϕ\n=\n(\n1\n+\n\n\n5\n)\n\n/\n2\n≈\n1.61803398875\n{\\displaystyle {\\displaystyle \\phi =(1+{\\sqrt {5}})/2\\approx 1.61803398875}}\n.\n\nThe golden ratio has the slowest convergence of any continued fraction, as one might guess by noting that the denominators are made of the smallest positive integer. This task treats the problem of convergence in a somewhat backwards fashion: we are going to iterate the recursion \n\nϕ\n\nn\n+\n1\n=\n1\n+\n\n1\n\n/\n\nϕ\n\nn\n{\\displaystyle {\\displaystyle \\phi \\_{n+1}=1+{1/\\phi \\_{n}}}}\n, \n\nϕ\n\n0\n=\n1\n{\\displaystyle {\\displaystyle \\phi \\_{0}=1}}\n, and see how long it takes to get an answer.\n\n### Task\n\nIterate \n\nϕ\n\nn\n+\n1\n=\n1\n+\n\n1\n\n/\n\nϕ\n\nn\n{\\displaystyle {\\displaystyle \\phi \\_{n+1}=1+{1/\\phi \\_{n}}}}\n, \n\nϕ\n\n0\n=\n1\n{\\displaystyle {\\displaystyle \\phi \\_{0}=1}}\n, until \n\n|\n\nϕ\n\nn\n+\n1\n−\n\nϕ\n\nn\n\n|\n≤\n1\n×\n\n10\n\n−\n5\n{\\displaystyle {\\displaystyle |\\phi \\_{n+1}-\\phi \\_{n}|\\leq 1\\times 10^{-5}}}\n. Report the final value of \n\nϕ\n\nn\n+\n1\n{\\displaystyle {\\displaystyle \\phi \\_{n+1}}}\n, the number of iterations required, and the error with respect to \n\n(\n1\n+\n\n\n5\n)\n\n/\n2\n{\\displaystyle {\\displaystyle (1+{\\sqrt {5}})/2}}\n.\n\n### See also\n\n* Metallic ratios" }, { "role": "assistant", "content": "```\nconstant phi = 1.FatRat, 1 + 1/* ... { abs($^a-$^b)≤1e-5 };\n\nsay \"It took {phi.elems} iterations to reach {phi.tail}\";\nsay \"The error is {{ ($^a - $^b)/$^b }(phi.tail, (1+sqrt(5))/2)}\"\n\n```\n\nOutput:\n\n```\nIt took 15 iterations to reach 1.618033\nThe error is -7.427932029059675e-07\n```" } ]
[ { "role": "user", "content": "Background\n\nGoodstein sequences are sequences defined for a given counting number n by applying increasing bases to a representation of n after n has been\nused to construct a *hereditary representation* of that number, originally in base 2.\n\nStart by defining the hereditary base-b representation of a number n. Write n as a sum of powers of b, staring with b = 2. For example, with\nn = 29, write 31 = 16 + 8 + 4 + 1. Now we write each exponent as a sum of powers of n, so as 2^4 + 2^3 + 2^1 + 2^0.\n\nContinue by re-writing all of the current term's exponents that are still > b as a sum of terms that are <= b, using a sum of powers of b: so,\nn = 16 + 8 + 4 + 1 = 2^4 + 2^3 + 2 + 1 = 2^(2^2) + 2^(2 + 1) + 2 + 1.\n\nIf we consider this representation as a representation of a calculation with b = 2, we have the hereditary representation\nb^(b^b) + b^(b + 1) + b + 1.\n\nOther integers and bases are done similarly. Note that an exponential term can be repeated up to (b - 1) times, so that, for example,\nif b = 5, 513 = b^3 + b^3 + b^3 + b^3 + b + b + 3 = 4 \\* b^3 + 2 \\* b + 3.\n\nThe Goodstein sequence for n, G(n) is then defined as follows:\n\nThe first term, considered the zeroeth term or G(n)(0), is always 0. The second term G(n)(1) is always n. For further terms,\nthe m-th term G(n)(m) is defined by the following procedure:\n\n```\n 1. Write G(n)(m - 1) as a hereditary representation with base (m - 1).\n 2. Calculate the results of using the hereditary representation found in step 1 using base m rather than (m - 1)\n 3. Subtract 1 from the result calculated in step 2.\n\n```\n\nTask\n\n* Create a function to calculate the Goodstein sequence for a given integer.\n\n* Use this to show the first 10 values of Goodstein(n) for the numbers from 0 through 7.\n\n* Find the nth term (counting from 0) of Goodstein(n) for n from 0 through 10.\n\nStretch task\n\n* Find the nth term (counting from 0) of Goodstein(n) for n = 11 through 16.\n\nSee also\n\n: * Wikipedia entry for Goodstein's theorem\n * OEIS Goodstein numbers such that a(n) = G\\_n(n), where G is the Goodstein function\n * [| \"Googology site article \" ]" }, { "role": "assistant", "content": "**Translation of**: Phix\n\n```\n# 20240219 Raku programming solution\n\nsub bump($n is copy, $b) {\n loop ( my ($res, $i) = 0, 0; $n.Bool or return $res; $i++,$n div= $b) {\n if my $d = $n % $b { $res += $d * ($b+1) ** bump($i,$b) }\n }\n}\n\nsub goodstein($n, $maxterms = 10) {\n my @res = $n;\n while @res.elems < $maxterms && @res[*-1] != 0 {\n @res.push(bump(@res[*-1], (@res.elems + 1)) - 1)\n }\n return @res\n}\n\nsay \"Goodstein(n) sequence (first 10) for values of n from 0 through 7:\";\nfor 0..7 -> $i { say \"Goodstein of $i: \", goodstein($i) }\n\nmy $max = 16;\nsay \"\\nThe Nth term of Goodstein(N) sequence counting from 0, for values of N from 0 through $max :\";\nfor 0..$max -> $i { say \"Term $i of Goodstein($i): {goodstein($i, $i+1)[*-1]}\" }\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "**Gosper's Hack** is an efficient method of computing the next higher integer with the same number of set bits (Hamming weight). It was invented by Bill Gosper. The algorithm is widely used in combinatorics for enumerating combinations.\n\nTask\n\nWrite a function or procedure to compute the next higher integer with the same number of set bits as a given positive integer, using Gosper’s Hack.\n\nShow the result of applying it ten times to each of the numbers 1, 3, 7, and 15.\n\nReference\n\n* Gosper's Hack explained" }, { "role": "assistant", "content": "```\nsub gosper ($x) {\n my $c = $x +& -$x;\n my $r = $x + $c;\n ((($r +^ $x) +> 2) / $c) +| $r\n}\n\nfor 1, 3, 7, 15 -> $start {\n my @g = $start, { gosper $_ } … *;\n say @g[^11].fmt('%8d');\n say @g[^11].fmt('%08b');\n say '';\n}\n\n```\n\nOutput:\n\n```\n 1 2 4 8 16 32 64 128 256 512 1024\n00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 100000000 1000000000 10000000000\n\n 3 5 6 9 10 12 17 18 20 24 33\n00000011 00000101 00000110 00001001 00001010 00001100 00010001 00010010 00010100 00011000 00100001\n\n 7 11 13 14 19 21 22 25 26 28 35\n00000111 00001011 00001101 00001110 00010011 00010101 00010110 00011001 00011010 00011100 00100011\n\n 15 23 27 29 30 39 43 45 46 51 53\n00001111 00010111 00011011 00011101 00011110 00100111 00101011 00101101 00101110 00110011 00110101\n\n```" } ]
[ { "role": "user", "content": "Definition\n\nIn programming, a gotcha is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome.\n\nTask\n\nGive an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools." }, { "role": "assistant", "content": "Raku embraces the philosophy of DWIM or \"Do What I Mean\". A DWIMmy\nlanguage tends to avoid lots of boilerplate code, and accept a certain amount of\nimprecision to return the result that, for the vast majority of the time, is\nwhat the user intended.\n\nFor example, a numeric string may be treated as either a numeric value or a\nstring literal, without needing to explicitly coerce it to one or the other.\nThis makes for easy translation of ideas into code, and is generally a good\nthing. HOWEVER, it doesn't always work out. Sometimes it leads to unexpected\nbehavior, commonly referred to as WAT.\n\nIt is something of a running joke in the Raku community that \"For every DWIM,\nthere is an equal and opposite WAT\".\n\nLarry Wall, the author and designer of Perl and\nlead designer of Raku, coined a term to describe this DWIM / WAT\ncontinuum. The Waterbed Theory of Computational Complexity.\n\nThe Waterbed theory is the observation that complicated systems contain a minimum\namount of complexity, and that attempting to \"push down\" the complexity of such\na system in one place will invariably cause complexity to \"pop up\" elsewhere.\n\nMuch like how in a waterbed mattress, it is possible to push down the mattress in one\nplace, but the displaced water will always cause the mattress to rise elsewhere,\nbecause water does not compress. It is impossible to push down the waterbed\neverywhere at once.\n\nThere is a whole chapter in the Raku documentation about\n\"Traps to Avoid\" when beginning in Raku,\nmost of which, at least partially are due to WATs arising from DWIMmy behavior\nsomeplace else.\n\nExpanding on the numeric string example cited above; numeric values and numeric\nstrings may be used almost interchangeably in most cases.\n\n```\nsay 123 ~ 456; # join two integers together\nsay \"12\" + \"5.7\"; # add two numeric strings together\nsay .sqrt for <4 6 8>; # take the square root of several allomorphic numerics\n\n```\n\n```\n123456\n17.7\n2\n2.449489742783178\n2.8284271247461903\n```\n\nYou can run into problems though with certain constructs that are more strict about\nobject typing.\n\nA Bag is a \"counting\" construct. It takes a collection and counts how many of\neach object are within. Works great for strings.\n\n```\nsay my $bag = <a b a c a b d>.Bag;\nsay $bag{'a'}; # a count?\nsay $bag< a >; # another way\n\n```\n\n```\nBag(a(3) b(2) c d)\n3\n3\n```\n\nBut numerics can present unobvious problems.\n\n```\nsay my $bag = (1, '1', '1', <1 1 1>).Bag;\nsay $bag{ 1 }; # how many 1s?\nsay $bag{'1'}; # wait, how many?\nsay $bag< 1 >; # WAT\ndd $bag; # The different numeric types LOOK the same, but are different types behind the scenes\n\n```\n\n```\nBag(1 1(2) 1(3))\n1\n2\n3\nBag $bag = (1=>1,\"1\"=>2,IntStr.new(1, \"1\")=>3).Bag\n```\n\nThe different '1's are distinctive to the type system even if they visually look\nidentical when printing them to the console. They all have a value of 1 but are\nrespectively and Int, a String, and an IntStr allomorph. Many of the \"collective\"\nobjects have this property (Bags, Sets, Maps, etc.) This behavior is correct\nbut can be very jarring when you are used to being able to use numeric strings\nand numeric values nearly interchangeably.\n\nAnother such DWIMmy construct, which can trip up even experienced Raku programmers is\nThe Single Argument Rule.\n\nSingle argument is a special exception to parameterization rules causing an iterable\nobject to be be automatically flattened when passed to an iterator if only a single\nobject is passed.\n\nE.G. Say we have two small list objects; `(1,2,3)` and `(4,5,6)`,\nand we want to print the contents to the console.\n\n```\n.say for (1,2,3), (4,5,6);\n\n```\n\n```\n(1,2,3)\n(4,5,6)\n```\n\nHowever, if we only pass a single list to the iterator (`for`), it will\nflatten the object due to the single argument rule.\n\n```\n.say for (1,2,3);\n\n```\n\n```\n1\n2\n3\n```\n\nIf we want the multiple object non-flattening behavior, we need to \"fake it out\"\nby adding a trailing comma to signal to the compiler that this should be treated\nlike multiple object parameters even if there is only one. (Note the trailing comma after the list.)\n\n```\n.say for (1,2,3),;\n\n```\n\n```\n(1,2,3)\n```\n\nConversely, if we want the flattening behavior when passing multiple objects, we need to manually, explicitly flatten the objects.\n\n```\n.say for flat (1,2,3), (4,5,6);\n\n```\n\n```\n1\n2\n3\n4\n5\n6\n```\n\nSingle argument mostly arose in Raku to make it act more like Perl 5, for which\nit was originally conceived of as a replacement. Perl 5 flattens collective\nobject parameters by default, and the original non-flattening behavior was\n*extremely* confusing to early Perl / Raku crossover programmers. Larry Wall\ncame up with single argument to reduce confusion and increase DWIMiness, and it\nhas overall, but it still leads to the occasional WAT when programmers first bump up against it." } ]
[ { "role": "user", "content": "Gradient descent (also known as steepest descent) is a first-order iterative optimization algorithm for finding the minimum of a function which is described in this Wikipedia article.\n\nTask\n\nUse this algorithm to search for minimum values of the bi-variate function:\n\n```\n f(x, y) = (x - 1)(x - 1)e^(-y^2) + y(y+2)e^(-2x^2)\n\n```\n\naround x = 0.1 and y = -1.\n\nThis book excerpt shows sample C# code for solving this task." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Go\n\n```\n# 20200904 Updated Raku programming solution\n\nsub steepestDescent(@x, $alpha is copy, $h) {\n\n my $g0 = g |@x ; # Initial estimate of result.\n\n my @fi = gradG |@x ; # Calculate initial gradient\n\n my $b = $alpha / my $delG = sqrt ( sum @fi»² ) ; # Calculate initial norm.\n\n while ( $delG > $h ) { # Iterate until value is <= tolerance.\n\n @x «-»= $b «*« @fi; # Calculate next value.\n\n @fi = gradG |@x ; # Calculate next gradient and next value\n\n $b = $alpha / ($delG = sqrt( sum @fi»² )); # Calculate next norm.\n\n my $g1 = g |@x ;\n\n $g1 > $g0 ?? ( $alpha /= 2 ) !! ( $g0 = $g1 ) # Adjust parameter.\n }\n}\n\nsub gradG(\\x,\\y) { # gives a rough calculation of gradient g(x).\n 2*(x-1)*exp(-y²) - 4*x*exp(-2*x²)*y*(y+2) , -2*(x-1)²*y*exp(-y²) + exp(-2*x²)*(2*y+2)\n}\n\n# Function for which minimum is to be found.\nsub g(\\x,\\y) { (x-1)² * exp(-y²) + y*(y+2) * exp(-2*x²) }\n\nmy $tolerance = 0.0000006 ; my $alpha = 0.1;\n\nmy @x = 0.1, -1; # Initial guess of location of minimum.\n\nsteepestDescent(@x, $alpha, $tolerance);\n\nsay \"Testing steepest descent method:\";\nsay \"The minimum is at x[0] = \", @x[0], \", x[1] = \", @x[1];\n\n```\n\nOutput:\n\n```\nTesting steepest descent method:\nThe minimum is at x[0] = 0.10762682432947938, x[1] = -1.2232596548816097\n\n```" } ]
[ { "role": "user", "content": "A Graph is a collection of nodes\n(or vertices), connected by edges (or not).\nNodes directly connected by edges are called neighbours.\n\nIn our representation of graphs, nodes are numbered and edges are represented\nby the two node numbers connected by the edge separated by a dash.\nEdges define the nodes being connected. Only unconnected nodes *need* a separate\ndescription.\n\nFor example,\n\n```\n0-1 1-2 2-0 3\n```\n\nDescribes the following graph. Note that node 3 has no neighbours\n\nExample graph\n\n```\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n```\n\nA useful internal datastructure for a graph and for later graph algorithms is\nas a mapping between each node and the set/list of its neighbours.\n\nIn the above example:\n\n```\n0 maps-to 1 and 2\n1 maps to 2 and 0\n2 maps-to 1 and 0\n3 maps-to <nothing>\n```\n\nGraph colouring task\n\nColour the vertices of a given graph so that no edge is between verticies of\nthe same colour.\n\n* Integers may be used to denote different colours.\n* Algorithm should do better than just assigning each vertex a separate colour. The idea is to minimise the number of colours used, although no algorithm short of exhaustive search for the minimum is known at present, (and exhaustive search is **not** a requirement).\n* Show for each edge, the colours assigned on each vertex.\n* Show the total number of nodes, edges, and colours used for each graph.\n\nUse the following graphs\n\n\nEx1\n\n```\n 0-1 1-2 2-0 3\n\n```\n\n```\n+---+\n| 3 |\n+---+\n\n +-------------------+\n | |\n+---+ +---+ +---+\n| 0 | --- | 1 | --- | 2 |\n+---+ +---+ +---+\n\n```\n\nEx2\n\nThe wp articles left-side graph\n\n```\n 1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7\n\n```\n\n```\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 3 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 6 | --- | 4 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 7 | --- | 2 | --- | 5 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n```\n\nEx3\n\nThe wp articles right-side graph which is the same graph as Ex2, but with\ndifferent node orderings and namings.\n\n```\n 1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6\n\n```\n\n```\n\n\n +----------------------------------+\n | |\n | +---+ |\n | +-----------------| 5 | ------+----+\n | | +---+ | |\n | | | | |\n | | | | |\n | | | | |\n | +---+ +---+ +---+ +---+ |\n | | 8 | --- | 1 | --- | 4 | --- | 7 | |\n | +---+ +---+ +---+ +---+ |\n | | | | |\n | | | | |\n | | | | |\n | | +---+ +---+ +---+ |\n +----+------ | 6 | --- | 3 | --- | 2 | -+\n | +---+ +---+ +---+\n | |\n +-------------------+\n\n```\n\nEx4\n\nThis is the same graph, node naming, and edge order as Ex2 except some of the edges x-y are flipped to y-x.\nThis might alter the node order used in the greedy algorithm leading to differing numbers of colours.\n\n```\n 1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7\n\n```\n\n```\n\n\n +-------------------------------------------------+\n | |\n | |\n +-------------------+---------+ |\n | | | |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n| 4 | --- | 5 | --- | 2 | --- | 7 | --- | 1 | --- | 6 | --- | 3 | --- | 8 |\n+---+ +---+ +---+ +---+ +---+ +---+ +---+ +---+\n | | | | | |\n +---------+-----------------------------+---------+ | |\n | | | |\n | | | |\n +-----------------------------+-------------------+ |\n | |\n | |\n +-----------------------------+\n\n```\n\nReferences\n\n* Greedy coloring Wikipedia.\n* Graph Coloring : Greedy Algorithm & Welsh Powell Algorithm by Priyank Jain." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub GraphNodeColor(@RAW) {\n my %OneMany = my %NodeColor;\n for @RAW { %OneMany{$_[0]}.push: $_[1] ; %OneMany{$_[1]}.push: $_[0] }\n my @ColorPool = \"0\", \"1\" … ^+%OneMany.elems; # as string\n my %NodePool = %OneMany.BagHash; # this DWIM is nice\n if %OneMany<NaN>:exists { %NodePool{$_}:delete for %OneMany<NaN>, NaN } # pending\n while %NodePool.Bool {\n my $color = @ColorPool.shift;\n my %TempPool = %NodePool;\n while (my \\n = %TempPool.keys.sort.first) {\n %NodeColor{n} = $color;\n %TempPool{n}:delete;\n %TempPool{$_}:delete for @(%OneMany{n}) ; # skip neighbors as well\n %NodePool{n}:delete;\n }\n }\n if %OneMany<NaN>:exists { # islanders use an existing color\n %NodeColor{$_} = %NodeColor.values.sort.first for @(%OneMany<NaN>)\n }\n return %NodeColor\n}\n\nmy \\DATA = [\n [<0 1>,<1 2>,<2 0>,<3 NaN>,<4 NaN>,<5 NaN>],\n [<1 6>,<1 7>,<1 8>,<2 5>,<2 7>,<2 8>,<3 5>,<3 6>,<3 8>,<4 5>,<4 6>,<4 7>],\n [<1 4>,<1 6>,<1 8>,<3 2>,<3 6>,<3 8>,<5 2>,<5 4>,<5 8>,<7 2>,<7 4>,<7 6>],\n [<1 6>,<7 1>,<8 1>,<5 2>,<2 7>,<2 8>,<3 5>,<6 3>,<3 8>,<4 5>,<4 6>,<4 7>],\n];\n\nfor DATA {\n say \"DATA  : \", $_;\n say \"Result : \";\n my %out = GraphNodeColor $_;\n say \"$_[0]-$_[1]:\\t Color %out{$_[0]} \",$_[1].isNaN??''!!%out{$_[1]} for @$_;\n say \"Nodes  : \", %out.keys.elems;\n say \"Edges  : \", $_.elems;\n say \"Colors : \", %out.values.Set.elems;\n}\n\n```\n\nOutput:\n\n```\nDATA  : [(0 1) (1 2) (2 0) (3 NaN) (4 NaN) (5 NaN)]\nResult :\n0-1: Color 0 1\n1-2: Color 1 2\n2-0: Color 2 0\n3-NaN: Color 0\n4-NaN: Color 0\n5-NaN: Color 0\nNodes  : 6\nEdges  : 6\nColors : 3\nDATA  : [(1 6) (1 7) (1 8) (2 5) (2 7) (2 8) (3 5) (3 6) (3 8) (4 5) (4 6) (4 7)]\nResult :\n1-6: Color 0 1\n1-7: Color 0 1\n1-8: Color 0 1\n2-5: Color 0 1\n2-7: Color 0 1\n2-8: Color 0 1\n3-5: Color 0 1\n3-6: Color 0 1\n3-8: Color 0 1\n4-5: Color 0 1\n4-6: Color 0 1\n4-7: Color 0 1\nNodes  : 8\nEdges  : 12\nColors : 2\nDATA  : [(1 4) (1 6) (1 8) (3 2) (3 6) (3 8) (5 2) (5 4) (5 8) (7 2) (7 4) (7 6)]\nResult :\n1-4: Color 0 1\n1-6: Color 0 2\n1-8: Color 0 3\n3-2: Color 1 0\n3-6: Color 1 2\n3-8: Color 1 3\n5-2: Color 2 0\n5-4: Color 2 1\n5-8: Color 2 3\n7-2: Color 3 0\n7-4: Color 3 1\n7-6: Color 3 2\nNodes  : 8\nEdges  : 12\nColors : 4\nDATA  : [(1 6) (7 1) (8 1) (5 2) (2 7) (2 8) (3 5) (6 3) (3 8) (4 5) (4 6) (4 7)]\nResult :\n1-6: Color 0 1\n7-1: Color 1 0\n8-1: Color 1 0\n5-2: Color 1 0\n2-7: Color 0 1\n2-8: Color 0 1\n3-5: Color 0 1\n6-3: Color 1 0\n3-8: Color 0 1\n4-5: Color 0 1\n4-6: Color 0 1\n4-7: Color 0 1\nNodes  : 8\nEdges  : 12\nColors : 2\n```" } ]
[ { "role": "user", "content": "Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps in order from left to right or top to bottom.\n\nCreate functions to encode a number to and decode a number from Gray code.\n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\n```\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n```\n\nOr:\n\n```\ng = b xor (b logically right shifted 1 time)\n```\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\n```\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n```\n\nReference\n\n* Converting Between Gray and Binary Codes. It includes step-by-step animations." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub gray_encode ( Int $n --> Int ) {\n return $n +^ ( $n +> 1 );\n}\n\nsub gray_decode ( Int $n is copy --> Int ) {\n my $mask = 1 +< (32-2);\n $n +^= $mask +> 1 if $n +& $mask while $mask +>= 1;\n return $n;\n}\n\nfor ^32 -> $n {\n my $g = gray_encode($n);\n my $d = gray_decode($g);\n printf \"%2d: %5b => %5b => %5b: %2d\\n\", $n, $n, $g, $d, $d;\n die if $d != $n;\n}\n\n```\n\nOutput:\n\n```\n 0: 0 => 0 => 0: 0\n 1: 1 => 1 => 1: 1\n 2: 10 => 11 => 10: 2\n 3: 11 => 10 => 11: 3\n 4: 100 => 110 => 100: 4\n 5: 101 => 111 => 101: 5\n 6: 110 => 101 => 110: 6\n 7: 111 => 100 => 111: 7\n 8: 1000 => 1100 => 1000: 8\n 9: 1001 => 1101 => 1001: 9\n10: 1010 => 1111 => 1010: 10\n11: 1011 => 1110 => 1011: 11\n12: 1100 => 1010 => 1100: 12\n13: 1101 => 1011 => 1101: 13\n14: 1110 => 1001 => 1110: 14\n15: 1111 => 1000 => 1111: 15\n16: 10000 => 11000 => 10000: 16\n17: 10001 => 11001 => 10001: 17\n18: 10010 => 11011 => 10010: 18\n19: 10011 => 11010 => 10011: 19\n20: 10100 => 11110 => 10100: 20\n21: 10101 => 11111 => 10101: 21\n22: 10110 => 11101 => 10110: 22\n23: 10111 => 11100 => 10111: 23\n24: 11000 => 10100 => 11000: 24\n25: 11001 => 10101 => 11001: 25\n26: 11010 => 10111 => 11010: 26\n27: 11011 => 10110 => 11011: 27\n28: 11100 => 10010 => 11100: 28\n29: 11101 => 10011 => 11101: 29\n30: 11110 => 10001 => 11110: 30\n31: 11111 => 10000 => 11111: 31\n\n```\n\nRaku distinguishes numeric bitwise operators with a leading + sign,\nso +< and +> are left and right shift,\nwhile +& is a bitwise AND, while +^ is bitwise XOR\n(here used as part of an assignment metaoperator)." } ]
[ { "role": "user", "content": "Many image processing algorithms are defined for grayscale (or else monochromatic) images.\n\nTask\n\nExtend the data storage type defined on this page to support grayscale images.\n\nDefine two operations, one to convert a color image to a grayscale image and one for the backward conversion.\n\nTo get luminance of a color use the formula recommended by CIE:\n\n```\n L = 0.2126 × R + 0.7152 × G + 0.0722 × B \n\n```\n\nWhen using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis script expects to be fed a P6 .ppm file name at the command line. It will convert it to grey scale and save it as a binary portable grey map (P5 .pgm) file.\n\n```\nsub MAIN ($filename = 'default.ppm') {\n\n my $in = open($filename, :r, :enc<iso-8859-1>) or die $in;\n\n my ($type, $dim, $depth) = $in.lines[^3];\n\n my $outfile = $filename.subst('.ppm', '.pgm');\n my $out = open($outfile, :w, :enc<iso-8859-1>) or die $out;\n\n $out.say(\"P5\\n$dim\\n$depth\");\n\n for $in.lines.ords -> $r, $g, $b {\n my $gs = $r * 0.2126 + $g * 0.7152 + $b * 0.0722;\n $out.print: chr($gs.floor min 255);\n }\n\n $in.close;\n $out.close;\n}\n\n```\n\nUsing the .ppm file from the Write a PPM file task:\n\nOriginal: Grey Scale:" } ]
[ { "role": "user", "content": "Task\n\nFind the greatest common divisor   (**GCD**)   of two integers.\n\n*Greatest common divisor*   is also known as   *greatest common factor* **(gcf)**   and   *greatest common measure*.\n\nRelated task\n: * least common multiple.\n\nSee also\n: * MathWorld entry:   greatest common divisor.\n * Wikipedia entry:     greatest common divisor." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Iterative\n\n```\nsub gcd (Int $a is copy, Int $b is copy) {\n $a & $b == 0 and fail;\n ($a, $b) = ($b, $a % $b) while $b;\n return abs $a;\n}\n```\n\n### Recursive\n\n```\nmulti gcd (0, 0) { fail }\nmulti gcd (Int $a, 0) { abs $a }\nmulti gcd (Int $a, Int $b) { gcd $b, $a % $b }\n```\n\n### Recursive(inline coderef)\n\n```\n{ $^b ?? &?BLOCK( $^b, $^a % $^b ) !! $^a }\n```\n\n### Concise\n\n```\nmy &gcd = { ($^a.abs, $^b.abs, * % * ... 0)[*-2] }\n```\n\n### Actually, it's a built-in infix\n\n```\nmy $gcd = $a gcd $b;\n```\n\nBecause it's an infix, you can use it with various meta-operators:\n\n```\n[gcd] @list; # reduce with gcd\n@alist Zgcd @blist; # lazy zip with gcd\n@alist Xgcd @blist; # lazy cross with gcd\n@alist »gcd« @blist; # parallel gcd\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a function that returns the maximum value in a provided set of values,\n \nwhere the number of values may not be known until run-time." }, { "role": "assistant", "content": "(formerly Perl 6)\nThe built-in function works with any type that defines ordering.\n\n```\nsay max 10, 4, 5, -2, 11;\nsay max <zero one two three four five six seven eight nine>;\n\n# Even when the values and number of values aren't known until runtime\nmy @list = flat(0..9,'A'..'H').roll((^60).pick).rotor(4,:partial)».join.words;\nsay @list, ': ', max @list;\n```\n\nSample output:\n\n```\n11\nzero\n[6808 013C 6D5B 4219 29G9 DC13 CA4F 55F3 AA06 0AGF DAB0 2]: DC13\n```" } ]
[ { "role": "user", "content": "Definitions\n\nA cubefree number is a positive integer whose prime factorization does not contain any third (or higher) power factors. If follows that all primes are trivially cubefree and the first cubefree number is 1 because it has no prime factors.\n\nLet a[n] be the greatest prime dividing the n-th cubefree number for n >= 2. By convention, let a[1] = 1 even though the first cubefree number, 1, has no prime factors.\n\nExamples\n\na[2] is clearly 2 because it is the second cubefree number and also prime. The fourth cubefree number is 4 and it's highest prime factor is 2, hence a[4] = 2.\n\nTask\n\nCompute and show on this page the first **100** terms of a[n].\nAlso compute and show the **1,000th**, **10,000th** and **100,000th** members of the sequence.\n\nStretch\n\nCompute and show the **1 millionth** and **10 millionth** terms of the sequence.\n\nThis may take a while for interpreted languages.\n\nReference\n\n* OEIS sequence: A370833: a(n) is the greatest prime dividing the n-th cubefree number, for n >= 2; a(1)=1.\n* The number of integers in a given interval which are multiple of at least one of the given numbers" }, { "role": "assistant", "content": "```\nuse Prime::Factor;\n\nsub max_factor_if_cubefree ($i) {\n my @f = prime-factors($i);\n return @f.tail if @f.elems < 3\n or @f.Bag.values.all < 3;\n}\n\nconstant @Aₙ = lazy flat 1, map &max_factor_if_cubefree, 2..*;\n\nsay 'The first terms of A370833 are:';\nsay .fmt('%3d') for @Aₙ.head(100).batch(10);\n\nsay '';\n\nfor 10 X** (3..6) -> $k {\n printf \"The %8dth term of A370833 is %7d\\n\", $k, @Aₙ[$k-1];\n}\n\n```\n\nOutput:\n\n```\nThe first terms of A370833 are:\n 1 2 3 2 5 3 7 3 5 11\n 3 13 7 5 17 3 19 5 7 11\n 23 5 13 7 29 5 31 11 17 7\n 3 37 19 13 41 7 43 11 5 23\n 47 7 5 17 13 53 11 19 29 59\n 5 61 31 7 13 11 67 17 23 7\n 71 73 37 5 19 11 13 79 41 83\n 7 17 43 29 89 5 13 23 31 47\n 19 97 7 11 5 101 17 103 7 53\n107 109 11 37 113 19 23 29 13 59\n\nThe 1000th term of A370833 is 109\nThe 10000th term of A370833 is 101\nThe 100000th term of A370833 is 1693\nThe 1000000th term of A370833 is 1202057\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.\n\nAn empty subsequence is considered to have the sum of   **0**;   thus if all elements are negative, the result must be the empty sequence." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n**Works with**: Rakudo version 2016.12\n\n```\nsub max-subseq (*@a) {\n my ($start, $end, $sum, $maxsum) = -1, -1, 0, 0;\n for @a.kv -> $i, $x {\n $sum += $x;\n if $maxsum < $sum {\n ($maxsum, $end) = $sum, $i;\n }\n elsif $sum < 0 {\n ($sum, $start) = 0, $i;\n }\n }\n return @a[$start ^.. $end];\n}\n\n```\n\nAnother solution, not translated from any other language:\n\nFor each starting position, we calculate all the subsets starting at that position.\nThey are combined with the best subset ($max-subset) from previous loops, to form (@subsets).\nThe best of those @subsets is saved at the new $max-subset.\n\nConsuming the array (.shift) allows us to skip tracking the starting point; it is always 0.\n\nThe empty sequence is used to initialize $max-subset, which fulfils the \"all negative\" requirement of the problem.\n\n```\nsub max-subseq ( *@a ) {\n\n my $max-subset = ();\n while @a {\n my @subsets = [\\,] @a;\n @subsets.push: $max-subset;\n $max-subset = @subsets.max: { [+] .list };\n @a.shift;\n }\n\n return $max-subset;\n}\n\nmax-subseq( -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ).say;\nmax-subseq( -2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1 ).say;\nmax-subseq( -2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1 ).say;\n\n```\n\nOutput:\n\n```\n(3 5 6 -2 -1 4)\n(3 5 6 -1 4)\n()\n```" } ]
[ { "role": "user", "content": "This task is about making a clone of the game \"GREED\" by Matthew Day.\n\nThis game is played on a grid of   **79**   column by   **22**   rows of random numbers from   **1**   to   **9**   (inclusive).\n\nThe player location is signified by the   **@**   symbol.\n\nThe object of Greed is to erase as much of the screen as possible by moving around   (all 8 directions are allowed in this grid).\n\nWhen you move in a direction,   **N**   number of grid squares are erased (\"eaten\") in that direction,   **N**   being the first number in that direction.\n\nYour score reflects the total number of squares \"eaten\".\n\nYou may not make a move that places you off the grid or over a previously eaten square.\n\nThe game is over if there is no more valid moves.\n\nVideo on YouTube" }, { "role": "assistant", "content": "**Translation of**: Phix\n\n```\n# 20200913 added Raku programming solution\n\nsrand 123456;\n\nmy @board = [ (1..9).roll xx my \\w = 79 ] xx my \\h = 22 ;\nmy \\X = $ = w.rand.Int ; my \\Y = $ = h.rand.Int;\n@board[Y;X] = '@';\nmy \\score = $ = 0;\n\nsub execute (\\y,\\x) {\n my \\i = $ = @board[Y+y;X+x];\n if countSteps(i, x, y) {\n score += i;\n @board[ Y + y*$_ ; X + x*$_ ] = ' ' for ^i;\n @board[ Y += y*i  ; X += x*i ] = '@';\n }\n}\n\nsub countSteps(\\i, \\x, \\y) {\n my \\tX = $ = X ; my \\tY = $ = Y;\n for ^i {\n tX += x; tY += y;\n return False if tX < 0 or tY < 0 or tX ≥ w or tY ≥ h or @board[tY;tX] eq ' ' \n }\n return True;\n}\n\nsub existsMoves {\n for (-1 .. 1) X (-1 .. 1) -> (\\x,\\y) {\n next if x == 0 and y == 0;\n next if X+x < 0 or X+x > w or Y+y < 0 or Y+y > h ;\n my \\i = @board[Y+y;X+x];\n return True if ( i ne ' ' and countSteps(i, x, y) )\n }\n return False;\n}\n\nloop {\n for @board { .join.print ; print \"\\r\\n\" } ;\n { say \"Game over.\" and last } unless existsMoves();\n print \"Current score : \", score, \"\\r\\n\";\n given my $c = $*IN.getc {\n when 'q' { say \"So long.\" and last}\n when 'e' { execute(-1,-1) if X > 0 and Y > 0 } # North-West\n when 'r' { execute(-1, 0) if Y > 0 } # North\n when 't' { execute(-1, 1) if X < w and Y > 0 } # North-East\n when 'd' { execute( 0,-1) if X > 0 } # West\n when 'g' { execute( 0, 1) if X < w } # East\n when 'x' { execute( 1,-1) if X > 0 and Y < h } # South-West\n when 'c' { execute( 1, 0) if Y < h } # South\n when 'v' { execute( 1, 1) if X < w and Y < h } # South-East\n }\n}\n\n```" } ]
[ { "role": "user", "content": "An   Egyptian fraction   is the sum of distinct unit fractions such as:\n\n: : : : 1\n 2\n +\n\n 1\n 3\n +\n\n 1\n 16\n\n (\n =\n\n 43\n 48\n )\n {\\displaystyle {\\displaystyle {\\tfrac {1}{2}}+{\\tfrac {1}{3}}+{\\tfrac {1}{16}}\\,(={\\tfrac {43}{48}})}}\n\nEach fraction in the expression has a numerator equal to   **1**   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions).\n\nFibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction   \n\nx\ny\n{\\displaystyle {\\displaystyle {\\tfrac {x}{y}}}}\n   to be represented by repeatedly performing the replacement\n\n: : : : x\n y\n =\n\n\n 1\n\n ⌈\n y\n\n /\n x\n ⌉\n +\n\n (\n −\n y\n )\n\n mod\n\n\n x\n\n y\n ⌈\n y\n\n /\n x\n ⌉\n {\\displaystyle {\\displaystyle {\\frac {x}{y}}={\\frac {1}{\\lceil y/x\\rceil }}+{\\frac {(-y)\\!\\!\\!\\!\\mod x}{y\\lceil y/x\\rceil }}}}\n\n(simplifying the 2nd term in this replacement as necessary, and where   \n\n⌈\nx\n⌉\n{\\displaystyle {\\displaystyle \\lceil x\\rceil }}\n   is the   *ceiling*   function).\n\nFor this task,   Proper and improper fractions   must be able to be expressed.\n\nProper  fractions   are of the form   \n\na\nb\n{\\displaystyle {\\displaystyle {\\tfrac {a}{b}}}}\n   where   \n\na\n{\\displaystyle {\\displaystyle a}}\n   and   \n\nb\n{\\displaystyle {\\displaystyle b}}\n   are positive integers, such that   \n\na\n<\nb\n{\\displaystyle {\\displaystyle a<b}}\n,     and\n\nimproper fractions are of the form   \n\na\nb\n{\\displaystyle {\\displaystyle {\\tfrac {a}{b}}}}\n   where   \n\na\n{\\displaystyle {\\displaystyle a}}\n   and   \n\nb\n{\\displaystyle {\\displaystyle b}}\n   are positive integers, such that   *a* ≥ *b*.\n\n(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)\n\nFor improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [*n*].\n\nTask requirements\n\n* show the Egyptian fractions for: \n\n 43\n 48\n {\\displaystyle {\\displaystyle {\\tfrac {43}{48}}}}\n and \n\n 5\n 121\n {\\displaystyle {\\displaystyle {\\tfrac {5}{121}}}}\n and \n\n 2014\n 59\n {\\displaystyle {\\displaystyle {\\tfrac {2014}{59}}}}\n* for all proper fractions,   \n\n a\n b\n {\\displaystyle {\\displaystyle {\\tfrac {a}{b}}}}\n   where   \n\n a\n {\\displaystyle {\\displaystyle a}}\n   and   \n\n b\n {\\displaystyle {\\displaystyle b}}\n   are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n\n: : * the largest number of terms,\n * the largest denominator.\n\n* for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit}\n\nAlso see\n\n* Wolfram MathWorld™ entry: Egyptian fraction\n* Numberphile YouTube video: Egyptian Fractions and the Greedy Algorithm" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nrole Egyptian {\n method gist {\n\tjoin ' + ',\n\t (\"[{self.floor}]\" if self.abs >= 1),\n\t map {\"1/$_\"}, self.denominators;\n }\n method denominators {\n\tmy ($x, $y) = self.nude;\n\t$x %= $y;\n\tmy @denom = gather ($x, $y) = -$y % $x, $y * take ($y / $x).ceiling\n\t while $x;\n }\n}\n\nsay .nude.join('/'), \" = \", $_ but Egyptian for 43/48, 5/121, 2014/59;\n\nmy @sample = map { $_ => .denominators },\n grep * < 1, \n map {$_ but Egyptian}, \n (2 .. 99 X/ 2 .. 99);\n\nsay .key.nude.join(\"/\"),\n \" has max denominator, namely \",\n .value.max\n given max :by(*.value.max), @sample;\n\nsay .key.nude.join(\"/\"),\n \" has max number of denominators, namely \",\n .value.elems\n given max :by(*.value.elems), @sample;\n\n```\n\nOutput:\n\n```\n43/48 = 1/2 + 1/3 + 1/16\n5/121 = 1/25 + 1/757 + 1/763309 + 1/873960180913 + 1/1527612795642093418846225\n2014/59 = [34] + 1/8 + 1/95 + 1/14947 + 1/670223480\n8/97 has max denominator, namely 579504587067542801713103191859918608251030291952195423583529357653899418686342360361798689053273749372615043661810228371898539583862011424993909789665\n8/97 has max number of denominators, namely 8\n```\n\nBecause the harmonic series diverges (albeit very slowly), it is possible to write even improper fractions as a sum of distinct unit fractions. Here is a code to do that:\n\n```\nrole Egyptian {\n method gist { join ' + ', map {\"1/$_\"}, self.list }\n method list {\n\tmy $sum = 0;\n\tgather for 2 .. * {\n\t last if $sum == self;\n\t $sum += 1 / .take unless $sum + 1 / $_ > self;\n\t}\n }\n}\n \nsay 5/4 but Egyptian;\n\n```\n\nOutput:\n\n```\n1/2 + 1/3 + 1/4 + 1/6\n```\n\nThe list of terms grows exponentially with the value of the fraction, though." } ]
[ { "role": "user", "content": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.\n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy ($width,$height) = 1280,768;\n \nmy $PGM = open \"Greyscale-bars-perl6.pgm\", :w orelse die \"Can't create Greyscale-bars-perl6.pgm: $_\";\n \n$PGM.print: qq:to/EOH/;\n P2\n # Greyscale-bars-perl6.pgm\n $width $height\n 65535\n EOH\n \nmy ($h1,$h2,$h3,$h4) = divvy($height,4);\n \nmy @nums = ((0/7,1/7...7/7) X* 65535)».floor;\nmy $line = ~(@nums Zxx divvy($width,8));\n$PGM.say: $line for ^$h1;\n \n@nums = ((15/15,14/15...0/15) X* 65535)».floor;\n$line = ~(@nums Zxx divvy($width,16));\n$PGM.say: $line for ^$h2;\n \n@nums = ((0/31,1/31...31/31) X* 65535)».floor;\n$line = ~(@nums Zxx divvy($width,32));\n$PGM.say: $line for ^$h3;\n \n@nums = ((63/63,62/63...0/63) X* 65535)».floor;\n$line = ~(@nums Zxx divvy($width,64));\n$PGM.say: $line for ^$h4;\n \n$PGM.close;\n \nsub divvy($all, $div) {\n my @marks = ((1/$div,2/$div ... 1) X* $all)».round;\n @marks Z- 0,|@marks;\n}\n\n```\n\nSee Greyscale-bars-perl6 (offsite image)" } ]
[ { "role": "user", "content": "**GSTrans** string encoding is a method of encoding all 8-bit character values 0-255 with only printable characters. It originates on Acorn computers to allow command line\ncommands to process non-printable characters.\n\n```\n Character Encoding\n 0-31 |letter eg |@, |A, |i |[ etc.\n 32-126 character, except for:\n \" |\"\n | ||\n 127 |?\n 128-255 |! followed by encoding, eg |!|@ = 128\n\n```\n\nA string can be surrounded in quotes, eg \"ALERT|G\".\n\nSee http://www.riscos.com/support/developers/prm/conversions.html\n\nExamples:\n\n```\n |LHello|G|J|M encodes CHR$12;\"Hello\";CHR$7;CHR$10;CHR$13\n \"|m|j|@|e|!t|m|!|?\" encodes 13,10,0,5,244,13,255\n\n```\n\nTask\n\n: * Write two functions, one to encode a string of characters into a GSTrans string, and one to decode a GSTrans string. Indicate if any error checking is done, and how it is indicated." }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\n# 20231105 Raku programming solution\n\nsub GSTrans-encode(Str $str) {\n return [~] $str.encode('utf8').list.chrs.comb.map: -> $c { \n my $i = $c.ord;\n die \"Char value of $c, $i, is out of range\" unless 0 <= $i <= 255;\n given ($i,$c) { \n when 0 <= $i <= 31 { '|' ~ chr(64 + $i) } \n when $c eq '\"' { '|\"' }\n when $c eq '|' { '||' }\n when $i == 127 { '|?' }\n when 128 <= $i <= 255 { '|!' ~ GSTrans-encode(chr($i - 128)) }\n default { $c }\n }\n }\n}\n\nsub GSTrans-decode(Str $str) {\n my ($gotbar, $gotbang, $bangadd) = False, False, 0;\n\n my @result = gather for $str.comb -> $c {\n if $gotbang {\n if $c eq '|' {\n $bangadd = 128;\n $gotbar = True;\n } else {\n take $c.ord + 128;\n }\n $gotbang = False;\n } elsif $gotbar {\n given $c {\n when $c eq '?' { take 127 + $bangadd }\n when $c eq '!' { $gotbang = True }\n when $c eq '|' || $c eq '\"' || $c eq '<' { take $c.ord + $bangadd }\n when $c eq '[' || $c eq '{' { take 27 + $bangadd } \n when $c eq '\\\\' { take 28 + $bangadd } \n when $c eq ']' || $c eq '}' { take 29 + $bangadd } \n when $c eq '^' || $c eq '~' { take 30 + $bangadd }\n when $c eq '_' || $c eq '`' { take 31 + $bangadd }\n default { my $i = $c.uc.ord - 64 + $bangadd;\n take $i >= 0 ?? $i !! $c.ord }\n }\n $gotbar = False;\n $bangadd = 0;\n } elsif $c eq '|' {\n $gotbar = True\n } else {\n take $c.ord\n }\n }\n return Blob.new(@result).decode('utf8c8')\n}\n\nmy @TESTS = <ALERT|G 'wert↑>;\nmy @RAND_TESTS = ^256 .roll(10).chrs.join xx 8;\nmy @DECODE_TESTS = < |LHello|G|J|M |m|j|@|e|!t|m|!|? abc|1de|5f >; \n\nfor |@TESTS, |@RAND_TESTS -> $t {\n my $encoded = GSTrans-encode($t);\n my $decoded = GSTrans-decode($encoded);\n say \"String $t encoded is: $encoded, decoded is: $decoded.\";\n die unless $t ~~ $decoded;\n}\nfor @DECODE_TESTS -> $enc {\n say \"Encoded string $enc decoded is: \", GSTrans-decode($enc);\n}\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Task\n\nWrite a program where the program chooses a number between   **1**   and   **10**.\n\nA player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct.\n\nWhen the player has made a successful guess the computer will issue a   \"Well guessed!\"   message,   and the program exits.\n\nA   conditional loop   may be used to repeat the guessing until the user is correct.\n\nRelated tasks\n\n* Bulls and cows\n* Bulls and cows/Player\n* Guess the number/With Feedback\n* Mastermind" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $number = (1..10).pick;\nrepeat {} until prompt(\"Guess a number: \") == $number;\nsay \"Guessed right!\";\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a game (computer program) that follows the following rules:\n\n: : * The computer chooses a number between given set limits.\n * The player is asked for repeated guesses until the the target number is guessed correctly\n * At each guess, the computer responds with whether the guess is:\n\n : : : * higher than the target,\n * equal to the target,\n * less than the target,   or\n * the input was inappropriate.\n\nRelated task\n\n* Guess the number/With Feedback (Player)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $maxnum = prompt(\"Hello, please give me an upper boundary: \");\nuntil 0 < $maxnum < Inf {\n say \"Oops! The upper boundary should be > 0 and not Inf\";\n $maxnum = prompt(\"Please give me a valid upper boundary: \");\n}\n\nmy $count = 0;\nmy $number = (1..$maxnum).pick;\n\nsay \"I'm thinking of a number from 1 to $maxnum, try to guess it!\";\nrepeat until my $guessed-right {\n given prompt(\"Your guess: \") {\n when /^[e|q]/ { say 'Goodbye.'; exit; }\n when not 1 <= $_ <= $maxnum {\n say \"You really should give me a number from 1 to $maxnum.\"\n }\n $count++;\n when $number { $guessed-right = True }\n when $number < $_ { say \"Sorry, my number is smaller.\" }\n when $number > $_ { say \"Sorry, my number is bigger.\" }\n }\n}\nsay \"Great you guessed right after $count attempts!\";\n\n```\n\n```\nHello, please give me an upper boundary: 10 \nI'm thinking of a number from 1 to 10, try to guess it!\nYour guess: 5\nSorry, my number is bigger.\nYour guess: 7\nSorry, my number is smaller.\nYour guess: 6\nGreat you guessed right after 3 attempts!\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a player for the game that follows the following rules:\n\n: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.\n\nThe computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.\n\nRelated tasks\n\n* Guess the number/With Feedback\n* Bulls and cows/Player" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmulti sub MAIN() { MAIN(0, 100) }\nmulti sub MAIN($min is copy where ($min >= 0), $max is copy where ($max > $min)) {\n say \"Think of a number between $min and $max and I'll guess it!\";\n while $min <= $max {\n my $guess = (($max + $min)/2).floor;\n given lc prompt \"My guess is $guess. Is your number higher, lower or equal? \" {\n when /^e/ { say \"I knew it!\"; exit }\n when /^h/ { $min = $guess + 1 }\n when /^l/ { $max = $guess }\n default { say \"WHAT!?!?!\" }\n }\n }\n say \"How can your number be both higher and lower than $max?!?!?\";\n}\n\n```\n\nYou may execute this program with 'raku program' or with 'raku program min max'. Raku creates a usage for us if we don't give the right parameters. It also parses the parameters for us and provides them via $min and $max. We use multi-subs to provide two MAIN subroutines so the user is able to choose between min and max parameters and no parameters at all, in which case min is set to 0 and max to 100." } ]
[ { "role": "user", "content": "Almost every application needs to communicate with the user in some way.\nTherefore, a substantial part of the code deals with the interaction\nof program logic with GUI components.\n\nTypically, the following is needed:\n\n* put values into input fields under program control\n* read and check input from the user\n* pop up dialogs to query the user for further information\n\nTask\n\nFor a minimal \"application\", write a program that presents a form with three components to the user:\n\n: : * a numeric input field (\"Value\")\n * a button (\"increment\")\n * a button (\"random\")\n\nThe field is initialized to zero.\n\nThe user may manually enter a new value into the field,\nor increment its value with the \"increment\" button.\n\nEntering a non-numeric value should be either impossible,\nor issue an error message.\n\nPressing the \"random\" button presents a confirmation dialog,\nand resets the field's value to a random value if the answer is \"Yes\".\n\n(This task may be regarded as an extension of the task Simple windowed application)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Library:** GTK\n\n```\nuse GTK::Simple;\nuse GTK::Simple::App;\n\nmy GTK::Simple::App $app .= new(title => 'GUI component interaction');\n\n$app.set-content(\n my $box = GTK::Simple::VBox.new(\n my $value = GTK::Simple::Entry.new(text => '0'),\n my $increment = GTK::Simple::Button.new(label => 'Increment'),\n my $random = GTK::Simple::Button.new(label => 'Random'),\n )\n);\n\n$app.size-request(400, 100);\n$app.border-width = 20;\n$box.spacing = 10;\n\n$value.changed.tap: {\n ($value.text ||= '0') ~~ s:g/<-[0..9]>//;\n}\n\n$increment.clicked.tap: {\n my $val = $value.text; $val += 1; $value.text = $val.Str\n}\n\n$random.clicked.tap: {\n # Dirty hack to work around the fact that GTK::Simple doesn't provide\n # access to GTK message dialogs yet :P\n if run «zenity --question --text \"Reset to random value?\"» {\n $value.text = (^100).pick.Str\n }\n}\n\n$app.run;\n\n```" } ]
[ { "role": "user", "content": "In addition to fundamental GUI component interaction, an application should\ndynamically enable and disable GUI components, to give some guidance to the\nuser, and prohibit (inter)actions which are inappropriate in the current state\nof the application.\n\nTask\n\nSimilar to the task GUI component interaction, write a program\nthat presents a form with three components to the user:\n\n: : 1. a numeric input field (\"Value\")\n 2. a button   (\"increment\")\n 3. a button   (\"decrement\")\n\nThe field is initialized to zero.\nThe user may manually enter a new value into the field,\nincrement its value with the \"increment\" button,\nor decrement the value with the \"decrement\" button.\n\nThe input field should be enabled only when its value is zero.\nThe \"increment\" button only as long as the field's value is less then 10:\nWhen the value 10 is reached, the button should go into a disabled state.\nAnalogously, the \"decrement\" button should be enabled only as long as\nthe value is greater than zero.\n\nEffectively, the user can now either increment up to 10, or down to zero.\nManually entering values outside that range is still legal,\nbut the buttons should reflect that and enable/disable accordingly." }, { "role": "assistant", "content": "(formerly Perl 6)\nExtremely basic implementation using the GTK library.\n\n```\nuse GTK::Simple;\nuse GTK::Simple::App;\n\nmy GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' );\n\n$app.set-content(\n my $box = GTK::Simple::HBox.new(\n my $inc = GTK::Simple::Button.new( label => ' + ' ),\n my $value = GTK::Simple::Entry.new,\n my $dec = GTK::Simple::Button.new( label => ' - ' )\n )\n);\n\n$app.border-width = 10;\n$box.spacing = 10;\n\n$value.changed.tap: {\n $value.text.=subst(/\\D/, '');\n $inc.sensitive = $value.text < 10;\n $dec.sensitive = $value.text > 0;\n}\n\n$value.text = '0';\n\n$inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str }\n$dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str }\n\n$app.run;\n\n```" } ]
[ { "role": "user", "content": "The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling.\n\nThis is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations and menubars.\n\nThe idea is to determine the physical display parameters for the maximum height and width of the usable display area in pixels (without scrolling).\n\nThe values calculated should represent the usable desktop area of a window maximized to fit the the screen.\n\nConsiderations\n\n--- Multiple Monitors\n\nFor multiple monitors, the values calculated should represent the size of the usable display area on the monitor which is related to the task (i.e.:   the monitor which would display a window if such instructions were given).\n\n--- Tiling Window Managers\n\nFor a tiling window manager, the values calculated should represent the maximum height and width of the display area of the maximum size a window can be created (without scrolling). This would typically be a full screen window (minus any areas occupied by desktop bars), unless the window manager has restrictions that prevents the creation of a full screen window, in which case the values represent the usable area of the desktop that occupies the maximum permissible window size (without scrolling)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nThis is kind-of a silly task. The maximum window size is going to depend on your OS, hardware, display server and graphics toolkit, not your programming language. Taken at face value, using a Linux system running an X11 display server, the maximum displayable window size is the resolution of your monitor. Basically, the size of your desktop viewport. The Raku module X11::libxdo returns the desktop viewport size for get-desktop-dimensions which is the effective maximum window size.\n\n```\nuse X11::libxdo;\n\nmy $xdo = Xdo.new;\n\nmy ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );\n\nsay \"Desktop viewport dimensions: (maximum-fullscreen size) $dw x $dh\";\n\n```\n\nOn my system returns:\n\n```\nDesktop viewport dimensions: (maximum-fullscreen size) 1920 x 1080\n```" } ]
[ { "role": "user", "content": "The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:\n\n* If   n   is     **1**     then the sequence ends.\n* If   n   is   **even** then the next   n   of the sequence   `= n/2`\n* If   n   is   **odd**   then the next   n   of the sequence   `= (3 * n) + 1`\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\nThis sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):\n\n: : : * hailstone sequence,   hailstone numbers\n * 3x + 2 mapping,   3n + 1 problem\n * Collatz sequence\n * Hasse's algorithm\n * Kakutani's problem\n * Syracuse algorithm,   Syracuse problem\n * Thwaites conjecture\n * Ulam's problem\n\nThe hailstone sequence is also known as   *hailstone numbers*   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\nTask\n\n1. Create a routine to generate the hailstone sequence for a number.\n2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with `27, 82, 41, 124` and ending with `8, 4, 2, 1`\n3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. \n   (But don't show the actual sequence!)\n\nSee also\n\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }\n\nmy @h = hailstone(27);\nsay \"Length of hailstone(27) = {+@h}\";\nsay ~@h;\n\nmy $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );\nsay \"Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000\";\n```\n\nOutput:\n\n```\nLength of hailstone(27) = 112\n27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1\nMax length 351 was found for hailstone(77031) for numbers < 100_000\n\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok?\n\nThe code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an internal corruption has been detected and it would be dangerous and irresponsible to continue.\n\nReferences\n\n* Wikipedia: Halt and Catch Fire\n\nRelated Tasks\n\n* Program termination" }, { "role": "assistant", "content": "```\n++8\n\n```\n\nSyntactically: Valid.\n\nSemantically: Change the mathematical concept of 8 to 9, either in your whole computer, or maybe the whole universe.\n\nFails with this run-time error:\n\nOutput:\n\n```\nCannot resolve caller prefix:<++>(Int:D); the following candidates\nmatch the type but require mutable arguments:\n (Mu:D $a is rw)\n (Int:D $a is rw --> Int:D)\n\nThe following do not match for other reasons:\n (Bool $a is rw)\n (Mu:U $a is rw)\n (Num:D $a is rw)\n (Num:U $a is rw)\n (int $a is rw --> int)\n (num $a is rw --> num)\n in block <unit> at -e line 1\n```\n\nAlternately, and perhaps more community condoned, to end the program as soon as possible without trying to change the Laws of the Universe, you could just enter:\n\n```\ndie\n\n```\n\nIn REPL:\n\n```\nDied\n in block <unit> at <unknown file> line 1\n```\n\nSame character count, exits the program as soon as possible (though trappable if desired through the exception system,) and it looks more like an intentional act rather than a typo. Plus, you can add a message that will be added *when* it dies to explain why.\n\nHere is a silly alternative : A standalone Unicode counterpart for the yada yada yada operator takes up 3 code units but visually just a single codepoint,\n\nOutput:\n\n```\ncat test.raku ; wc test.raku\n…\n1 1 4 test.raku\n\nraku -c test.raku ; echo $?\nSyntax OK\n0\n\nraku test.raku ; echo $?\nStub code executed\n in block <unit> at test.raku line 1\n\n1\n```\n\nHowever when I tried to combine all to test against the Test module, the last one somehow lived through an EVAL,\n\n```\nuse Test;\n\ndies-ok { ++8 };\ndies-ok { die };\ndies-ok { … };\n\neval-dies-ok '++8';\neval-dies-ok 'die';\neval-dies-ok '…' ;\n\n```\n\nOutput:\n\n```\nok 1 -\nok 2 -\nok 3 -\nok 4 -\nok 5 -\nnot ok 6 -\n# Failed test at all.raku line 11\n```\n\nso it is indeed at one's discretion whether this one is qualified as a crasher." } ]