messages
listlengths 2
2
|
---|
[
{
"role": "user",
"content": "Create a Hash/Associative Array/Dictionary-like object that can be initialized with key/value pairs. The object should behave like a native Hash/Associative Array/Dictionary of the language, but with the following differences:\n\n* No new keys can be added;\n* Keys cannot be removed;\n* Attempting to delete a key should set that keys value back to that used during initialisation.\n\n(The value assigned to keys may be changed by normal assignment however).\n\nIf the language supports **Magic Methods**, then show how these work."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.08\n\nHere we use delegation to handle all the normal hash methods that we don't need to override to define our new class.\n\n```\nclass FixedHash {\n has $.hash handles *;\n method new(*@args) { self.bless: hash => Hash.new: @args }\n method AT-KEY(FixedHash:D: $key is copy) is rw {\n $!hash.EXISTS-KEY($key) ?? $!hash.AT-KEY($key) !! Failure.new(q{can't store value for unknown key});\n }\n method DELETE-KEY($key) { $!hash.{$key} = Nil }\n}\n\n# Testing\nmy $fh = FixedHash.new: \"a\" => 1, \"b\" => 2;\nsay $fh<a b>; # 1 2\n$fh<b>:delete;\nsay $fh<a b>; # 1 Nil\n$fh<b> = 42;\nsay $fh<a b>; # 1 42\nsay $fh<c>; # Nil\n$fh<c> = 43; # error\n\n```\n\nOutput:\n\n```\n(1 2)\n(1 (Any))\n(1 42)\ncan't store value for unknown key\n in block <unit> at native-demonstration.p6:17\n\nActually thrown at:\n in block <unit> at native-demonstration.p6:17\n```\n\nBy defining FALLBACK any class can handle undefined method calls. Since any class inherits plenty of methods from Any our magic object will be more of a novice conjurer then a master wizard proper.\n\n```\nclass Magic {\n has %.hash;\n multi method FALLBACK($name, |c) is rw { # this will eat any extra parameters\n %.hash{$name}\n }\n\n multi method FALLBACK($name) is rw {\n %.hash{$name}\n }\n}\n\nmy $magic = Magic.new;\n$magic.foo = 10;\nsay $magic.foo;\n$magic.defined = False; # error\n\n```\n\nOutput:\n\n```\n10\nCannot modify an immutable Bool\n in block <unit> at native-demonstration.p6:15\n```"
}
]
|
[
{
"role": "user",
"content": "A control code is a text character or sequence of characters with a special meaning that, rather than print a text character to the terminal or screen, instructs the computer to do something text-related. Examples include:\n\n* `NUL` (ASCII 0) = The null terminator. Most programming languages silently place this at the end of a string so that the print function knows when to stop.\n* `\\n` (New Line) = This tells the print function to start a new line. Older computers don't have this, rather they use an ASCII 13 (carriage return) followed by an ASCII 10 (line feed).\n* `\\` (Escape Character) = Any control code placed directly after the escape character loses is special meaning and is printed as-is.\n* `%d` = Insert a base 10 numeral into the string. The value is loaded from a variable specified after the string, separated by commas.\n\nThe C code below shows the `%d` control code in action:\n\n```\nint foo = 1;\nint bar = 2;\nint baz = foo + bar;\nprintf(\"%d plus %d is: %d\",foo,bar,baz); //outputs \"1 plus 2 is: 3\"\n\n```\n\nTask\n\nAdd a new control code to your language's standard print function, which does some sort of text related task that is not already built into the language. Have the standard print function print a string that uses that code, and display the output. What the control code actually does is up to you, but some examples include:\n\n* Changing the color of the text\n* Starting a new line at a custom location, without padding the string with blank spaces\n\nIf the language allows, try to make something entirely new that isn't just a macro of existing control codes combined to produce a trivial result (e.g. `\\n\\n\\n\\n` for four new lines would be trivial)\n\nIf your language doesn't allow you to modify the standard print function, note it.\n(This is a draft task for now because I don't know if anything other than assembly can do this.)"
},
{
"role": "assistant",
"content": "This, in general would be a bad idea. It isn't smart to add a lot of overhead to core functions, especially for so little gain. That being said, something being a bad idea never stopped us before.\n\nprintf already has so many directives, most of the good mnemonics are already taken. Add a \"commas\" directive as %y and an \"invert\" directive as %z.\n\nSome languages already have a commas directive as that one is actually useful. I doubt if any language has an \"invert\" directive.\n\nThis is *really* basic and sketchy. It only modifies printf, not sprintf, so probably isn't terribly useful as is... but it satisfies the task requirements. It actually *does* add new, non-standard directives to the core printf function, not just implement a separate formatting function to pre-format a string which is then passed to the printing function.\n\n```\nuse Lingua::EN::Numbers;\nuse Acme::Text::UpsideDown;\n\nsub printf (Str $format is copy, *@vars is copy) {\n my @directives = $format.comb(/ <?after <-[%]>|^> '%' <[ +0#-]>* <alpha>/);\n for ^@directives {\n if @directives[$_] eq '%y' {\n $format.=subst('%y', '%s');\n @vars[$_].=,\n } elsif @directives[$_] eq '%z' {\n $format.=subst('%z', '%s');\n @vars[$_].=&upsidedown;\n }\n }\n &CORE::printf($format, @vars)\n}\n\nprintf \"Integer %d with commas: %y\\nSpelled out: %s\\nInverted: %z\\n\",\n 12345, 12345, 12345.&cardinal, 12345.&cardinal;\n\n```\n\nOutput:\n\n```\nInteger 12345 with commas: 12,345\nSpelled out: twelve thousand, three hundred forty-five\nInverted: ǝʌᴉɟ-ʎʇɹoɟ pǝɹpunɥ ǝǝɹɥʇ ‘puɐsnoɥʇ ǝʌꞁǝʍʇ\n```"
}
]
|
[
{
"role": "user",
"content": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.\n\nThe CSV format is flexible but somewhat ill-defined.\n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\nTask\n\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n```\nC1,C2,C3,C4,C5\n1,5,9,13,17\n2,6,10,14,18\n3,7,11,15,19\n4,8,12,16,20\n\n```\n\n*Suggestions*\n\nShow how to add a column, headed 'SUM', of the sums of the rows.\nIf possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\nRelated tasks\n\n* Convert\\_CSV\\_records\\_to\\_TSV"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nOn the face of it this task is pretty simple. Especially given the sample CSV file and the total lack of specification of *what* changes to make to the file. Something like this would suffice.\n\n```\nmy $csvfile = './whatever.csv';\nmy $fh = open($csvfile, :r);\nmy @header = $fh.get.split(',');\nmy @csv = map {[.split(',')]>>.Num}, $fh.lines;\nclose $fh;\n\nmy $out = open($csvfile, :w);\n$out.say((@header,'SUM').join(','));\n$out.say((@$_, [+] @$_).join(',')) for @csv;\nclose $out;\n\n```\n\nBut if your CSV file is at all complex you are better off using a CSV parsing module. (Complex meaning fields that contain commas, quotes, newlines, etc.)\n\n```\nuse Text::CSV;\nmy $csvfile = './whatever.csv';\nmy @csv = Text::CSV.parse-file($csvfile);\n# modify(@csv); # do whatever;\ncsv-write-file( @csv, :file($csvfile) );\n\n```"
}
]
|
[
{
"role": "user",
"content": "Consider a simplified CSV format where all rows are separated by a newline\nand all columns are separated by commas.\n\nNo commas are allowed as field data, but the data may contain\nother characters and character sequences that would\nnormally be *escaped* when converted to HTML\n\nTask\n\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data.\n\nUse the following data as the CSV text to convert, and show your output.\n\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\nExtra credit\n\n*Optionally* allow special formatting for the first row of the table as if it is the tables header row\n(via <thead> preferably; CSS if you must)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.09\n\nA very lispy solution:\n\n```\nmy $str = \"Character,Speech\nThe multitude,The messiah! Show us the messiah!\nBrians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\nThe multitude,Who are you?\nBrians mother,I'm his mother; that's who!\nThe multitude,Behold his mother! Behold his mother!\";\n\n# comment the next line out, if you want to read from standard input instead of the hard-coded $str above\n# my $str = $*IN.slurp;\n\nmy &escape = *.trans(« & < > » => « & < > »); # a function with one argument that escapes the entities\nmy &tag = {\"<$^tag>\"~$^what~\"</$^tag>\"};\n\nprintf\n'<!DOCTYPE html>\n<html>\n<head><title>Some Text</title></head>\n<body><table>\n%s\n</table></body></html>\n', [~] # concatenation reduction ('a', 'b', 'c') → 'abc'\n(escape($str).split(/\\n/) # escape the string and split at newline\n ==> map -> $line {tag 'tr', # feed that into a map, that map function will tag as 'tr, and has an argument called $line\n ([~] $line.split(/','/)\\ # split $line at ',', \n # that / at the end is just an unspace, you can omit it, but then you have to delete\n # all whitespace and comments between split(…) and .map\n .map({tag 'td', $^cell}))})\\ # map those cells as td\n\t\t .join(\"\\n\"); # append a newline for nicer output\n```\n\nOutput:\n\n```\n<!DOCTYPE html>\n<html>\n<head><title>Some Text</title></head>\n<body><table>\n<tr><td>Character</td><td>Speech</td></tr>\n<tr><td>The multitude</td><td>The messiah! Show us the messiah!</td></tr>\n<tr><td>Brians mother</td><td><angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry></td></tr>\n<tr><td>The multitude</td><td>Who are you?</td></tr>\n<tr><td>Brians mother</td><td>I'm his mother; that's who!</td></tr>\n<tr><td>The multitude</td><td>Behold his mother! Behold his mother!</td></tr>\n</table></body></html>\n```"
}
]
|
[
{
"role": "user",
"content": "The name **cuban** has nothing to do with Cuba (the country), but has to do with the\nfact that cubes (3rd powers) play a role in its definition.\n\nSome definitions of cuban primes\n: : * primes which are the difference of two consecutive cubes.\n * primes of the form: (n+1)3 - n3.\n * primes of the form: n3 - (n-1)3.\n * primes *p* such that n2(*p*+n) is a cube for some n>0.\n * primes *p* such that 4*p* = 1 + 3n2.\n\nCuban primes were named in 1923 by Allan Joseph Champneys Cunningham.\n\nTask requirements\n: : * show the first 200 cuban primes (in a multi─line horizontal format).\n * show the 100,000th cuban prime.\n * show all cuban primes with commas (if appropriate).\n * show all output here.\n\nNote that **cuban prime** isn't capitalized (as it doesn't refer to the nation of Cuba).\n\nAlso see\n: * Wikipedia entry: cuban prime.\n * MathWorld entry: cuban prime.\n * The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd *example* on this OEIS web page."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Library:** ntheory\n\n### The task (k == 1)\n\nNot the most efficient, but concise, and good enough for this task. Use the ntheory library for prime testing; gets it down to around 20 seconds.\n\n```\nuse Lingua::EN::Numbers;\nuse ntheory:from<Perl5> <:all>;\n\nmy @cubans = lazy (1..Inf).map({ ($_+1)³ - .³ }).grep: *.&is_prime;\n\nput @cubans[^200]».&comma».fmt(\"%9s\").rotor(10).join: \"\\n\";\n\nput '';\n\nput @cubans[99_999]., # zero indexed\n\n```\n\nOutput:\n\n```\n 7 19 37 61 127 271 331 397 547 631\n 919 1,657 1,801 1,951 2,269 2,437 2,791 3,169 3,571 4,219\n 4,447 5,167 5,419 6,211 7,057 7,351 8,269 9,241 10,267 11,719\n 12,097 13,267 13,669 16,651 19,441 19,927 22,447 23,497 24,571 25,117\n 26,227 27,361 33,391 35,317 42,841 45,757 47,251 49,537 50,311 55,897\n 59,221 60,919 65,269 70,687 73,477 74,419 75,367 81,181 82,171 87,211\n 88,237 89,269 92,401 96,661 102,121 103,231 104,347 110,017 112,327 114,661\n 115,837 126,691 129,169 131,671 135,469 140,617 144,541 145,861 151,201 155,269\n 163,567 169,219 170,647 176,419 180,811 189,757 200,467 202,021 213,067 231,019\n 234,361 241,117 246,247 251,431 260,191 263,737 267,307 276,337 279,991 283,669\n 285,517 292,969 296,731 298,621 310,087 329,677 333,667 337,681 347,821 351,919\n 360,187 368,551 372,769 374,887 377,011 383,419 387,721 398,581 407,377 423,001\n 436,627 452,797 459,817 476,407 478,801 493,291 522,919 527,941 553,411 574,219\n 584,767 590,077 592,741 595,411 603,457 608,851 611,557 619,711 627,919 650,071\n 658,477 666,937 689,761 692,641 698,419 707,131 733,591 742,519 760,537 769,627\n 772,669 784,897 791,047 812,761 825,301 837,937 847,477 863,497 879,667 886,177\n 895,987 909,151 915,769 925,741 929,077 932,419 939,121 952,597 972,991 976,411\n 986,707 990,151 997,057 1,021,417 1,024,921 1,035,469 1,074,607 1,085,407 1,110,817 1,114,471\n1,125,469 1,155,061 1,177,507 1,181,269 1,215,397 1,253,887 1,281,187 1,285,111 1,324,681 1,328,671\n1,372,957 1,409,731 1,422,097 1,426,231 1,442,827 1,451,161 1,480,519 1,484,737 1,527,247 1,570,357\n\n1,792,617,147,127\n```\n\n### k == 2 through 10\n\nAfter reading up a bit, the general equation for cuban primes is prime numbers of the form ((x+k)3 - x3)/k where k mod 3 is not equal 0.\n\nThe cubans where k == 1 (the focus of this task) is one of many possible groups. In general, it seems like the cubans where k == 1 and k == 2 are the two primary cases, but it is possible to have cubans with a k of any integer that is not a multiple of 3.\n\nHere are the first 20 for each valid k up to 10:\n\n```\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nfor 2..10 -> \\k {\n next if k %% 3;\n my @cubans = lazy (1..Inf).map({ (($_+k)³ - .³)/k }).grep: *.is-prime;\n put \"First 20 cuban primes where k = {k}:\";\n put @cubans[^20]».&comma».fmt(\"%7s\").rotor(10).join: \"\\n\";\n put '';\n}\n\n```\n\nOutput:\n\n```\nFirst 20 cuban primes where k = 2:\n 13 109 193 433 769 1,201 1,453 2,029 3,469 3,889\n 4,801 10,093 12,289 13,873 18,253 20,173 21,169 22,189 28,813 37,633\n\nFirst 20 cuban primes where k = 4:\n 31 79 151 367 1,087 1,327 1,879 2,887 3,271 4,111\n 4,567 6,079 7,207 8,431 15,991 16,879 17,791 19,687 23,767 24,847\n\nFirst 20 cuban primes where k = 5:\n 43 67 97 223 277 337 727 823 1,033 1,663\n 2,113 2,617 2,797 3,373 4,003 5,683 6,217 7,963 10,273 10,627\n\nFirst 20 cuban primes where k = 7:\n 73 103 139 181 229 283 409 643 733 829\n 1,039 1,153 1,399 1,531 1,669 2,281 2,803 3,181 3,583 3,793\n\nFirst 20 cuban primes where k = 8:\n 163 379 523 691 883 2,203 2,539 3,691 5,059 5,563\n 6,091 7,219 8,443 9,091 10,459 11,923 15,139 19,699 24,859 27,091\n\nFirst 20 cuban primes where k = 10:\n 457 613 997 1,753 2,053 2,377 4,357 6,373 9,433 13,093\n 16,453 21,193 27,673 28,837 31,237 37,657 46,153 47,653 49,177 62,233\n```\n\n### k == 2^128\n\nNote that Raku has native support for arbitrarily large integers and does not need to generate primes to test for primality. Using k of 2^128; finishes in *well* under a second.\n\n```\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nmy \\k = 2**128;\nput \"First 10 cuban primes where k = {k}:\";\n.&comma.put for (lazy (0..Inf).map({ (($_+k)³ - .³)/k }).grep: *.is-prime)[^10];\n\n```\n\n```\nFirst 10 cuban primes where k = 340282366920938463463374607431768211456:\n115,792,089,237,316,195,423,570,985,008,687,908,160,544,961,995,247,996,546,884,854,518,799,824,856,507\n115,792,089,237,316,195,423,570,985,008,687,908,174,836,821,405,927,412,012,346,588,030,934,089,763,531\n115,792,089,237,316,195,423,570,985,008,687,908,219,754,093,839,491,289,189,512,036,211,927,493,764,691\n115,792,089,237,316,195,423,570,985,008,687,908,383,089,629,961,541,751,651,931,847,779,176,235,685,011\n115,792,089,237,316,195,423,570,985,008,687,908,491,299,422,642,400,183,033,284,972,942,478,527,291,811\n115,792,089,237,316,195,423,570,985,008,687,908,771,011,528,251,411,600,000,178,900,251,391,998,361,371\n115,792,089,237,316,195,423,570,985,008,687,908,875,137,932,529,218,769,819,971,530,125,513,071,648,307\n115,792,089,237,316,195,423,570,985,008,687,908,956,805,700,590,244,001,051,181,435,909,137,442,897,427\n115,792,089,237,316,195,423,570,985,008,687,909,028,264,997,643,641,078,378,490,103,469,808,767,771,907\n115,792,089,237,316,195,423,570,985,008,687,909,158,933,426,541,281,448,348,425,952,723,607,761,904,131\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\n**n** is smallest prime such that the difference of successive terms are the smallest cubics of positive integers,\nwhere **n** < **15000**."
},
{
"role": "assistant",
"content": "A two character difference from the Quadrat Special Primes entry. (And it could have been one.)\n\n```\nmy @sqp = 2, -> $previous {\n my $next;\n for (1..∞).map: *³ {\n $next = $previous + $_;\n last if $next.is-prime;\n }\n $next\n} … *;\n\nsay \"{+$_} matching numbers:\\n\", $_».fmt('%5d').batch(7).join: \"\\n\" given\n @sqp[^(@sqp.first: * > 15000, :k)];\n\n```\n\nOutput:\n\n```\n23 matching numbers:\n 2 3 11 19 83 1811 2027\n 2243 2251 2467 2531 2539 3539 3547\n 4547 5059 10891 12619 13619 13627 13691\n13907 14419\n```"
}
]
|
[
{
"role": "user",
"content": "A Cullen number is a number of the form **n × 2n + 1** where **n** is a natural number.\n\nA Woodall number is very similar. It is a number of the form **n × 2n - 1** where **n** is a natural number.\n\nSo for each **n** the associated Cullen number and Woodall number differ by 2.\n\n*Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.*\n\n**Cullen primes** are Cullen numbers that are prime. Similarly, **Woodall primes** are Woodall numbers that are prime.\n\nIt is common to list the Cullen and Woodall primes by the value of **n** rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, **n** == 4713, has 1423 digits when evaluated.\n\nTask\n\n* Write procedures to find Cullen numbers and Woodall numbers.\n\n* Use those procedures to find and show here, on this page the first 20 of each.\n\nStretch\n\n* Find and show the first **5** **Cullen primes** in terms of **n**.\n\n* Find and show the first **12** **Woodall primes** in terms of **n**.\n\nSee also\n\n* OEIS:A002064 - Cullen numbers: a(n) = n\\*2^n + 1\n\n* OEIS:A003261 - Woodall (or Riesel) numbers: n\\*2^n - 1\n\n* OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k\\*2^k + 1 is prime\n\n* OEIS:A002234 - Numbers k such that the Woodall number k\\*2^k - 1 is prime"
},
{
"role": "assistant",
"content": "```\nmy @cullen = ^∞ .map: { $_ × 1 +< $_ + 1 };\nmy @woodall = ^∞ .map: { $_ × 1 +< $_ - 1 };\n\nput \"First 20 Cullen numbers: ( n × 2**n + 1)\\n\", @cullen[1..20]; # A002064\nput \"\\nFirst 20 Woodall numbers: ( n × 2**n - 1)\\n\", @woodall[1..20]; # A003261\nput \"\\nFirst 5 Cullen primes: (in terms of n)\\n\", @cullen.grep( &is-prime, :k )[^5]; # A005849\nput \"\\nFirst 12 Woodall primes: (in terms of n)\\n\", @woodall.grep( &is-prime, :k )[^12]; # A002234\n\n```\n\nOutput:\n\n```\nFirst 20 Cullen numbers: ( n × 2**n + 1)\n3 9 25 65 161 385 897 2049 4609 10241 22529 49153 106497 229377 491521 1048577 2228225 4718593 9961473 20971521\n\nFirst 20 Woodall numbers: ( n × 2**n - 1)\n1 7 23 63 159 383 895 2047 4607 10239 22527 49151 106495 229375 491519 1048575 2228223 4718591 9961471 20971519\n\nFirst 5 Cullen primes: (in terms of n)\n1 141 4713 5795 6611\n\nFirst 12 Woodall primes: (in terms of n)\n2 3 6 30 75 81 115 123 249 362 384 462\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a stateful function, class, generator or co-routine that takes a series of floating point numbers, *one at a time*, and returns the running standard deviation of the series.\n\nThe task implementation should use the most natural programming style of those listed for the function in the implementation language; the task *must* state which is being used.\n\nDo not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.\n\nTest case\n\nUse this to compute the standard deviation of this demonstration set, \n\n{\n2\n,\n4\n,\n4\n,\n4\n,\n5\n,\n5\n,\n7\n,\n9\n}\n{\\displaystyle {\\displaystyle \\{2,4,4,4,5,5,7,9\\}}}\n, which is \n\n2\n{\\displaystyle {\\displaystyle 2}}\n.\n\nRelated tasks\n\n* Random numbers\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nUsing a closure:\n\n```\nsub sd (@a) {\n my $mean = @a R/ [+] @a;\n sqrt @a R/ [+] map (* - $mean)², @a;\n}\n \nsub sdaccum {\n my @a;\n return { push @a, $^x; sd @a; };\n}\n \nmy &f = sdaccum;\nsay f $_ for 2, 4, 4, 4, 5, 5, 7, 9;\n\n```\n\nUsing a state variable (remember that <(x-<x>)²> = <x²> - <x>²):\n\n```\nsub stddev($x) {\n sqrt\n ( .[2] += $x²) / ++.[0]\n - ((.[1] += $x ) / .[0])²\n given state @;\n}\n\nsay .&stddev for <2 4 4 4 5 5 7 9>;\n\n```\n\nOutput:\n\n```\n0\n1\n0.942809041582063\n0.866025403784439\n0.979795897113271\n1\n1.39970842444753\n2\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.\n\nNote\n\nThe **IEEE 754** binary floating point representations of numbers like **2.86** and **.0765** are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.\n\nUse the values:\n\n: : * 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n * 2 milkshakes at $2.86 each, and\n * a tax rate of 7.65%.\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)\n\nCompute and output (show results on this page):\n\n: : * the total price before tax\n * the tax\n * the total with tax\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.\n\nThe output must show dollars and cents with a decimal point.\n\nThe three results displayed should be:\n\n: : * 22000000000000005.72\n * 1683000000000000.44\n * 23683000000000006.16\n\nDollar signs and thousands separators are optional."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.01\n\nNo need for a special type in Raku, since the Rat type is used for normal fractions.\n(In order to achieve imprecision, you have to explicitly use scientific notation,\nor use the Num type, or calculate a result that requires a denominator in excess of 2 \\*\\* 64. (There's no limit on the numerator.))\n\n```\nmy @check = q:to/END/.lines.map: { [.split(/\\s+/)] };\n Hamburger 5.50 4000000000000000\n Milkshake 2.86 2\n END\n\nmy $tax-rate = 0.0765;\n\nmy $fmt = \"%-10s %8s %18s %22s\\n\";\n\nprintf $fmt, <Item Price Quantity Extension>;\n\nmy $subtotal = [+] @check.map: -> [$item,$price,$quant] {\n my $extension = $price * $quant;\n printf $fmt, $item, $price, $quant, fix2($extension);\n $extension;\n}\n\nprintf $fmt, '', '', '', '-----------------';\nprintf $fmt, '', '', 'Subtotal ', $subtotal;\n\nmy $tax = ($subtotal * $tax-rate).round(0.01);\nprintf $fmt, '', '', 'Tax ', $tax;\n\nmy $total = $subtotal + $tax;\nprintf $fmt, '', '', 'Total ', $total;\n\n# make up for lack of a Rat fixed-point printf format\nsub fix2($x) { ($x + 0.001).subst(/ <?after \\.\\d\\d> .* $ /, '') }\n\n```\n\nOutput:\n\n```\nItem Price Quantity Extension\nHamburger 5.50 4000000000000000 22000000000000000.00\nMilkshake 2.86 2 5.72\n -----------------\n Subtotal 22000000000000005.72\n Tax 1683000000000000.44\n Total 23683000000000006.16\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nTask\n\nCreate a simple demonstrative example of Currying in a specific language.\n\nAdd any historic details as to how the feature made its way into the language."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nAll callable objects have an \"assuming\" method that can do partial application of either positional or named arguments. Here we curry the built-in subtraction operator.\n\n```\nmy &negative = &infix:<->.assuming(0);\nsay negative 1;\n\n```\n\nOutput:\n\n```\n-1\n```"
}
]
|
[
{
"role": "user",
"content": "Draw a curve that touches 3 points (1 starting point, 2 medium, 3 final point)\n\n: : 1. Do not use functions of a library, implement the curve() function yourself\n 2. coordinates:(x,y) starting point (10,10) medium point (100,200) final point (200,10)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nKind of bogus. There are an infinite number of curves that pass through those three points. I'll assume a quadratic curve. Lots of bits and pieces borrowed from other tasks to avoid relying on library functions.\n\nSaved as a png for wide viewing support. Note that png coordinate systems have 0,0 in the upper left corner.\n\n```\nuse Image::PNG::Portable;\n\n# the points of interest\nmy @points = (10,10), (100,200), (200,10);\n\n# Solve for a quadratic line that passes through those points\nmy (\\a, \\b, \\c) = (rref ([.[0]², .[0], 1, .[1]] for @points) )[*;*-1];\n\n# Evaluate quadratic equation\nsub f (\\x) { a×x² + b×x + c }\n\nmy ($w, $h) = 500, 500; # image size\nmy $scale = 2; # scaling factor\n\nmy $png = Image::PNG::Portable.new: :width($w), :height($h);\n\nmy ($lastx, $lasty) = 8, f(8).round;\n(9 .. 202).map: -> $x {\n my $f = f($x).round;\n line($lastx, $lasty, $x, $f, $png, [0,255,127]);\n ($lastx, $lasty) = $x, $f;\n}\n\n# Highlight the defining points\ndot( | $_, $(255,0,0), $png, 2) for @points;\n\n$png.write: 'Curve-3-points-perl6.png';\n\n# Assorted helper routines \nsub rref (@m) {\n return unless @m;\n my ($lead, $rows, $cols) = 0, @m, @m[0];\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 line($x0 is copy, $y0 is copy, $x1 is copy, $y1 is copy, $png, @rgb) {\n my $steep = abs($y1 - $y0) > abs($x1 - $x0);\n ($x0,$y0,$x1,$y1) »×=» $scale;\n if $steep {\n ($x0, $y0) = ($y0, $x0);\n ($x1, $y1) = ($y1, $x1);\n }\n if $x0 > $x1 {\n ($x0, $x1) = ($x1, $x0);\n ($y0, $y1) = ($y1, $y0);\n }\n my $Δx = $x1 - $x0;\n my $Δy = abs($y1 - $y0);\n my $error = 0;\n my $Δerror = $Δy / $Δx;\n my $y-step = $y0 < $y1 ?? 1 !! -1;\n my $y = $y0;\n next if $y < 0;\n for $x0 .. $x1 -> $x {\n next if $x < 0;\n if $steep {\n $png.set($y, $x, |@rgb);\n } else {\n $png.set($x, $y, |@rgb);\n }\n $error += $Δerror;\n if $error ≥ 0.5 {\n $y += $y-step;\n $error -= 1.0;\n }\n }\n}\n\nsub dot ($X is copy, $Y is copy, @rgb, $png, $radius = 3) {\n ($X, $Y) »×=» $scale;\n for ($X X+ -$radius .. $radius) X ($Y X+ -$radius .. $radius) -> ($x, $y) {\n $png.set($x, $y, |@rgb) if ( $X - $x + ($Y - $y) × i ).abs <= $radius;\n }\n}\n\n```\n\nSee Curve-3-points-perl6.png (offsite .png image)"
}
]
|
[
{
"role": "user",
"content": "A **Curzon number** is defined to be a positive integer **n** for which **2n + 1** is evenly divisible by **2 × n + 1**.\n\n**Generalized Curzon numbers** are those where the positive integer **n**, using a base integer **k**, satisfy the condition that **kn + 1** is evenly divisible by **k × n + 1**.\n\n*Base here does not imply the radix of the counting system; rather the integer the equation is based on. All calculations should be done in base 10.*\n\nGeneralized Curzon numbers only exist for even base integers.\n\nTask\n\n* Find and show the first **50 Generalized Curzon numbers** for even base integers from **2** through **10**.\n\nStretch\n\n* Find and show the **one thousandth**.\n\nSee also\n\n* Numbers Aplenty - Curzon numbers * OEIS:A224486 - Numbers k such that 2\\*k+1 divides 2^k+1 (Curzon numbers)\n\n*and even though it is not specifically mentioned that they are Curzon numbers:*\n\n* OEIS:A230076 - (A007521(n)-1)/4 (Generalized Curzon numbers with a base 4)"
},
{
"role": "assistant",
"content": "```\nsub curzon ($base) { lazy (1..∞).hyper.map: { $_ if (exp($_, $base) + 1) %% ($base × $_ + 1) } };\n\nfor <2 4 6 8 10> {\n my $curzon = .&curzon;\n say \"\\nFirst 50 Curzon numbers using a base of $_:\\n\" ~\n $curzon[^50].batch(10)».fmt(\"%4s\").join(\"\\n\") ~\n \"\\nOne thousandth: \" ~ $curzon[999]\n}\n\n```\n\nOutput:\n\n```\nFirst 50 Curzon numbers using a base of 2:\n 1 2 5 6 9 14 18 21 26 29\n 30 33 41 50 53 54 65 69 74 78\n 81 86 89 90 98 105 113 114 125 134\n 138 141 146 153 158 165 173 174 186 189\n 194 198 209 210 221 230 233 245 249 254\nOne thousandth: 8646\n\nFirst 50 Curzon numbers using a base of 4:\n 1 3 7 9 13 15 25 27 37 39\n 43 45 49 57 67 69 73 79 87 93\n 97 99 105 115 127 135 139 153 163 165\n 169 175 177 183 189 193 199 205 207 213\n 219 235 249 253 255 265 267 273 277 279\nOne thousandth: 9375\n\nFirst 50 Curzon numbers using a base of 6:\n 1 6 30 58 70 73 90 101 105 121\n 125 146 153 166 170 181 182 185 210 233\n 241 242 266 282 290 322 373 381 385 390\n 397 441 445 446 450 453 530 557 562 585\n 593 601 602 605 606 621 646 653 670 685\nOne thousandth: 20717\n\nFirst 50 Curzon numbers using a base of 8:\n 1 14 35 44 72 74 77 129 131 137\n 144 149 150 185 200 219 236 266 284 285\n 299 309 336 357 381 386 390 392 402 414\n 420 441 455 459 470 479 500 519 527 536\n 557 582 600 602 617 639 654 674 696 735\nOne thousandth: 22176\n\nFirst 50 Curzon numbers using a base of 10:\n 1 9 10 25 106 145 190 193 238 253\n 306 318 349 385 402 462 486 526 610 649\n 658 678 733 762 810 990 994 1033 1077 1125\n1126 1141 1149 1230 1405 1422 1441 1485 1509 1510\n1513 1606 1614 1630 1665 1681 1690 1702 1785 1837\nOne thousandth: 46845\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nA **CUSIP** is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.\n\nTask\n\nEnsure the last digit (i.e., the *check digit*) of the **CUSIP** code (the 1st column) is correct, against the following:\n\n* 037833100 Apple Incorporated\n* 17275R102 Cisco Systems\n* 38259P508 Google Incorporated\n* 594918104 Microsoft Corporation\n* 68389X106 Oracle Corporation (*incorrect*)\n* 68389X105 Oracle Corporation\n\nExample pseudo-code below.\n\n```\nalgorithm Cusip-Check-Digit(cusip) is\n Input: an 8-character CUSIP\n\n sum := 0\n for 1 ≤ i ≤ 8 do\n c := the ith character of cusip\n if c is a digit then\n v := numeric value of the digit c\n else if c is a letter then\n p := ordinal position of c in the alphabet (A=1, B=2...)\n v := p + 9\n else if c = \"*\" then\n v := 36\n else if c = \"@\" then\n v := 37\n else if' c = \"#\" then\n v := 38\n end if\n if i is even then\n v := v × 2\n end if\n\n sum := sum + int ( v div 10 ) + v mod 10\n repeat\n \n return (10 - (sum mod 10)) mod 10\nend function\n\n```\n\nSee related tasks\n\n* SEDOL\n* ISIN"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.01\n\n```\nsub divmod ($v, $r) { $v div $r, $v mod $r }\nmy %chr = (flat 0..9, 'A'..'Z', <* @ #>) Z=> 0..*;\n\nsub cuisp-check ($cuisp where *.chars == 9) {\n my ($code, $chk) = $cuisp.comb(8);\n my $sum = [+] $code.comb.kv.map: { [+] (($^k % 2 + 1) * %chr{$^v}).&divmod(10) };\n so (10 - $sum mod 10) mod 10 eq $chk;\n}\n\n# TESTING\nsay \"$_: \", $_.&cuisp-check for <\n037833100\n17275R102\n38259P508\n594918104\n68389X106\n68389X105\n>\n\n```\n\nOutput:\n\n```\n037833100: True\n17275R102: True\n38259P508: True\n594918104: True\n68389X106: False\n68389X105: True\n```"
}
]
|
[
{
"role": "user",
"content": "A given rectangle is made from *m* × *n* squares. If *m* and *n* are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.\n\nWrite a program that calculates the number of different ways to cut an *m* × *n* rectangle. Optionally, show each of the cuts.\n\nPossibly related task: Maze generation for depth-first search."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: C\n\n```\nsub solve($hh, $ww, $recurse) {\n my ($h, $w, $t, @grid) = $hh, $ww, 0;\n state $cnt;\n $cnt = 0 if $recurse;\n\n ($t, $w, $h) = ($w, $h, $w) if $h +& 1;\n return 0 if $h == 1;\n return 1 if $w == 1;\n return $h if $w == 2;\n return $w if $h == 2;\n\n my ($cy, $cx) = ($h, $w) «div» 2;\n my $len = ($h + 1) × ($w + 1);\n @grid[$len--] = 0;\n my @next = -1, -$w-1, 1, $w+1;\n\n for $cx+1 ..^ $w -> $x {\n $t = $cy × ($w + 1) + $x;\n @grid[$_] = 1 for $t, $len-$t;\n walk($cy - 1, $x);\n }\n\n sub walk($y, $x) {\n constant @dir = <0 -1 0 1> Z <-1 0 1 0>;\n $cnt += 2 and return if not $y or $y == $h or not $x or $x == $w;\n my $t = $y × ($w+1) + $x;\n @grid[$_]++ for $t, $len-$t;\n walk($y + @dir[$_;0], $x + @dir[$_;1]) if not @grid[$t + @next[$_]] for 0..3;\n @grid[$_]-- for $t, $len-$t;\n }\n\n $cnt++;\n if $h == $w { $cnt ×= 2 }\n elsif $recurse and not $w +& 1 { solve($w, $h, False) }\n $cnt\n}\n\n((1..9 X 1..9).grep:{ .[0] ≥ .[1] }).flat.map: -> $y, $x {\n say \"$y × $x: \" ~ solve $y, $x, True unless $x +& 1 and $y +& 1;\n}\n\n```\n\nOutput:\n\n```\n2 × 1: 1\n2 × 2: 2\n3 × 2: 3\n4 × 1: 1\n4 × 2: 4\n4 × 3: 9\n4 × 4: 22\n5 × 2: 5\n5 × 4: 39\n6 × 1: 1\n6 × 2: 6\n6 × 3: 23\n6 × 4: 90\n6 × 5: 263\n6 × 6: 1018\n7 × 2: 7\n7 × 4: 151\n7 × 6: 2947\n8 × 1: 1\n8 × 2: 8\n8 × 3: 53\n8 × 4: 340\n8 × 5: 1675\n8 × 6: 11174\n8 × 7: 55939\n8 × 8: 369050\n9 × 2: 9\n9 × 4: 553\n9 × 6: 31721\n9 × 8: 1812667\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDetect a cycle in an iterated function using Brent's algorithm.\n\nDetecting cycles in iterated function sequences is a sub-problem in many computer algorithms, such as factoring prime numbers. Some such algorithms are highly space efficient, such as Floyd's cycle-finding algorithm, also called the \"tortoise and the hare algorithm\". A more time efficient algorithm than \"tortoise and hare\" is Brent's Cycle algorithm. This task will implement Brent's algorithm.\n\nSee https://en.wikipedia.org/wiki/Cycle\\_detection for a discussion of the theory and discussions of other algorithms that are used to solve the problem.\n\nWhen testing the cycle detecting function, you need two things:\n\n1) An iterated function\n\n2) A starting value\n\nThe iterated function used in this example is: f(x) = (x\\*x + 1) modulo 255.\n\nThe starting value used is 3.\n\nWith these as inputs, a sample program output would be:\n\n**3,10,101,2,5,26,167,95,101,2,5,26,167,95,101,2,5,26,167,95,101,2,5,26,167,95,101,2,5,26,167,95,101,2,5,26,167,95,101,2,5**\n\n**Cycle length = 6**\n\n**Start index = 2**\n\nThe output prints the first several items in the number series produced by the iterated function, then identifies how long the cycle is (6) followed by the zero-based index of the start of the first cycle (2). From this you can see that the cycle is:\n\n101,2,5,26,167,95"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016-01\n\nPretty much a line for line translation of the Python code on the Wikipedia page.\n\n```\nsub cyclical-function (\\x) { (x * x + 1) % 255 };\n\nmy ( $l, $s ) = brent( &cyclical-function, 3 );\n\nput join ', ', (3, -> \\x { cyclical-function(x) } ... *)[^20], '...';\nsay \"Cycle length $l.\";\nsay \"Cycle start index $s.\";\nsay (3, -> \\x { cyclical-function(x) } ... *)[$s .. $s + $l - 1];\n\nsub brent (&f, $x0) {\n my $power = my $λ = 1;\n my $tortoise = $x0;\n my $hare = f($x0);\n while ($tortoise != $hare) {\n if $power == $λ {\n $tortoise = $hare;\n $power *= 2;\n $λ = 0;\n }\n $hare = f($hare);\n $λ += 1;\n }\n\n my $μ = 0;\n $tortoise = $hare = $x0;\n $hare = f($hare) for ^$λ;\n\n while ($tortoise != $hare) {\n $tortoise = f($tortoise);\n $hare = f($hare);\n $μ += 1;\n }\n return $λ, $μ;\n}\n\n```\n\nOutput:\n\n```\n3, 10, 101, 2, 5, 26, 167, 95, 101, 2, 5, 26, 167, 95, 101, 2, 5, 26, 167, 95, ...\nCycle length 6.\nCycle start index 2.\n(101 2 5 26 167 95)\n```"
}
]
|
[
{
"role": "user",
"content": "On the event of their marriage, Alf and Betty are gifted a magnificent and weighty set of twenty-six wrought iron letters, from A to Z, by their good friends Anna and Graham.\n\nAlf and Betty have, in their home, a shelf sturdy enough to display their gift, but it is only large enough to hold fifteen of the letters at one time. They decide to select fifteen of the letters and rearrange them every day, as part of their daily workout, and to select a different set of letters from time to time, when they grow bored of the current set.\n\nTo pass the time during their honeymoon, Alf and Betty select their first set of letters and find seven arrangements, one for each day of the week, that they think Anna and Graham would approve of. They are:\n\n```\n Mon: HANDY COILS ERUPT\n Tue: SPOIL UNDER YACHT\n Wed: DRAIN STYLE POUCH\n Thu: DITCH SYRUP ALONE\n Fri: SOAPY THIRD UNCLE\n Sat: SHINE PARTY CLOUD \n Sun: RADIO LUNCH TYPES\n\n```\n\nThey decide to write down instructions for how to rearrange Monday's arrangement of letters into Tuesday's arrangement, Tuesday's to Wednesday's and so on, ending with Sunday's to Monday's.\n\nHowever, rather than use the letters, they number the positions on the shelf from 1 to 15, and use those position numbers in their instructions. They decide to call these instructions \"permutations\".\n\nSo, for example, to move from the Wednesday arrangement to the Thursday arrangement, i.e.\n\n```\nPosition on shelf: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n Wed: D R A I N S T Y L E P O U C H\n Thu: D I T C H S Y R U P A L O N E\n\n```\n\nthey would write the permutation as:\n\n```\n Wed: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n Thu: 1 4 7 14 15 6 8 2 13 11 3 9 12 5 10\n\n```\n\n(i.e. The D that is in position 1 on Thursday stayed in position 1, the I that is in position 2 on Thursday came from position 4, the T in position 3 came from position 7, and so on.)\n\nThey decide to call this \"two-line notation\", because it takes two lines to write it down. They notice that the first line is always going to be the same, so it can be omitted, and simplify it to a \"one-line notation\" that would look like this:\n\n```\n Wed->Thu: 1 4 7 14 15 6 8 2 13 11 3 9 12 5 10\n\n```\n\nAs a subtle nuance, they figure out that when the letters at the right hand end don't move, they can safely leave them off the notation. For example, Mon and Tue both end with T, so for Mon->Tue the one-line notation would be fourteen numbers long rather than fifteen.\n\nThen they notice that the letter at position 9 moves to position 12, the letter at position 12 moves to position 13, and the letter at position 13 moves to position 9, forming the cycle 9->12->13->9->12->13-> etc., which they decide to write as (9 12 13). They call this a 3-cycle, because if they applied the cycle to the letters in those positions three times, they would end up back in their original positions.\n\nThey also notice that the letters in positions 1 and 6 do not move, so they decide to not write down any of the 1-cycles (not just the ones at the end as with the one-line notation.) They also decide that they will always write cycles starting with the smallest number in the cycle, and that when they write down the cycles in a permutation, the will be sorted by the first number in the permutation, smallest first.\n\nThe permutation Wed->Thur has a 10-cycle starting at position 2, a 3-cycle starting at position 9 and two 1-cycles (at positions 1 and 6), so they write down:\n\n```\n Wed->Thu: (2 8 7 3 11 10 15 5 14 4) (9 12 13) \n\n```\n\nThey decide to call this \"cycle notation\". (By pure coincidence all the names they have chosen are the same as those used by mathematicians working in the field of abstract algebra. The abstract algebra term for converting from one-line notation to cycle notation is \"decomposition\". Alf and Betty probably wouldn't have thought of that. 1-cycles, 2-cycles, 3-cycles et cetera are collectively called k-cycles. 2-cycles are also called transpositions. One more piece of terminology: two or more cycles are disjoint if they have no elements in common. The cycles of a permutation written in cycle notation are disjoint.)\n\nAlf and Betty notice that they can perform the first k-cycle as a series of transpositions, swapping the letters in positions 14 and 4, then the letters in positions 5 and 14, then 15 and 5, then 10 and 15 and so on, ending with swapping the letters in positions 4 and 2.\n\nThen it occurs to them that it would be more efficient if one of them took the letter in position 8 and held it while the other moved the letter in position 7 and moved it to position 8, then moved 3 to 7, 11 to 3 and so on. Finally the one who had been holding the letter from position 8 could put it in position 2.\n\nComputer programmers would call this an \"in-place\" solution. The one and two-line notations lend themselves to a not-in-place solution, i.e., having a second shelf that they could conveniently move they letters to while rearranging them.\n\nIf they accidentally did the Wed->Thu permutation on the wrong day of the week they would end up with a jumble of letters that they would need to undo using a Thu->Wed permutation. Mathematicians would call this the inverse of Wed->Thu.\n\nThey could do this in two-line notation by swapping the top and bottom lines and calculating the one-line notation result.\n\n```\n Wed->Thu: 1 4 7 14 15 6 8 2 13 11 3 9 12 5 10\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15\n --------------------------------------------\n Thu->Wed: 1 8 11 2 14 6 3 7 12 15 10 13 9 4 5 \n\n```\n\n(To perform the calculation: The 1 in the top line has a 1 below it, so 1 goes in the first position in the result. The 2 in the second line has an 4 above it, so write 2 in the fourth position in the result. Th 3 in the second line has a seven above it, so write 3 in the seventh position in the result and so on.)\n\nOr they could use cycle notation. To invert a cycle, reverse the order of the numbers in it. To maintain the convention that cycles start with the smallest number in the cycle, move the first number in the cycle to the end before reversing. So (9 13 12) -> (13 12 9) -> (9 12 13). Do this for every cycle.\n\n```\n Wed->Thu: (2 8 7 3 11 10 15 5 14 4) (9 12 13)\n Thu->Wed: (2 4 14 5 15 10 11 3 7 8) (9 13 12)\n \n\n```\n\nIf Alf and Betty went to visit Anna and Graham on a Wednesday and came home on a Friday, they'd need to figure out the permutation Wed->Fri from the permutations Wed->Thu and Thu->Fri. Mathematicians call this either composition or multiplication, and if A is the notation for Wed->Thu and B is the notation for Thu->Fri, they would write it as BA or B∙A. It may seem backwards, but that's they way mathematicians roll.\n\nNote that B∙A will NOT give the same result as A∙B – unlike regular multiplication of numbers, this sort of multiplication is generally not commutative. (There is an exception to this rule; when two or more cycles are disjoint they can be performed in any order.)\n\nThe cycle notation for Thu->Fri is\n\n```\n Thu->Fri: (1 10 4 13 2 8 9 11 3 6) (5 7) (12 14)\n\n```\n\nand the multiplication Thu->Fri∙Wed->Thu gives the result\n\n```\n Wed->Fri: (1 10 15 7 6 ) (2 9 14 13 11 4 8 5 12)\n\n```\n\nThe order of a permutation is the number of times it needs to be applied for the items being rearranged to return to their starting position, and the signature of a permutation is 1 if an even number of transpositions would be required to do the permutation, and -1 if it required an odd number of permutations.\n\nThe order of a permutation is the least common multiple of its cycles' lengths, and the signature is 1 if a permutation has an even number of cycles with an even number of elements, and -1 otherwise.\n\nFor a summary of the mathematics discussed here, and a demonstration of the manual method for multiplying permutations in cycle notation, I suggest the Socratica YouTube video Cycle Notation of Permutations - Abstract Algebra.\n\n(Other suitable videos are also available, including the first three parts of this YouTube playlist by Dr Angela Berardinelli.)\n\nWolfram Alpha is useful resource for testing code. If you enter one-line notation wrapped in parentheses and scroll down a little way when it has finished computing, you will find, amongst other things, the cycle decomposition and the inverse permutation. If you enter cycle notation preceded by the word \"permutation\" it will give the result of multiplying the cycles in all the notations mentioned above as well as the order and signature of the result.\n\nTask\n\n**Notes:**\n\nAlf and Betty chose to represent one-line notation as space delimited numbers without enclosing parentheses, brackets or braces. This representation is not mandated. If it is more convenient to, for example, use comma delimitation and enclosing braces, then do so. Similar considerations apply to their choice of representations for cycles and the cycles of a permutation. State which representations your solution uses.\n\nTheir choice of orderings for cycle notation (i.e. smallest number first for cycles, cycles sorted in ascending order by first number) is not mandated. If your solution uses a different ordering, describe it.\n\nSimilarly, right-to-left evaluation of cycle multiplication as composition of functions is not mandated. Show how Thu->Fri∙Wed->Thu would be written in your solution.\n\nAlf and Betty's system is one-based. If a zero-based system is more appropriate, then use that, but provide the means (e.g. one or more functions, procedures, subroutines, methods, or words, et cetera) to allow conversion to and from zero-based and one-based representations so that user I/O can be one-based. State if this is the case in your solution.\n\nTheir choice of orderings for cycle notation (i.e. smallest number first for cycles, cycles sorted in ascending order by first number) is not mandated. If your solution uses a different ordering, describe it.\n\nTheir choice of omitting trailing 1-cycles in one-line notation and all 1-cycles in cycle-notation is not mandated. Include 1-cycles in either notation if you prefer.\n\nOther names exist for some of the terms used in this task. For example, the signature is also known as the sign or parity. Use whichever terms you are comfortable with, but make it clear what they mean.\n\nData validation is not required for this task. You can assume that all arguments and user inputs are valid. If you do include sanity checks, they should not be to the detriment of the legibility of your code.\n\nIf the required functionality is available as part of your language or in a library well known to the language's user base, state this and consider writing equivalent code for bonus points.\n\n1. Provide routines (i.e. functions, procedures, subroutines, methods, words or whatever your language uses) that\n 1. given two strings containing the same characters as one another, and without repeated characters within the strings, returns the permutation in either one-line or cycle notation that transforms one of the strings into the other.\n 2. given a permutation, returns the inverse permutation, for both cycle and one-line notation.\n 3. given a permutation and a string of unique characters, returns the string with the characters permuted, for both cycle and one-line notation.\n 4. given two permutations A and B in cycle notation, returns a single permutation in cycle notation equivalent to applying first A and then B. i.e. A.B\n 5. convert permutations in one-line notation to cycle notation and vice versa.\n 6. return the order of a permutation.\n 7. return the signature of a permutation.\n2. Demonstrate how Alf and Betty can use this functionality in the scenario described above. Assume that Alf and Betty are novice programmers that have some famiiarity with your language. (i.e. Keep It Simple.) Provide the output from your demonstation code."
},
{
"role": "assistant",
"content": "```\n# one-line\nsub infix:<➜> ($start, $end) {$start.fc.comb(/\\w/).antipairs.hash{ $end.fc.comb(/\\w/) } »+» 1}\n\n# cycle\nsub infix:<➰> ($start, $end) {\n my @one-line = flat ($end ➜ $start);\n my @index = flat 1..+@one-line;\n my ($index, @cycles) = 0;\n for @index {\n my $this = $_ - 1;\n while @one-line[$this] {\n my $next = @one-line[$this];\n @cycles[$index].push: @index[$this];\n @one-line[$this] = Nil;\n $this = $next - 1;\n }\n ++$index;\n }\n @cycles.grep: *.elems > 1\n}\n\n# order of a cycle\nsub order (@cycles) { [lcm] @cycles }\n\n# signature of a cycle\nsub signature (@cycles) {\n (@cycles.elems %% 2 and all @@cycles».elems %% 2) ?? 1 !! -1\n}\n\n# apply a one-line transform\nsub apply-o ($string, @oneline) { $string.comb[@oneline].join }\n\n# apply a cyclical transform\nsub apply-c ($string, @cycle) {\n my @string = flat '', $string.comb;\n @cycle.map: { @string[|$_].=rotate(-1) }\n @string.join\n}\n\n# Alf & Bettys letter arrangements\nmy %arrangment =\n :Mon<HANDYCOILSERUPT>,\n :Tue<SPOILUNDERYACHT>,\n :Wed<DRAINSTYLEPOUCH>,\n :Thu<DITCHSYRUPALONE>,\n :Fri<SOAPYTHIRDUNCLE>,\n :Sat<SHINEPARTYCLOUD>,\n :Sun<RADIOLUNCHTYPES>;\n\n# some convenience variables \nmy @days = <Sun Mon Tue Wed Thu Fri Sat Sun>;\nmy @o = @days.rotor(2 => -1).map: { (%arrangment{.[0]} ➜ %arrangment{.[1]}) »-» 1 }\nmy @c = @days.rotor(2 => -1).map: { (%arrangment{.[0]} ➰ %arrangment{.[1]}) }\n\nmy $today;\n\n# The task\nsay qq:to/ALF&BETTY/;\nOn Thursdays Alf and Betty should rearrange\ntheir letters using these cycles: {gist %arrangment<Wed> ➰ %arrangment<Thu>}\n\nSo that {%arrangment<Wed>} becomes {%arrangment<Wed>.&apply-o: (%arrangment<Wed> ➜ %arrangment<Thu>) »-» 1}\n\nor they could use the one-line notation: {gist %arrangment<Wed> ➜ %arrangment<Thu>}\n\n\nTo revert to the Wednesday arrangement they\nshould use these cycles: {gist %arrangment<Thu> ➰ %arrangment<Wed>}\n\nor with the one-line notation: {gist %arrangment<Thu> ➜ %arrangment<Wed>}\n\nSo that {%arrangment<Thu>} becomes {%arrangment<Thu>.&apply-o: (%arrangment<Thu> ➜ %arrangment<Wed>) »-» 1}\n\n\nStarting with the Sunday arrangement and applying each of the daily\npermutations consecutively, the arrangements will be:\n\n {$today = %arrangment<Sun>}\n\n{join \"\\n\", @days[1..*].map: { sprintf \"%s: %s\", $_, $today = $today.&apply-o: @o[$++] } }\n\n\nTo go from Wednesday to Friday in a single step they should use these cycles:\n{gist %arrangment<Wed> ➰ %arrangment<Fri>}\n\nSo that {%arrangment<Wed>} becomes {%arrangment<Fri>}\n\n\nThese are the signatures of the permutations:\n\n Mon Tue Wed Thu Fri Sat Sun\n {@c.map(&signature)».fmt(\"%2d\").join: ' '}\n\nThese are the orders of the permutations:\n\n Mon Tue Wed Thu Fri Sat Sun\n {@c.map(&order)».fmt(\"%2d\").join: ' '}\n\nApplying the Friday cycle to a string 10 times:\n\n {$today = 'STOREDAILYPUNCH'}\n\n{join \"\\n\", (1..10).map: {sprintf \"%2d %s\", $_, $today = $today.&apply-c: @c[4]} }\nALF&BETTY\n\nsay 'and one last transform:';\nsay 'STOREDAILYPUNCH'.&apply-c: [[<1 6 12 2 3 4 13 15 9 11 5 14 8 10 7>],];\n\n```\n\nOutput:\n\n```\nOn Thursdays Alf and Betty should rearrange\ntheir letters using these cycles: ([2 8 7 3 11 10 15 5 14 4] [9 12 13])\n\nSo that DRAINSTYLEPOUCH becomes DITCHSYRUPALONE\n\nor they could use the one-line notation: (1 4 7 14 15 6 8 2 13 11 3 9 12 5 10)\n\n\nTo revert to the Wednesday arrangement they\nshould use these cycles: ([2 4 14 5 15 10 11 3 7 8] [9 13 12])\n\nor with the one-line notation: (1 8 11 2 14 6 3 7 12 15 10 13 9 4 5)\n\nSo that DITCHSYRUPALONE becomes DRAINSTYLEPOUCH\n\n\nStarting with the Sunday arrangement and applying each of the daily\npermutations consecutively, the arrangements will be:\n\n RADIOLUNCHTYPES\n\nMon: HANDYCOILSERUPT\nTue: SPOILUNDERYACHT\nWed: DRAINSTYLEPOUCH\nThu: DITCHSYRUPALONE\nFri: SOAPYTHIRDUNCLE\nSat: SHINEPARTYCLOUD\nSun: RADIOLUNCHTYPES\n\n\nTo go from Wednesday to Friday in a single step they should use these cycles:\n([1 10 15 7 6] [2 9 14 13 11 4 8 5 12])\n\nSo that DRAINSTYLEPOUCH becomes SOAPYTHIRDUNCLE\n\n\nThese are the signatures of the permutations:\n\n Mon Tue Wed Thu Fri Sat Sun\n -1 -1 1 1 -1 1 -1\n\nThese are the orders of the permutations:\n\n Mon Tue Wed Thu Fri Sat Sun\n 18 30 12 30 10 33 40\n\nApplying the Friday cycle to a string 10 times:\n\n STOREDAILYPUNCH\n\n 1 DNPYAOETISLCRUH\n 2 ORLSEPANTDIUYCH\n 3 PYIDALERNOTCSUH\n 4 LSTOEIAYRPNUDCH\n 5 IDNPATESYLRCOUH\n 6 TORLENADSIYUPCH\n 7 NPYIAREODTSCLUH\n 8 RLSTEYAPONDUICH\n 9 YIDNASELPROCTUH\n10 STOREDAILYPUNCH\n\nand one last transform:\nAUTOPSYCHILDREN\n\n```"
}
]
|
[
{
"role": "user",
"content": "A **cyclops number** is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.\n\nCyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.\n\nThere are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.\n\nTask\n\n* Find and display here on this page the first 50 **cyclops numbers** in base 10 (all of the sub tasks are restricted to base 10).\n\n* Find and display here on this page the first 50 **prime cyclops numbers**. (cyclops numbers that are prime.)\n\n* Find and display here on this page the first 50 **blind prime cyclops numbers**. (prime cyclops numbers that remain prime when \"blinded\"; the zero is removed from the center.)\n\n* Find and display here on this page the first 50 **palindromic prime cyclops numbers**. (prime cyclops numbers that are palindromes.)\n\nStretch\n\n* Find and display the first **cyclops number** greater than **ten million** (10,000,000) and the index (place) in the series where it is found.\n\n* Find and display the first **prime cyclops number** greater than **ten million** (10,000,000) and the index (place) in the series where it is found.\n\n* Find and display the first **blind prime cyclops number** greater than **ten million** (10,000,000) and the index (place) in the series where it is found.\n\n* Find and display the first **palindromic prime cyclops number** greater than **ten million** (10,000,000) and the index (place) in the series where it is found.\n\n(**Note:** there ***are*** no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)\n\nSee also\n\n* OEIS A134808 - Cyclops numbers\n\n* OEIS A134809 - Cyclops primes\n\n* OEIS A329737 - Cyclops primes that remain prime after being \"blinded\"\n\n* OEIS A136098 - Prime palindromic cyclops numbers"
},
{
"role": "assistant",
"content": "<\n\n```\nuse Lingua::EN::Numbers;\n\nmy @cyclops = 0, |flat lazy ^∞ .map: -> $exp {\n my @oom = (exp($exp, 10) ..^ exp($exp + 1, 10)).grep: { !.contains: 0 }\n |@oom.hyper.map: { $_ ~ 0 «~« @oom }\n}\n\nmy @prime-cyclops = @cyclops.grep: { .is-prime };\n\nfor '', @cyclops,\n 'prime ', @prime-cyclops,\n 'blind prime ', @prime-cyclops.grep( { .trans('0' => '').is-prime } ),\n 'palindromic prime ', @prime-cyclops.grep( { $_ eq .flip } )\n -> $type, $iterator {\n say \"\\n\\nFirst 50 {$type}cyclops numbers:\\n\" ~ $iterator[^50].batch(10)».fmt(\"%7d\").join(\"\\n\") ~\n \"\\n\\nFirst {$type}cyclops number > 10,000,000: \" ~ comma($iterator.first: * > 1e7 ) ~\n \" - at (zero based) index: \" ~ comma $iterator.first: * > 1e7, :k;\n}\n\n```\n\nOutput:\n\n```\nFirst 50 cyclops numbers:\n 0 101 102 103 104 105 106 107 108 109\n 201 202 203 204 205 206 207 208 209 301\n 302 303 304 305 306 307 308 309 401 402\n 403 404 405 406 407 408 409 501 502 503\n 504 505 506 507 508 509 601 602 603 604\n\nFirst cyclops number > 10,000,000: 111,101,111 - at (zero based) index: 538,084\n\n\nFirst 50 prime cyclops numbers:\n 101 103 107 109 307 401 409 503 509 601\n 607 701 709 809 907 11027 11047 11057 11059 11069\n 11071 11083 11087 11093 12011 12037 12041 12043 12049 12071\n 12073 12097 13033 13037 13043 13049 13063 13093 13099 14011\n 14029 14033 14051 14057 14071 14081 14083 14087 15013 15017\n\nFirst prime cyclops number > 10,000,000: 111,101,129 - at (zero based) index: 39,319\n\n\nFirst 50 blind prime cyclops numbers:\n 101 103 107 109 307 401 503 509 601 607\n 701 709 809 907 11071 11087 11093 12037 12049 12097\n 13099 14029 14033 14051 14071 14081 14083 14087 15031 15053\n 15083 16057 16063 16067 16069 16097 17021 17033 17041 17047\n 17053 17077 18047 18061 18077 18089 19013 19031 19051 19073\n\nFirst blind prime cyclops number > 10,000,000: 111,101,161 - at (zero based) index: 11,393\n\n\nFirst 50 palindromic prime cyclops numbers:\n 101 16061 31013 35053 38083 73037 74047 91019 94049 1120211\n1150511 1160611 1180811 1190911 1250521 1280821 1360631 1390931 1490941 1520251\n1550551 1580851 1630361 1640461 1660661 1670761 1730371 1820281 1880881 1930391\n1970791 3140413 3160613 3260623 3310133 3380833 3460643 3470743 3590953 3670763\n3680863 3970793 7190917 7250527 7310137 7540457 7630367 7690967 7750577 7820287\n\nFirst palindromic prime cyclops number > 10,000,000: 114,808,411 - at (zero based) index: 66\n```"
}
]
|
[
{
"role": "user",
"content": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.\n\nTask\n\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\nSee also\n\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.01\n\n**Translation of**: Perl\n\nUses the same library as Perl, so comes with the same caveats.\n\n```\nuse Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;\n\nsay 'First 30 cyclotomic polynomials:';\nmy $iterator = cyclo_poly_iterate(1);\nsay \"Φ($_) = \" ~ super $iterator().Str for 1..30;\n\nsay \"\\nSmallest cyclotomic polynomial with |n| as a coefficient:\";\nsay \"Φ(1) has a coefficient magnitude: 1\";\n\nmy $index = 0;\nfor 2..9 -> $coefficient {\n loop {\n $index += 5;\n my \\Φ = cyclo_poly($index);\n next unless Φ ~~ / $coefficient\\* /;\n say \"Φ($index) has a coefficient magnitude: $coefficient\";\n $index -= 5;\n last;\n }\n}\n\nsub super ($str) {\n $str.subst( / '^' (\\d+) /, { $0.trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]) }, :g)\n}\n\n```\n\n```\nFirst 30 cyclotomic polynomials:\nΦ(1) = (x - 1)\nΦ(2) = (x + 1)\nΦ(3) = (x² + x + 1)\nΦ(4) = (x² + 1)\nΦ(5) = (x⁴ + x³ + x² + x + 1)\nΦ(6) = (x² - x + 1)\nΦ(7) = (x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(8) = (x⁴ + 1)\nΦ(9) = (x⁶ + x³ + 1)\nΦ(10) = (x⁴ - x³ + x² - x + 1)\nΦ(11) = (x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(12) = (x⁴ - x² + 1)\nΦ(13) = (x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(14) = (x⁶ - x⁵ + x⁴ - x³ + x² - x + 1)\nΦ(15) = (x⁸ - x⁷ + x⁵ - x⁴ + x³ - x + 1)\nΦ(16) = (x⁸ + 1)\nΦ(17) = (x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(18) = (x⁶ - x³ + 1)\nΦ(19) = (x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(20) = (x⁸ - x⁶ + x⁴ - x² + 1)\nΦ(21) = (x¹² - x¹¹ + x⁹ - x⁸ + x⁶ - x⁴ + x³ - x + 1)\nΦ(22) = (x¹⁰ - x⁹ + x⁸ - x⁷ + x⁶ - x⁵ + x⁴ - x³ + x² - x + 1)\nΦ(23) = (x²² + x²¹ + x²⁰ + x¹⁹ + x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(24) = (x⁸ - x⁴ + 1)\nΦ(25) = (x²⁰ + x¹⁵ + x¹⁰ + x⁵ + 1)\nΦ(26) = (x¹² - x¹¹ + x¹⁰ - x⁹ + x⁸ - x⁷ + x⁶ - x⁵ + x⁴ - x³ + x² - x + 1)\nΦ(27) = (x¹⁸ + x⁹ + 1)\nΦ(28) = (x¹² - x¹⁰ + x⁸ - x⁶ + x⁴ - x² + 1)\nΦ(29) = (x²⁸ + x²⁷ + x²⁶ + x²⁵ + x²⁴ + x²³ + x²² + x²¹ + x²⁰ + x¹⁹ + x¹⁸ + x¹⁷ + x¹⁶ + x¹⁵ + x¹⁴ + x¹³ + x¹² + x¹¹ + x¹⁰ + x⁹ + x⁸ + x⁷ + x⁶ + x⁵ + x⁴ + x³ + x² + x + 1)\nΦ(30) = (x⁸ + x⁷ - x⁵ - x⁴ - x³ + x + 1)\n\nSmallest cyclotomic polynomial with |n| as a coefficient:\nΦ(1) has a coefficient magnitude: 1\nΦ(105) has a coefficient magnitude: 2\nΦ(385) has a coefficient magnitude: 3\nΦ(1365) has a coefficient magnitude: 4\nΦ(1785) has a coefficient magnitude: 5\nΦ(2805) has a coefficient magnitude: 6\nΦ(3135) has a coefficient magnitude: 7\nΦ(6545) has a coefficient magnitude: 8\nΦ(6545) has a coefficient magnitude: 9\n```"
}
]
|
[
{
"role": "user",
"content": "The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.\n\nThe algorithm is named after H. Michael Damm.\n\nTask\n\nVerify the checksum, stored as last digit of an input."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\n```\nsub damm ( *@digits ) {\n my @tbl = [0, 3, 1, 7, 5, 9, 8, 6, 4, 2],\n [7, 0, 9, 2, 1, 5, 4, 8, 6, 3],\n [4, 2, 0, 6, 8, 7, 1, 3, 5, 9],\n [1, 7, 5, 0, 9, 8, 3, 4, 2, 6],\n [6, 1, 2, 3, 0, 4, 5, 9, 7, 8],\n [3, 6, 7, 4, 2, 0, 9, 5, 8, 1],\n [5, 8, 6, 9, 7, 2, 0, 1, 3, 4],\n [8, 9, 4, 5, 3, 6, 2, 0, 1, 7],\n [9, 4, 3, 8, 6, 1, 7, 2, 0, 5],\n [2, 5, 8, 1, 4, 3, 6, 7, 9, 0];\n my $row = 0;\n for @digits -> $col { $row = @tbl[$row][$col] }\n not $row\n}\n\n# Testing\nfor 5724, 5727, 112946 {\n say \"$_:\\tChecksum digit { damm( $_.comb ) ?? '' !! 'in' }correct.\"\n}\n\n```\n\nOutput:\n\n```\n5724:\tChecksum digit correct.\n5727:\tChecksum digit incorrect.\n112946:\tChecksum digit correct.\n```"
}
]
|
[
{
"role": "user",
"content": "Demonstrate the Data Encryption Standard. For a complete description of the algorithm see: The DES Algorithm Illustrated\n\n**Task:**\n\nUse the\n\n: Key 0e329232ea6d0d73\n: to encrypt 8787878787878787\n: and display the result 0000000000000000.\n\nBonus (optional): add standard padding to match the C#, Java, Modula-2, Kotlin, and Phix entries, so the above encrypted result would instead be 0000000000000000A913F4CB0BD30F97."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThanks to SqrtNegInf for pointing out that \\r\\n is a single grapheme. (link 1, link 2)\n\n**Translation of**: Phix\n\n```\n# 20220222 Updated Raku programming solution\n\nmy \\PC1 = <\n 56 48 40 32 24 16 8 0 57 49 41 33 25 17 \n 9 1 58 50 42 34 26 18 10 2 59 51 43 35 \n 62 54 46 38 30 22 14 6 61 53 45 37 29 21 \n 13 5 60 52 44 36 28 20 12 4 27 19 11 3\n>; # Permuted choice 1 (PC-1) - Parity Drop Table, https://w.wiki/4yKS \n \nmy \\PC2 = <\n 13 16 10 23 0 4 2 27 14 5 20 9 22 18 11 3 \n 25 7 15 6 26 19 12 1 40 51 30 36 46 54 29 39 \n 50 44 32 47 43 48 38 55 33 52 45 41 49 35 28 31\n>; # Permuted choice 2 (PC-2) - Key Compression Table, https://w.wiki/4yKR\n \nmy \\IP = <\n 57 49 41 33 25 17 9 1 59 51 43 35 27 19 11 3 \n 61 53 45 37 29 21 13 5 63 55 47 39 31 23 15 7 \n 56 48 40 32 24 16 8 0 58 50 42 34 26 18 10 2 \n 60 52 44 36 28 20 12 4 62 54 46 38 30 22 14 6\n>; # Initial permutation (IP), https://w.wiki/4yKN\n \nmy \\IP2 = <\n 39 7 47 15 55 23 63 31 38 6 46 14 54 22 62 30 \n 37 5 45 13 53 21 61 29 36 4 44 12 52 20 60 28 \n 35 3 43 11 51 19 59 27 34 2 42 10 50 18 58 26 \n 33 1 41 9 49 17 57 25 32 0 40 8 48 16 56 24\n>; # Final permutation (IP⁻¹), https://w.wiki/4yKP\n \nmy \\S = ( <\n 14 4 13 1 2 15 11 8 3 10 6 12 5 9 0 7 0 15 7 4 14 2 13 1 10 6 12 11 9 5 3 8\n 4 1 14 8 13 6 2 11 15 12 9 7 3 10 5 0 15 12 8 2 4 9 1 7 5 11 3 14 10 0 6 13\n> , <\n 15 1 8 14 6 11 3 4 9 7 2 13 12 0 5 10 3 13 4 7 15 2 8 14 12 0 1 10 6 9 11 5\n 0 14 7 11 10 4 13 1 5 8 12 6 9 3 2 15 13 8 10 1 3 15 4 2 11 6 7 12 0 5 14 9\n> , <\n 10 0 9 14 6 3 15 5 1 13 12 7 11 4 2 8 13 7 0 9 3 4 6 10 2 8 5 14 12 11 15 1\n 13 6 4 9 8 15 3 0 11 1 2 12 5 10 14 7 1 10 13 0 6 9 8 7 4 15 14 3 11 5 2 12\n> , <\n 7 13 14 3 0 6 9 10 1 2 8 5 11 12 4 15 13 8 11 5 6 15 0 3 4 7 2 12 1 10 14 9\n 10 6 9 0 12 11 7 13 15 1 3 14 5 2 8 4 3 15 0 6 10 1 13 8 9 4 5 11 12 7 2 14\n> , <\n 2 12 4 1 7 10 11 6 8 5 3 15 13 0 14 9 14 11 2 12 4 7 13 1 5 0 15 10 3 9 8 6\n 4 2 1 11 10 13 7 8 15 9 12 5 6 3 0 14 11 8 12 7 1 14 2 13 6 15 0 9 10 4 5 3\n> , <\n 12 1 10 15 9 2 6 8 0 13 3 4 14 7 5 11 10 15 4 2 7 12 9 5 6 1 13 14 0 11 3 8\n 9 14 15 5 2 8 12 3 7 0 4 10 1 13 11 6 4 3 2 12 9 5 15 10 11 14 1 7 6 0 8 13\n> , <\n 4 11 2 14 15 0 8 13 3 12 9 7 5 10 6 1 13 0 11 7 4 9 1 10 14 3 5 12 2 15 8 6\n 1 4 11 13 12 3 7 14 10 15 6 8 0 5 9 2 6 11 13 8 1 4 10 7 9 5 0 15 14 2 3 12\n> , <\n 13 2 8 4 6 15 11 1 10 9 3 14 5 0 12 7 1 15 13 8 10 3 7 4 12 5 6 11 0 14 9 2\n 7 11 4 1 9 12 14 2 0 6 10 13 15 3 5 8 2 1 14 7 4 10 8 13 15 12 9 0 3 5 6 11\n> ); # S-Boxes, each replaces a 6-bit input with a 4-bit output, w.wiki/4yG8 \n \nmy \\P = <\n 15 6 19 20 28 11 27 16 0 14 22 25 4 17 30 9 \n 1 7 23 13 31 26 2 8 18 12 29 5 21 10 3 24\n>; # Permutation (P), shuffles the bits of a 32-bit half-block, w.wiki/4yKT\n \n# Expansion function (E), expand 32-bit half-block to 48 bits, w.wiki/4yGC\nmy \\E = flat 31,0..4,3..8,7..12,11..16,15..20,19..24,23..28,27..31,0;\n \nmy \\SHIFTS = flat 1, 1, 2 xx 6, 1, 2 xx 6, 1 ; # left shifts, w.wiki/4yKV\n \n## Helper subs\n \n# convert iso-8859-1 to hexadecimals(%02X)\nsub b2h (\\b) { b.ords.fmt('%02X','') }\n \n# convert UTF8s to bytes\nsub u2b (\\u) { u.encode.list.chrs } \n \n# convert hexadecimals(%02X) to UTF-8\nsub h2u (\\h) { Blob.new( h.comb(2)».&{ :16($_) } ).decode }\n \n# convert quadbits to hex\nsub q2h (\\q) { [~] q.comb(4)».&{ :2($_).fmt('%X') } }\n \n# convert every two quadbits to bytes\nsub q2b (\\q) { q.comb(8)».&{ :2($_) } }\n \n# turn a 16 digit hexadecimal str to a 64 bits list\nsub h2b (\\h) { flat h.comb».&{ :16($_).base(2).fmt('%04s').comb } }\n \n# convert hexadecimals to bytes\nsub h2B (\\h) { [~] h.comb(2)».&{ chr \"0x$_\" } }\n \n# s is 16 digit hexadecimal str, M is a permuation matrix/vector\nsub map64(\\s,\\M) { (h2b s)[M] } \n \n## Core subs\n \nsub get_subkeys(Str \\key --> Seq) { # return a Seq with 16 bit vectors\n my (@C,@D) := { .rotor(.elems div 2)».Array }(map64 key, PC1); #w.wiki/4yKV\n my \\CD = (^16)».&{ [ |@C.=rotate(SHIFTS[$_]), |@D.=rotate(SHIFTS[$_]) ] }\n # key compression rounds, https://w.wiki/4yKb\n return (^16).map: -> \\row { (^48).map: -> \\col { CD[row][ PC2[col] ] } }\n}\n \nsub ƒ (List \\R, Seq \\Kₙ --> List) {\n my @er = map { Kₙ[$_] +^ R[E[$_]] }, ^48;\n \n return ( flat (^8)».&{ # Sₙ(Bₙ) loop, process @er six bits at a time \n S[$_][ ([~] @er[$_*6 , $_*6+5]).parse-base(2)*16 + # 2 bits\n ([~] @er[$_*6+1 .. $_*6+4]).parse-base(2) ] # 4 bits\n .fmt('%04b').comb } # ((S[][] to binary).split)*8.flat \n )[P] \n}\n \nsub process_block(Str \\message, Seq \\K --> Str) { # return 8 quadbits\n my (@L,@R) := { .rotor(.elems div 2)».Array }(map64 (b2h message), IP); \n { my @Lₙ = @R; my @Rₙ = @L Z+^ ƒ @R, K[$_]; @L = @Lₙ; @R = @Rₙ } for ^16;\n \n return [~] (|@R, |@L)[IP2] # inverse of the initial permutation\n}\n \nsub des(Str \\key, Str $msg is copy, Bool \\DECODE --> Str) { # return hexdecimal\n \n my \\length = $msg.encode('iso-8859-1').bytes;\n \n die \"Message must be in multiples of 8 bytes\" if ( DECODE and length % 8 );\n \n my \\K = { DECODE ?? reverse $_ !! $_ }(get_subkeys key);\n \n # CMS style padding as per RFC 1423 & RFC 5652\n { $msg ~= (my \\Pad = 8 - length % 8).chr x Pad } unless DECODE; \n \n my $quad = [~] ( 0, 8 … $msg.encode('iso-8859-1').bytes-8 ).map: \n { process_block substr($msg,$_,8), K }\n \n DECODE ?? do { my @decrypt = q2b $quad; # quadbits to a byte code point list\n @decrypt.pop xx @decrypt.tail; # remove padding\n return b2h [~] @decrypt.chrs } \n !! do { return q2h $quad }\n}\n \nsay \"Encryption examples: \";\nsay des \"133457799BBCDFF1\", h2B(\"0123456789ABCDEF\"), False;\nsay des \"0E329232EA6D0D73\", h2B(\"8787878787878787\"), False;\nsay des \"0E329232EA6D0D73\", \"Your lips are smoother than vaseline\", False;\nsay des \"0E329232EA6D0D73\", \"Your lips are smoother than vaseline\\r\\n\", False;\nsay des \"0E329232EA6D0D73\", u2b(\"BMP: こんにちは ; Astral plane: 𝒳𝒴𝒵\"), False;\n \nsay \"\\nDecryption examples: \";\nsay des \"133457799BBCDFF1\", h2B(\"85E813540F0AB405FDF2E174492922F8\"), True;\nsay des \"0E329232EA6D0D73\", h2B(\"0000000000000000A913F4CB0BD30F97\"), True;\nsay h2B des \"0E329232EA6D0D73\", h2B(\"C0999FDDE378D7ED727DA00BCA5A84EE47F269A4D6438190D9D52F78F535849980A2E7453703513E\"), True;\nsay h2B des \"0E329232EA6D0D73\", h2B(\"C0999FDDE378D7ED727DA00BCA5A84EE47F269A4D6438190D9D52F78F53584997F922CCB5B068D99\"), True;\nsay h2u des \"0E329232EA6D0D73\", h2B(\"C040FB6A6E72D7C36D60CA9B9A35EB38D3194468AD808103C28E33AEF0B268D0E0366C160B028DDACF340003DCA8969343EBBD289DB94774\"), True;\n\n```\n\nOutput:\n\n```\nEncryption examples:\n85E813540F0AB405FDF2E174492922F8\n0000000000000000A913F4CB0BD30F97\nC0999FDDE378D7ED727DA00BCA5A84EE47F269A4D6438190D9D52F78F535849980A2E7453703513E\nC0999FDDE378D7ED727DA00BCA5A84EE47F269A4D6438190D9D52F78F53584997F922CCB5B068D99\nC040FB6A6E72D7C36D60CA9B9A35EB38D3194468AD808103C28E33AEF0B268D0E0366C160B028DDACF340003DCA8969343EBBD289DB94774\n\nDecryption examples:\n0123456789abcdef\n8787878787878787\nYour lips are smoother than vaseline\nYour lips are smoother than vaseline\n\nBMP: こんにちは ; Astral plane: 𝒳𝒴𝒵\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nTask\n\nDisplay the current date in the formats of:\n\n: : : * **2007-11-23** and\n * **Friday, November 23, 2007**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Library:** DateTime::Format\n\n```\nuse DateTime::Format;\n\nmy $dt = DateTime.now;\n\nsay strftime('%Y-%m-%d', $dt);\nsay strftime('%A, %B %d, %Y', $dt);\n\n```\n\nThe built-in Date and DateTime classes both offer support for the ISO format:\n\n```\nmy $d = Date.today;\n\nsay $d.yyyy-mm-dd;\n\n```\n\nThey don't include the longer format specified in the task, but you can always roll your own formatter instead of importing the library:\n\n```\nmy @months = <January February March April May June July\n August September October November December>;\nmy @days = <Monday Tuesday Wednesday Thursday Friday Saturday Sunday>;\nmy $us-long = sub ($self) { \"{@days[$self.day-of-week - 1]}, {@months[$self.month - 1]} {$self.day}, {$self.year}\" };\nmy $d = Date.today :formatter($us-long);\n\nsay $d.yyyy-mm-dd; # still works\nsay $d; # uses our formatter sub\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven the date string \"March 7 2009 7:30pm EST\", \noutput the time 12 hours later in any human-readable format.\n\nAs extra credit, display the resulting time in a time zone different from your own."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku comes with a built-in DateTime type to support most aspects of standard civic time calculation\nthat are not dependent on cultural idiosyncrasies.\n\nUnfortunately, Raku does not yet have a date parsing module – mostly due to a reticence to inflict Western cultural imperialism on other cultures... or maybe just due to laziness. But that just gives us another opportunity to demonstrate the built-in grammar support.\n\n```\nmy @month = <January February March April May June July August September October November December>;\nmy %month = flat (@month Z=> 1..12), (@month».substr(0,3) Z=> 1..12), 'Sept' => 9;\n\ngrammar US-DateTime {\n rule TOP { <month> <day>','? <year>','? <time> <tz> }\n\n token month {\n\t(\\w+)'.'? { make %month{$0} // die \"Bad month name: $0\" }\n }\n\n token day { (\\d ** 1..2) { make +$0 } }\n\n token year { (\\d ** 1..4) { make +$0 } }\n\n token time {\n\t(\\d ** 1..2) ':' (\\d ** 2) \\h* ( :i <[ap]> \\.? m | '' )\n\t{\n\t my $h = $0 % 12;\n\t my $m = $1;\n\t $h += 12 if $2 and $2.substr(0,1).lc eq 'p';\n\t make $h * 60 + $m;\n\t}\n }\n\n token tz { # quick and dirty for this task\n [\n | EDT { make -4 }\n | [ EST| CDT] { make -5 }\n | [ CST| MDT] { make -6 }\n | [ MST| PDT] { make -7 }\n | [ PST|AKDT] { make -8 }\n | [AKST|HADT] { make -9 }\n | HAST\n ]\n }\n}\n\n$/ = US-DateTime.parse('March 7 2009 7:30pm EST') or die \"Can't parse date\";\n\nmy $year = $<year>.ast;\nmy $month = $<month>.ast;\nmy $day = $<day>.ast;\nmy $hour = $<time>.ast div 60;\nmy $minute = $<time>.ast mod 60;\nmy $timezone = $<tz>.ast * 3600;\n\nmy $dt = DateTime.new(:$year, :$month, :$day, :$hour, :$minute, :$timezone).in-timezone(0);\n\n$dt = $dt.later(hours => 12);\n\nsay \"12 hours later, UTC: $dt\";\nsay \"12 hours later, PDT: $dt.in-timezone(-7 * 3600)\";\n\n```\n\nOutput:\n\n```\n12 hours later, UTC: 2009-03-08T12:30:00Z\n12 hours later, PDT: 2009-03-08T05:30:00-08:00\n```"
}
]
|
[
{
"role": "user",
"content": "Scenario\n\nA sailor signs up to a dating agency hoping to find a suitable mate.\n\nThe dating agency has 10 ladies on its books who may be suitable and uses the algorithm \"all the nice girls love a sailor\" to decide which ones to put forward for the sailor's consideration.\n\nThe sailor uses a different algorithm (\"lady is lovable\") to decide which ladies to actually date.\n\nTask\n\nModel this scenario in your language.\n\nGive the sailor and ladies some names.\n\nUse some arbitrary method based on the ladies' names to determine whether they're *nice* and/or *lovable*. For preference, choose a method where the outcomes are (more or less) equally likely.\n\nHence, determine which ladies the dating agency should suggest and which of these the sailor should offer to date.\n\nNote\n\nThis task is intended as a bit of fun as well as a simple exercise in object modelling so hopefully it won't offend anyone!"
},
{
"role": "assistant",
"content": "Welcome to the **Arbitrary and Capricious Dating Agency**, (We don't use zodiacs, but we're just as arbitrary!)\n\n```\nuse Digest::SHA1::Native;\n\nmy %ladies = < Alice Beth Cecilia Donna Eunice Fran Genevieve Holly Irene Josephine Kathlene Loralie Margaret\n Nancy Odelle Pamela Quinci Rhonda Stephanie Theresa Ursula Victoria Wren Yasmine Zoey >.map: -> $name {\n $name => {\n loves => :16(sha1-hex($name).substr(0,4)),\n lovable => :16(sha1-hex($name).substr(*-4))\n }\n}\n\nmy %sailors = < Ahab Brutus Popeye >.map: -> $name {\n $name => {\n loves => :16(sha1-hex($name).substr(0,4)),\n lovable => :16(sha1-hex($name).substr(*-4))\n }\n}\n\nfor %sailors.sort( *.key ) -> $sailor {\n printf \"%6s will like: \", $sailor.key;\n say join ', ', my @likes = %ladies.sort( { abs $sailor.value.<loves> - .value.<loves> } ).head(10)».key;\n print ' Is liked by: ';\n say join ', ', my @liked = %ladies.sort( { abs $sailor.value.<lovable> - .value.<lovable> } ).head(10)».key;\n my %matches;\n for @liked.reverse Z, (1..10) { %matches{.[0]} += .[1] };\n for @likes.reverse Z, (1..10) { %matches{.[0]} += .[1] };\n say 'Best match(s): ' ~ %matches.grep(*.value == %matches.values.max)».key.sort.join(', ');\n say '';\n}\n\n```\n\n```\n Ahab will like: Eunice, Ursula, Irene, Holly, Fran, Genevieve, Zoey, Donna, Cecilia, Alice\n Is liked by: Nancy, Theresa, Victoria, Genevieve, Alice, Rhonda, Kathlene, Odelle, Eunice, Pamela\nBest match(s): Eunice, Genevieve\n\nBrutus will like: Beth, Nancy, Quinci, Odelle, Josephine, Kathlene, Theresa, Rhonda, Wren, Margaret\n Is liked by: Yasmine, Margaret, Loralie, Holly, Wren, Fran, Quinci, Eunice, Alice, Victoria\nBest match(s): Quinci\n\nPopeye will like: Loralie, Theresa, Stephanie, Yasmine, Alice, Cecilia, Donna, Zoey, Nancy, Genevieve\n Is liked by: Loralie, Margaret, Holly, Wren, Yasmine, Fran, Quinci, Eunice, Alice, Victoria\nBest match(s): Loralie\n```"
}
]
|
[
{
"role": "user",
"content": "A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).\n\nTask\n\n**In what years between 2008 and 2121 will the 25th of December be a Sunday?**\n\nUsing any standard date handling libraries of your programming language;\ncompare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2010.07\n\nAs Perl 5, except `DateTime` is built-in, so you don't need to download a module of that name:\n\n```\nsay join ' ', grep { Date.new($_, 12, 25).day-of-week == 7 }, 2008 .. 2121;\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDetermine programatically and show on this page on what weekday Christmas Day, 2021 and New Year's Day, 2022 will fall or did fall."
},
{
"role": "assistant",
"content": "```\nmy @d-o-w = < Sunday Monday Tuesday Wednesday Thursday Friday Saturday >;\n\n.say for (flat 2020..2022, (1500 .. 2500).roll(7)).sort.map: {\n \"In {$_}, New Years is on a { @d-o-w[Date.new($_, 1, 1).day-of-week % 7] }, \" ~\n \"and Christmas on a { @d-o-w[Date.new($_, 12, 25).day-of-week % 7] }.\"\n}\n\n```\n\nSample output:\n\n```\nIn 1578, New Years is on a Sunday, and Christmas on a Monday.\nIn 1590, New Years is on a Monday, and Christmas on a Tuesday.\nIn 1642, New Years is on a Wednesday, and Christmas on a Thursday.\nIn 1957, New Years is on a Tuesday, and Christmas on a Wednesday.\nIn 2020, New Years is on a Wednesday, and Christmas on a Friday.\nIn 2021, New Years is on a Friday, and Christmas on a Saturday.\nIn 2022, New Years is on a Saturday, and Christmas on a Sunday.\nIn 2242, New Years is on a Saturday, and Christmas on a Sunday.\nIn 2245, New Years is on a Wednesday, and Christmas on a Thursday.\nIn 2393, New Years is on a Friday, and Christmas on a Saturday.\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCalculate the number of days between two dates.\n\nDate input should be of the form **YYYY-MM-DD**.\n\nMotivation\n\nTo demonstrate one of the numerous ways this can be done."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nDates are first class objects in Raku and may have arithmetic in days done directly on them.\n\n```\nsay Date.new('2019-09-30') - Date.new('2019-01-01');\n\nsay Date.new('2019-03-01') - Date.new('2019-02-01');\n\nsay Date.new('2020-03-01') - Date.new('2020-02-01');\n\nsay Date.new('2029-03-29') - Date.new('2019-03-29');\n\nsay Date.new('2019-01-01') + 90;\n\nsay Date.new('2020-01-01') + 90;\n\nsay Date.new('2019-02-29') + 30;\n\nCATCH { default { .message.say; exit; } };\n\n```\n\n```\n272\n28\n29\n3653\n2019-04-01\n2020-03-31\nDay out of range. Is: 29, should be in 1..28\n```"
}
]
|
[
{
"role": "user",
"content": "The sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\nA note on Dutch capitalization: Nicolaas' last name is **de Bruijn**, the **de** isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\nIn combinatorial mathematics, a **de Bruijn sequence** of order *n* on\na size-*k* alphabet (computer science) *A* is a cyclic sequence in which every\npossible length-*n* string (computer science, formal theory) on *A* occurs\nexactly once as a contiguous substring.\n\nSuch a sequence is denoted by *B*(*k*, *n*) and has\nlength *k**n*, which is also the number of distinct substrings of\nlength *n* on *A*; \n \nde Bruijn sequences are therefore optimally short.\n\nThere are:\n\n```\n (k!)k(n-1) ÷ kn\n\n```\n\ndistinct de Bruijn sequences *B*(*k*, *n*).\n\nTask\n\nFor this Rosetta Code task, a **de Bruijn** sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last *n* digits entered.\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\nExample\n\nA digital door lock with a 4-digit code would\nhave *B* (10, 4) solutions, with a length of **10,000** (digits).\n\nTherefore, only at most **10,000 + 3** (as the solutions are cyclic or *wrap-around*) presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require **4 × 10,000** or **40,000** presses.\n\nTask requirements\n: * Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n\n : : * Show the length of the generated de Bruijn sequence.\n * (There are many possible de Bruijn sequences that solve this task, one solution is shown on the *discussion* page).\n * Show the first and last **130** digits of the de Bruijn sequence.\n\n * Verify that all four-digit (decimal) **1,000** PIN codes are contained within the de Bruijn sequence.\n\n : : * 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n\n * Reverse the de Bruijn sequence.\n * Again, perform the (above) verification test.\n * Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n\n : : * Perform the verification test (again). There should be four PIN codes missing.\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all 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\n\nReferences\n: * Wikipedia entry: de Bruijn sequence.\n * MathWorld entry: de Bruijn sequence.\n * An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nDeviates very slightly from the task spec. Generates a randomized de Bruijn sequence and replaces the 4444th digit with a the digit plus 1 mod 10 rather than a '.', mostly so it can demonstrate detection of extra PINs as well as missing ones.\n\n```\n# Generate the sequence\nmy $seq;\n\nfor ^100 {\n my $a = .fmt: '%02d';\n next if $a.substr(1,1) < $a.substr(0,1);\n $seq ~= ($a.substr(0,1) == $a.substr(1,1)) ?? $a.substr(0,1) !! $a;\n for +$a ^..^ 100 {\n next if .fmt('%02d').substr(1,1) <= $a.substr(0,1);\n $seq ~= sprintf \"%s%02d\", $a, $_ ;\n }\n}\n\n$seq = $seq.comb.list.rotate((^10000).pick).join;\n\n$seq ~= $seq.substr(0,3);\n\nsub check ($seq) {\n my %chk;\n for ^($seq.chars) { %chk{$seq.substr( $_, 4 )}++ }\n put 'Missing: ', (^9999).grep( { not %chk{ .fmt: '%04d' } } ).fmt: '%04d';\n put 'Extra: ', %chk.grep( *.value > 1 )».key.sort.fmt: '%04d';\n}\n\n## The Task\nput \"de Bruijn sequence length: \" ~ $seq.chars;\n\nput \"\\nFirst 130 characters:\\n\" ~ $seq.substr( 0, 130 );\n\nput \"\\nLast 130 characters:\\n\" ~ $seq.substr( * - 130 );\n\nput \"\\nIncorrect 4 digit PINs in this sequence:\";\ncheck $seq;\n\nput \"\\nIncorrect 4 digit PINs in the reversed sequence:\";\ncheck $seq.flip;\n\nmy $digit = $seq.substr(4443,1);\nput \"\\nReplacing the 4444th digit, ($digit) with { ($digit += 1) %= 10 }\";\nput \"Incorrect 4 digit PINs in the revised sequence:\";\n$seq.substr-rw(4443,1) = $digit;\ncheck $seq;\n\n```\n\nSample output:\n\n```\nde Bruijn sequence length: 10003\n\nFirst 130 characters:\n4558455945654566456745684569457545764577457845794585458645874588458945954596459745984599464647464846494655465646574658465946654666\n\nLast 130 characters:\n5445644574458445944654466446744684469447544764477447844794485448644874488448944954496449744984499454546454745484549455545564557455\n\nIncorrect 4 digit PINs in this sequence:\nMissing: \nExtra: \n\nIncorrect 4 digit PINs in the reversed sequence:\nMissing: \nExtra: \n\nReplacing the 4444th digit, (1) with 2\nIncorrect 4 digit PINs in the revised sequence:\nMissing: 0961 1096 6109 9610\nExtra: 0962 2096 6209 9620\n```"
}
]
|
[
{
"role": "user",
"content": "Alphonse de Polignac, a French mathematician in the 1800s, conjectured that every positive odd integer could be formed from the sum of a power of 2 and a prime number.\n\nHe was subsequently proved incorrect.\n\nThe numbers that fail this condition are now known as de Polignac numbers.\n\nTechnically **1** is a de Polignac number, as there is no prime and power of 2 that sum to **1**. De Polignac was aware but thought that **1** was a special case. However.\n\n**127** is also fails that condition, as there is no prime and power of 2 that sum to **127**.\n\nAs it turns out, de Polignac numbers are not uncommon, in fact, there are an infinite number of them.\n\nTask\n\n* Find and display the first fifty de Polignac numbers.\n\nStretch\n\n* Find and display the one thousandth de Polignac number.\n* Find and display the ten thousandth de Polignac number.\n\nSee also\n\n* Numbers Aplenty - de Polignac numbers * OEIS:A006285 - Odd numbers not of form p + 2^k (de Polignac numbers)"
},
{
"role": "assistant",
"content": "```\nuse List::Divvy;\nuse Lingua::EN::Numbers;\nconstant @po2 = (1..∞).map: 2 ** *;\nmy @dePolignac = lazy 1, |(2..∞).hyper.map(* × 2 + 1).grep: -> $n { all @po2.&upto($n).map: { !is-prime $n - $_ } };\n\nsay \"First fifty de Polignac numbers:\\n\" ~ @dePolignac[^50]».&comma».fmt(\"%5s\").batch(10).join: \"\\n\";\nsay \"\\nOne thousandth: \" ~ comma @dePolignac[999];\nsay \"\\nTen thousandth: \" ~ comma @dePolignac[9999];\n\n```\n\nOutput:\n\n```\nFirst fifty de Polignac numbers:\n 1 127 149 251 331 337 373 509 599 701\n 757 809 877 905 907 959 977 997 1,019 1,087\n1,199 1,207 1,211 1,243 1,259 1,271 1,477 1,529 1,541 1,549\n1,589 1,597 1,619 1,649 1,657 1,719 1,759 1,777 1,783 1,807\n1,829 1,859 1,867 1,927 1,969 1,973 1,985 2,171 2,203 2,213\n\nOne thousandth: 31,941\n\nTen thousandth: 273,421\n```"
}
]
|
[
{
"role": "user",
"content": "*Free Cell* is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to *FreeCell* and reimplemented the game for DOS, then Windows. \nThis version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)\n\nAs the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. \nThese deals are numbered from 1 to 32000.\nNewer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.\n\nThe algorithm uses this linear congruential generator from Microsoft C:\n\n* s\n t\n a\n t\n\n e\n\n n\n +\n 1\n ≡\n 214013\n ×\n s\n t\n a\n t\n\n e\n\n n\n +\n 2531011\n\n\n (\n mod\n\n\n 2\n\n 31\n )\n {\\displaystyle {\\displaystyle state\\_{n+1}\\equiv 214013\\times state\\_{n}+2531011{\\pmod {2^{31}}}}}\n* r\n a\n n\n\n d\n\n n\n =\n s\n t\n a\n t\n\n e\n\n n\n ÷\n\n 2\n\n 16\n {\\displaystyle {\\displaystyle rand\\_{n}=state\\_{n}\\div 2^{16}}}\n* r\n a\n n\n\n d\n\n n\n {\\displaystyle {\\displaystyle rand\\_{n}}}\n is in range 0 to 32767.\n* Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.\n\nThe algorithm follows:\n\n1. Seed the RNG with the number of the deal.\n2. Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.\n3. Until the array is empty:\n * Choose a random card at *index* ≡ *next random number* (mod *array length*).\n * Swap this random card with the last card of the array.\n * Remove this random card from the array. (Array length goes down by 1.)\n * Deal this random card.\n4. Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.\n\n: : : : | Order to deal cards | Game #1 | Game #617 |\n | --- | --- | --- |\n | ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 ``` | ``` JD 2D 9H JC 5D 7H 7C 5H KD KC 9S 5S AD QC KH 3H 2S KS 9D QD JS AS AH 3C 4C 5C TS QH 4H AC 4D 7S 3S TD 4S TH 8H 2C JH 7D 6D 8S 8D QS 6C 3D 8C TC 6S 9C 2H 6H ``` | ``` 7D AD 5C 3S 5S 8C 2D AH TD 7S QD AC 6D 8H AS KH TH QC 3H 9D 6S 8D 3D TC KD 5H 9S 3C 8S 7H 4D JS 4C QS 9C 9H 7C 6H 2C 2S 4S TS 2H 5D JC 6C JH QH JD KS KC 4H ``` |\n\nDeals can also be checked against FreeCell solutions to 1000000 games.\n(Summon a video solution, and it displays the initial deal.)\n\nWrite a program to take a deal number and deal cards in the same order as this algorithm.\nThe program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.\n\nRelated tasks:\n\n* Playing cards\n* Card shuffles\n* War Card\\_Game\n* Poker hand\\_analyser\n* Go Fish"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.05\n\n```\nsub dealgame ($game-number = 1) {\n sub ms-lcg-method($seed = $game-number) { ( 214013 * $seed + 2531011 ) % 2**31 }\n\n # lazy list of the random sequence\n my @ms-lcg = |(&ms-lcg-method ... *).map: * +> 16;\n\n constant CardBlock = '🂠'.ord;\n my @deck = gather for flat(1..11,13,14) X+ (48,32...0) -> $off {\n take chr CardBlock + $off;\n }\n\n my @game = gather while @deck {\n @deck[@ms-lcg.shift % @deck, @deck-1] .= reverse;\n take @deck.pop;\n }\n\n say \"Game #$game-number\";\n say @game.splice(0, 8 min +@game) while @game;\n}\n\ndealgame;\ndealgame 617;\n\n```\n\nOutput:\n\n```\nGame #1\n🃋 🃂 🂹 🃛 🃅 🂷 🃗 🂵\n🃎 🃞 🂩 🂥 🃁 🃝 🂾 🂳\n🂢 🂮 🃉 🃍 🂫 🂡 🂱 🃓\n🃔 🃕 🂪 🂽 🂴 🃑 🃄 🂧\n🂣 🃊 🂤 🂺 🂸 🃒 🂻 🃇\n🃆 🂨 🃈 🂭 🃖 🃃 🃘 🃚\n🂦 🃙 🂲 🂶\nGame #617\n🃇 🃁 🃕 🂣 🂥 🃘 🃂 🂱\n🃊 🂧 🃍 🃑 🃆 🂸 🂡 🂾\n🂺 🃝 🂳 🃉 🂦 🃈 🃃 🃚\n🃎 🂵 🂩 🃓 🂨 🂷 🃄 🂫\n🃔 🂭 🃙 🂹 🃗 🂶 🃒 🂢\n🂤 🂪 🂲 🃅 🃛 🃖 🂻 🂽\n🃋 🂮 🃞 🂴\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDisplay a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction.\n\n(This will basically produce a shape like a \"death star\".)\n\nRelated tasks\n\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: C\n\nReimplemented to output a .pgm image.\n\n**Works with**: Rakudo version 2018.10\n\n```\nclass sphere {\n has $.cx; # center x coordinate\n has $.cy; # center y coordinate\n has $.cz; # center z coordinate\n has $.r; # radius\n}\n\nmy $depth = 255; # image color depth\n\nmy $width = my $height = 255; # dimensions of generated .pgm; must be odd\n\nmy $s = ($width - 1)/2; # scaled dimension to build geometry\n\nmy @light = normalize([ 4, -1, -3 ]);\n\n# positive sphere at origin\nmy $pos = sphere.new(\n cx => 0,\n cy => 0,\n cz => 0,\n r => $s.Int\n);\n\n# negative sphere offset to upper left\nmy $neg = sphere.new(\n cx => (-$s*.90).Int,\n cy => (-$s*.90).Int,\n cz => (-$s*.3).Int,\n r => ($s*.7).Int\n);\n\nsub MAIN ($outfile = 'deathstar-perl6.pgm') {\n spurt $outfile, (\"P5\\n$width $height\\n$depth\\n\"); # .pgm header\n my $out = open( $outfile, :a, :bin ) orelse .die;\n say 'Working...';\n $out.write( Blob.new( |draw_ds(3, .15) ) );\n say 'File written.';\n $out.close;\n}\n\nsub draw_ds ( $k, $ambient ) {\n my @pixels[$height];\n\n (($pos.cy - $pos.r) .. ($pos.cy + $pos.r)).race.map: -> $y {\n my @row[$width];\n (($pos.cx - $pos.r) .. ($pos.cx + $pos.r)).map: -> $x {\n # black if we don't hit positive sphere, ignore negative sphere\n if not hit($pos, $x, $y, my $posz) {\n @row[$x + $s] = 0;\n next;\n }\n my @vec;\n # is front of positive sphere inside negative sphere?\n if hit($neg, $x, $y, my $negz) and $negz.min < $posz.min < $negz.max {\n # make black if whole positive sphere eaten here\n if $negz.min < $posz.max < $negz.max { @row[$x + $s] = 0; next; }\n # render inside of negative sphere\n @vec = normalize([$neg.cx - $x, $neg.cy - $y, -$negz.max - $neg.cz]);\n }\n else {\n # render outside of positive sphere\n @vec = normalize([$x - $pos.cx, $y - $pos.cy, $posz.max - $pos.cz]);\n }\n my $intensity = dot(@light, @vec) ** $k + $ambient;\n @row[$x + $s] = ($intensity * $depth).Int min $depth;\n }\n @pixels[$y + $s] = @row;\n }\n flat |@pixels.map: *.list;\n}\n\n# normalize a vector\nsub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }\n\n# dot product of two vectors\nsub dot (@x, @y) { -([+] @x »*« @y) max 0 }\n\n# are the coordinates within the radius of the sphere?\nsub hit ($sphere, $x is copy, $y is copy, $z is rw) {\n $x -= $sphere.cx;\n $y -= $sphere.cy;\n my $z2 = $sphere.r * $sphere.r - $x * $x - $y * $y;\n return False if $z2 < 0;\n $z2 = $z2.sqrt;\n $z = $sphere.cz - $z2 .. $sphere.cz + $z2;\n True;\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Repunits are numbers that consist entirely of repetitions of the digit one (unity). The notation **Rn** symbolizes the repunit made up of **n** ones.\n\nEvery prime **p** larger than 5, evenly divides the repunit **Rp-1**.\n\nE.G.\n\nThe repunit **R6** is evenly divisible by **7**.\n\n111111 / 7 = 15873\n\nThe repunit **R42** is evenly divisible by **43**.\n\n111111111111111111111111111111111111111111 / 43 = 2583979328165374677002583979328165374677\n\nAnd so on.\n\nThere are composite numbers that also have this same property. They are often referred to as *deceptive non-primes* or *deceptive numbers*.\n\nThe repunit **R90** is evenly divisible by the composite number **91** (=7\\*13).\n\n111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 / 91 = 1221001221001221001221001221001221001221001221001221001221001221001221001221001221001221\n\nTask\n\n* Find and show at least the first **10 deceptive numbers**; composite numbers **n** that evenly divide the repunit **Rn-1**\n\nSee also\n\n* Numbers Aplenty - Deceptive numbers * OEIS:A000864 - Deceptive nonprimes: composite numbers k that divide the repunit R\\_{k-1}"
},
{
"role": "assistant",
"content": "```\nmy \\R = [\\+] 1, 10, 100 … *;\nput (2..∞).grep( {$_ % 2 && $_ % 3 && $_ % 5 && !.is-prime} ).grep( { R[$_-2] %% $_ } )[^25];\n\n```\n\nOutput:\n\n```\n91 259 451 481 703 1729 2821 2981 3367 4141 4187 5461 6533 6541 6601 7471 7777 8149 8401 8911 10001 11111 12403 13981 14701\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a program that takes a decimal floating point number and displays its binary representation and vice versa: takes a floating point binary number and outputs its decimal representation.\n\nThe output might be something like this:\n\n```\n 23.34375 => 10111.01011\n 1011.11101 => 11.90625\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\ngiven \"23.34375\" { say \"$_ => \", :10($_).base(2) }\ngiven \"1011.11101\" { say \"$_ => \", :2($_).base(10) }\n\n```\n\nOutput:\n\n```\n23.34375 => 10111.01011\n1011.11101 => 11.90625\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Decision Table. 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\nDecision Tables are a precise yet compact way to model complicated logic.\n\nTask\n\nDemonstrate how your language implements decision tables.\n\nUse this example of Printer Troubleshooting given in the Wikipedia article."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub decide (@q, @s) {\n my $bit = 2 ** [+] (1,2,4...*) Z* reverse @q.map: {\n\tso prompt(.value ~ \"? \") ~~ /:i ^y/;\n }\n say \" $_\" for @s.grep(*.key +& $bit)».value || \"No clue!\";\n}\n\nloop {\n decide\n (\n\t \"Y Y Y Y N N N N\" => \"Printer does not print\", \n\t \"Y Y N N Y Y N N\" => \"A red light is flashing\", \n\t \"Y N Y N Y N Y N\" => \"Printer is unrecognised\", \n ), \n (\n\t:2<0_0_1_0_0_0_0_0> => \"Check the power cable\", \n\t:2<1_0_1_0_0_0_0_0> => \"Check the printer-computer cable\", \n\t:2<1_0_1_0_1_0_1_0> => \"Ensure printer software is installed\", \n\t:2<1_1_0_0_1_1_0_0> => \"Check/replace ink\", \n\t:2<0_1_0_1_0_0_0_0> => \"Check for paper jam\", \n );\n say '';\n}\n\n```\n\nA bit of explanation: we pass in two pair lists for the questions and solutions; we ignore the keys of the questions, since they can be\ngenerated by regarding them as a binary counter from right to left, with the least significant bit on the bottom. The @q.map runs the prompts and maps them to booleans\nusing case-insensitive matching. We reverse that list and zip multiply with powers of two to figure out which bit we're going to grep for. (The zip stops on the shorter list, which is always going to be the list of booleans, since the list of powers of two is infinite.) We sum up those powers of two using a [+] reduction metaoperator, which in this case gives us a number from 0 to 7. Then we take 2 to that power.\n\nThe solutions list of pairs is conveniently keyed on binary numbers written in colon radix notation, so we grep the keys containing the correct bit, then map the pair list to its values using a hyperoperator to parallelize it. Unlike in Perl 5, we can use || on lists as well as scalars to provide a default result if nothing matches.\n\nOutput:\n\n```\nPrinter does not print? n\nA red light is flashing? y\nPrinter is unrecognised? n\n Check/replace ink\n\nPrinter does not print? y\nA red light is flashing? n\nPrinter is unrecognised? y\n Check the power cable\n Check the printer-computer cable\n Ensure printer software is installed\n\nPrinter does not print? n\nA red light is flashing? n\nPrinter is unrecognised? n\n No clue!\n\nPrinter does not print? ^C\n```"
}
]
|
[
{
"role": "user",
"content": "The convolution of two functions \n\nF\n{\\displaystyle {\\displaystyle {\\mathit {F}}}}\n and \n\nH\n{\\displaystyle {\\displaystyle {\\mathit {H}}}}\n of\nan integer variable is defined as the function \n\nG\n{\\displaystyle {\\displaystyle {\\mathit {G}}}}\nsatisfying\n\n: G\n (\n n\n )\n =\n\n ∑\n\n m\n =\n −\n ∞\n\n ∞\n F\n (\n m\n )\n H\n (\n n\n −\n m\n )\n {\\displaystyle {\\displaystyle G(n)=\\sum \\_{m=-\\infty }^{\\infty }F(m)H(n-m)}}\n\nfor all integers \n\nn\n{\\displaystyle {\\displaystyle {\\mathit {n}}}}\n. Assume \n\nF\n(\nn\n)\n{\\displaystyle {\\displaystyle F(n)}}\n can be non-zero only for \n\n0\n{\\displaystyle {\\displaystyle 0}}\n ≤ \n\nn\n{\\displaystyle {\\displaystyle {\\mathit {n}}}}\n ≤ \n\n|\n\n\nF\n\n|\n{\\displaystyle {\\displaystyle |{\\mathit {F}}|}}\n, where \n\n|\n\n\nF\n\n|\n{\\displaystyle {\\displaystyle |{\\mathit {F}}|}}\n is the \"length\" of \n\nF\n{\\displaystyle {\\displaystyle {\\mathit {F}}}}\n, and similarly for \n\nG\n{\\displaystyle {\\displaystyle {\\mathit {G}}}}\n and \n\nH\n{\\displaystyle {\\displaystyle {\\mathit {H}}}}\n, so that the functions can be modeled as finite sequences by identifying \n\nf\n\n0\n,\n\nf\n\n1\n,\n\nf\n\n2\n,\n…\n{\\displaystyle {\\displaystyle f\\_{0},f\\_{1},f\\_{2},\\dots }}\n with \n\nF\n(\n0\n)\n,\nF\n(\n1\n)\n,\nF\n(\n2\n)\n,\n…\n{\\displaystyle {\\displaystyle F(0),F(1),F(2),\\dots }}\n, etc.\nThen for example, values of \n\n|\n\n\nF\n\n|\n=\n6\n{\\displaystyle {\\displaystyle |{\\mathit {F}}|=6}}\n and \n\n|\n\n\nH\n\n|\n=\n5\n{\\displaystyle {\\displaystyle |{\\mathit {H}}|=5}}\n would determine the following value of \n\ng\n{\\displaystyle {\\displaystyle {\\mathit {g}}}}\n by definition.\n\n: g\n\n 0\n\n =\n\n\n f\n\n 0\n\n h\n\n 0\n\n g\n\n 1\n\n =\n\n\n f\n\n 1\n\n h\n\n 0\n\n +\n\n\n f\n\n 0\n\n h\n\n 1\n\n g\n\n 2\n\n =\n\n\n f\n\n 2\n\n h\n\n 0\n\n +\n\n\n f\n\n 1\n\n h\n\n 1\n\n +\n\n\n f\n\n 0\n\n h\n\n 2\n\n g\n\n 3\n\n =\n\n\n f\n\n 3\n\n h\n\n 0\n\n +\n\n\n f\n\n 2\n\n h\n\n 1\n\n +\n\n\n f\n\n 1\n\n h\n\n 2\n\n +\n\n\n f\n\n 0\n\n h\n\n 3\n\n g\n\n 4\n\n =\n\n\n f\n\n 4\n\n h\n\n 0\n\n +\n\n\n f\n\n 3\n\n h\n\n 1\n\n +\n\n\n f\n\n 2\n\n h\n\n 2\n\n +\n\n\n f\n\n 1\n\n h\n\n 3\n\n +\n\n\n f\n\n 0\n\n h\n\n 4\n\n g\n\n 5\n\n =\n\n\n f\n\n 5\n\n h\n\n 0\n\n +\n\n\n f\n\n 4\n\n h\n\n 1\n\n +\n\n\n f\n\n 3\n\n h\n\n 2\n\n +\n\n\n f\n\n 2\n\n h\n\n 3\n\n +\n\n\n f\n\n 1\n\n h\n\n 4\n\n g\n\n 6\n\n =\n\n f\n\n 5\n\n h\n\n 1\n\n +\n\n\n f\n\n 4\n\n h\n\n 2\n\n +\n\n\n f\n\n 3\n\n h\n\n 3\n\n +\n\n\n f\n\n 2\n\n h\n\n 4\n\n g\n\n 7\n\n =\n\n f\n\n 5\n\n h\n\n 2\n\n +\n\n\n f\n\n 4\n\n h\n\n 3\n\n +\n\n\n f\n\n 3\n\n h\n\n 4\n\n g\n\n 8\n\n =\n\n f\n\n 5\n\n h\n\n 3\n\n +\n\n\n f\n\n 4\n\n h\n\n 4\n\n g\n\n 9\n\n =\n\n f\n\n 5\n\n h\n\n 4\n {\\displaystyle {\\displaystyle {\\begin{array}{lllllllllll}g\\_{0}&=&f\\_{0}h\\_{0}\\\\g\\_{1}&=&f\\_{1}h\\_{0}&+&f\\_{0}h\\_{1}\\\\g\\_{2}&=&f\\_{2}h\\_{0}&+&f\\_{1}h\\_{1}&+&f\\_{0}h\\_{2}\\\\g\\_{3}&=&f\\_{3}h\\_{0}&+&f\\_{2}h\\_{1}&+&f\\_{1}h\\_{2}&+&f\\_{0}h\\_{3}\\\\g\\_{4}&=&f\\_{4}h\\_{0}&+&f\\_{3}h\\_{1}&+&f\\_{2}h\\_{2}&+&f\\_{1}h\\_{3}&+&f\\_{0}h\\_{4}\\\\g\\_{5}&=&f\\_{5}h\\_{0}&+&f\\_{4}h\\_{1}&+&f\\_{3}h\\_{2}&+&f\\_{2}h\\_{3}&+&f\\_{1}h\\_{4}\\\\g\\_{6}&=&&&f\\_{5}h\\_{1}&+&f\\_{4}h\\_{2}&+&f\\_{3}h\\_{3}&+&f\\_{2}h\\_{4}\\\\g\\_{7}&=&&&&&f\\_{5}h\\_{2}&+&f\\_{4}h\\_{3}&+&f\\_{3}h\\_{4}\\\\g\\_{8}&=&&&&&&&f\\_{5}h\\_{3}&+&f\\_{4}h\\_{4}\\\\g\\_{9}&=&&&&&&&&&f\\_{5}h\\_{4}\\end{array}}}}\n\nWe can write this in matrix form as:\n\n: (\n\n g\n\n 0\n\n g\n\n 1\n\n g\n\n 2\n\n g\n\n 3\n\n g\n\n 4\n\n g\n\n 5\n\n g\n\n 6\n\n g\n\n 7\n\n g\n\n 8\n\n g\n\n 9\n )\n =\n\n (\n\n f\n\n 0\n\n f\n\n 1\n\n\n f\n\n 0\n\n f\n\n 2\n\n\n f\n\n 1\n\n\n f\n\n 0\n\n f\n\n 3\n\n\n f\n\n 2\n\n\n f\n\n 1\n\n\n f\n\n 0\n\n f\n\n 4\n\n\n f\n\n 3\n\n\n f\n\n 2\n\n\n f\n\n 1\n\n\n f\n\n 0\n\n f\n\n 5\n\n\n f\n\n 4\n\n\n f\n\n 3\n\n\n f\n\n 2\n\n\n f\n\n 1\n\n f\n\n 5\n\n\n f\n\n 4\n\n\n f\n\n 3\n\n\n f\n\n 2\n\n f\n\n 5\n\n\n f\n\n 4\n\n\n f\n\n 3\n\n f\n\n 5\n\n\n f\n\n 4\n\n f\n\n 5\n )\n\n\n (\n\n h\n\n 0\n\n h\n\n 1\n\n h\n\n 2\n\n h\n\n 3\n\n h\n\n 4\n )\n {\\displaystyle {\\displaystyle \\left({\\begin{array}{l}g\\_{0}\\\\g\\_{1}\\\\g\\_{2}\\\\g\\_{3}\\\\g\\_{4}\\\\g\\_{5}\\\\g\\_{6}\\\\g\\_{7}\\\\g\\_{8}\\\\g\\_{9}\\\\\\end{array}}\\right)=\\left({\\begin{array}{lllll}f\\_{0}\\\\f\\_{1}&f\\_{0}\\\\f\\_{2}&f\\_{1}&f\\_{0}\\\\f\\_{3}&f\\_{2}&f\\_{1}&f\\_{0}\\\\f\\_{4}&f\\_{3}&f\\_{2}&f\\_{1}&f\\_{0}\\\\f\\_{5}&f\\_{4}&f\\_{3}&f\\_{2}&f\\_{1}\\\\&f\\_{5}&f\\_{4}&f\\_{3}&f\\_{2}\\\\&&f\\_{5}&f\\_{4}&f\\_{3}\\\\&&&f\\_{5}&f\\_{4}\\\\&&&&f\\_{5}\\end{array}}\\right)\\;\\left({\\begin{array}{l}h\\_{0}\\\\h\\_{1}\\\\h\\_{2}\\\\h\\_{3}\\\\h\\_{4}\\\\\\end{array}}\\right)}}\n\nor\n\n: g\n =\n A\n\n h\n {\\displaystyle {\\displaystyle g=A\\;h}}\n\nFor this task, implement a function (or method, procedure, subroutine, etc.) `deconv` to perform *deconvolution* (i.e., the *inverse* of convolution) by constructing and solving such a system of equations represented by the above matrix \n\nA\n{\\displaystyle {\\displaystyle A}}\n for \n\nh\n{\\displaystyle {\\displaystyle {\\mathit {h}}}}\n given \n\nf\n{\\displaystyle {\\displaystyle {\\mathit {f}}}}\n and \n\ng\n{\\displaystyle {\\displaystyle {\\mathit {g}}}}\n.\n\n* The function should work for \n\n G\n {\\displaystyle {\\displaystyle {\\mathit {G}}}}\n of arbitrary length (i.e., not hard coded or constant) and \n\n F\n {\\displaystyle {\\displaystyle {\\mathit {F}}}}\n of any length up to that of \n\n G\n {\\displaystyle {\\displaystyle {\\mathit {G}}}}\n . Note that \n\n |\n\n\n H\n\n |\n {\\displaystyle {\\displaystyle |{\\mathit {H}}|}}\n will be given by \n\n |\n\n\n G\n\n |\n −\n\n |\n\n\n F\n\n |\n +\n 1\n {\\displaystyle {\\displaystyle |{\\mathit {G}}|-|{\\mathit {F}}|+1}}\n .\n* There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task.\n* Test your solution on the following data. Be sure to verify both that `deconv`\n\n (\n g\n ,\n f\n )\n =\n h\n {\\displaystyle {\\displaystyle (g,f)=h}}\n and `deconv`\n\n (\n g\n ,\n h\n )\n =\n f\n {\\displaystyle {\\displaystyle (g,h)=f}}\n and display the results in a human readable form.\n\n`h = [-8,-9,-3,-1,-6,7] \nf = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1] \ng = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]`"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nTranslation of Python, using a modified version of the subroutine `rref` from Reduced row echelon form task.\n\n```\nsub deconvolve (@g, @f) {\n my \\h = 1 + @g - @f;\n my @m;\n @m[^@g;^h] »+=» 0;\n @m[^@g; h] »=« @g;\n for ^h -> \\j { for @f.kv -> \\k, \\v { @m[j+k;j] = v } }\n (rref @m)[^h;h]\n}\n\nsub convolve (@f, @h) {\n my @g = 0 xx + @f + @h - 1;\n @g[^@f X+ ^@h] »+=« (@f X× @h);\n @g\n}\n \n# Reduced Row Echelon Form simultaneous equation solver\n# Can handle over-specified systems of equations (N unknowns in N + M equations)\nsub rref (@m) {\n @m = trim-system @m;\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n for ^$rows -> $r {\n return @m unless $lead < $cols;\n my $i = $r;\n until @m[$i;$lead] {\n next unless ++$i == $rows;\n $i = $r;\n return @m if ++$lead == $cols;\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\n# Reduce to N equations in N unknowns; a no-op unless rows > cols\nsub trim-system (@m) {\n return @m unless @m ≥ @m[0]; \n my (\\vars, @t) = @m[0] - 1;\n for ^vars -> \\lead {\n for ^@m -> \\row {\n @t.append: @m.splice(row, 1) and last if @m[row;lead];\n }\n }\n while @t < vars and @m { @t.push: shift @m }\n @t\n}\n \nmy @h = (-8,-9,-3,-1,-6,7);\nmy @f = (-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1);\nmy @g = (24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7);\n \n.say for ~@g, ~convolve(@f, @h),'';\n.say for ~@h, ~deconvolve(@g, @f),'';\n.say for ~@f, ~deconvolve(@g, @h),'';\n\n```\n\nOutput:\n\n```\n24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7\n24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7\n\n-8 -9 -3 -1 -6 7\n-8 -9 -3 -1 -6 7\n\n-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1\n-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1\n```"
}
]
|
[
{
"role": "user",
"content": "This task is a straightforward generalization of Deconvolution/1D to higher dimensions. For example, the one dimensional case would be applicable to audio signals, whereas two dimensions would pertain to images. Define the discrete convolution in \n\nd\n{\\displaystyle {\\displaystyle {\\mathit {d}}}}\n dimensions of two functions\n\n: H\n ,\n F\n :\n\n\n Z\n\n d\n →\n\n R\n {\\displaystyle {\\displaystyle H,F:\\mathbb {Z} ^{d}\\rightarrow \\mathbb {R} }}\n\ntaking \n\nd\n{\\displaystyle {\\displaystyle {\\mathit {d}}}}\n-tuples of integers to real numbers as the function\n\n: G\n :\n\n\n Z\n\n d\n →\n\n R\n {\\displaystyle {\\displaystyle G:\\mathbb {Z} ^{d}\\rightarrow \\mathbb {R} }}\n\nalso taking \n\nd\n{\\displaystyle {\\displaystyle {\\mathit {d}}}}\n-tuples of integers to reals and satisfying\n\n: G\n (\n\n n\n\n 0\n ,\n …\n ,\n\n n\n\n d\n −\n 1\n )\n =\n\n ∑\n\n\n m\n\n 0\n =\n −\n ∞\n\n ∞\n …\n\n ∑\n\n\n m\n\n d\n −\n 1\n =\n −\n ∞\n\n ∞\n F\n (\n\n m\n\n 0\n ,\n …\n ,\n\n m\n\n d\n −\n 1\n )\n H\n (\n\n n\n\n 0\n −\n\n m\n\n 0\n ,\n …\n ,\n\n n\n\n d\n −\n 1\n −\n\n m\n\n d\n −\n 1\n )\n {\\displaystyle {\\displaystyle G(n\\_{0},\\dots ,n\\_{d-1})=\\sum \\_{m\\_{0}=-\\infty }^{\\infty }\\dots \\sum \\_{m\\_{d-1}=-\\infty }^{\\infty }F(m\\_{0},\\dots ,m\\_{d-1})H(n\\_{0}-m\\_{0},\\dots ,n\\_{d-1}-m\\_{d-1})}}\n\nfor all \n\nd\n{\\displaystyle {\\displaystyle {\\mathit {d}}}}\n-tuples of integers \n\n(\n\nn\n\n0\n,\n…\n,\n\nn\n\nd\n−\n1\n)\n∈\n\n\nZ\n\nd\n{\\displaystyle {\\displaystyle (n\\_{0},\\dots ,n\\_{d-1})\\in \\mathbb {Z} ^{d}}}\n. Assume\n\nF\n{\\displaystyle {\\displaystyle {\\mathit {F}}}}\n and \n\nH\n{\\displaystyle {\\displaystyle {\\mathit {H}}}}\n (and therefore \n\nG\n{\\displaystyle {\\displaystyle {\\mathit {G}}}}\n) are non-zero over only a finite domain bounded by the origin, hence possible to represent as finite multi-dimensional arrays or nested lists \n\nf\n{\\displaystyle {\\displaystyle {\\mathit {f}}}}\n, \n\nh\n{\\displaystyle {\\displaystyle {\\mathit {h}}}}\n, and \n\ng\n{\\displaystyle {\\displaystyle {\\mathit {g}}}}\n.\n\nFor this task, implement a function (or method, procedure, subroutine, etc.) `deconv` to perform *deconvolution* (i.e., the *inverse* of convolution) by solving for \n\nh\n{\\displaystyle {\\displaystyle {\\mathit {h}}}}\n given \n\nf\n{\\displaystyle {\\displaystyle {\\mathit {f}}}}\n and \n\ng\n{\\displaystyle {\\displaystyle {\\mathit {g}}}}\n. (See Deconvolution/1D for details.)\n\n* The function should work for \n\n g\n {\\displaystyle {\\displaystyle {\\mathit {g}}}}\n of arbitrary length in each dimension (i.e., not hard coded or constant) and \n\n f\n {\\displaystyle {\\displaystyle {\\mathit {f}}}}\n of any length up to that of \n\n g\n {\\displaystyle {\\displaystyle {\\mathit {g}}}}\n in the corresponding dimension.\n* The `deconv` function will need to be parameterized by the dimension \n\n d\n {\\displaystyle {\\displaystyle {\\mathit {d}}}}\n unless the dimension can be inferred from the data structures representing \n\n g\n {\\displaystyle {\\displaystyle {\\mathit {g}}}}\n and \n\n f\n {\\displaystyle {\\displaystyle {\\mathit {f}}}}\n .\n* There may be more equations than unknowns. If convenient, use a function from a library that finds the best fitting solution to an overdetermined system of linear equations (as in the Multiple regression task). Otherwise, prune the set of equations as needed and solve as in the Reduced row echelon form task.\n* Debug your solution using this test data, of which a portion is shown below. Be sure to verify both that the deconvolution of \n\n g\n {\\displaystyle {\\displaystyle {\\mathit {g}}}}\n with \n\n f\n {\\displaystyle {\\displaystyle {\\mathit {f}}}}\n is \n\n h\n {\\displaystyle {\\displaystyle {\\mathit {h}}}}\n and that the deconvolution of \n\n g\n {\\displaystyle {\\displaystyle {\\mathit {g}}}}\n with \n\n h\n {\\displaystyle {\\displaystyle {\\mathit {h}}}}\n is \n\n f\n {\\displaystyle {\\displaystyle {\\mathit {f}}}}\n . Display the results in a human readable form for the three dimensional case *only*.\n\ndimension 1:\n\n```\nh: [-8, 2, -9, -2, 9, -8, -2]\nf: [ 6, -9, -7, -5]\ng: [-48, 84, -16, 95, 125, -70, 7, 29, 54, 10]\n\n```\n\ndimension 2:\n\n```\nh: [\n [-8, 1, -7, -2, -9, 4], \n [4, 5, -5, 2, 7, -1], \n [-6, -3, -3, -6, 9, 5]]\nf: [\n [-5, 2, -2, -6, -7], \n [9, 7, -6, 5, -7], \n [1, -1, 9, 2, -7], \n [5, 9, -9, 2, -5], \n [-8, 5, -2, 8, 5]]\ng: [\n [40, -21, 53, 42, 105, 1, 87, 60, 39, -28], \n [-92, -64, 19, -167, -71, -47, 128, -109, 40, -21], \n [58, 85, -93, 37, 101, -14, 5, 37, -76, -56], \n [-90, -135, 60, -125, 68, 53, 223, 4, -36, -48], \n [78, 16, 7, -199, 156, -162, 29, 28, -103, -10], \n [-62, -89, 69, -61, 66, 193, -61, 71, -8, -30], \n [48, -6, 21, -9, -150, -22, -56, 32, 85, 25]]\n\n```\n\ndimension 3:\n\n```\nh: [\n [[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], \n [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]\nf: [\n [[-9, 5, -8], [3, 5, 1]], \n [[-1, -7, 2], [-5, -6, 6]], \n [[8, 5, 8],[-2, -6, -4]]]\ng: [\n [\n [54, 42, 53, -42, 85, -72], \n [45, -170, 94, -36, 48, 73], \n [-39, 65, -112, -16, -78, -72], \n [6, -11, -6, 62, 49, 8]], \n [\n [-57, 49, -23, 52, -135, 66], \n [-23, 127, -58, -5, -118, 64], \n [87, -16, 121, 23, -41, -12], \n [-19, 29, 35, -148, -11, 45]], \n [\n [-55, -147, -146, -31, 55, 60], \n [-88, -45, -28, 46, -26, -144], \n [-12, -107, -34, 150, 249, 66], \n [11, -15, -34, 27, -78, -50]], \n [\n [56, 67, 108, 4, 2, -48], \n [58, 67, 89, 32, 32, -8], \n [-42, -31, -103, -30, -23, -8],\n [6, 4, -26, -10, 26, 12]]]\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nTranslation of Tcl.\n\n```\n# Deconvolution of N dimensional matrices.\nsub deconvolve-N ( @g, @f ) {\n my @hsize = @g.shape »-« @f.shape »+» 1;\n\n my @toSolve = coords(@g.shape).map:\n { [row(@g, @f, $^coords, @hsize)] };\n\n my @solved = rref( @toSolve );\n\n my @h;\n for flat coords(@hsize) Z @solved[*;*-1] -> $_, $v {\n @h.AT-POS(|$_) = $v;\n }\n @h\n}\n\n# Construct a row for each value in @g to be sent to the simultaneous equation solver\nsub row ( @g, @f, @gcoord, $hsize ) {\n my @row;\n @gcoord = @gcoord[(^@f.shape)]; # clip extraneous values\n for coords( $hsize ) -> @hc {\n my @fcoord;\n for ^@hc -> $i {\n my $window = @gcoord[$i] - @hc[$i];\n @fcoord.push($window) and next if 0 ≤ $window < @f.shape[$i];\n last;\n }\n @row.push: @fcoord == @hc ?? @f.AT-POS(|@fcoord) !! 0;\n }\n @row.push: @g.AT-POS(|@gcoord);\n @row\n}\n\n# Constructs an AoA of coordinates to all elements of N dimensional array\nsub coords ( @dim ) {\n @[reverse $_ for [X] ([^$_] for reverse @dim)]\n}\n\n# Reduced Row Echelon Form simultaneous equation solver\n# Can handle over-specified systems (N unknowns in N + M equations)\nsub rref (@m) {\n @m = trim-system @m;\n my ($lead, $rows, $cols) = 0, @m, @m[0];\n for ^$rows -> $r {\n return @m unless $lead < $cols;\n my $i = $r;\n until @m[$i;$lead] {\n next unless ++$i == $rows;\n $i = $r;\n return @m if ++$lead == $cols;\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\n# Reduce to N equations in N unknowns; a no-op unless rows > cols\nsub trim-system (@m) {\n return @m unless @m ≥ @m[0]; \n my (\\vars, @t) = @m[0] - 1;\n for ^vars -> \\lead {\n for ^@m -> \\row {\n @t.append: @m.splice(row, 1) and last if @m[row;lead];\n }\n }\n while @t < vars and @m { @t.push: shift @m }\n @t\n}\n\n# Pretty printer for N dimensional arrays\n# Assumes if first element in level is an array, then all are\nsub pretty-print ( @array, $indent = 0 ) {\n if @array[0] ~~ Array {\n say ' ' x $indent,\"[\";\n pretty-print( $_, $indent + 2 ) for @array;\n say ' ' x $indent, \"]{$indent??','!!''}\";\n } else {\n say ' ' x $indent, \"[{say_it(@array)} ]{$indent??','!!''}\";\n }\n\n sub say_it ( @array ) { return join \",\", @array».fmt(\"%4s\"); }\n}\n\nmy @f[3;2;3] = (\n [\n [ -9, 5, -8 ],\n [ 3, 5, 1 ],\n ],\n [\n [ -1, -7, 2 ],\n [ -5, -6, 6 ],\n ],\n [\n [ 8, 5, 8 ],\n [ -2, -6, -4 ],\n ]\n);\n\nmy @g[4;4;6] = (\n [\n [ 54, 42, 53, -42, 85, -72 ],\n [ 45,-170, 94, -36, 48, 73 ],\n [ -39, 65,-112, -16, -78, -72 ],\n [ 6, -11, -6, 62, 49, 8 ],\n ],\n [\n [ -57, 49, -23, 52,-135, 66 ],\n [ -23, 127, -58, -5,-118, 64 ],\n [ 87, -16, 121, 23, -41, -12 ],\n [ -19, 29, 35,-148, -11, 45 ],\n ],\n [\n [ -55,-147,-146, -31, 55, 60 ],\n [ -88, -45, -28, 46, -26,-144 ],\n [ -12,-107, -34, 150, 249, 66 ],\n [ 11, -15, -34, 27, -78, -50 ],\n ],\n [\n [ 56, 67, 108, 4, 2, -48 ],\n [ 58, 67, 89, 32, 32, -8 ],\n [ -42, -31,-103, -30, -23, -8 ],\n [ 6, 4, -26, -10, 26, 12 ],\n ]\n);\n\nsay \"# {[email protected]}D array:\";\nmy @h = deconvolve-N( @g, @f );\nsay \"h =\";\npretty-print( @h );\nmy @h-shaped[2;3;4] = @(deconvolve-N( @g, @f ));\nmy @ff = deconvolve-N( @g, @h-shaped );\nsay \"\\nff =\";\npretty-print( @ff );\n\n```\n\nOutput:\n\n```\n# 3D array:\nh =\n[\n [\n [ -6, -8, -5, 9 ],\n [ -7, 9, -6, -8 ],\n [ 2, -7, 9, 8 ],\n ],\n [\n [ 7, 4, 4, -6 ],\n [ 9, 9, 4, -4 ],\n [ -3, 7, -2, -3 ],\n ],\n]\n\nff =\n[\n [\n [ -9, 5, -8 ],\n [ 3, 5, 1 ],\n ],\n [\n [ -1, -7, 2 ],\n [ -5, -6, 6 ],\n ],\n [\n [ 8, 5, 8 ],\n [ -2, -6, -4 ],\n ],\n]\n```"
}
]
|
[
{
"role": "user",
"content": "Introduction\n\nSuppose you have to sort a list of strings based on a property of each, called \"the key\", i.e. their lenghts. The most popular solution would require the use of a sorting algorithm with a custom comparator.\n\nNow suppose that key computation is an expensive operation, for example, it might involve intensive reading of files, databases, or exchanging information over a network. In such a case, using a sorting algorithm with a custom comparator is not optimal, because the key is computed multiple times for each element in the array, once each time the element needs to be compared to another (and also requires the calculation of the key for that other).\n\nThe decorate-sort-undecorate idiom\n\nOne solution of the problem is called the \"decorate-sort-undecorate\" idiom, pattern or technique. It was originated and named by the Lisp community.\n\nSuppose we want to sort the following list of words according to their lengths (the length was chosen for illustrative purposes, it is not precisely an \"expensive\" operation).\n\n`{\"Rosetta\", \"Code\", \"is\", \"a\", \"programming\", \"chrestomathy\", \"site\"}`\n\nAccording to the decorate-sort-decorate idiom, we have to \"decorate\" each element with its key, so each element of the original list becomes a pair. Notice that the key is calculated once (and only once) for each element in the list:\n\n`{{\"Rosetta\", 7}, {\"Code\", 4}, {\"is\", 2}, {\"a\", 1}, {\"programming\", 11}, {\"chrestomathy\", 12}, {\"site\", 4}}`\n\nThe list is then sorted according to the second element of each pair (the key), perhaps using a custom comparator:\n\n`{{\"a\", 1}, {\"is\", 2}, {\"site\", 4}, {\"Code\", 4}, {\"Rosetta\", 7}, {\"programming\", 11}, {\"chrestomathy\", 12}}`\n\nAnd finally, the list must be undecorated, we have to remove the second element of each pair (the key):\n\n`{\"a\", \"is\", \"site\", \"Code\", \"Rosetta\", \"programming\", \"chrestomathy\"}`\n\nSo, the decoration acts as a form of memoization.\n\nThe Schwartzian transform\n\nRandal L. Schwartz wrote an implementation of the decorate-sort-undecorate idiom in Perl in 1994, which gained much popularity in the Perl community. It was named \"Schwartzian transform\". Today the terms decorate-sort-undecorate and the Schwartzian transform are used interchangeably, even outside the Perl community.\n\nThe Wikipedia page states that a solution can be called a \"Schwartzian transform\" only if it does not use named temporary lists or arrays. The Lisp solution and even the solution shown by Schwartz actually use intermediate lists, but these lists do not have explicit names, instead they use a functional composition of map-sort-map operations.\n\nTask\n\nWrite in your programming language, a function, procedure, method, routine, etc. to sort a list of words by length (the key function), using the decorate-sort-undecorate idiom.\n\n* **Bonus 1**. If your solution can accept the key function as a callback.\n* **Bonus 2**. If your solution is also a \"Schwartzian transform\", this is, it does not use **named** temporary lists/arrays.\n\nYou can, at your choice, show two solutions, the first using intermediate named lists/arrays, and the second one not using them (a Schwartzian transform)(if applicable). The first solution is sometimes more valuable, because the use of named entities makes the code clearer.\n\nReferences\n\n: * Wikipedia: Schwartzian transform"
},
{
"role": "assistant",
"content": "It is somewhat rare to do, or even need to do an explicit schwartzian transform in Raku. You can pass a transform function to the sort operator, and it will use it to do its comparisons. As long as the transform is arity one (only takes one value,) the sort will *automatically* perform a schwartzian transform transparently, behind the scenes.\n\nHere the transform `.chars` is arity one, so a schwartzian transform is performed automatically by the compiler.\n\n```\n# automatic schwartzian transform\ndd <Rosetta Code is a programming chrestomathy site>.sort: *.chars;\n\n# explicit schwartzian transform\ndd <Rosetta Code is a programming chrestomathy site>.map({$_=>.chars}).sort({$^one.value cmp $^the-other.value}).map({.key});\n\n```\n\nOutput:\n\n( `dd` is the built in \"data-dumper\" function; a verbose and explicit representation of an objects contents.)\n\n```\n(\"a\", \"is\", \"Code\", \"site\", \"Rosetta\", \"programming\", \"chrestomathy\").Seq\n(\"a\", \"is\", \"Code\", \"site\", \"Rosetta\", \"programming\", \"chrestomathy\").Seq\n```\n\nMore complicated transforms may *require* an explicit schwartzian transform routine. An example of where an explicit transform is desirable is the `schwartzian()` routine in the Raku entry for the P-value\\_correction task."
}
]
|
[
{
"role": "user",
"content": "Given a List (abstract data type) of integer values, find all its maximal-length non-increasing subsequences. Categorize each of these subsequences by its percentage change using the following groups:\n\n* Greater than 0% and less than 4%\n* Greater than or equal to 4% and less than 8%\n* Greater than or equal to 8% and less than 12%\n* Greater than or equal to 12% and less than 16%\n* Greater than or equal to 16% and less than 25%\n* Greater than or equal to 25%\n\nIf we were to plot these values, we'd be looking for peaks and troughs, categorized by the difference between the local maximum and the local minimum, as a percentage of the local maximum.\n\nA plot highlighting decreasing contiguous subsequences\n\nUsing the following example sequence, display the count of subsequences per group.\n\n```\n90, 90, 90, 91, 91, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89, 89, 88, 87, 87, 87, 86, 86, 86, 85, 85,\n86, 86, 87, 87, 88, 89, 89, 89, 90, 90, 91, 91, 91, 92, 92, 92, 92, 92, 92, 92, 92, 92, 91, 91, 90,\n90, 90, 90, 90, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89,\n89, 90, 90, 90, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 87, 88, 88, 88, 88, 88, 88, 88, 88,\n88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 89,\n89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87,\n87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88,\n88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 87, 87, 87, 87, 86, 86, 86, 86,\n86, 86, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89,\n88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 89, 89, 91,\n94, 94, 95, 96, 96, 96, 97, 97, 96, 96, 96, 96, 95, 95, 94, 93, 93, 92, 92, 91, 91, 90, 89, 89, 88,\n86, 86, 85, 83, 83, 81, 80, 80, 80, 79, 79, 79, 78, 78, 79, 81, 82, 82, 85, 89, 89, 91, 93, 93, 94,\n95, 95, 95, 95, 95, 95, 95, 95, 95, 94, 94, 94, 94, 93, 93, 93, 92, 92, 91, 91, 91, 90, 90, 90, 88,\n87, 87, 86, 85, 85, 84, 84, 84, 83, 84, 84, 84, 85, 86, 86, 87, 87, 87, 88, 88, 88, 89, 90, 90, 90,\n91, 91, 92, 92, 92, 93, 94, 94, 94, 95, 95, 95, 95, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91, 91, 90,\n89, 89, 87, 86, 85, 85, 84, 83, 83, 82, 82, 82, 81, 81, 81, 81, 81, 81, 82, 85, 85, 86, 89, 89, 91,\n92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 89, 89,\n88, 88, 88, 87, 87, 87, 86, 86, 86, 85, 85, 85, 85, 85, 85, 86, 87, 87, 87, 88, 88, 88, 88, 88, 88,\n89, 89, 89, 89, 89, 89, 90, 90, 90, 90, 91, 91, 92, 93, 93, 94, 94, 95, 95, 95, 96, 96, 96, 95, 95,\n95, 94, 94, 93, 93, 93, 92, 90, 90, 89, 87, 87, 87, 85, 83, 83, 82, 81, 81, 81, 80, 80, 81, 81, 81,\n81, 81, 81, 81, 81, 81, 81, 81, 81, 83, 86, 88, 88, 90, 91, 91, 91, 92, 92, 93, 93, 93, 94, 95, 95,\n95, 96, 96, 96, 96, 96, 96, 96, 95, 95, 95, 95, 95, 94, 93, 93, 92, 92, 92, 91, 90, 90, 90, 90, 90,\n91, 93, 93, 94, 94, 94, 94, 95, 94, 94, 94, 94, 94, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 92, 92,\n91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 89, 89, 89, 89, 89, 89, 89, 89, 89,\n89, 90, 90, 90, 90, 91, 91, 92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 95, 95, 95, 95, 95,\n95, 95, 95, 95, 94, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 91, 90, 90, 90, 89, 89, 89, 88, 88,\n88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91,\n91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 92,\n92, 93, 93, 93, 93, 94, 94, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89, 88,\n88, 87, 87, 87, 86, 86, 85, 85, 85, 86, 86, 86, 87, 87, 88, 88, 88, 89, 90, 90, 90, 91, 91, 91, 91,\n91, 91, 91, 91, 91, 92, 92, 92, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 90, 90, 90, 89, 88,\n87, 87, 87, 86, 86, 86, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86, 87, 88, 88, 88,\n89, 89, 90, 91, 91, 92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91,\n90, 90, 90, 89, 89, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88,\n90, 90, 91, 93, 93, 93, 93, 93, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89,\n89, 89, 88, 87, 87, 87, 87, 87, 86, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88,\n89\n\n```\n\nIt's OK to hard code the example sequence or read it from a file. Plotting decreasing subsequences is optional."
},
{
"role": "assistant",
"content": "Since these are percentages, no need to specify a span. The span is automatically 0-100. The carat in the bin ranges mean \"upto, but not including\".\n\n```\nmy @values =\n90, 90, 90, 91, 91, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89, 89, 88, 87, 87, 87, 86, 86, 86, 85, 85,\n86, 86, 87, 87, 88, 89, 89, 89, 90, 90, 91, 91, 91, 92, 92, 92, 92, 92, 92, 92, 92, 92, 91, 91, 90,\n90, 90, 90, 90, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89,\n89, 90, 90, 90, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 87, 88, 88, 88, 88, 88, 88, 88, 88,\n88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 89,\n89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87,\n87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 88, 88, 88, 88,\n88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89, 89, 89, 89, 88, 88, 88, 87, 87, 87, 87, 86, 86, 86, 86,\n86, 86, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 89, 89, 89,\n88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 89, 89, 91,\n94, 94, 95, 96, 96, 96, 97, 97, 96, 96, 96, 96, 95, 95, 94, 93, 93, 92, 92, 91, 91, 90, 89, 89, 88,\n86, 86, 85, 83, 83, 81, 80, 80, 80, 79, 79, 79, 78, 78, 79, 81, 82, 82, 85, 89, 89, 91, 93, 93, 94,\n95, 95, 95, 95, 95, 95, 95, 95, 95, 94, 94, 94, 94, 93, 93, 93, 92, 92, 91, 91, 91, 90, 90, 90, 88,\n87, 87, 86, 85, 85, 84, 84, 84, 83, 84, 84, 84, 85, 86, 86, 87, 87, 87, 88, 88, 88, 89, 90, 90, 90,\n91, 91, 92, 92, 92, 93, 94, 94, 94, 95, 95, 95, 95, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91, 91, 90,\n89, 89, 87, 86, 85, 85, 84, 83, 83, 82, 82, 82, 81, 81, 81, 81, 81, 81, 82, 85, 85, 86, 89, 89, 91,\n92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 89, 89,\n88, 88, 88, 87, 87, 87, 86, 86, 86, 85, 85, 85, 85, 85, 85, 86, 87, 87, 87, 88, 88, 88, 88, 88, 88,\n89, 89, 89, 89, 89, 89, 90, 90, 90, 90, 91, 91, 92, 93, 93, 94, 94, 95, 95, 95, 96, 96, 96, 95, 95,\n95, 94, 94, 93, 93, 93, 92, 90, 90, 89, 87, 87, 87, 85, 83, 83, 82, 81, 81, 81, 80, 80, 81, 81, 81,\n81, 81, 81, 81, 81, 81, 81, 81, 81, 83, 86, 88, 88, 90, 91, 91, 91, 92, 92, 93, 93, 93, 94, 95, 95,\n95, 96, 96, 96, 96, 96, 96, 96, 95, 95, 95, 95, 95, 94, 93, 93, 92, 92, 92, 91, 90, 90, 90, 90, 90,\n91, 93, 93, 94, 94, 94, 94, 95, 94, 94, 94, 94, 94, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 92, 92,\n91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 89, 89, 89, 89, 89, 89, 89, 89, 89,\n89, 90, 90, 90, 90, 91, 91, 92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 95, 95, 95, 95, 95,\n95, 95, 95, 95, 94, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 91, 90, 90, 90, 89, 89, 89, 88, 88,\n88, 88, 88, 88, 88, 88, 88, 89, 89, 89, 89, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 91, 91, 91,\n91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 92,\n92, 93, 93, 93, 93, 94, 94, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89, 88,\n88, 87, 87, 87, 86, 86, 85, 85, 85, 86, 86, 86, 87, 87, 88, 88, 88, 89, 90, 90, 90, 91, 91, 91, 91,\n91, 91, 91, 91, 91, 92, 92, 92, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 90, 90, 90, 89, 88,\n87, 87, 87, 86, 86, 86, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 86, 86, 86, 86, 87, 88, 88, 88,\n89, 89, 90, 91, 91, 92, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 93, 93, 93, 92, 92, 92, 91,\n90, 90, 90, 89, 89, 88, 88, 88, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88,\n90, 90, 91, 93, 93, 93, 93, 93, 94, 93, 93, 93, 93, 93, 93, 92, 92, 92, 91, 91, 91, 90, 90, 90, 89,\n89, 89, 88, 87, 87, 87, 87, 87, 86, 87, 87, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88,\n89;\n\nmy @bins = 0^..^4, 4..^8, 8..^12, 12..^16, 16..^25, 25..100;\n\nmy @subseqs;\n\[email protected]: {\n state $last = $_;\n state $incr = 0;\n ++$incr if $_ > $last;\n @subseqs[$incr].push: $_;\n $last = $_;\n};\n\nsub bin (@items, @bins, :&as) {\n my @classified;\n for @items {\n my $value = .&as;\n for @bins {\n state $index = 0;\n @classified[$index]++ if $value ∈ $_;\n ++$index;\n }\n }\n @classified\n}\n\nsay \"{.[0].gist}% : {.[1]}\" for @bins Z flat @subseqs.&bin(@bins, :as{[R-] .minmax.bounds}), 0 xx *;\n\n```\n\nOutput:\n\n```\n0^..^4% : 7\n4..^8% : 6\n8..^12% : 4\n12..^16% : 2\n16..^25% : 2\n25..100% : 0\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDemonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.\n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku doesn't currently provide a proper mechanism for deep copies, but depending on your requirements you could use one of these work-arounds:\n\n**1) Use `.deepmap(*.clone)`:**\n\n.deepmap constructs a copy of the data structure, and .clone makes a shallow copy of each leaf node. Limitations:\n\n* Hangs indefinitely when given a self-referential data structure.\n* Descends only into Iterable collections (like Array/Hash), which means that a Pair or a typical custom object would be considered a leaf node.\n\n```\nmy %x = foo => 0, bar => [0, 1];\nmy %y = %x.deepmap(*.clone);\n\n%x<bar>[1]++;\nsay %x;\nsay %y;\n\n```\n\nOutput:\n\n```\n{bar => [0 2], foo => 0}\n{bar => [0 1], foo => 0}\n\n```\n\n**2) Use `.raku.EVAL`:**\n\n.raku serializes the data structure to Raku code, and .EVAL deserializes it. Limitations:\n\n* Doesn't work correctly if the data structure contains elements that can't be properly serialized, such as closures or file handles.\n\n```\nmy %x = foo => 0, bar => [0, 1];\nmy %y = %x.raku.EVAL;\n\n%x<bar>[1]++;\nsay %x;\nsay %y;\n\n```\n\nOutput:\n\n```\n{bar => [0 2], foo => 0}\n{bar => [0 1], foo => 0}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsubset OneToTen of Int where 1..10;\n\nmy OneToTen $n = 5;\n$n += 6;\n\n```\n\nHere the result 11 fails to smartmatch against the range `1..10`, so the second assignment throws an exception. You may use any valid smartmatch predicate within a `where` clause, so the following one-argument closure is also legal:\n\n```\nsubset Prime of Int where -> $n { $n > 1 and so $n %% none 2 .. $n.sqrt }\n\n```"
}
]
|
[
{
"role": "user",
"content": "A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.\n\nObjects responsibilities:\n\nDelegator:\n\n* Keep an optional delegate instance.\n* Implement \"operation\" method, returning the delegate \"thing\" if the delegate respond to \"thing\", or the string \"default implementation\".\n\nDelegate:\n\n* Implement \"thing\" and return the string \"delegate implementation\"\n\nShow how objects are created and used. First, without a delegate, then with a delegate that does not implement \"thing\", and last with a delegate that implements \"thing\"."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nclass Non-Delegate { }\n\nclass Delegate {\n\tmethod thing {\n\t\treturn \"delegate implementation\"\n\t}\n}\n\nclass Delegator {\n\thas $.delegate is rw;\n\n\tmethod operation {\n\t\t$.delegate.^can( 'thing' ) ?? $.delegate.thing\n\t\t!! \"default implementation\"\n\t}\n}\n\nmy Delegator $d .= new;\n\nsay \"empty: \"~$d.operation;\n\n$d.delegate = Non-Delegate.new;\n\nsay \"Non-Delegate: \"~$d.operation;\n\n$d.delegate = Delegate.new;\n\nsay \"Delegate: \"~$d.operation;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDelete a file called \"input.txt\" and delete a directory called \"docs\".\n\nThis should be done twice: once \"here\", i.e. in the current working directory and once in the filesystem root."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nunlink 'input.txt';\nunlink '/input.txt';\nrmdir 'docs';\nrmdir '/docs';\n\n```"
}
]
|
[
{
"role": "user",
"content": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* **Rule 1**: The funnel remains directly above the target.\n* **Rule 2**: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* **Rule 3**: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* **Rule 4**: The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. **Output**: calculate the mean and standard-deviations of the resulting x and y values for each rule.\n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n**Stretch goal 1**: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n**Stretch goal 2**: Show scatter plots of all four results.\n\nFurther information\n\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\n```\nsub mean { @_ R/ [+] @_ }\nsub stddev {\n # <(x - <x>)²> = <x²> - <x>²\n sqrt( mean(@_ »**» 2) - mean(@_)**2 )\n}\n\nconstant @dz = <\n -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275\n 1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001\n -0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014\n 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047\n -0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021\n -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315\n 0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181\n -0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658\n 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774\n -1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106\n 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017\n 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598\n 0.443 -0.521 -0.799 0.087\n> Z+ (1i X* <\n 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395\n 0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000\n 0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208\n 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096\n -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007\n 0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226\n 0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295\n 1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217\n -0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219\n 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104\n -0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477\n 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224\n -0.947 -1.424 -0.542 -1.032\n>);\n\nconstant @rule = \n-> \\z, \\dz { 0 },\n-> \\z, \\dz { -dz },\n-> \\z, \\dz { -z - dz },\n-> \\z, \\dz { z + dz },\n;\n\nfor @rule {\n say \"Rule $(++$):\";\n my $target = 0i;\n my @z = gather for @dz -> $dz {\n\ttake $target + $dz;\n\t$target = .($target, $dz)\n }\n printf \"Mean x, y : %7.4f %7.4f\\n\", mean(@z».re), mean(@z».im);\n printf \"Std dev x, y : %7.4f %7.4f\\n\", stddev(@z».re), stddev(@z».im);\n}\n\n```\n\nOutput:\n\n```\nRule 1:\nMean x, y : 0.0004 0.0702\nStd dev x, y : 0.7153 0.6462\nRule 2:\nMean x, y : 0.0009 -0.0103\nStd dev x, y : 1.0371 0.8999\nRule 3:\nMean x, y : 0.0439 -0.0063\nStd dev x, y : 7.9871 4.7784\nRule 4:\nMean x, y : 3.1341 5.4210\nStd dev x, y : 1.5874 3.9304\n```"
}
]
|
[
{
"role": "user",
"content": "There is a highly organized city that has decided to assign a number to each of their departments:\n\n: : * police department\n * sanitation department\n * fire department\n\nEach department can have a number between **1** and **7** (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to **12**.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\nTask\n\nWrite a computer program which outputs all valid combinations.\n\nPossible output (for the 1st and 14th solutions):\n\n```\n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nfor (1..7).combinations(3).grep(*.sum == 12) {\n for .permutations\\ .grep(*.[0] %% 2) {\n say <police fire sanitation> Z=> .list;\n }\n}\n\n```\n\nOutput:\n\n```\n(police => 4 fire => 1 sanitation => 7)\n(police => 4 fire => 7 sanitation => 1)\n(police => 6 fire => 1 sanitation => 5)\n(police => 6 fire => 5 sanitation => 1)\n(police => 2 fire => 3 sanitation => 7)\n(police => 2 fire => 7 sanitation => 3)\n(police => 2 fire => 4 sanitation => 6)\n(police => 2 fire => 6 sanitation => 4)\n(police => 4 fire => 2 sanitation => 6)\n(police => 4 fire => 6 sanitation => 2)\n(police => 6 fire => 2 sanitation => 4)\n(police => 6 fire => 4 sanitation => 2)\n(police => 4 fire => 3 sanitation => 5)\n(police => 4 fire => 5 sanitation => 3)\n\n```"
}
]
|
[
{
"role": "user",
"content": "Generate and show all primes with strictly descending decimal digits.\n\nSee also\n\n* OEIS:A052014 - Primes with distinct digits in descending order\n\nRelated\n\n* Ascending primes"
},
{
"role": "assistant",
"content": "Trivial variation of Ascending primes task.\n\n```\nput (flat 2, 3, 5, 7, sort +*, gather (3..9).map: &recurse ).batch(10)».fmt(\"%8d\").join: \"\\n\";\n\nsub recurse ($str) {\n .take for ($str X~ (1, 3, 7)).grep: { .is-prime && [>] .comb };\n recurse $str × 10 + $_ for 2 ..^ $str % 10;\n}\n\n```\n\nOutput:\n\n```\n 2 3 5 7 31 41 43 53 61 71\n 73 83 97 421 431 521 541 631 641 643\n 653 743 751 761 821 853 863 941 953 971\n 983 5431 6421 6521 7321 7541 7621 7643 8431 8521\n 8543 8641 8731 8741 8753 8761 9421 9431 9521 9631\n 9643 9721 9743 9851 9871 75431 76421 76541 76543 86531\n 87421 87541 87631 87641 87643 94321 96431 97651 98321 98543\n 98621 98641 98731 764321 865321 876431 975421 986543 987541 987631\n 8764321 8765321 9754321 9875321 97654321 98764321 98765431\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a function to detect a *divide by zero error* without checking if the denominator is zero."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n#### Try/Catch\n\n```\nsub div($a, $b) {\n my $r;\n try {\n $r = $a / $b;\n CATCH {\n default { note \"Unexpected exception, $_\" }\n }\n }\n return $r // Nil;\n}\nsay div(10,2);\nsay div(1, sin(0));\n\n```\n\nOutput:\n\n```\n5\nUnexpected exception, Attempt to divide 1 by zero using /\nNil\n```\n\n#### Multi Method Dispatch\n\n```\nmulti div($a, $b) { return $a / $b }\nmulti div($a, $b where { $b == 0 }) { note 'Attempt to divide by zero.'; return Nil }\n\nsay div(10, 2);\nsay div(1, sin(0));\n\n```\n\nOutput:\n\n```\n5\nAttempt to divide by zero.\nNil\n```"
}
]
|
[
{
"role": "user",
"content": "For a given matrix, return the determinant and the permanent of the matrix.\n\nThe determinant is given by\n\n: : det\n (\n A\n )\n =\n\n ∑\n\n σ\n sgn\n \n (\n σ\n )\n\n ∏\n\n i\n =\n 1\n\n n\n\n M\n\n i\n ,\n\n σ\n\n i\n {\\displaystyle {\\displaystyle \\det(A)=\\sum \\_{\\sigma }\\operatorname {sgn}(\\sigma )\\prod \\_{i=1}^{n}M\\_{i,\\sigma \\_{i}}}}\n\nwhile the permanent is given by\n\n: : perm\n \n (\n A\n )\n =\n\n ∑\n\n σ\n\n ∏\n\n i\n =\n 1\n\n n\n\n M\n\n i\n ,\n\n σ\n\n i\n {\\displaystyle {\\displaystyle \\operatorname {perm} (A)=\\sum \\_{\\sigma }\\prod \\_{i=1}^{n}M\\_{i,\\sigma \\_{i}}}}\n\nIn both cases the sum is over the permutations \n\nσ\n{\\displaystyle {\\displaystyle \\sigma }}\n of the permutations of 1, 2, ..., *n*. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.\n\nRelated task\n\n* Permutations by swapping"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nUses the permutations generator from the Permutations by swapping task. This implementation is naive and brute-force (slow) but exact.\n\n```\nsub insert ($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. @xs) }\nsub order ($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }\n\nmulti σ_permutations ([]) { [] => 1 }\n\nmulti σ_permutations ([$x, *@xs]) {\n σ_permutations(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(1,-1) xx *\n}\n\nsub m_arith ( @a, $op ) {\n note \"Not a square matrix\" and return\n if [||] map { @a.elems cmp @a[$_].elems }, ^@a;\n sum σ_permutations([^@a]).race.map: {\n my $permutation = .key;\n my $term = $op eq 'perm' ?? 1 !! .value;\n for $permutation.kv -> $i, $j { $term *= @a[$i][$j] };\n $term\n }\n}\n\n######### helper subs #########\nsub hilbert-matrix (\\h) {[(1..h).map(-> \\n {[(n..^n+h).map: {(1/$_).FatRat}]})]}\n\nsub rat-or-int ($num) {\n return $num unless $num ~~ Rat|FatRat;\n return $num.narrow if $num.narrow.WHAT ~~ 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\n########### Testing ###########\nmy @tests = (\n [\n [ 1, 2 ],\n [ 3, 4 ]\n ],\n [\n [ 1, 2, 3, 4 ],\n [ 4, 5, 6, 7 ],\n [ 7, 8, 9, 10 ],\n [ 10, 11, 12, 13 ]\n ],\n hilbert-matrix 7\n);\n\nfor @tests -> @matrix {\n say-it 'Matrix:', @matrix;\n say \"Determinant:\\t\", rat-or-int @matrix.&m_arith: <det>;\n say \"Permanent: \\t\", rat-or-int @matrix.&m_arith: <perm>;\n say '-' x 40;\n}\n\n```\n\n**Output**\n\n```\nMatrix:\n 1 2\n 3 4\nDeterminant:\t-2\nPermanent: \t10\n----------------------------------------\n\nMatrix:\n 1 2 3 4\n 4 5 6 7\n 7 8 9 10\n 10 11 12 13\nDeterminant:\t0\nPermanent: \t29556\n----------------------------------------\n\nMatrix:\n 1 1/2 1/3 1/4 1/5 1/6 1/7\n 1/2 1/3 1/4 1/5 1/6 1/7 1/8\n 1/3 1/4 1/5 1/6 1/7 1/8 1/9\n 1/4 1/5 1/6 1/7 1/8 1/9 1/10\n 1/5 1/6 1/7 1/8 1/9 1/10 1/11\n 1/6 1/7 1/8 1/9 1/10 1/11 1/12\n 1/7 1/8 1/9 1/10 1/11 1/12 1/13\nDeterminant:\t1/2067909047925770649600000\nPermanent: \t29453515169174062608487/2067909047925770649600000\n----------------------------------------\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven a character string (which may be empty, or have a length of zero characters):\n\n: : * create a function/procedure/routine to:\n\n : : * determine if all the characters in the string are the same\n * indicate if or which character is different from the previous character\n\n * display each string and its length (as the strings are being examined)\n * a zero─length (empty) string shall be considered as all the same character(s)\n * process the strings from left─to─right\n * if all the same character, display a message saying such\n * if not all the same character, then:\n\n : : * display a message saying such\n * display what character is different\n * only the 1st different character need be displayed\n * display where the different character is in the string\n * the above messages can be part of a single message\n * display the hexadecimal value of the different character\n\nUse (at least) these seven test values (strings):\n\n: : : * a string of length 0 (an empty string)\n * a string of length 3 which contains three blanks\n * a string of length 1 which contains: **2**\n * a string of length 3 which contains: **333**\n * a string of length 3 which contains: **.55**\n * a string of length 6 which contains: **tttTTT**\n * a string of length 9 with a blank in the middle: **4444 444k**\n\nShow all 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": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nThe last string demonstrates how Raku can recognize that glyphs made up of different combinations of combining characters can compare the same. It is built up from explicit codepoints to show that each of the glyphs is made up of different combinations.\n\n```\n -> $str {\n my $i = 0;\n print \"\\n{$str.raku} (length: {$str.chars}), has \";\n my %m;\n %m{$_}.push: ++$i for $str.comb;\n\n if %m > 1 {\n say \"different characters:\";\n say \"'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: \"0x%X\"})\" ~\n \" in positions: {.value.join: ', '}\" for %m.sort( *.value[0] );\n } else {\n say \"the same character in all positions.\"\n }\n} for\n '',\n ' ',\n '2',\n '333',\n '.55',\n 'tttTTT',\n '4444 444k',\n '🇬🇧🇬🇧🇬🇧🇬🇧',\n \"\\c[LATIN CAPITAL LETTER A]\\c[COMBINING DIAERESIS]\\c[COMBINING MACRON]\" ~\n \"\\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\\c[COMBINING MACRON]\" ~\n \"\\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]\",\n 'AАΑꓮ𐌀𐊠Ꭺ'\n\n```\n\nOutput:\n\n```\n\"\" (length: 0), has the same character in all positions.\n\n\" \" (length: 3), has the same character in all positions.\n\n\"2\" (length: 1), has the same character in all positions.\n\n\"333\" (length: 3), has the same character in all positions.\n\n\".55\" (length: 3), has different characters:\n'.' (FULL STOP; hex ordinal: 0x2E) in positions: 1\n'5' (DIGIT FIVE; hex ordinal: 0x35) in positions: 2, 3\n\n\"tttTTT\" (length: 6), has different characters:\n't' (LATIN SMALL LETTER T; hex ordinal: 0x74) in positions: 1, 2, 3\n'T' (LATIN CAPITAL LETTER T; hex ordinal: 0x54) in positions: 4, 5, 6\n\n\"4444 444k\" (length: 9), has different characters:\n'4' (DIGIT FOUR; hex ordinal: 0x34) in positions: 1, 2, 3, 4, 6, 7, 8\n' ' (SPACE; hex ordinal: 0x20) in positions: 5\n'k' (LATIN SMALL LETTER K; hex ordinal: 0x6B) in positions: 9\n\n\"🇬🇧🇬🇧🇬🇧🇬🇧\" (length: 4), has the same character in all positions.\n\n\"ǞǞǞ\" (length: 3), has the same character in all positions.\n\n\"AАΑꓮ𐌀𐊠Ꭺ\" (length: 7), has different characters:\n'A' (LATIN CAPITAL LETTER A; hex ordinal: 0x41) in positions: 1\n'А' (CYRILLIC CAPITAL LETTER A; hex ordinal: 0x410) in positions: 2\n'Α' (GREEK CAPITAL LETTER ALPHA; hex ordinal: 0x391) in positions: 3\n'ꓮ' (LISU LETTER A; hex ordinal: 0xA4EE) in positions: 4\n'𐌀' (OLD ITALIC LETTER A; hex ordinal: 0x10300) in positions: 5\n'𐊠' (CARIAN LETTER A; hex ordinal: 0x102A0) in positions: 6\n'Ꭺ' (CHEROKEE LETTER GO; hex ordinal: 0x13AA) in positions: 7\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven a character string (which may be empty, or have a length of zero characters):\n\n: : * create a function/procedure/routine to:\n\n : : * determine if all the characters in the string are unique\n * indicate if or which character is duplicated and where\n\n * display each string and its length (as the strings are being examined)\n * a zero─length (empty) string shall be considered as unique\n * process the strings from left─to─right\n * if unique, display a message saying such\n * if not unique, then:\n\n : : * display a message saying such\n * display what character is duplicated\n * only the 1st non─unique character need be displayed\n * display where \"both\" duplicated characters are in the string\n * the above messages can be part of a single message\n * display the hexadecimal value of the duplicated character\n\nUse (at least) these five test values (strings):\n\n: : : * a string of length 0 (an empty string)\n * a string of length 1 which is a single period (**.**)\n * a string of length 6 which contains: **abcABC**\n * a string of length 7 which contains a blank in the middle: **XYZ ZYX**\n * a string of length 36 which *doesn't* contain the letter \"oh\":\n\n : : : : : **1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ**\n\nShow all 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": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nRaku works with unicode natively and handles combining characters and multi-byte emoji correctly. In the last string, notice the the length is correctly shown as 11 characters and that the delta with a combining circumflex in position 6 is not the same as the deltas without in positions 5 & 9.\n\n```\n -> $str {\n my $i = 0;\n print \"\\n{$str.raku} (length: {$str.chars}), has \";\n my %m = $str.comb.Bag;\n if any(%m.values) > 1 {\n say \"duplicated characters:\";\n say \"'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: \"0x%X\"})\" ~\n \" in positions: {.value.join: ', '}\" for %m.grep( *.value > 1 ).sort( *.value[0] );\n } else {\n say \"no duplicated characters.\"\n }\n} for\n '',\n '.',\n 'abcABC',\n 'XYZ ZYX',\n '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ',\n '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X',\n '🦋🙂👨👩👧👦🙄ΔΔ̂ 🦋Δ👍👨👩👧👦'\n\n```\n\nOutput:\n\n```\n\"\" (length: 0), has no duplicated characters.\n\n\".\" (length: 1), has no duplicated characters.\n\n\"abcABC\" (length: 6), has no duplicated characters.\n\n\"XYZ ZYX\" (length: 7), has duplicated characters:\n'X' (LATIN CAPITAL LETTER X; hex ordinal: 0x58) in positions: 1, 7\n'Y' (LATIN CAPITAL LETTER Y; hex ordinal: 0x59) in positions: 2, 6\n'Z' (LATIN CAPITAL LETTER Z; hex ordinal: 0x5A) in positions: 3, 5\n\n\"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\" (length: 36), has duplicated characters:\n'0' (DIGIT ZERO; hex ordinal: 0x30) in positions: 10, 25\n\n\"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X\" (length: 39), has duplicated characters:\n'0' (DIGIT ZERO; hex ordinal: 0x30) in positions: 1, 11, 26, 38\n'X' (LATIN CAPITAL LETTER X; hex ordinal: 0x58) in positions: 35, 39\n\n\"🦋🙂👨👩👧👦🙄ΔΔ̂ 🦋Δ👍👨👩👧👦\" (length: 11), has duplicated characters:\n'🦋' (BUTTERFLY; hex ordinal: 0x1F98B) in positions: 1, 8\n'👨👩👧👦' (MAN ZERO WIDTH JOINER WOMAN ZERO WIDTH JOINER GIRL ZERO WIDTH JOINER BOY; hex ordinal: 0x1F468 0x200D 0x1F469 0x200D 0x1F467 0x200D 0x1F466) in positions: 3, 11\n'Δ' (GREEK CAPITAL LETTER DELTA; hex ordinal: 0x394) in positions: 5, 9\n\n```"
}
]
|
[
{
"role": "user",
"content": "Determine if a character string is *collapsible*.\n\nAnd if so, collapse the string (by removing *immediately repeated* characters).\n\nIf a character string has *immediately repeated* character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\nAn *immediately repeated* character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been *duplicated character*, but that\nmight have ruled out (to some readers) triplicated characters ··· or more.\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) **PL/I** BIF: **collapse**.}\n\nExamples\n\nIn the following character string:\n\n```\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n```\n\nOnly the 2nd **t**, **e**, and **l** are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\nSo, after *collapsing* the string, the result would be:\n\n```\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n```\n\nAnother example:\nIn the following character string:\n\n```\n headmistressship \n\n```\n\nThe \"collapsed\" string would be:\n\n```\n headmistreship \n\n```\n\nTask\n\nWrite a subroutine/function/procedure/routine··· to\nlocate *repeated* characters and *collapse* (delete) them from the character\nstring. The character string can be processed from either direction.\n\nShow all output here, on this page:\n\n: * the original string and its length\n * the resultant string and its length\n * the above strings should be \"bracketed\" with **<<<** and **>>>** (to delineate blanks)\n * «««Guillemets may be used instead for \"bracketing\" for the more artistic programmers, shown used here»»»\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n```\n string\n number\n ╔╗\n 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)\n 2 ║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║\n 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║\n 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║\n 5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks\n ╚════════════════════════════════════════════════════════════════════════╝\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 2019.07.1\n\nTechnically, the task is asking for a boolean. \"Determine if a string is collapsible\" is answerable with True/False, so return a boolean as well.\n\n```\nmap {\n my $squish = .comb.squish.join;\n printf \"\\nLength: %2d <<<%s>>>\\nCollapsible: %s\\nLength: %2d <<<%s>>>\\n\",\n .chars, $_, .chars != $squish.chars, $squish.chars, $squish\n}, lines\n \nq:to/STRINGS/;\n \n \"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln \n ..1111111111111111111111111111111111111111111111111111111111111117777888\n I never give 'em hell, I just tell the truth, and they think it's hell. \n --- Harry S Truman \n The American people have a right to know if their president is a crook. \n --- Richard Nixon \n AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ\n AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n STRINGS\n\n```\n\nOutput:\n\n```\nLength: 0 <<<>>>\nCollapsible: False\nLength: 0 <<<>>>\n\nLength: 72 <<<\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln >>>\nCollapsible: True\nLength: 70 <<<\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln >>>\n\nLength: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>\nCollapsible: True\nLength: 4 <<<.178>>>\n\nLength: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>\nCollapsible: True\nLength: 69 <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>\n\nLength: 72 <<< --- Harry S Truman >>>\nCollapsible: True\nLength: 17 <<< - Hary S Truman >>>\n\nLength: 72 <<<The American people have a right to know if their president is a crook. >>>\nCollapsible: True\nLength: 71 <<<The American people have a right to know if their president is a crok. >>>\n\nLength: 72 <<< --- Richard Nixon >>>\nCollapsible: True\nLength: 17 <<< - Richard Nixon >>>\n\nLength: 72 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>\nCollapsible: False\nLength: 72 <<<AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ>>>\n\nLength: 72 <<<AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA>>>\nCollapsible: True\nLength: 1 <<<A>>>\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.\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 2017.11\n\nRaku tries very hard to DWIM (do what I mean). As part of that, numeric strings are by default stored as allomorphic types which can be used as numbers or strings without any conversion. If we truly want to operate on strings, we have to explicitly coerce the allomorphs to strings. A subtlety that may not be immediately apparent, whitespace, empty strings and null strings may be treated as (False) boolean values in Raku, however booleans are allomorphic to numeric, so empty strings will coerce to a numeric value (0), and return as numeric unless specifically checked for. Interestingly, the actual strings 'True' and 'False' **don't** evaluate as numeric. (because there are no String | Boolean allomorphs.)\n\nNote: These routines are usable for most cases but won't detect unicode non-digit numeric forms; E.G. vulgar fractions, Roman numerals, circled numbers, etc. If it is necessary to detect those as numeric, a full fledged grammar may be necessary.\n\n```\nsub is-number-w-ws( Str $term --> Bool ) { # treat Falsey strings as numeric\n $term.Numeric !~~ Failure;\n}\n\nsub is-number-wo-ws( Str $term --> Bool ) { # treat Falsey strings as non-numeric\n ?($term ~~ / \\S /) && $term.Numeric !~~ Failure;\n}\n\nsay \" Coerce Don't coerce\";\nsay ' String whitespace whitespace';\nprintf \"%10s %8s %11s\\n\",\n\"<$_>\", .&is-number-w-ws, .&is-number-wo-ws for\n(|<1 1.2 1.2.3 -6 1/2 12e B17 1.3e+12 1.3e12 -2.6e-3 zero 0x 0xA10 0b1001 0o16 \n0o18 2+5i True False Inf NaN 0x10.50 0b102 0o_5_3 ௫௯>, ' 12 ', '1 1 1', '', ' ' ).map: *.Str;\n```\n\n```\n Coerce Don't coerce\n String whitespace whitespace\n <1> True True\n <1.2> True True\n <1.2.3> False False\n <-6> True True\n <1/2> True True\n <12e> False False\n <B17> False False\n <1.3e+12> True True\n <1.3e12> True True\n <-2.6e-3> True True\n <zero> False False\n <0x> False False\n <0xA10> True True\n <0b1001> True True\n <0o16> True True\n <0o18> False False\n <2+5i> True True\n <True> False False\n <False> False False\n <Inf> True True\n <NaN> True True\n <0x10.50> True True\n <0b102> False False\n <0o_5_3> True True\n <௫௯> True True\n < 12 > True True\n <1 1 1> False False\n <> True False\n < > True False\n```"
}
]
|
[
{
"role": "user",
"content": "Determine if a character string is *squeezable*.\n\nAnd if so, squeeze the string (by removing any number of\na *specified* *immediately repeated* character).\n\nThis task is very similar to the task **Determine if a character string is collapsible** except\nthat only a specified character is *squeezed* instead of any character that is *immediately repeated*.\n\nIf a character string has a specified *immediately repeated* character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\nA specified *immediately repeated* character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been *duplicated*\ncharacter*, but that might have ruled out (to some readers) triplicated characters ··· or more.*\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) **PL/I** BIF: **squeeze**.}\n\nExamples\n\nIn the following character string with a specified *immediately repeated* character of **e**:\n\n```\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n```\n\nOnly the 2nd **e** is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\nSo, after *squeezing* the string, the result would be:\n\n```\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n```\n\nAnother example:\nIn the following character string, using a specified immediately repeated character **s**:\n\n```\n headmistressship \n\n```\n\nThe \"squeezed\" string would be:\n\n```\n headmistreship \n\n```\n\nTask\n\nWrite a subroutine/function/procedure/routine··· to locate a *specified immediately repeated* character\nand *squeeze* (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\nShow all output here, on this page:\n\n: * the specified repeated character (to be searched for and possibly *squeezed*):\n * the original string and its length\n * the resultant string and its length\n * the above strings should be \"bracketed\" with **<<<** and **>>>** (to delineate blanks)\n * «««Guillemets may be used instead for \"bracketing\" for the more artistic programmers, shown used here»»»\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n```\n immediately\n string repeated\n number character\n ( ↓ a blank, a minus, a seven, a period)\n ╔╗\n 1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)\n 2 ║\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ║ '-'\n 3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'\n 4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'\n 5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks\n ╚════════════════════════════════════════════════════════════════════════╝ ↑\n │\n │\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n • a blank\n • a minus\n • a lowercase r\n\n```\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n```\nmap {\n my $squeeze = $^phrase;\n sink $^reg;\n $squeeze ~~ s:g/($reg)$0+/$0/;\n printf \"\\nOriginal length: %d <<<%s>>>\\nSqueezable on \\\"%s\\\": %s\\nSqueezed length: %d <<<%s>>>\\n\",\n $phrase.chars, $phrase, $reg.uniname, $phrase ne $squeeze, $squeeze.chars, $squeeze\n}, \n '', ' ', \n '\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ', '-',\n '..1111111111111111111111111111111111111111111111111111111111111117777888', '7',\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \", '.',\n ' --- Harry S Truman ', ' ',\n ' --- Harry S Truman ', '-',\n ' --- Harry S Truman ', 'r'\n\n```\n\nOutput:\n\n```\nOriginal length: 0 <<<>>>\nSqueezable on \"SPACE\": False\nSqueezed length: 0 <<<>>>\n\nOriginal length: 72 <<<\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln >>>\nSqueezable on \"HYPHEN-MINUS\": True\nSqueezed length: 70 <<<\"If I were two-faced, would I be wearing this one?\" - Abraham Lincoln >>>\n\nOriginal length: 72 <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>\nSqueezable on \"DIGIT SEVEN\": True\nSqueezed length: 69 <<<..1111111111111111111111111111111111111111111111111111111111111117888>>>\n\nOriginal length: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>\nSqueezable on \"FULL STOP\": False\nSqueezed length: 72 <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>\n\nOriginal length: 72 <<< --- Harry S Truman >>>\nSqueezable on \"SPACE\": True\nSqueezed length: 20 <<< --- Harry S Truman >>>\n\nOriginal length: 72 <<< --- Harry S Truman >>>\nSqueezable on \"HYPHEN-MINUS\": True\nSqueezed length: 70 <<< - Harry S Truman >>>\n\nOriginal length: 72 <<< --- Harry S Truman >>>\nSqueezable on \"LATIN SMALL LETTER R\": True\nSqueezed length: 71 <<< --- Hary S Truman >>>\n\n```"
}
]
|
[
{
"role": "user",
"content": "This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nAn old-school Unix solution, none the worse for the wear:\n\n```\nmy $name = $*PROGRAM-NAME;\nmy $pid = $*PID;\n\nmy $lockdir = \"/tmp\";\nmy $lockfile = \"$lockdir/$name.pid\";\nmy $lockpid = \"$lockfile$pid\";\nmy $havelock = False;\n\nEND {\n unlink $lockfile if $havelock;\n try unlink $lockpid;\n}\n\nmy $pidfile = open \"$lockpid\", :w orelse .die;\n$pidfile.say($pid);\n$pidfile.close;\n\nif try link($lockpid, $lockfile) {\n $havelock = True;\n}\nelse {\n shell \"kill -CONT `cat $lockfile` || rm $lockfile\";\n if try link($lockfile, $lockpid) {\n $havelock = True;\n }\n else {\n die \"You can't run right now!\";\n }\n}\nnote \"Got lock!\";\nunlink $lockpid;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\nTask\n\nDetermine which of these pairs of triangles overlap in 2D:\n\n: : : * (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n * (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n * (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n * (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n * (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n * (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n\n: : : * (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\nRelated tasks\n\n* Check if two polygons overlap\n* Check if a polygon overlaps with a rectangle"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nFirst, check if any vertex is inside each other triangle (that should cover most overlapping cases including enclosures). Then see if an edge of triangle A intersects any of two edges of B (for shapes like Star of David [1])\n\n```\n# Reference:\n# https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle\n# https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/\n\nsub if-overlap ($triangle-pair) {\n my (\\A,\\B) = $triangle-pair;\n my Bool $result = False;\n\n sub sign (\\T) {\n return (T[0;0] - T[2;0]) × (T[1;1] - T[2;1]) -\n (T[1;0] - T[2;0]) × (T[0;1] - T[2;1]);\n }\n\n sub point-in-triangle (\\pt, \\Y --> Bool) {\n my $d1 = sign (pt, Y[0], Y[1]);\n my $d2 = sign (pt, Y[1], Y[2]);\n my $d3 = sign (pt, Y[2], Y[0]);\n\n my $has_neg = [or] $d1 < 0, $d2 < 0, $d3 < 0;\n my $has_pos = [or] $d1 > 0, $d2 > 0, $d3 > 0;\n\n return not ($has_neg and $has_pos);\n }\n\n sub orientation(\\P, \\Q, \\R --> Int) {\n my \\val = (Q[1] - P[1]) × (R[0] - Q[0]) -\n (Q[0] - P[0]) × (R[1] - Q[1]);\n\n return 0 if val == 0; # colinear\n return val > 0 ?? 1 !! 2; # clock or counterclock wise\n }\n\n sub onSegment(\\P, \\Q, \\R --> Bool) {\n Q[0] ≤ max(P[0], R[0]) and Q[0] ≥ min(P[0], R[0]) and\n Q[1] ≤ max(P[1], R[1]) and Q[1] ≥ min(P[0], R[1])\n ?? True !! False\n }\n\n sub intersect(\\A,\\B,\\C,\\D --> Bool) {\n my \\o1 = orientation A, C, D;\n my \\o2 = orientation B, C, D;\n my \\o3 = orientation A, B, C;\n my \\o4 = orientation A, B, D;\n\n o1 != o2 and o3 != o4\n or o1 == 0 and onSegment A, C, D\n or o2 == 0 and onSegment B, C, D\n or o3 == 0 and onSegment A, B, C\n or o4 == 0 and onSegment A, B, D\n ?? True !! False\n }\n\n for ^3 {\n { $result = True; last } if\n point-in-triangle A.[$^i], B or\n point-in-triangle B.[$^i], A ;\n }\n\n unless $result {\n $result = True if\n intersect A.[0], A.[1], B.[0], B.[1] or\n intersect A.[0], A.[1], B.[0], B.[2]\n }\n\n say \"{A.gist} and {B.gist} do{' NOT' unless $result} overlap.\";\n}\n\nmy \\DATA = [\n [ [(0,0),(5,0),(0,5)] , [(0,0),(5,0),(0,6)] ],\n [ [(0,0),(0,5),(5,0)] , [(0,0),(0,5),(5,0)] ],\n [ [(0,0),(5,0),(0,5)] , [(-10,0),(-5,0),(-1,6)] ],\n [ [(0,0),(5,0),(2.5,5)] , [ (0,4),(2.5,-1),(5,4)] ],\n [ [(0,0),(1,1),(0,2)] , [(2,1),(3,0),(3,2)] ],\n [ [(0,0),(1,1),(0,2)] , [(2,1),(3,-2),(3,4)] ],\n [ [(0,0),(1,0),(0,1)] , [(1,0),(2,0),(1,1)] ]\n];\n\nif-overlap $_ for DATA ;\n\n```\n\nOutput:\n\n```\n[(0 0) (5 0) (0 5)] and [(0 0) (5 0) (0 6)] do overlap.\n[(0 0) (0 5) (5 0)] and [(0 0) (0 5) (5 0)] do overlap.\n[(0 0) (5 0) (0 5)] and [(-10 0) (-5 0) (-1 6)] do NOT overlap.\n[(0 0) (5 0) (2.5 5)] and [(0 4) (2.5 -1) (5 4)] do overlap.\n[(0 0) (1 1) (0 2)] and [(2 1) (3 0) (3 2)] do NOT overlap.\n[(0 0) (1 1) (0 2)] and [(2 1) (3 -2) (3 4)] do NOT overlap.\n[(0 0) (1 0) (0 1)] and [(1 0) (2 0) (1 1)] do overlap.\n```"
}
]
|
[
{
"role": "user",
"content": "Use these sentences:\n\"hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it”\n\nTask\n: Search for the last used punctuation in a sentence, and determine its type according to its punctuation.\n\nOutput one of these letters\n: \"E\" (Exclamation!), \"Q\" (Question?), \"S\" (Serious.), \"N\" (Neutral).\n\nExtra\n: Make your code able to determine multiple sentences.\n\nDon't leave any errors!\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": "```\nuse Lingua::EN::Sentence;\n\nmy $paragraph = q:to/PARAGRAPH/;\nhi there, how are you today? I'd like to present to you the washing machine\n9001. You have been nominated to win one of these! Just make sure you don't\nbreak it\n\n\nJust because there are punctuation characters like \"?\", \"!\" or especially \".\"\npresent, it doesn't necessarily mean you have reached the end of a sentence,\ndoes it Mr. Magoo? The syntax highlighting here for Raku isn't the best.\nPARAGRAPH\n\nsay join \"\\n\\n\", $paragraph.&sentences.map: {\n /(<:punct>)$/;\n $_ ~ ' | ' ~ do\n given $0 {\n when '!' { 'E' };\n when '?' { 'Q' };\n when '.' { 'S' };\n default { 'N' };\n }\n}\n\n```\n\nOutput:\n\n```\nhi there, how are you today? | Q\n\nI'd like to present to you the washing machine\n9001. | S\n\nYou have been nominated to win one of these! | E\n\nJust make sure you don't\nbreak it | N\n\nJust because there are punctuation characters like \"?\", \"!\" or especially \".\"\npresent, it doesn't necessarily mean you have reached the end of a sentence,\ndoes it Mr. Magoo? | Q\n\nThe syntax highlighting here for Raku isn't the best. | S\n```"
}
]
|
[
{
"role": "user",
"content": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\n```\nsub likelihoods ($roll) {\n my ($dice, $faces) = $roll.comb(/\\d+/);\n my @counts;\n @counts[$_]++ for [X+] |(1..$faces,) xx $dice;\n return [@counts[]:p], $faces ** $dice;\n}\n \nsub beating-probability ([$roll1, $roll2]) {\n my (@c1, $p1) := likelihoods $roll1;\n my (@c2, $p2) := likelihoods $roll2;\n my $p12 = $p1 * $p2;\n \n [+] gather for flat @c1 X @c2 -> $p, $q {\n\ttake $p.value * $q.value / $p12 if $p.key > $q.key;\n }\n}\n\n# We're using standard DnD notation for dice rolls here.\nsay .gist, \"\\t\", .raku given beating-probability < 9d4 6d6 >;\nsay .gist, \"\\t\", .raku given beating-probability < 5d10 6d7 >;\n\n```\n\nOutput:\n\n```\n0.573144077\t<48679795/84934656>\n0.64278862872\t<3781171969/5882450000>\n```\n\nNote that all calculations are in integer and rational arithmetic, so the results in fractional notation are exact."
}
]
|
[
{
"role": "user",
"content": "Task\n\nTask desciption is taken from Project Euler (https://projecteuler.net/problem=30)\n \nFind the sum of all the numbers that can be written as the sum of fifth powers of their digits.\n\nEven though 15 = 1, it is not expressed as a *sum* (a sum being the summation of a list of two or more numbers), and is therefore not included."
},
{
"role": "assistant",
"content": "```\nprint q:to/EXPANATION/;\nSum of all integers (except 1 for some mysterious reason ¯\\_(ツ)_/¯),\nfor which the individual digits to the nth power sum to itself.\nEXPANATION\n\nsub super($i) { $i.trans('0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹') }\n\nfor 3..8 -> $power {\n print \"\\nSum of powers of n{super $power}: \";\n my $threshold = 9**$power * $power;\n put .join(' + '), ' = ', .sum with cache\n (2..$threshold).hyper.map: {\n state %p = ^10 .map: { $_ => $_ ** $power };\n $_ if %p{.comb}.sum == $_\n }\n}\n\n```\n\nOutput:\n\n```\nSum of all integers (except 1 for some mysterious reason ¯\\_(ツ)_/¯),\nfor which the individual digits to the nth power sum to itself.\n\nSum of powers of n³: 153 + 370 + 371 + 407 = 1301\n\nSum of powers of n⁴: 1634 + 8208 + 9474 = 19316\n\nSum of powers of n⁵: 4150 + 4151 + 54748 + 92727 + 93084 + 194979 = 443839\n\nSum of powers of n⁶: 548834 = 548834\n\nSum of powers of n⁷: 1741725 + 4210818 + 9800817 + 9926315 + 14459929 = 40139604\n\nSum of powers of n⁸: 24678050 + 24678051 + 88593477 = 137949578\n```"
}
]
|
[
{
"role": "user",
"content": "The digital root, \n\nX\n{\\displaystyle {\\displaystyle X}}\n, of a number, \n\nn\n{\\displaystyle {\\displaystyle n}}\n, is calculated:\n\n: find \n\n X\n {\\displaystyle {\\displaystyle X}}\n as the sum of the digits of \n\n n\n {\\displaystyle {\\displaystyle n}}\n: find a new \n\n X\n {\\displaystyle {\\displaystyle X}}\n by summing the digits of \n\n X\n {\\displaystyle {\\displaystyle X}}\n , repeating until \n\n X\n {\\displaystyle {\\displaystyle X}}\n has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit.\n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n\n: 627615\n {\\displaystyle {\\displaystyle 627615}}\n has additive persistence \n\n 2\n {\\displaystyle {\\displaystyle 2}}\n and digital root of \n\n 9\n {\\displaystyle {\\displaystyle 9}}\n ;\n: 39390\n {\\displaystyle {\\displaystyle 39390}}\n has additive persistence \n\n 2\n {\\displaystyle {\\displaystyle 2}}\n and digital root of \n\n 6\n {\\displaystyle {\\displaystyle 6}}\n ;\n: 588225\n {\\displaystyle {\\displaystyle 588225}}\n has additive persistence \n\n 2\n {\\displaystyle {\\displaystyle 2}}\n and digital root of \n\n 3\n {\\displaystyle {\\displaystyle 3}}\n ;\n: 393900588225\n {\\displaystyle {\\displaystyle 393900588225}}\n has additive persistence \n\n 2\n {\\displaystyle {\\displaystyle 2}}\n and digital root of \n\n 9\n {\\displaystyle {\\displaystyle 9}}\n ;\n\nThe digital root may be calculated in bases other than 10.\n\nSee\n\n* Casting out nines for this wiki's use of this procedure.\n* Digital root/Multiplicative digital root\n* Sum digits of an integer\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* Iterated digits squaring"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub digital-root ($r, :$base = 10) {\n my $root = $r.base($base);\n my $persistence = 0;\n while $root.chars > 1 {\n $root = $root.comb.map({:36($_)}).sum.base($base);\n $persistence++;\n }\n $root, $persistence;\n}\n\nmy @testnums =\n 627615,\n 39390,\n 588225,\n 393900588225,\n 58142718981673030403681039458302204471300738980834668522257090844071443085937;\n\nfor 10, 8, 16, 36 -> $b {\n for @testnums -> $n {\n printf \":$b\\<%s>\\ndigital root %s, persistence %s\\n\\n\",\n $n.base($b), digital-root $n, :base($b);\n }\n}\n\n```\n\nOutput:\n\n```\n:10<627615>\ndigital root 9, persistence 2\n\n:10<39390>\ndigital root 6, persistence 2\n\n:10<588225>\ndigital root 3, persistence 2\n\n:10<393900588225>\ndigital root 9, persistence 2\n\n:10<58142718981673030403681039458302204471300738980834668522257090844071443085937>\ndigital root 4, persistence 3\n\n:8<2311637>\ndigital root 2, persistence 3\n\n:8<114736>\ndigital root 1, persistence 3\n\n:8<2174701>\ndigital root 1, persistence 3\n\n:8<5566623376301>\ndigital root 4, persistence 3\n\n:8<10021347156245115014463623107370014314341751427033746320331121536631531505161175135161>\ndigital root 3, persistence 3\n\n:16<9939F>\ndigital root F, persistence 2\n\n:16<99DE>\ndigital root F, persistence 2\n\n:16<8F9C1>\ndigital root F, persistence 2\n\n:16<5BB64DFCC1>\ndigital root F, persistence 2\n\n:16<808B9CDCA526832679323BE018CC70FA62E1BF3341B251AF666B345389F4BA71>\ndigital root 7, persistence 3\n\n:36<DG9R>\ndigital root U, persistence 2\n\n:36<UE6>\ndigital root F, persistence 2\n\n:36<CLVL>\ndigital root F, persistence 2\n\n:36<50YE8N29>\ndigital root P, persistence 2\n\n:36<37C71GOYNYJ25M3JTQQVR0FXUK0W9QM71C1LVNCBWNRVNOJYPD>\ndigital root H, persistence 3\n```\n\nOr if you are more inclined to the functional programming persuasion, you can use the … sequence operator to calculate the values without side effects:\n\n```\nsub digital-root ($r, :$base = 10) {\n my &sum = { .comb.map({:36($_)}).sum.base($base) }\n\n return .[*-1], .elems-1\n given $r.base($base), &sum … { .chars == 1 }\n}\n\n```\n\nOutput same as above."
}
]
|
[
{
"role": "user",
"content": "The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, \n\nn\n{\\displaystyle {\\displaystyle n}}\n, is calculated rather like the Digital root except digits are multiplied instead of being added:\n\n1. Set \n\n m\n {\\displaystyle {\\displaystyle m}}\n to \n\n n\n {\\displaystyle {\\displaystyle n}}\n and \n\n i\n {\\displaystyle {\\displaystyle i}}\n to \n\n 0\n {\\displaystyle {\\displaystyle 0}}\n .\n2. While \n\n m\n {\\displaystyle {\\displaystyle m}}\n has more than one digit:\n * Find a replacement \n\n m\n {\\displaystyle {\\displaystyle m}}\n as the multiplication of the digits of the current value of \n\n m\n {\\displaystyle {\\displaystyle m}}\n .\n * Increment \n\n i\n {\\displaystyle {\\displaystyle i}}\n .\n3. Return \n\n i\n {\\displaystyle {\\displaystyle i}}\n (= MP) and \n\n m\n {\\displaystyle {\\displaystyle m}}\n (= MDR)\n\nTask\n\n* Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998\n* Tabulate MDR versus the first five numbers having that MDR, something like:\n\n```\nMDR: [n0..n4]\n=== ========\n 0: [0, 10, 20, 25, 30]\n 1: [1, 11, 111, 1111, 11111]\n 2: [2, 12, 21, 26, 34]\n 3: [3, 13, 31, 113, 131]\n 4: [4, 14, 22, 27, 39]\n 5: [5, 15, 35, 51, 53]\n 6: [6, 16, 23, 28, 32]\n 7: [7, 17, 71, 117, 171]\n 8: [8, 18, 24, 29, 36]\n 9: [9, 19, 33, 91, 119]\n\n```\n\nShow all output on this page.\n\nSimilar\n\nThe Product of decimal digits of n page was redirected here, and had the following description\n\n```\nFind the product of the decimal digits of a positive integer n, where n <= 100\n\n```\n\nThe three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.\n\nReferences\n\n* Multiplicative Digital Root on Wolfram Mathworld.\n* Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.\n* What's special about 277777788888899? - Numberphile video"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub multiplicative-digital-root(Int $n) {\n return .elems - 1, .[.end]\n given cache($n, {[*] .comb} ... *.chars == 1)\n}\n\nfor 123321, 7739, 893, 899998 {\n say \"$_: \", .&multiplicative-digital-root;\n}\n\nfor ^10 -> $d {\n say \"$d : \", .[^5]\n given (1..*).grep: *.&multiplicative-digital-root[1] == $d;\n}\n\n```\n\nOutput:\n\n```\n123321: 3 8\n7739: 3 8\n893: 3 2\n899998: 2 0\n0 : 10 20 25 30 40\n1 : 1 11 111 1111 11111\n2 : 2 12 21 26 34\n3 : 3 13 31 113 131\n4 : 4 14 22 27 39\n5 : 5 15 35 51 53\n6 : 6 16 23 28 32\n7 : 7 17 71 117 171\n8 : 8 18 24 29 36\n9 : 9 19 33 91 119\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\n**Dijkstra's algorithm**, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.\n\nThis algorithm is often used in routing and as a subroutine in other graph algorithms.\n\nFor a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.\n\nFor instance\n\nIf the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.\n\nAs a result, the shortest path first is widely used in network routing protocols, most notably:\n\n: : * IS-IS (Intermediate System to Intermediate System) and\n * OSPF (Open Shortest Path First).\n\nImportant note\n\nThe inputs to Dijkstra's algorithm are a directed and weighted graph consisting of **2** or more nodes, generally represented by:\n\n: : * an adjacency matrix or list, and\n * a start node.\n\nA destination node is not specified.\n\nThe output is a set of edges depicting the shortest path to each destination node.\n\nAn example, starting with\n\n```\n a──►b, cost=7, lastNode=a \n a──►c, cost=9, lastNode=a \n a──►d, cost=NA, lastNode=a\n a──►e, cost=NA, lastNode=a \n a──►f, cost=14, lastNode=a\n\n The lowest cost is a──►b so a──►b is added to the output. \n\n There is a connection from b──►d so the input is updated to: \n a──►c, cost=9, lastNode=a \n a──►d, cost=22, lastNode=b \n a──►e, cost=NA, lastNode=a \n a──►f, cost=14, lastNode=a\n\n The lowest cost is a──►c so a──►c is added to the output. \n\n Paths to d and f are cheaper via c so the input is updated to:\n a──►d, cost=20, lastNode=c \n a──►e, cost=NA, lastNode=a \n a──►f, cost=11, lastNode=c\n\n The lowest cost is a──►f so c──►f is added to the output. \n\n The input is updated to:\n a──►d, cost=20, lastNode=c \n a──►e, cost=NA, lastNode=a\n\n The lowest cost is a──►d so c──►d is added to the output. \n\n There is a connection from d──►e so the input is updated to:\n a──►e, cost=26, lastNode=d\n\n Which just leaves adding d──►e to the output.\n\n The output should now be:\n [ d──►e\n c──►d\n c──►f\n a──►c\n a──►b ]\n\n```\n\nTask\n\n1. Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.\n2. Run your program with the following directed graph starting at node **a**.\n3. Write a program which interprets the output from the above and use it to output the shortest path from node **a** to nodes **e** and **f**.\n\n: : : : : : : : : Vertices\n\n | Number | Name |\n | --- | --- |\n | 1 | a |\n | 2 | b |\n | 3 | c |\n | 4 | d |\n | 5 | e |\n | 6 | f |\n\nEdges\n\n| Start | End | Cost |\n| --- | --- | --- |\n| a | b | 7 |\n| a | c | 9 |\n| a | f | 14 |\n| b | c | 10 |\n| b | d | 15 |\n| c | d | 11 |\n| c | f | 2 |\n| d | e | 6 |\n| e | f | 9 |\n\nYou can use numbers or names to identify vertices in your program.\n\nSee also\n\n* Dijkstra's Algorithm vs. A\\* Search vs. Concurrent Dijkstra's Algorithm (youtube)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nclass Graph {\n has (%.edges, %.nodes);\n\n method new(*@args){\n my (%edges, %nodes);\n for @args {\n %edges{.[0] ~ .[1]} = $_;\n %nodes{.[0]}.push( .[0] ~ .[1] );\n %nodes{.[1]}.push( .[0] ~ .[1] );\n }\n self.bless(edges => %edges, nodes => %nodes);\n }\n\n method neighbours ($source) {\n my (%neighbours, $edges);\n $edges = self.nodes{$source};\n for @$edges -> $x {\n for self.edges{$x}[0..1] -> $y {\n if $y ne $source {\n %neighbours{$y} = self.edges{$x}\n }\n }\n }\n return %neighbours\n }\n\n method dijkstra ($source, $dest) {\n my (%node_data, $v, $u);\n my @q = self.nodes.keys;\n\n for self.nodes.keys {\n %node_data{$_}{'dist'} = Inf;\n %node_data{$_}{'prev'} = '';\n }\n %node_data{$source}{'dist'} = 0;\n\n while @q {\n # %node_data.perl.say;\n my ($mindist, $idx) =\n @((map {[%node_data{@q[$_]}{'dist'},$_]},^@q).min(*[0]));\n $u = @q[$idx];\n\n if $mindist eq Inf {\n return ()\n }\n elsif $u eq $dest {\n my @s;\n while %node_data{$u}{'prev'} {\n @s.unshift($u);\n $u = %node_data{$u}{'prev'}\n }\n @s.unshift($source);\n return @s;\n }\n else {\n @q.splice($idx,1);\n }\n\n for self.neighbours($u).kv -> $v, $edge {\n my $alt = %node_data{$u}{'dist'} + $edge[2];\n if $alt < %node_data{$v}{'dist'} {\n %node_data{$v}{'dist'} = $alt;\n %node_data{$v}{'prev'} = $u\n }\n }\n }\n }\n}\n\nmy $a = Graph.new([\n [\"a\", \"b\", 7],\n [\"a\", \"c\", 9],\n [\"a\", \"f\", 14],\n [\"b\", \"c\", 10],\n [\"b\", \"d\", 15],\n [\"c\", \"d\", 11],\n [\"c\", \"f\", 2],\n [\"d\", \"e\", 6],\n [\"e\", \"f\", 9]\n]).dijkstra('a', 'e').say;\n\n```\n\nOutput:\n\n```\n[a c f e]\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSolve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.\n\nSolutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.\n\nExamples may be be split into \"setup\", \"problem statement\", and \"output\" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.\n\nExample output should be shown here, as well as any comments on the examples flexibility.\n\nThe problem\n\nBaker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.\n\n: : * Baker does not live on the top floor.\n * Cooper does not live on the bottom floor.\n * Fletcher does not live on either the top or the bottom floor.\n * Miller lives on a higher floor than does Cooper.\n * Smith does not live on a floor adjacent to Fletcher's.\n * Fletcher does not live on a floor adjacent to Cooper's.\n\n*Where does everyone live?*"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### By parsing the problem\n\n**Translation of**: Perl\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nsub parse_and_solve ($text) {\n my %ids;\n my $expr = (grammar {\n state $c = 0;\n rule TOP { <fact>+ { make join ' && ', $<fact>>>.made } }\n \n rule fact { <name> (not)? <position>\n { make sprintf $<position>.made.fmt($0 ?? \"!(%s)\" !! \"%s\"),\n $<name>.made }\n }\n rule position {\n || on bottom { make \"\\@f[%s] == 1\" }\n || on top { make \"\\@f[%s] == +\\@f\" }\n || lower than <name> { make \"\\@f[%s] < \\@f[{$<name>.made}]\" }\n || higher than <name> { make \"\\@f[%s] > \\@f[{$<name>.made}]\" }\n || directly below <name> { make \"\\@f[%s] == \\@f[{$<name>.made}] - 1\" }\n || directly above <name> { make \"\\@f[%s] == \\@f[{$<name>.made}] + 1\" }\n || adjacent to <name> { make \"\\@f[%s] == \\@f[{$<name>.made}] + (-1|1)\" }\n || on <ordinal> { make \"\\@f[%s] == {$<ordinal>.made}\" }\n || { note \"Failed to parse line \" ~ +$/.prematch.comb(/^^/); exit 1; }\n }\n \n token name { :i <[a..z]>+ { make %ids{~$/} //= $c++ } }\n token ordinal { [1st | 2nd | 3rd | \\d+th] { make +$/.match(/(\\d+)/)[0] } }\n }).parse($text).made;\n \n EVAL 'for [1..%ids.elems].permutations -> @f {\n say %ids.kv.map({ \"$^a=@f[$^b]\" }) if (' ~ $expr ~ ');\n }'\n}\n\nparse_and_solve Q:to/END/;\n Baker not on top\n Cooper not on bottom\n Fletcher not on top\n Fletcher not on bottom\n Miller higher than Cooper\n Smith not adjacent to Fletcher\n Fletcher not adjacent to Cooper\n END\n\n```\n\nSupports the same grammar for the problem statement, as the Perl solution.\n\nOutput:\n\n```\nBaker=3 Cooper=2 Fletcher=4 Miller=5 Smith=1\n\n```\n\n### Simple solution\n\n**Works with**: rakudo version 2015-11-15\n\n```\n# Contains only five floors. 5! = 120 permutations.\nfor (flat (1..5).permutations) -> $b, $c, $f, $m, $s {\n say \"Baker=$b Cooper=$c Fletcher=$f Miller=$m Smith=$s\"\n if $b != 5 # Baker !live on top floor.\n and $c != 1 # Cooper !live on bottom floor.\n and $f != 1|5 # Fletcher !live on top or the bottom floor.\n and $m > $c # Miller lives on a higher floor than Cooper.\n and $s != $f-1|$f+1 # Smith !live adjacent to Fletcher\n and $f != $c-1|$c+1 # Fletcher !live adjacent to Cooper\n ;\n}\n\n```\n\nAdding more people and floors requires changing the list that's being used for the permutations, adding a variable for the new person, a piece of output in the string and finally to adjust all mentions of the \"top\" floor.\nAdjusting to different rules requires changing the multi-line if statement in the loop.\n\nOutput:\n\n```\nBaker=3 Cooper=2 Fletcher=4 Miller=5 Smith=1\n```"
}
]
|
[
{
"role": "user",
"content": "The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.\n\nFive philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.\n\nIt can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.\n\nThere are many solutions of the problem, program at least one, and explain how the deadlock is prevented."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-09-09\n\nWe use locking mutexes for the forks, and a lollipop to keep the last person who finished eating from getting hungry until the next person finishes eating, which prevents a cycle of dependency from forming. The algorithm should scale to many philosophers, and no philosopher need be singled out to be left-handed, so it's fair in that sense.\n\n```\nclass Fork {\n has $!lock = Lock.new;\n method grab($who, $which) {\n\tsay \"$who grabbing $which fork\";\n\t$!lock.lock;\n }\n method drop($who, $which) {\n\tsay \"$who dropping $which fork\";\n\t$!lock.unlock;\n }\n}\n \nclass Lollipop {\n has $!channel = Channel.new;\n method mine($who) { $!channel.send($who) }\n method yours { $!channel.receive }\n}\n \nsub dally($sec) { sleep 0.01 + rand * $sec }\n \nsub MAIN(*@names) {\n @names ||= <Aristotle Kant Spinoza Marx Russell>;\n \n my @lfork = Fork.new xx @names;\n my @rfork = @lfork.rotate;\n \n my $lollipop = Lollipop.new;\n start { $lollipop.yours; }\n \n my @philosophers = do for flat @names Z @lfork Z @rfork -> $n, $l, $r {\n\tstart { \n\t sleep 1 + rand*4;\n\t loop {\n\t\t$l.grab($n,'left');\n\t\tdally 1; # give opportunity for deadlock\n\t\t$r.grab($n,'right');\n\t\tsay \"$n eating\";\n\t\tdally 10;\n\t\t$l.drop($n,'left');\n\t\t$r.drop($n,'right');\n \n\t\t$lollipop.mine($n);\n\t\tsleep 1; # lick at least once\n\t\tsay \"$n lost lollipop to $lollipop.yours(), now digesting\";\n \n\t\tdally 20;\n\t }\n\t}\n }\n sink await @philosophers;\n}\n\n```\n\nOutput:\n\n```\nAristotle grabbing left fork\nAristotle grabbing right fork\nAristotle eating\nMarx grabbing left fork\nMarx grabbing right fork\nMarx eating\nSpinoza grabbing left fork\nAristotle dropping left fork\nAristotle dropping right fork\nRussell grabbing left fork\nKant grabbing left fork\nKant grabbing right fork\nSpinoza grabbing right fork\nMarx dropping left fork\nMarx dropping right fork\nAristotle lost lollipop to Marx, now digesting\nSpinoza eating\nSpinoza dropping left fork\nSpinoza dropping right fork\nKant eating\nRussell grabbing right fork\nRussell eating\nMarx lost lollipop to Spinoza, now digesting\nKant dropping left fork\nKant dropping right fork\nSpinoza lost lollipop to Kant, now digesting\nRussell dropping left fork\nRussell dropping right fork\nKant lost lollipop to Russell, now digesting\nSpinoza grabbing left fork\nSpinoza grabbing right fork\nSpinoza eating\nAristotle grabbing left fork\nAristotle grabbing right fork\nAristotle eating\nAristotle dropping left fork\nAristotle dropping right fork\nRussell lost lollipop to Aristotle, now digesting\nSpinoza dropping left fork\nSpinoza dropping right fork\nAristotle lost lollipop to Spinoza, now digesting\nRussell grabbing left fork\nMarx grabbing left fork\nRussell grabbing right fork\nRussell eating\nMarx grabbing right fork\nKant grabbing left fork\nKant grabbing right fork\nKant eating\nRussell dropping left fork\nRussell dropping right fork\nSpinoza lost lollipop to Russell, now digesting\nMarx eating\nSpinoza grabbing left fork\nKant dropping left fork\nKant dropping right fork\nRussell lost lollipop to Kant, now digesting\nSpinoza grabbing right fork\n^C\n```"
}
]
|
[
{
"role": "user",
"content": "A **Disarium number** is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\nE.G.\n\n**135** is a **Disarium number**:\n\n11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of **Disarium numbers**.\n\nTask\n\n* Find and display the first 18 **Disarium numbers**.\n\nStretch\n\n* Find and display all 20 **Disarium numbers**.\n\nSee also\n\n* Geeks for Geeks - Disarium numbers * OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) * Related task: Narcissistic decimal number * Related task: Own digits power sum *Which seems to be the same task as Narcissistic decimal number...*"
},
{
"role": "assistant",
"content": "Not an efficient algorithm. First 18 in less than 1/4 second. 19th in around 45 seconds. Pretty much unusable for the 20th.\n\n```\nmy $disarium = (^∞).hyper.map: { $_ if $_ == sum .polymod(10 xx *).reverse Z** 1..* };\n\nput $disarium[^18];\nput $disarium[18];\n\n```\n\nOutput:\n\n```\n0 1 2 3 4 5 6 7 8 9 89 135 175 518 598 1306 1676 2427\n2646798\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nConvert a given date from the Gregorian calendar to the Discordian calendar."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-04\n\n```\nmy @seasons = << Chaos Discord Confusion Bureaucracy 'The Aftermath' >>;\nmy @days = << Sweetmorn Boomtime Pungenday Prickle-Prickle 'Setting Orange' >>;\nsub ordinal ( Int $n ) { $n ~ ( $n % 100 == 11|12|13\n ?? 'th' !! < th st nd rd th th th th th th >[$n % 10] ) }\n\nsub ddate ( Str $ymd ) {\n my $d = DateTime.new: \"{$ymd}T00:00:00Z\" or die;\n\n my $yold = 'in the YOLD ' ~ $d.year + 1166;\n\n my $day_of_year0 = $d.day-of-year - 1;\n\n if $d.is-leap-year {\n return \"St. Tib's Day, $yold\" if $d.month == 2 and $d.day == 29;\n $day_of_year0-- if $day_of_year0 >= 60; # Compensate for St. Tib's Day\n }\n\n my $weekday = @days[ $day_of_year0 mod 5 ];\n my $season = @seasons[ $day_of_year0 div 73 ];\n my $season_day = ordinal( $day_of_year0 mod 73 + 1 );\n\n return \"$weekday, the $season_day day of $season $yold\";\n}\n\nsay \"$_ is {.&ddate}\" for < 2010-07-22 2012-02-28 2012-02-29 2012-03-01 >;\n\n```\n\nOutput:\n\n```\n2010-07-22 is Pungenday, the 57th day of Confusion in the YOLD 3176\n2012-02-28 is Prickle-Prickle, the 59th day of Chaos in the YOLD 3178\n2012-02-29 is St. Tib's Day, in the YOLD 3178\n2012-03-01 is Setting Orange, the 60th day of Chaos in the YOLD 3178\n\n```"
}
]
|
[
{
"role": "user",
"content": "The discrete Fourier transform is a linear, invertible transformation which transforms an arbitrary sequence of complex numbers to another sequence of complex numbers of the same length. The Fast Fourier transform (FFT) is an efficient implementation of this mechanism, but one which only works for sequences which have a length which is a power of 2.\n\nThe discrete Fourier transform is a useful testing mechanism to verify the correctness of code bases which use or implement the FFT.\n\nFor this task:\n\n1. Implement the discrete fourier transform\n2. Implement the inverse fourier transform\n3. (optional) implement a cleaning mechanism to remove small errors introduced by floating point representation.\n4. Verify the correctness of your implementation using a small sequence of integers, such as 2 3 5 7 11\n\nThe fourier transform of a sequence \n\nx\n\nn\n{\\displaystyle {\\displaystyle x\\_{n}}}\n of length \n\nN\n{\\displaystyle {\\displaystyle N}}\n is given by:\n\nX\n\nn\n=\n\n∑\n\nk\n=\n0\n\nN\n−\n1\n\nx\n\nk\n⋅\n\ne\n\n−\ni\n\n2\nπ\nN\nk\nn\n{\\displaystyle {\\displaystyle X\\_{n}=\\sum \\_{k=0}^{N-1}x\\_{k}\\cdot e^{-i{\\frac {2\\pi }{N}}kn}}}\n\nThe inverse transform is given by:\n\nx\n\nn\n=\n\n\n1\nN\n\n∑\n\nk\n=\n0\n\nN\n−\n1\n\nX\n\nk\n⋅\n\ne\n\ni\n\n2\nπ\nN\nk\nn\n{\\displaystyle {\\displaystyle x\\_{n}={\\frac {1}{N}}\\sum \\_{k=0}^{N-1}X\\_{k}\\cdot e^{i{\\frac {2\\pi }{N}}kn}}}"
},
{
"role": "assistant",
"content": "* This task could be done with a loop of maps like \n @X[k] = sum @x.kv.map: -> \\n, \\v { v \\* exp( -i \\* tau / N \\* k \\* n ) } \n , but it is a better fit for Raku's concurrent Hyper-operators.\n* In the DFT formula, *N* becomes *+@x*, the element count. We would usually omit the plus sign and get the same result from numeric context, but that gets confusing to read when mixed with hyper-ops like »\\*« .\n* The exponents of DFT and IDFT only differ from each other in the sign of *i*, and the calculation of any given elements only differ by the *k* index of the element being output, so the inner loop is cleanly shareable between DFT and IDFT.\n* Euler's constant, imaginary unit, pi, and 2pi are built-in, with ASCII and Unicode spellings: e 𝑒 i pi π tau τ .\n* $one\\_thing «op« @many\\_things vectorizes the *op* operation: 5 «+« (1,2,3) is (6,7,8) .\n* @many\\_things »op« @many\\_more\\_things distributes the *op* operation pairwise: (5,6,7) »+« (1,2,3) is (6,8,10) .\n* (list)».method applies the method to each element of the list.\n* @array.keys, when @array has e.g. 4 elements, is 0,1,2,3 .\n* $n.round($r) returns *$n* rounded to the nearest *$r*. (13/16).round(1/4) is 3/4 .\n* .narrow changes a Numeric's type to a \"narrower\" type, when no precision would be lost. \n 8/2 is 4, but is type Rat (rational). (8/2).narrow is also 4, but type Int.\n\n```\nsub ft_inner ( @x, $k, $pos_neg_i where * == i|-i ) {\n my @exp := ( $pos_neg_i * tau / +@x * $k ) «*« @x.keys;\n return sum @x »*« 𝑒 «**« @exp;\n}\nsub dft ( @x ) { return @x.keys.map: { ft_inner( @x, $_, -i ) } }\nsub idft ( @x ) { return @x.keys.map: { ft_inner( @x, $_, i ) / +@x } }\nsub clean ( @x ) { @x».round(1e-12)».narrow }\n\nmy @tests = ( 1, 2-i, -i, -1+2i ),\n ( 2, 3, 5, 7, 11 ),\n;\nfor @tests -> @x {\n my @x_dft = dft(@x);\n my @x_idft = idft(@x_dft);\n\n say .key.fmt('%6s:'), .value.&clean.fmt('%5s', ', ') for :@x, :@x_dft, :@x_idft;\n say '';\n warn \"Round-trip failed\" unless ( clean(@x) Z== clean(@x_idft) ).all;\n}\n\n```\n\nOutput:\n\n```\n x: 1, 2-1i, 0-1i, -1+2i\n x_dft: 2, -2-2i, 0-2i, 4+4i\nx_idft: 1, 2-1i, 0-1i, -1+2i\n\n x: 2, 3, 5, 7, 11\n x_dft: 28, -3.38196601125+8.784022634946i, -5.61803398875+2.800168985749i, -5.61803398875-2.800168985749i, -3.38196601125-8.784022634946i\nx_idft: 2, 3, 5, 7, 11\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDisplay a finite linear combination in an infinite vector basis \n\n(\n\ne\n\n1\n,\n\ne\n\n2\n,\n…\n)\n{\\displaystyle {\\displaystyle (e\\_{1},e\\_{2},\\ldots )}}\n.\n\nWrite a function that, when given a finite list of scalars \n\n(\n\nα\n\n1\n,\n\nα\n\n2\n,\n…\n)\n{\\displaystyle {\\displaystyle (\\alpha ^{1},\\alpha ^{2},\\ldots )}}\n, \ncreates a string representing the linear combination \n\n∑\n\ni\n\nα\n\ni\n\ne\n\ni\n{\\displaystyle {\\displaystyle \\sum \\_{i}\\alpha ^{i}e\\_{i}}}\n in an explicit format often used in mathematics, that is:\n\n: α\n\n\n i\n\n 1\n\n e\n\n\n i\n\n 1\n ±\n\n |\n\n α\n\n\n i\n\n 2\n\n |\n\n e\n\n\n i\n\n 2\n ±\n\n |\n\n α\n\n\n i\n\n 3\n\n |\n\n e\n\n\n i\n\n 3\n ±\n …\n {\\displaystyle {\\displaystyle \\alpha ^{i\\_{1}}e\\_{i\\_{1}}\\pm |\\alpha ^{i\\_{2}}|e\\_{i\\_{2}}\\pm |\\alpha ^{i\\_{3}}|e\\_{i\\_{3}}\\pm \\ldots }}\n\nwhere \n\nα\n\n\ni\n\nk\n≠\n0\n{\\displaystyle {\\displaystyle \\alpha ^{i\\_{k}}\\neq 0}}\n\nThe output must comply to the following rules:\n\n* don't show null terms, unless the whole combination is null.\n\n: : : : : : : **e(1)** is fine, **e(1) + 0\\*e(3)** or **e(1) + 0** is wrong.\n\n* don't show scalars when they are equal to one or minus one.\n\n: : : : : : : **e(3)** is fine, **1\\*e(3)** is wrong.\n\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.\n\n: : : : : : : **e(4) - e(5)** is fine, **e(4) + -e(5)** is wrong.\n\nShow here output for the following lists of scalars:\n\n```\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub linear-combination(@coeff) {\n (@coeff Z=> map { \"e($_)\" }, 1 .. *)\n .grep(+*.key)\n .map({ .key ~ '*' ~ .value })\n .join(' + ')\n .subst('+ -', '- ', :g)\n .subst(/<|w>1\\*/, '', :g)\n || '0'\n}\n \nsay linear-combination($_) for \n[1, 2, 3],\n[0, 1, 2, 3],\n[1, 0, 3, 4],\n[1, 2, 0],\n[0, 0, 0],\n[0],\n[1, 1, 1],\n[-1, -1, -1],\n[-1, -2, 0, -3],\n[-1 ]\n;\n\n```\n\nOutput:\n\n```\ne(1) + 2*e(2) + 3*e(3)\ne(2) + 2*e(3) + 3*e(4)\ne(1) + 3*e(3) + 4*e(4)\ne(1) + 2*e(2)\n0\n0\ne(1) + e(2) + e(3)\n-e(1) - e(2) - e(3)\n-e(1) - 2*e(2) - 3*e(4)\n-e(1)\n```"
}
]
|
[
{
"role": "user",
"content": "| | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- |\n| Display an outline as a nested table. | | | | | | |\n| Parse the outline to a tree, | | | count the leaves descending from each node, | | and write out a table with 'colspan' values | |\n| measuring the indent of each line, | translating the indentation to a nested structure, | and padding the tree to even depth. | defining the width of a leaf as 1, | and the width of a parent node as a sum. | either as a wiki table, | or as HTML. |\n| | | | | (The sum of the widths of its children) | | |\n\nThe graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.\n\nTask\n\nGiven a outline with at least 3 levels of indentation, for example:\n\n```\nDisplay an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n```\n\nwrite a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.\n\nThe WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:\n\n```\n{| class=\"wikitable\" style=\"text-align: center;\"\n|-\n| style=\"background: #ffffe6; \" colspan=7 | Display an outline as a nested table.\n|-\n| style=\"background: #ffebd2; \" colspan=3 | Parse the outline to a tree,\n| style=\"background: #f0fff0; \" colspan=2 | count the leaves descending from each node,\n| style=\"background: #e6ffff; \" colspan=2 | and write out a table with 'colspan' values\n|-\n| style=\"background: #ffebd2; \" | measuring the indent of each line,\n| style=\"background: #ffebd2; \" | translating the indentation to a nested structure,\n| style=\"background: #ffebd2; \" | and padding the tree to even depth.\n| style=\"background: #f0fff0; \" | defining the width of a leaf as 1,\n| style=\"background: #f0fff0; \" | and the width of a parent node as a sum.\n| style=\"background: #e6ffff; \" | either as a wiki table,\n| style=\"background: #e6ffff; \" | or as HTML.\n|-\n| | \n| | \n| | \n| | \n| style=\"background: #f0fff0; \" | (The sum of the widths of its children)\n| | \n| | \n|}\n```\n\nExtra credit\n\nUse background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.\n\nOutput\n\nDisplay your nested table on this page."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nUse a slightly more complicated outline than the task example to test some edge conditions. Limited to 10 direct subnodes on any one node as is. Easily adapted for larger if necessary.\n\nStrictly speaking, this is not a nested table. It is just a single level table that has some column spans > 1. For an example of using actual nested tables, see the task entry: List\\_authors\\_of\\_task\\_descriptions#Raku, (and full output).\n\n```\nmy $outline = q:to/END/;\n Display an outline as a nested table.\n Parse the outline to a tree,\n measuring the indent of each line,\n translating the indentation to a nested structure,\n and padding the tree to even depth.\n count the leaves descending from each node,\n defining the width of a leaf as 1,\n and the width of a parent node as a sum.\n (The sum of the widths of its children)\n Propagating the sums upward as necessary.\n and write out a table with 'colspan' values\n either as a wiki table,\n or as HTML.\n Optionally add color to the nodes.\n END\n\n# Import outline paragraph into native data structure\nsub import (Str $trees, $level = ' ') {\n my $forest;\n my $last = -Inf;\n\n for $trees.lines -> $branch {\n $branch ~~ / ($($level))* /;\n my $this = +$0;\n $forest ~= do {\n given $this cmp $last {\n when More { \"\\['{esc $branch.trim}', \" }\n when Same { \"'{esc $branch.trim}', \" }\n when Less { \"{']' x $last - $this}, '{esc $branch.trim}', \" }\n }\n }\n $last = $this;\n }\n\n sub esc { $^s.subst( /(<['\\\\]>)/, -> $/ { \"\\\\$0\" }, :g) }\n\n $forest ~= ']' x 1 + $last;\n use MONKEY-SEE-NO-EVAL;\n $forest.EVAL;\n}\n\nmy @AoA = import $outline, ' ';\nmy @layout;\n\n# Collect information about node depth, position and children\n{\n my @width = 0;\n my $depth = -1;\n @AoA.&insert;\n\n multi insert ($item) {\n @width[*-1]++;\n @layout.push: { :depth($depth.clone), :id(@width[*-1].clone), :text($item) };\n }\n\n multi insert (@array) {\n @width.push: @width[*-1] * 10;\n ++$depth;\n @array.map: &insert;\n --$depth;\n @width.pop;\n }\n}\n\nmy $max-depth = @layout.max( *.<depth> )<depth>;\n\n# Pad ragged nodes\nfor (^$max-depth) -> $d {\n my @nodes = @layout.grep( *.<depth> == $d );\n for @nodes.sort( +*.<id> ) -> $n {\n unless @layout.first( *.<id> == $n<id> ~ 1 ) {\n @layout.push: { :depth($n<depth> + 1), :id($n<id> *10 + 1), :text('') };\n }\n }\n}\n\n# Calculate spans (child nodes)\nfor (0..$max-depth).reverse -> $d {\n my @nodes = @layout.grep( *.<depth> == $d );\n for @nodes.sort( +*.<id> ) -> $n {\n my @span = @layout.grep: {.<depth> == $d + 1 && .<id>.starts-with: $n<id> };\n $n<span> = ( sum @span.map( { .<span> // 0} )) || +@span || 1;\n }\n}\n\n# Programatically assign colors\nfor (0..$max-depth) -> $d {\n my @nodes = @layout.grep( *.<depth> == $d );\n my $incr = 1 / (1 + @nodes);\n for @nodes.sort( +*.<id> ) -> $n {\n my $color = $d > 1 ??\n @layout.first( *.<id> eq $n<id>.chop )<color> !!\n \"style=\\\"background: #\" ~ hsv2rgb( ++$ * $incr, .1, 1) ~ '\" ';\n $n<color> = $n<text> ?? $color !! '';\n }\n}\n\n# Generate wikitable\nsay '{| class=\"wikitable\" style=\"text-align: center;\"' ~ \"\\n\" ~\n(join \"\\n|-\\n\", (0..$max-depth).map: -> $d {\n my @nodes = @layout.grep( *.<depth> == $d );\n (join \"\\n\", @nodes.sort( +*.<id> ).map( -> $node {\n '| ' ~\n ($node<color> // '' ) ~\n ($node<span> > 1 ?? \"colspan=$node<span>\" !! '' ) ~\n ' | ' ~ $node<text> }\n ))\n}) ~ \"\\n|}\";\n\nsay \"\\n\\nSometimes it makes more sense to display an outline as...\nwell... as an outline, rather than as a table.\" ~ Q|¯\\_(ツ)_/¯| ~ \"\\n\";\n\n{ ## Outline - Ordered List #######\n my @type = <upper-roman upper-latin decimal lower-latin lower-roman>;\n my $depth = 0;\n\n multi ol ($item) { \"\\<li>$item\\n\" }\n\n multi ol (@array) {\n my $li = $depth ?? \"</li>\" !! '';\n $depth++;\n my $list = \"<ol style=\\\"list-style: {@type[$depth - 1]};\\\">\\n\" ~\n ( @array.map( &ol ).join ) ~ \"</ol>$li\\n\";\n $depth--;\n $list\n }\n\n say \"<div style=\\\"background: #fee;\\\">\\n\" ~ @AoA.&ol ~ \"</div>\";\n}\n\nsub hsv2rgb ( $h, $s, $v ){\n my $c = $v * $s;\n my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );\n my $m = $v - $c;\n my ($r, $g, $b) = do given $h {\n when 0..^(1/6) { $c, $x, 0 }\n when 1/6..^(1/3) { $x, $c, 0 }\n when 1/3..^(1/2) { 0, $c, $x }\n when 1/2..^(2/3) { 0, $x, $c }\n when 2/3..^(5/6) { $x, 0, $c }\n when 5/6..1 { $c, 0, $x }\n }\n ( $r, $g, $b ).map( ((*+$m) * 255).Int)».base(16).join\n}\n\n```\n\nOutput:\n\n| | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| Display an outline as a nested table. | | | | | | | | |\n| Parse the outline to a tree, | | | count the leaves descending from each node, | | | and write out a table with 'colspan' values | | Optionally add color to the nodes. |\n| measuring the indent of each line, | translating the indentation to a nested structure, | and padding the tree to even depth. | defining the width of a leaf as 1, | and the width of a parent node as a sum. | | either as a wiki table, | or as HTML. | |\n| | | | | (The sum of the widths of its children) | Propagating the sums upward as necessary. | | | |\n\nSometimes it makes more sense to display an outline as...\nwell... as an outline, rather than as a table.¯\\\\_(ツ)\\_/¯\n\n1. Display an outline as a nested table.\n 1. Parse the outline to a tree,\n 1. measuring the indent of each line,\n 2. translating the indentation to a nested structure,\n 3. and padding the tree to even depth.\n 2. count the leaves descending from each node,\n 1. defining the width of a leaf as 1,\n 2. and the width of a parent node as a sum.\n 1. (The sum of the widths of its children)\n 2. Propagating the sums upward as necessary.\n 3. and write out a table with 'colspan' values\n 1. either as a wiki table,\n 2. or as HTML.\n 4. Optionally add color to the nodes."
}
]
|
[
{
"role": "user",
"content": "It is very important in aviation to have knowledge of the nearby airports at any time in flight.\n\nTask\n\nDetermine the distance and bearing from an Airplane to the 20 nearest Airports whenever requested.\nUse the non-commercial data from openflights.org airports.dat as reference.\n\nA request comes from an airplane at position ( latitude, longitude ): ( **51.514669, 2.198581** ).\n\nYour report should contain the following information from table airports.dat (column shown in brackets):\n\nName(2), Country(4), ICAO(6), Distance and Bearing calculated from Latitude(7) and Longitude(8).\n\nDistance is measured in nautical miles (NM). Resolution is 0.1 NM.\n\nBearing is measured in degrees (°). 0° = 360° = north then clockwise 90° = east, 180° = south, 270° = west. Resolution is 1°.\n\nSee\n: * openflights.org/data: Airport, airline and route data\n * Movable Type Scripts: Calculate distance, bearing and more between Latitude/Longitude points"
},
{
"role": "assistant",
"content": "```\nuse Text::CSV;\n\nconstant $EARTH_RADIUS_IN_NAUTICAL_MILES = 6372.8 / 1.852;\n\nsub degrees ( Real $rad ) { $rad / tau * 360 }\nsub radians ( Real $deg ) { $deg * tau / 360 }\nsub haversine ( Real $x ) { ($x / 2).sin.² }\nsub arc_haver ( Real $x ) { $x.sqrt.asin * 2 }\n\nsub great_circle_distance ( \\φ1, \\λ1, \\φ2, \\λ2 ) {\n # https://en.wikipedia.org/wiki/Haversine_formula\n # latitude (represented by φ) and longitude (represented by λ)\n # hav(θ) = hav(φ₂ − φ₁) + cos(φ₁) cos(φ₂) hav(λ₂ − λ₁)\n arc_haver(\n haversine(φ2 - φ1)\n + haversine(λ2 - λ1) * cos(φ1) * cos(φ2)\n );\n}\n\nsub great_circle_bearing ( \\φ1, \\λ1, \\φ2, \\λ2 ) {\n atan2( φ2.cos * (λ2 - λ1).sin,\n φ1.cos * φ2.sin - φ1.sin * φ2.cos * (λ2 - λ1).cos,\n );\n}\n\nsub distance_and_bearing ( $lat1, $lon1, $lat2, $lon2 ) {\n my @ll = map &radians, $lat1, $lon1, $lat2, $lon2;\n\n my $dist = great_circle_distance(|@ll);\n my $theta = great_circle_bearing( |@ll);\n\n return $dist * $EARTH_RADIUS_IN_NAUTICAL_MILES,\n degrees( $theta + (tau if $theta < 0) )\n}\n\nsub find_nearest_airports ( $latitude, $longitude, $csv_path ) {\n my &d_and_b_from_here = &distance_and_bearing.assuming($latitude, $longitude);\n\n my @airports = csv(\n in => $csv_path,\n headers => [<ID Name City Country IATA ICAO Latitude Longitude>],\n );\n\n for @airports -> %row {\n %row<Distance Bearing> = d_and_b_from_here( +%row<Latitude>, +%row<Longitude> );\n }\n\n return @airports.sort(*.<Distance>);\n}\n\nsub MAIN ( $lat = 51.514669, $long = 2.198581, $wanted = 20, $csv = 'airports.dat' ) {\n printf \"%7s\\t%7s\\t%-7s\\t%-15s\\t%s\\n\", <Dist Bear ICAO Country Name>;\n\n for find_nearest_airports($lat, $long, $csv).head($wanted) {\n printf \"%7.1f\\t %03d\\t%-7s\\t%-15s\\t%s\\n\",\n .<Distance Bearing ICAO Country Name>;\n }\n}\n\n```\n\nOutput:\n\n```\n Dist\t Bear\tICAO \tCountry \tName\n 30.7\t 146\tEBFN \tBelgium \tKoksijde Air Base\n 31.3\t 127\tEBOS \tBelgium \tOstend-Bruges International Airport\n 33.6\t 252\tEGMH \tUnited Kingdom \tKent International Airport\n 34.4\t 195\tLFAC \tFrance \tCalais-Dunkerque Airport\n 42.6\t 105\tEBKW \tBelgium \tWestkapelle heliport\n 51.6\t 240\tEGMK \tUnited Kingdom \tLympne Airport\n 52.8\t 114\tEBUL \tBelgium \tUrsel Air Base\n 56.2\t 274\tEGMC \tUnited Kingdom \tSouthend Airport\n 56.4\t 162\tLFQT \tFrance \tMerville-Calonne Airport\n 56.5\t 137\tEBKT \tBelgium \tWevelgem Airport\n 57.3\t 089\tEHMZ \tNetherlands \tMidden-Zeeland Airport\n 58.0\t 235\tEGMD \tUnited Kingdom \tLydd Airport\n 59.0\t 309\tEGUW \tUnited Kingdom \tRAF Wattisham\n 59.3\t 339\tEGSM \tUnited Kingdom \tBeccles Airport\n 59.7\t 146\tLFQO \tFrance \tLille/Marcq-en-Baroeul Airport\n 62.2\t 250\tEGKH \tUnited Kingdom \tLashenden (Headcorn) Airfield\n 63.7\t 200\tLFAT \tFrance \tLe Touquet-Côte d'Opale Airport\n 64.2\t 261\tEGTO \tUnited Kingdom \tRochester Airport\n 66.3\t 149\tLFQQ \tFrance \tLille-Lesquin Airport\n 68.4\t 271\tEGMT \tUnited Kingdom \tThurrock Airfield\n```"
}
]
|
[
{
"role": "user",
"content": "Find all distinct palindromes contained as substrings in decimal representation of n. Note that for the\npurpose of the initial function, a single digit will be considered a palindrome.\n\nTask\n\n1. Find all the palindromes including single digits in the integers from 100 to 125, inclusive.\n2. Determine which if any of the following decimal integers contain palindromes of 2 digits or more:\n\n```\n 9, 169, 12769, 1238769, 123498769, 12346098769, 1234572098769,\n 123456832098769, 12345679432098769, 1234567905432098769, 123456790165432098769,\n 83071934127905179083, 1320267947849490361205695\n\n```\n\nAlso see\n: * OEIS entry: A262188 (Task 1).\n * OEIS entry: A151997 (Task 2).\n\nRelated tasks\n\nPalindrome\\_detection \nLongest\\_palindromic\\_substrings \nN\\_1's\\_followed\\_by\\_a\\_3"
},
{
"role": "assistant",
"content": "A minor modification of the Longest palindromic substrings task. As such, works for any string, not just integers.\n\n```\nuse Sort::Naturally;\n\nsub getpal ($str) {\n my @chars = $str.comb;\n my @pal = flat @chars,\n (1 ..^ @chars).map: -> \\idx {\n my @s;\n for 1, 2 {\n my int ($rev, $fwd) = $_, 1;\n loop {\n quietly last if ($rev > idx) || (@chars[idx - $rev] ne @chars[idx + $fwd]);\n $rev = $rev + 1;\n $fwd = $fwd + 1;\n }\n @s.push: @chars[idx - $rev ^..^ idx + $fwd].join if $rev + $fwd > 2;\n last if @chars[idx - 1] ne @chars[idx];\n }\n next unless +@s;\n @s\n }\n @pal.unique.sort({.chars, .&naturally});\n}\n\nsay 'All palindromic substrings including (bizarrely enough) single characters:';\nput \"$_ => \", getpal $_ for 100..125;\nput \"\\nDo these strings contain a minimum two character palindrome?\";\nprintf \"%25s => %s\\n\", $_, getpal($_).tail.chars > 1 for flat\n 9, 169, 12769, 1238769, 123498769, 12346098769, 1234572098769,\n 123456832098769, 12345679432098769, 1234567905432098769,\n 123456790165432098769, 83071934127905179083, 1320267947849490361205695,\n <Do these strings contain a minimum two character palindrome?>\n\n```\n\nOutput:\n\n```\nAll palindromic substrings including (bizarrely enough) single characters:\n100 => 0 1 00\n101 => 0 1 101\n102 => 0 1 2\n103 => 0 1 3\n104 => 0 1 4\n105 => 0 1 5\n106 => 0 1 6\n107 => 0 1 7\n108 => 0 1 8\n109 => 0 1 9\n110 => 0 1 11\n111 => 1 11 111\n112 => 1 2 11\n113 => 1 3 11\n114 => 1 4 11\n115 => 1 5 11\n116 => 1 6 11\n117 => 1 7 11\n118 => 1 8 11\n119 => 1 9 11\n120 => 0 1 2\n121 => 1 2 121\n122 => 1 2 22\n123 => 1 2 3\n124 => 1 2 4\n125 => 1 2 5\n\nDo these strings contain a minimum two character palindrome?\n 9 => False\n 169 => False\n 12769 => False\n 1238769 => False\n 123498769 => False\n 12346098769 => False\n 1234572098769 => False\n 123456832098769 => False\n 12345679432098769 => False\n 1234567905432098769 => False\n 123456790165432098769 => False\n 83071934127905179083 => False\n1320267947849490361205695 => True\n Do => False\n these => True\n strings => False\n contain => False\n a => False\n minimum => True\n two => False\n character => True\n palindrome? => False\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCompute all combinations of \n\na\n\nb\n{\\displaystyle {\\displaystyle a^{b}}}\n where a and b are integers between 2 and 5 inclusive.\n \n \nPlace them in numerical order, with any repeats removed.\n \n \nYou should get the following sequence of 15 distinct terms:\n \n4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125"
},
{
"role": "assistant",
"content": "```\nput squish sort [X**] (2..5) xx 2;\n\n```\n\nOutput:\n\n```\n4 8 9 16 25 27 32 64 81 125 243 256 625 1024 3125\n```"
}
]
|
[
{
"role": "user",
"content": "Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.\n\nThe protocol used may be language-specific or not, and should be **suitable for general distributed programming**; that is, the *protocol* should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.\n\nThis task is intended to demonstrate high-level communication facilities beyond just creating sockets."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nServer listens for JSON encoded messages. It processes requests for set|get|dump. 'set' stores a message, 'get' returns message, 'dump' returns all stored messages. Optional parameters for ip address and port.\n\nServer.raku:\n\n```\n./server.raku --usage\nUsage:\n server.p6 [--server=<Any>] [--port=<Any>]\n```\n\n```\n#!/usr/bin/env raku\nuse JSON::Fast ;\nsub MAIN( :$server='0.0.0.0' , :$port=3333 ) {\n my %db ;\n react {\n whenever IO::Socket::Async.listen( $server , $port ) -> $conn {\n whenever $conn.Supply.lines -> $line {\n my %response = 'status' => '' ;\n my $msg = from-json $line ;\n say $msg.raku;\n given $msg{\"function\"} {\n when 'set' {\n %db{ $msg<topic> } = $msg<message> ;\n %response<status> = 'ok' ;\n }\n when 'get' {\n %response<topic> = $msg<topic> ;\n %response<message> = %db{ $msg<topic> } ;\n %response<status> = 'ok' ;\n }\n when 'dump' {\n %response = %db ;\n }\n when 'delete' {\n %db{ $msg<topic> }:delete;\n %response<status> = 'ok' ;\n }\n }\n $conn.print( to-json(%response, :!pretty) ~ \"\\n\" ) ;\n LAST { $conn.close ; }\n QUIT { default { $conn.close ; say \"oh no, $_\";}}\n CATCH { default { say .^name, ': ', .Str , \" handled in $?LINE\";}}\n }\n }\n }\n}\n\n```\n\nclient.raku:\n\n```\nUsage:\n client.raku [--server=<Any>] [--port=<Any>] [--json=<Any>] set <topic> [<message>]\n client.raku [--server=<Any>] [--port=<Any>] get <topic>\n client.raku [--server=<Any>] [--port=<Any>] dump\n```\n\n```\n#!/usr/bin/env raku\nuse JSON::Fast ;\nmulti MAIN('set', $topic, $message='', :$server='localhost', :$port='3333', :$json='') {\n my %msg = function => 'set' , topic=> $topic , message=> $message ;\n %msg{\"message\"} = from-json( $json ) if $json ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('get', $topic, :$server='localhost', :$port='3333') {\n my %msg = function => 'get' , topic=> $topic ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('delete', $topic, :$server='localhost', :$port='3333') {\n my %msg = function => 'delete' , topic=> $topic ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('dump', :$server='localhost', :$port='3333') {\n my %msg = function => 'dump' ;\n sendmsg( %msg , $server, $port) ;\n}\nsub sendmsg( %msg , $server, $port){\n my $conn = await IO::Socket::Async.connect( $server , $port );\n $conn.print: to-json( %msg,:!pretty)~\"\\n\";\n react {\n whenever $conn.Supply -> $data {\n print $data;\n $conn.close;\n }\n }\n}\n\n```\n\nexamples:\n\n```\necho '{\"function\":\"set\",\"topic\":\"push\",\"message\":[\"perl5\",\"raku\",\"rakudo\"]}' | nc localhost 3333\n\n./client.raku set version raku\n{\"status\": \"ok\"}\n./client.raku get version\n{\"status\": \"ok\",\"topic\": \"version\",\"message\": \"raku\"}\n./client.raku --json='[\"one\",\"two\",\"three\"]' set mylist\n{\"status\": \"ok\"}\n./client.raku dump\n{\"push\": [\"perl5\",\"raku\",\"rakudo\"],\"version\": \"raku\",\"mylist\": [\"one\",\"two\",\"three\"]}\n./client.raku delete version\n{\"status\": \"ok\"}\n\nserver output:\n${:function(\"set\"), :message($[\"perl5\", \"raku\", \"rakudo\"]), :topic(\"push\")}\n${:function(\"set\"), :message(\"raku\"), :topic(\"version\")}\n${:function(\"get\"), :topic(\"version\")}\n${:function(\"set\"), :message($[\"one\", \"two\", \"three\"]), :topic(\"mylist\")}\n${:function(\"dump\")}\n${:function(\"delete\"), :topic(\"version\")}\n```"
}
]
|
[
{
"role": "user",
"content": "Large Factorials and the Distribution of '0' in base 10 digits.\n\nAbout the task\n\nWe can see that some features of factorial numbers (the series of numbers 1!, 2!, 3!, ...)\ncome about because such numbers are the product of a series of counting numbers, and so those\nproducts have predictable factors. For example, all factorials above 1! are even numbers,\nsince they have 2 as a factor. Similarly, all factorials from 5! up end in a 0, because they\nhave 5 and 2 as factors, and thus have 10 as a factor. In fact, the factorial integers add\nanother 0 at the end of the factorial for every step of 5 upward: 5! = 120, 10! = 3628800,\n15! = 1307674368000, 16! = 20922789888000 and so on.\n\nBecause factorial numbers, which quickly become quite large, continue to have another terminal 0\non the right hand side of the number for every factor of 5 added to the factorial product, one might\nthink that the proportion of zeros in a base 10 factorial number might be close to 1/5. However,\nthough the factorial products add another terminating 0 every factor of 5 multiplied into the product,\nas the numbers become quite large, the number of digits in the factorial product expands exponentially,\nand so the number above the terminating zeros tends toward 10% of each digit from 0 to 1 as the factorial\nbecomes larger. Thus, as the factorials become larger, the proportion of 0 digits in the factorial products\nshifts slowly from around 1/5 toward 1/10, since the number of terminating zeros in n! increases only in\nproportion to n, whereas the number of digits of n! in base 10 increases exponentially.\n\nThe task\n\nCreate a function to calculate the mean of the proportions of 0 digits out of the total digits found in each factorial\nproduct from 1! to N!. This proportion of 0 digits in base 10 should be calculated using the number as printed as a base 10 integer.\n\nExample: for 1 to 6 we have 1!, 2!, 3!, 4!, 5!, 6!, or (1, 2, 6, 24, 120, 720), so we need the mean of\n(0/1, 0/1, 0/1, 0/2, 1/3, 1/3) = (2/3) (totals of each proportion) / 6 (= N), or 0.1111111...\n\nExample: for 1 to 25 the mean of the proportions of 0 digits in the factorial products series of N! with N from 1 to 25 is 0.26787.\n\nDo this task for 1 to N where N is in (100, 1000, and 10000), so, compute the mean of the proportion of 0 digits for each product\nin the series of each of the factorials from 1 to 100, 1 to 1000, and 1 to 10000.\n\nStretch task\n\nFind the N in 10000 < N < 50000 where the mean of the proportions of 0 digits in the factorial products from 1 to N\npermanently falls below 0.16. This task took many hours in the Python example, though I wonder if there is a faster\nalgorithm out there."
},
{
"role": "assistant",
"content": "Works, but depressingly slow for 10000.\n\n```\nsub postfix:<!> (Int $n) { ( constant factorial = 1, 1, |[\\*] 2..* )[$n] }\nsink 10000!; # prime the iterator to allow multithreading\n\nsub zs ($n) { ( constant zero-share = (^Inf).race(:32batch).map: { (.!.comb.Bag){'0'} / .!.chars } )[$n+1] }\n\n.say for (\n 100\n ,1000\n ,10000\n).map: -> \\n { \"{n}: {([+] (^n).map: *.&zs) / n}\" }\n\n```\n\nOutput:\n\n```\n100: 0.24675318616743216\n1000: 0.20354455110316458\n10000: 0.17300384824186605\n\n```"
}
]
|
[
{
"role": "user",
"content": "The *wisdom of the crowd* is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.\n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\nScott E. Page introduced the diversity prediction theorem:\n\n: *The squared error of the collective prediction equals the average squared error minus the predictive diversity*.\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\nDefinitions\n: : * Average Individual Error: Average of the individual squared errors\n * Collective Error: Squared error of the collective prediction\n * Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n * Diversity Prediction Theorem: *Given a crowd of predictive models*, then\n\n : : : : Collective Error = Average Individual Error ─ Prediction Diversity\n\nTask\n\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n\n: : : * the true value and the crowd estimates\n * the average error\n * the crowd error\n * the prediction diversity\n\nUse (at least) these two examples:\n\n: : : * a true value of **49** with crowd estimates of: **48 47 51**\n * a true value of **49** with crowd estimates of: **48 47 51 42**\n\nAlso see\n: * Wikipedia entry: Wisdom of the crowd\n * University of Michigan: PDF paper (exists on a web archive, the *Wayback Machine*)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub diversity-calc($truth, @pred) {\n my $ae = avg-error($truth, @pred); # average individual error\n my $cp = ([+] @pred)/+@pred; # collective prediction\n my $ce = ($cp - $truth)**2; # collective error\n my $pd = avg-error($cp, @pred); # prediction diversity\n return $ae, $ce, $pd;\n}\n\nsub avg-error ($m, @v) { ([+] (@v X- $m) X**2) / +@v }\n\nsub diversity-format (@stats) {\n gather {\n for <average-error crowd-error diversity> Z @stats -> ($label,$value) {\n take $label.fmt(\"%13s\") ~ ':' ~ $value.fmt(\"%7.3f\");\n }\n }\n}\n\n.say for diversity-format diversity-calc(49, <48 47 51>);\n.say for diversity-format diversity-calc(49, <48 47 51 42>);\n\n```\n\nOutput:\n\n```\naverage-error: 3.000\n crowd-error: 0.111\n diversity: 2.889\naverage-error: 14.500\n crowd-error: 4.000\n diversity: 10.500\n\n```"
}
]
|
[
{
"role": "user",
"content": "Given the coordinates of a rectangle and a number, cut the rectangle into that\nnumber of random, non-similar triangles that exactly cover the rectangle without\ngaps or overlaps.\n\nThe number of triangles may have reasonable limits such as being above a small\nlimit, and/or odd or even, and/or prime for example. \nThe number should not have an upper bound however, so that many triangles can be generated.\n\n* Explain, or refer to the algorithm employed.\n* Give a sample of sets of triangles produced from running the algorithm, on this page."
},
{
"role": "assistant",
"content": "The first triangle bisects the rectangle via the diagonal. The rest of them all got one vertex at the origin and a side defined by ratios of numbers from a descending positive integer sequence.\n\n```\n# 20220123 Raku programming solution \n\n# Proof :\n#\n# H-----------A---------B-------C-----D---E\n# | |\n# | |\n# | |\n# O---------------------------------------L\n#\n# ▲OEL is unique as its area is the sum of the rest.\n#\n# and also in terms of area ▲OHA > ▲OAB > ... > ▲ODE\n \n\nsub UnequalDivider (\\L,\\H,\\N where N > 2) { \n\n my \\sum = $ = 0 ; my \\part = $ = 0 ; my @sequence = (N^...1) ; \n\n loop { # if ▲OHA ~ ▲OEL \n sum = @sequence.sum; # increase 1st term \n @sequence[0]*L*L/sum == H*H ?? (@sequence[0] +=1) !! last \n }\n\n ( [ (0,0), (L,H), (L,0) ], ).Array.append: @sequence.map: -> \\chunk {\n [ (0,0), (L*part/sum,H), (L*(part+=chunk)/sum,H) ] ;\n } \n}\n\n.say for UnequalDivider(1000,500,5);\n\n```\n\nOutput:\n\n```\n[(0 0) (1000 500) (1000 0)]\n[(0 0) (0 500) (400 500)]\n[(0 0) (400 500) (700 500)]\n[(0 0) (700 500) (900 500)]\n[(0 0) (900 500) (1000 500)]\n\n```"
}
]
|
[
{
"role": "user",
"content": "DNS is an internet service that maps domain names, like `rosettacode.org`, to IP addresses, like `66.220.0.231`.\n\nUse DNS to resolve `www.kame.net` to both IPv4 and IPv6 addresses. Print these addresses."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.01\n\n```\nuse Net::DNS;\n\nmy $resolver = Net::DNS.new('8.8.8.8');\n\nmy $ip4 = $resolver.lookup('A', 'orange.kame.net');\nmy $ip6 = $resolver.lookup('AAAA', 'orange.kame.net');\n\nsay $ip4[0].octets.join: '.';\nsay $ip6[0].octets.».fmt(\"%.2X\").join.comb(4).join: ':';\n\n```\n\nOutput:\n\n```\n203.178.141.194\n2001:0200:0dff:fff1:0216:3eff:feb1:44d7\n```"
}
]
|
[
{
"role": "user",
"content": "Show how to insert documentation for classes, functions, and/or variables in your language. If this documentation is built-in to the language, note it. If this documentation requires external tools, note them.\n\nSee also\n\n* Related task: Comments\n* Related task: Here\\_document"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nSimilarly to Perl 5, Raku is documented using Pod (a redesigned version of POD). However, it's not simply ignored by the parser as in Perl 5, it's an internal part of the language spec and can be used to attach documentation objects to almost any part of the code.\n\n```\n#= it's yellow\nsub marine { ... }\nsay &marine.WHY; # \"it's yellow\"\n\n#= a shaggy little thing\nclass Sheep {\n #= not too scary\n method roar { 'roar!' }\n}\nsay Sheep.WHY; # \"a shaggy little thing\"\nsay Sheep.^find_method('roar').WHY; # \"not too scary\"\n\n```\n\nA compiler has a built-in `--doc` switch that will generate documentation from a given source file. An output format can be specified in the switch. For example, `--doc=Markdown` will generate Markdown from Pod provided that the `Pod::To::Markdown` is installed."
}
]
|
[
{
"role": "user",
"content": "Warning: If you are looking for pizza delivery you have come to the wrong page. Bloody Google (other search engines are available).\n\nTake a box of dominoes give them a good shuffle and then arrange them in diverse orientations such that they form a rectangle with 7 rows of 8 columns. Make a tableau of the face values e.g.\n\n```\n 05132231\n 05505246\n 43036620\n 06235126\n 11300245\n 21433466\n 64515414\n\n```\n\nNow torment your computer by making it identify where each domino is.\n\nDo this for the above tableau and one of your own construction.\n\nExtra credit:\n\nHow many ways are there to arrange dominoes in an 8x7 rectangle, first ignoring their values, then considering their values, and finally considering values but ignoring value symmetry, i.e. transposing 5 and 4."
},
{
"role": "assistant",
"content": "```\nsub domino (Str $s) { $s.comb.sort.join }\n\nsub solve ( UInt $rows, UInt $cols, @tab ) {\n die unless @tab.elems == $rows*$cols;\n die unless @tab.elems %% 2;\n\n my @orientations = 'A' xx @tab.elems; # [A]vailable,[R]ight,[D]own,[L]eft,[U]p\n\n my SetHash $hand .= new: map &domino, [X~] @tab.unique xx 2;\n\n return gather {\n my sub place_domino_at_first_available_after ( UInt $pos_last = 0 ) {\n my $p1 = $pos_last + @orientations.skip($pos_last).first(:k, 'A');\n\n for (False, $p1+1 , <L R>),\n (True , $p1+$cols, <D U>) -> ($is_down, $p2, @two_letters) {\n\n next if $p2 > @tab.end or (!$is_down && $p2 %% $cols); # Board boundaries.\n\n my @two_cells := @orientations[$p1, $p2]; # Bind to candidate location\n\n next if @two_cells !eqv <A A>; # Both cells must be available for placement.\n\n my $dom = domino( @tab[$p1, $p2].join );\n\n $hand{$dom}-- or next; # Take domino from hand, iff present\n @two_cells = @two_letters; # Assign placement\n\n # Either the solution is complete, or we must recurse.\n if !$hand { take @orientations.clone }\n else { place_domino_at_first_available_after($p1) }\n\n @two_cells = <A A>; # Unassign placement\n $hand{$dom}++; # Restore domino into hand\n }\n }\n place_domino_at_first_available_after();\n }\n}\nsub bonus ( UInt $rows, UInt $cols ) {\n die \"Both are odd, so no tiling possible\" if $rows !%% 2 and $cols !%% 2;\n\n my $half = $rows * $cols div 2;\n\n my sub T ($N) { map { ( pi * $_/($N+1) ).cos² * 4 }, 1..($N/2).ceiling }\n\n my $arrangements = [*] T($rows) X+ T($cols);\n my $flips = 2 ** $half;\n my $permutations = [*] 1 .. $half;\n my $product = [*] ($arrangements, $flips, $permutations);\n return :$arrangements, :$flips, :$permutations, :$product;\n}\nmy @tests =\n (7, 8, '05132231055052464303662006235126113002452143346664515414'),\n (7, 8, '64220650162341432102355113505610426040114420536366525334'),\n (3, 4, '001102221201'),\n;\nsub solution_works ( UInt $rows, UInt $cols, @tab, @sol --> Bool ) {\n die unless @sol.all eq <L R U D>.any;\n my BagHash $b .= new;\n for @sol.keys -> $p1 {\n given @sol[$p1] {\n when 'L' { my $p2 = $p1+1; die unless @sol[$p2] eq 'R'; $b{ domino( @tab[$p1,$p2].join ) }++; }\n when 'D' { my $p2 = $p1+$cols; die unless @sol[$p2] eq 'U'; $b{ domino( @tab[$p1,$p2].join ) }++; }\n }\n }\n die unless $b.values.max == 1 and $b.elems == $rows * $cols / 2;\n return True;\n}\nfor @tests -> ( $rows, $cols, $flat_table ) {\n my @solutions = solve($rows, $cols, $flat_table.comb);\n say 'Solutions found: ', +@solutions;\n\n # Confirm that every solution is valid.\n solution_works($rows, $cols, $flat_table.comb, $_) or die for @solutions;\n\n # Print first solution\n say .join.trans( [<L R D U>] => [<╼ ╾ ╽ ╿>]) for @solutions[0].batch($cols);\n\n if ++$ == 1 {\n say 'Bonus:';\n say .value.fmt(\"%45d \"), .key.tclc for bonus($rows, $cols);\n say '';\n }\n}\n\n```\n\nOutput:\n\n```\nSolutions found: 1\n╼╾╼╾╽╼╾╽\n╽╼╾╽╿╼╾╿\n╿╽╽╿╼╾╽╽\n╽╿╿╼╾╽╿╿\n╿╽╽╼╾╿╽╽\n╽╿╿╼╾╽╿╿\n╿╼╾╼╾╿╼╾\nBonus:\n 1292697 Arrangements\n 268435456 Flips\n 304888344611713860501504000000 Permutations\n105797996085635619122449324709940305294524416 Product\n\nSolutions found: 2025\n╼╾╼╾╼╾╽╽\n╼╾╼╾╼╾╿╿\n╼╾╼╾╼╾╼╾\n╼╾╼╾╼╾╼╾\n╼╾╽╽╼╾╼╾\n╼╾╿╿╽╼╾╽\n╼╾╼╾╿╼╾╿\nSolutions found: 4\n╼╾╼╾\n╼╾╼╾\n╼╾╼╾\n\n```"
}
]
|
[
{
"role": "user",
"content": "About the task\n\nJohn Conway (1937-2020), was a mathematician who also invented several mathematically\noriented computer pastimes, such as the famous Game of Life cellular automaton program.\nDr. Conway invented a simple algorithm for finding the day of the week, given any date.\nThe algorithm was based on calculating the distance of a given date from certain\n\"anchor days\" which follow a pattern for the day of the week upon which they fall.\n\nAlgorithm\n\nThe formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and\n\n```\n doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7\n\n```\n\nwhich, for 2021, is 0 (Sunday).\n\nTo calculate the day of the week, we then count days from a close doomsday,\nwith these as charted here by month, then add the doomsday for the year,\nthen get the remainder after dividing by 7. This should give us the number\ncorresponding to the day of the week for that date.\n\n```\n Month\t Doomsday Dates for Month\n --------------------------------------------\n January (common years) 3, 10, 17, 24, 31\n January (leap years) 4, 11, 18, 25\n February (common years) 7, 14, 21, 28\n February (leap years) 1, 8, 15, 22, 29\n March 7, 14, 21, 28\n April 4, 11, 18, 25\n May 2, 9, 16, 23, 30\n June 6, 13, 20, 27\n July 4, 11, 18, 25\n August 1, 8, 15, 22, 29\n September 5, 12, 19, 26\n October 3, 10, 17, 24, 31\n November 7, 14, 21, 28\n December 5, 12, 19, 26\n\n```\n\nTask\n\nGiven the following dates:\n\n* 1800-01-06 (January 6, 1800)\n* 1875-03-29 (March 29, 1875)\n* 1915-12-07 (December 7, 1915)\n* 1970-12-23 (December 23, 1970)\n* 2043-05-14 (May 14, 2043)\n* 2077-02-12 (February 12, 2077)\n* 2101-04-02 (April 2, 2101)\n\nUse Conway's Doomsday rule to calculate the day of the week for each date.\n\nsee also\n\n* Doomsday rule\n* Tomorrow is the Day After Doomsday (p.28)"
},
{
"role": "assistant",
"content": "```\nmy @dow = < Sunday Monday Tuesday Wednesday Thursday Friday Saturday >;\n\nmy %doomsday = False => [3,7,7,4,2,6,4,1,5,3,7,5], True => [4,1,7,4,2,6,4,1,5,3,7,5];\n\nsub conway ($date) {\n my ($year, $month, $day) = $date.comb(/\\d+/)».Int;\n my $is-leap = ($year %% 4) && (($year % 100) || ($year %% 400));\n\n my $c = $year div 100;\n my $s = ($year % 100) div 12;\n my $t = ($year % 100) % 12;\n my $a = ( 5 * ($c % 4) + 2 ) % 7;\n my $b = ( $s + $t + ($t div 4) + $a ) % 7;\n\n ($b + $day - %doomsday{$is-leap}[$month - 1] + 7) % 7\n}\n\n\nfor < 1800-01-06 1875-03-29 1915-12-07 1970-12-23 2043-05-14 2077-02-12 2101-04-02 >\n{\n say \"Conway - $_ is a: \", @dow[.&conway];\n # Or, we could use the method built into the compiler...\n say \"Builtin - $_ is a: \", @dow[Date.new($_).day-of-week];\n say '';\n}\n\n```\n\nOutput:\n\n```\nConway - 1800-01-06 is a: Monday\nBuiltin - 1800-01-06 is a: Monday\n\nConway - 1875-03-29 is a: Monday\nBuiltin - 1875-03-29 is a: Monday\n\nConway - 1915-12-07 is a: Tuesday\nBuiltin - 1915-12-07 is a: Tuesday\n\nConway - 1970-12-23 is a: Wednesday\nBuiltin - 1970-12-23 is a: Wednesday\n\nConway - 2043-05-14 is a: Thursday\nBuiltin - 2043-05-14 is a: Thursday\n\nConway - 2077-02-12 is a: Friday\nBuiltin - 2077-02-12 is a: Friday\n\nConway - 2101-04-02 is a: Saturday\nBuiltin - 2101-04-02 is a: Saturday\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a function/use an in-built function, to compute the **dot product**, also known as the **scalar product** of two vectors.\n\nIf possible, make the vectors of arbitrary length.\n\nAs an example, compute the dot product of the vectors:\n\n: : : : `[1, 3, -5]` and\n : `[4, -2, -1]`\n\nIf implementing the dot product of two vectors directly:\n\n: : : * each vector must be the same length\n * multiply corresponding terms from each vector\n * sum the products (to produce the answer)\n\nRelated task\n\n* Vector products"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2010.07\n\nWe use the square-bracket meta-operator to turn the infix operator `+` into a reducing list operator, and the guillemet meta-operator to vectorize the infix operator `*`. Length validation is automatic in this form.\n\n```\nsub infix:<·> { [+] @^a »*« @^b }\n\nsay (1, 3, 5)·(4, -2, 1);\n```"
}
]
|
[
{
"role": "user",
"content": "**Definition**\n \nLet (p1,p2) and (p3,p4) be twin primes where p3 - p2 = 4.\n \nSuch primes called **Double Twin Primes**\n \n \n**Example**\n \n[5,7,11,13]\n \n**Task**\n \nFind and show here all Double Twin Primes under 1000.\n\nSee also\n: * OEIS:A007530\n * Wikipedia:Prime\\_k-tuple"
},
{
"role": "assistant",
"content": "Cousin twin primes:\n\n```\nsub dt { $^p, $p+2, $p+6, $p+8 }\n.&dt.say for (^1000).grep: { all .&dt».is-prime };\n\n```\n\nOutput:\n\n```\n(5 7 11 13)\n(11 13 17 19)\n(101 103 107 109)\n(191 193 197 199)\n(821 823 827 829)\n```"
}
]
|
[
{
"role": "user",
"content": "Define the data structure for a complete Doubly Linked List.\n\n* The structure should support adding elements to the head, tail and middle of the list.\n* The structure should not allow circular loops\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThis shows a complete example. (Other entries in the section focus on aspects of this solution.)\n\n```\nrole DLElem[::T] {\n has DLElem[T] $.prev is rw;\n has DLElem[T] $.next is rw;\n has T $.payload = T;\n\n method pre-insert(T $payload) {\n\tdie \"Can't insert before beginning\" unless $!prev;\n\tmy $elem = ::?CLASS.new(:$payload);\n\t$!prev.next = $elem;\n\t$elem.prev = $!prev;\n\t$elem.next = self;\n\t$!prev = $elem;\n\t$elem;\n }\n\n method post-insert(T $payload) {\n\tdie \"Can't insert after end\" unless $!next;\n\tmy $elem = ::?CLASS.new(:$payload);\n\t$!next.prev = $elem;\n\t$elem.next = $!next;\n\t$elem.prev = self;\n\t$!next = $elem;\n\t$elem;\n }\n\n method delete {\n\tdie \"Can't delete a sentinel\" unless $!prev and $!next;\n\t$!next.prev = $!prev;\n\t$!prev.next = $!next;\t# conveniently returns next element\n }\n}\n\nrole DLList[::DLE] {\n has DLE $.first;\n has DLE $.last;\n\n submethod BUILD {\n\t$!first = DLE.new;\n\t$!last = DLE.new;\n\t$!first.next = $!last;\n\t$!last.prev = $!first;\n }\n\n method list { ($!first.next, *.next ...^ !*.next).map: *.payload }\n method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload }\n}\n\nclass DLElem_Int does DLElem[Int] {}\nclass DLList_Int does DLList[DLElem_Int] {}\n\nmy $dll = DLList_Int.new;\n\n$dll.first.post-insert(1).post-insert(2).post-insert(3);\n$dll.first.post-insert(0);\n\n$dll.last.pre-insert(41).pre-insert(40).prev.delete; # (deletes 3)\n$dll.last.pre-insert(42);\n\nsay $dll.list; # 0 1 2 40 41 42\nsay $dll.reverse; # 42 41 40 2 1 0\n\n```\n\nOutput:\n\n```\n0 1 2 40 41 42\n42 41 40 2 1 0\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDefine the data structure for a doubly-linked list element.\n\nThe element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list.\n\nThe pointers should be mutable.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nrole DLElem[::T] {\n has DLElem[T] $.prev is rw;\n has DLElem[T] $.next is rw;\n has T $.payload = T;\n\n method pre-insert(T $payload) {\n die \"Can't insert before beginning\" unless $!prev;\n my $elem = ::?CLASS.new(:$payload);\n $!prev.next = $elem;\n $elem.prev = $!prev;\n $elem.next = self;\n $!prev = $elem;\n $elem;\n }\n\n method post-insert(T $payload) {\n die \"Can't insert after end\" unless $!next;\n my $elem = ::?CLASS.new(:$payload);\n $!next.prev = $elem;\n $elem.next = $!next;\n $elem.prev = self;\n $!next = $elem;\n $elem;\n }\n\n method delete {\n die \"Can't delete a sentinel\" unless $!prev and $!next;\n $!next.prev = $!prev;\n $!prev.next = $!next; # conveniently returns next element\n }\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Use the link structure defined in Doubly-Linked List (element) to define a procedure for inserting a link into a doubly-linked list. Call this procedure to insert element C into a list {A,B}, between elements A and B.\n\nThis is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nUsing the generic definitions from Doubly-linked\\_list/Definition#Raku:\n\n```\nrole DLElem[::T] {\n has DLElem[T] $.prev is rw;\n has DLElem[T] $.next is rw;\n has T $.payload = T;\n\n method pre-insert(T $payload) {\n die \"Can't insert before beginning\" unless $!prev;\n my $elem = ::?CLASS.new(:$payload);\n $!prev.next = $elem;\n $elem.prev = $!prev;\n $elem.next = self;\n $!prev = $elem;\n $elem;\n }\n\n method post-insert(T $payload) {\n die \"Can't insert after end\" unless $!next;\n my $elem = ::?CLASS.new(:$payload);\n $!next.prev = $elem;\n $elem.next = $!next;\n $elem.prev = self;\n $!next = $elem;\n $elem;\n }\n\n method delete {\n die \"Can't delete a sentinel\" unless $!prev and $!next;\n $!next.prev = $!prev;\n $!prev.next = $!next; # conveniently returns next element\n }\n}\n\nrole DLList[::DLE] {\n has DLE $.first;\n has DLE $.last;\n\n submethod BUILD {\n\t$!first = DLE.new;\n\t$!last = DLE.new;\n\t$!first.next = $!last;\n\t$!last.prev = $!first;\n }\n\n method list { ($!first.next, *.next ...^ !*.next).map: *.payload }\n method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload }\n}\n\nclass DLElem_Str does DLElem[Str] {}\nclass DLList_Str does DLList[DLElem_Str] {}\n\nmy $sdll = DLList_Str.new;\nmy $b = $sdll.first.post-insert('A').post-insert('B');\n$b.pre-insert('C');\nsay $sdll.list; # A C B\n\n```\n\nOutput:\n\n```\nA C B\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDefine a method to remove an element from a doubly-linked list and demonstrate its use.\n\nYou may wish to use the list element defined in Doubly-Linked List (element) for the purposes of this task."
},
{
"role": "assistant",
"content": "Already implemented and demonstrated as part of Doubly-linked\\_list/Definition#Raku. Not going to duplicate the entire entry from there to here."
}
]
|
[
{
"role": "user",
"content": "Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nSince the list routines are supplied by the generic roles defined in Doubly-linked\\_list/Definition#Raku, it suffices to say:\n\n```\nsay $dll.list;\nsay $dll.reverse;\n\n```\n\nThese automatically return just the payloads, hiding the elements containing the forward and backward pointers."
}
]
|
[
{
"role": "user",
"content": "Create and display a dragon curve fractal.\n\n(You may either display the curve directly or write it to an image file.)\n\nAlgorithms\n\nHere are some brief notes the algorithms used and how they might suit various languages.\n\n* Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.\n\n```\n*---R----* expands to * *\n \\ /\n R L\n \\ /\n *\n\n *\n / \\\n L R\n / \\\n*---L---* expands to * *\n```\n\n: The co-routines `dcl` and `dcr` in various examples do this recursively to a desired expansion level.\n\n* The curl direction right or left can be a parameter instead of two separate routines.\n\n* Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.\n\n```\n*------->* becomes * * Recursive copies drawn\n \\ / from the ends towards\n \\ / the centre.\n v v\n *\n```\n\n: This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.\n\n* Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,\n\n```\n * \n*-----* becomes / \\ bend to left\n / \\ if N odd\n * *\n\n * * \n*-----* becomes \\ / bend to right \n \\ / if N even \n *\n```\n\n: Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.\n\n: The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.\n\n* Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.\n\n```\nn = 1010110000\n ^\n bit above lowest 1-bit, turn left or right as 0 or 1\n\nLowMask = n BITXOR (n-1) # eg. giving 0000011111\nAboveMask = LowMask + 1 # eg. giving 0000100000\nBitAboveLowestOne = n BITAND AboveMask\n```\n\n: The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.\n\n: If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because \"...10000\" minus 1 is \"...01111\" so the lowest 0 in n-1 is where the lowest 1 in n is.\n\n: Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.\n\n* If a language doesn't maintain a \"current direction\" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.\n\n* Absolute direction to move at point n can be calculated by the number of bit-transitions in n.\n\n```\nn = 11 00 1111 0 1\n ^ ^ ^ ^ 4 places where change bit value\n so direction=4*90degrees=East\n```\n\n: This can be calculated by counting the number of 1 bits in \"n XOR (n RIGHTSHIFT 1)\" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.\n\n* Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.\n\n* Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.\n\n: A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an \"even\" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)\n\n: The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.\n\n* As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.\n\n```\nAxiom F, angle 90 degrees\nF -> F+S\nS -> F-S\n```\n\nThis always has F at even positions and S at odd. Eg. after 3 levels `F_S_F_S_F_S_F_S`. The +/- turns in between bend to the left or right the same as the \"successive approximation\" method above. Read more at for instance Joel Castellanos' L-system page.\n\nVariations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.\n\nThe string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as \"recursive with parameter\" above but can draw other curves defined by L-systems."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nWe'll use a L-System role, and draw the dragon in SVG.\n\n```\nuse SVG;\n\nrole Lindenmayer {\n has %.rules;\n method succ { \n\t self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)\n }\n}\n\nmy $dragon = \"FX\" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } );\n\n$dragon++ xx ^15;\n\nmy @points = 215, 350;\n\nfor $dragon.comb {\n state ($x, $y) = @points[0,1];\n state $d = 2 + 0i;\n if /'F'/ { @points.append: ($x += $d.re).round(.1), ($y += $d.im).round(.1) }\n elsif /< + - >/ { $d *= \"{$_}1i\" }\n}\n\nsay SVG.serialize(\n svg => [\n :600width, :450height, :style<stroke:rgb(0,0,255)>,\n :rect[:width<100%>, :height<100%>, :fill<white>],\n :polyline[ :points(@points.join: ','), :fill<white> ],\n ],\n);\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDraw a clock.\n\nMore specific:\n\n1. Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be *drawn*; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n2. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n3. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n4. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\nKey points\n\n* animate simple object\n* timed event\n* polling system resources\n* code clarity"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy ($rows,$cols) = qx/stty size/.words;\nmy $v = floor $rows / 2;\nmy $h = floor $cols / 2 - 16;\n\nmy @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>;\nmy @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>;\n\nloop {\n my @x = DateTime.now.Str.substr(11,8).ords X- ord('0');\n print \"\\e[H\\e[J\";\n print \"\\e[$v;{$h}H\";\n print ~@t[@x];\n print \"\\e[{$v+1};{$h}H\";\n print ~@b[@x];\n print \"\\e[H\";\n sleep 1;\n}\n\n```\n\nOutput:\n\n```\n⠀⢺⠀ ⢀⠔⡇ ⠀⠶⠀ ⠊⠉⡱ ⠊⣉⡱ ⠀⠶⠀ ⣏⣉⡉ ⡎⢉⢵\n⢀⣸⣀ ⠉⠉⡏ ⠀⠶⠀ ⣔⣉⣀ ⢄⣀⡸ ⠀⠶⠀ ⢄⣀⡸ ⢗⣁⡸\n```\n\nA simpler version that does not clear the screen:\n\n```\nconstant @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>;\nconstant @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>;\n\nsignal(SIGINT).tap: { print \"\\e[?25h\\n\"; exit }\nprint \"\\e7\\e[?25l\"; # saves cursor position, make it invisible\nloop {\n my @x = DateTime.now.Str.substr(11,8).ords X- ord('0');\n put ~.[@x] for @t, @b;\n sleep 1;\n print \"\\e8\"; # restores cursor position\n}\n\n```\n\nFinally a more minimalist version that shows three progress bars (hours, minutes, seconds):\n\n```\nprint \"\\e7\";\nloop {\n my $time = DateTime.now;\n put '#' x $_ ~ '.' x (24 - $_) given $time.hour.round;\n put '#' x $_ ~ '.' x (60 - $_) given $time.minute.round;\n put '#' x $_ ~ '.' x (60 - $_) given $time.second.round;\n sleep 1;\n print \"\\e8\";\n}\nEND put \"\\n\";\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDraw a cuboid with relative dimensions of 2 × 3 × 4.\n\nThe cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.\n\nTo fulfill the criteria of being a cuboid, three faces must be visible.\n\nEither static or rotational projection is acceptable for this task.\n\nRelated tasks\n\n* draw a sphere\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: moar version 2015-11-27\n\n```\nsub braille-graphics (%a) {\n my ($ylo, $yhi, $xlo, $xhi);\n for %a.keys -> $y {\n\t$ylo min= +$y; $yhi max= +$y;\n\tfor %a{$y}.keys -> $x {\n\t $xlo min= +$x; $xhi max= +$x;\n\t}\n }\n\n for $ylo, $ylo + 4 ...^ * > $yhi -> \\y {\n\tfor $xlo, $xlo + 2 ...^ * > $xhi -> \\x {\n\t my $cell = 0x2800;\n\t $cell += 1 if %a{y + 0}{x + 0};\n\t $cell += 2 if %a{y + 1}{x + 0};\n\t $cell += 4 if %a{y + 2}{x + 0};\n\t $cell += 8 if %a{y + 0}{x + 1};\n\t $cell += 16 if %a{y + 1}{x + 1};\n\t $cell += 32 if %a{y + 2}{x + 1};\n\t $cell += 64 if %a{y + 3}{x + 0};\n\t $cell += 128 if %a{y + 3}{x + 1};\n\t print chr($cell);\n\t}\n\tprint \"\\n\";\n }\n}\n\nsub cuboid ( [$x, $y, $z] ) {\n my \\x = $x * 4;\n my \\y = $y * 4;\n my \\z = $z * 2;\n my %t;\n sub horz ($X, $Y) { %t{$Y }{$X + $_} = True for 0 .. x }\n sub vert ($X, $Y) { %t{$Y + $_}{$X } = True for 0 .. y }\n sub diag ($X, $Y) { %t{$Y - $_}{$X + $_} = True for 0 .. z }\n \n horz(0, z); horz(z, 0); horz( 0, z+y);\n vert(0, z); vert(x, z); vert(z+x, 0);\n diag(0, z); diag(x, z); diag( x, z+y);\n \n say \"[$x, $y, $z]\";\n braille-graphics %t;\n}\n \ncuboid $_ for [2,3,4], [3,4,2], [4,2,3], [1,1,1], [8,1,1], [1,8,1], [1,1,8];\n\n```\n\nOutput:"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a window and draw a pixel in it, subject to the following:\n\n: : 1. the window is 320 x 240\n 2. the color of the pixel must be red (255,0,0)\n 3. the position of the pixel is x = 100, y = 100"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\nReally? Draw a single pixel? Sigh.\n\n```\nuse GTK::Simple;\nuse GTK::Simple::DrawingArea;\nuse Cairo;\n\nmy $app = GTK::Simple::App.new(:title('Draw a Pixel'));\nmy $da = GTK::Simple::DrawingArea.new;\ngtk_simple_use_cairo;\n\n$app.set-content( $da );\n$app.border-width = 5;\n$da.size-request(320,240);\n\nsub rect-do( $d, $ctx ) {\n given $ctx {\n .rgb(1, 0, 0);\n .rectangle(100, 100, 1, 1);\n .fill;\n }\n}\n\nmy $ctx = $da.add-draw-handler( &rect-do );\n$app.run;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDraw a rotating cube.\n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\nRelated tasks\n\n* Draw a cuboid\n* write language name in 3D ASCII"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nRaku has no native graphics libraries built in, but makes it fairly easy to bind to third party libraries. Here we'll use bindings to Libcaca, the **C**olor **A**S**C**II **A**rt library to generate a rotating cube in an ASCII terminal.\n\n```\nuse Terminal::Caca;\ngiven my $canvas = Terminal::Caca.new {\n .title('Rosetta Code - Rotating cube - Press any key to exit');\n\n sub scale-and-translate($x, $y, $z) {\n $x * 5 / ( 5 + $z ) * 15 + 40,\n $y * 5 / ( 5 + $z ) * 7 + 15,\n $z;\n }\n\n sub rotate3d-x( $x, $y, $z, $angle ) {\n my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals;\n $x,\n $y * $cosθ - $z * $sinθ,\n $y * $sinθ + $z * $cosθ;\n }\n\n sub rotate3d-y( $x, $y, $z, $angle ) {\n my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals;\n $x * $cosθ - $z * $sinθ,\n $y,\n $x * $sinθ + $z * $cosθ;\n }\n\n sub rotate3d-z( $x, $y, $z, $angle ) {\n my ($cosθ, $sinθ) = cis( $angle * π / 180.0 ).reals;\n $x * $cosθ - $y * $sinθ,\n $x * $cosθ + $y * $sinθ,\n $z;\n }\n\n # Unit cube from polygon mesh, aligned to axes\n my @mesh =\n [ [1, 1, -1], [-1, -1, -1], [-1, 1, -1] ], # far face\n [ [1, 1, -1], [-1, -1, -1], [ 1, -1, -1] ],\n [ [1, 1, 1], [-1, -1, 1], [-1, 1, 1] ], # near face\n [ [1, 1, 1], [-1, -1, 1], [ 1, -1, 1] ];\n @mesh.push: [$_».rotate( 1)».Array] for @mesh[^4]; # positive and\n @mesh.push: [$_».rotate(-1)».Array] for @mesh[^4]; # negative rotations\n\n # Rotate to correct orientation for task\n for ^@mesh X ^@mesh[0] -> ($i, $j) {\n @(@mesh[$i;$j]) = rotate3d-x |@mesh[$i;$j], 45;\n @(@mesh[$i;$j]) = rotate3d-z |@mesh[$i;$j], 40;\n }\n\n my @colors = red, blue, green, cyan, magenta, yellow;\n\n loop {\n for ^359 -> $angle {\n .color( white, white );\n .clear;\n\n # Flatten 3D into 2D and rotate for all faces\n my @faces-z;\n my $c-index = 0;\n for @mesh -> @triangle {\n my @points;\n my $sum-z = 0;\n for @triangle -> @node {\n my ($px, $py, $z) = scale-and-translate |rotate3d-y |@node, $angle;\n @points.append: $px.Int, $py.Int;\n $sum-z += $z;\n }\n\n @faces-z.push: %(\n color => @colors[$c-index++ div 2],\n points => @points,\n avg-z => $sum-z / +@points;\n );\n }\n\n # Draw all faces\n # Sort by z to draw farthest first\n for @faces-z.sort( -*.<avg-z> ) -> %face {\n # Draw filled triangle\n .color( %face<color>, %face<color> );\n .fill-triangle( |%face<points> );\n # And frame\n .color( black, black );\n .thin-triangle( |%face<points> );\n }\n\n .refresh;\n exit if .wait-for-event(key-press);\n }\n }\n\n # Cleanup on scope exit\n LEAVE {\n .cleanup;\n }\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDraw a sphere.\n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities.\n\nEither static or rotational projection is acceptable for this task.\n\nRelated tasks\n\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Pure Raku\n\n**Translation of**: C\n\nThe C code is modified to output a .pgm file.\n\n**Works with**: Rakudo version 2018.10\n\n```\nmy $width = my $height = 255; # must be odd\n\nmy @light = normalize([ 3, 2, -5 ]);\n\nmy $depth = 255;\n\nsub MAIN ($outfile = 'sphere-perl6.pgm') {\n spurt $outfile, \"P5\\n$width $height\\n$depth\\n\"; # .pgm header\n my $out = open( $outfile, :a, :bin ) orelse .die;\n $out.write( Blob.new(draw_sphere( ($width-1)/2, .9, .2) ) );\n $out.close;\n}\n\nsub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }\n\nsub dot (@x, @y) { -([+] @x »*« @y) max 0 }\n\nsub draw_sphere ( $rad, $k, $ambient ) {\n my @pixels[$height];\n my $r2 = $rad * $rad;\n my @range = -$rad .. $rad;\n @range.hyper.map: -> $x {\n my @row[$width];\n @range.map: -> $y {\n if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 {\n my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]);\n my $intensity = dot(@light, @vector) ** $k + $ambient;\n my $pixel = (0 max ($intensity * $depth).Int) min $depth;\n @row[$y+$rad] = $pixel;\n }\n else {\n @row[$y+$rad] = 0;\n }\n }\n @pixels[$x+$rad] = @row;\n }\n flat |@pixels.map: *.list;\n}\n\n```\n\n### Cairo graphics library\n\n```\nuse Cairo;\n\ngiven Cairo::Image.create(Cairo::FORMAT_ARGB32, 256, 256) {\n given Cairo::Context.new($_) {\n\n my Cairo::Pattern::Solid $bg .= create(.5,.5,.5);\n .rectangle(0, 0, 256, 256);\n .pattern($bg);\n .fill;\n $bg.destroy;\n\n my Cairo::Pattern::Gradient::Radial $shadow .=\n create(105.2, 102.4, 15.6, 102.4, 102.4, 128.0);\n $shadow.add_color_stop_rgba(0, .3, .3, .3, .3);\n $shadow.add_color_stop_rgba(1, .1, .1, .1, .02);\n .pattern($shadow);\n .arc(136.0, 134.0, 110, 0, 2 * pi);\n .fill;\n $shadow.destroy;\n\n my Cairo::Pattern::Gradient::Radial $sphere .=\n create(115.2, 102.4, 25.6, 102.4, 102.4, 128.0);\n $sphere.add_color_stop_rgba(0, 1, 1, .698, 1);\n $sphere.add_color_stop_rgba(1, .923, .669, .144, 1);\n .pattern($sphere);\n .arc(128.0, 128.0, 110, 0, 2 * pi);\n .fill;\n $sphere.destroy;\n };\n .write_png('sphere2-perl6.png');\n}\n\n```\n\nSee sphere2-perl6.png (offsite .png image)"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a window and draw a pixel in it, subject to the following:\n\n: : 1. the window is 640 x 480\n 2. the color of the pixel must be yellow (255,255,0)\n 3. the position of the pixel is random"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\nCoordinates of random pixel displayed in window title. To make the single pixel show up better I filled in the drawing area background with black to get better contrast.\n\n```\nuse GTK::Simple;\nuse GTK::Simple::DrawingArea;\nuse Cairo;\nmy ($w, $h) = 640, 480;\nmy ($x, $y) = (^$w).pick, (^$h).pick;\n\nmy $app = GTK::Simple::App.new(:title(\"Draw Pixel 2 @ $x,$y\"));\nmy $da = GTK::Simple::DrawingArea.new;\ngtk_simple_use_cairo;\n\n$app.set-content( $da );\n$app.border-width = 5;\n$da.size-request($w, $h);\n\nsub rect-do( $d, $ctx ) {\n given $ctx {\n .rgb(0, 0, 0);\n .rectangle(0, 0, $w, $h);\n .fill;\n .rgb(1, 1, 0);\n .rectangle($x, $y, 1, 1);\n .fill;\n }\n}\n\nmy $ctx = $da.add-draw-handler( &rect-do );\n$app.run;\n\n```"
}
]
|
[
{
"role": "user",
"content": "A **Duffinian number** is a composite number **k** that is relatively prime to its sigma sum **σ**.\n\n*The sigma sum of **k** is the sum of the divisors of **k**.*\n\nE.G.\n\n**161** is a **Duffinian number**.\n\n* It is composite. (7 × 23)\n* The sigma sum **192** (1 + 7 + 23 + 161) is relatively prime to **161**.\n\nDuffinian numbers are very common.\n\nIt is not uncommon for two consecutive integers to be Duffinian (a Duffinian twin) (8, 9), (35, 36), (49, 50), etc.\n\nLess common are Duffinian triplets; three consecutive Duffinian numbers. (63, 64, 65), (323, 324, 325), etc.\n\nMuch, much less common are Duffinian quadruplets and quintuplets. The first Duffinian quintuplet is (202605639573839041, 202605639573839042, 202605639573839043, 202605639573839044, 202605639573839045).\n\nIt is not possible to have six consecutive Duffinian numbers\n\nTask\n\n* Find and show the first 50 Duffinian numbers.\n* Find and show at least the first 15 Duffinian triplets.\n\nSee also\n\n* Numbers Aplenty - Duffinian numbers * OEIS:A003624 - Duffinian numbers: composite numbers k relatively prime to sigma(k)"
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor;\n\nmy @duffinians = lazy (3..*).hyper.grep: { !.is-prime && $_ gcd .&divisors.sum == 1 };\n\nput \"First 50 Duffinian numbers:\\n\" ~\n@duffinians[^50].batch(10)».fmt(\"%3d\").join: \"\\n\";\n\nput \"\\nFirst 40 Duffinian triplets:\\n\" ~\n ((^∞).grep: -> $n { (@duffinians[$n] + 1 == @duffinians[$n + 1]) && (@duffinians[$n] + 2 == @duffinians[$n + 2]) })[^40]\\\n .map( { \"({@duffinians[$_ .. $_+2].join: ', '})\" } ).batch(4)».fmt(\"%-24s\").join: \"\\n\";\n\n```\n\nOutput:\n\n```\nFirst 50 Duffinian numbers:\n 4 8 9 16 21 25 27 32 35 36\n 39 49 50 55 57 63 64 65 75 77\n 81 85 93 98 100 111 115 119 121 125\n128 129 133 143 144 155 161 169 171 175\n183 185 187 189 201 203 205 209 215 217\n\nFirst 40 Duffinian triplets:\n(63, 64, 65) (323, 324, 325) (511, 512, 513) (721, 722, 723) \n(899, 900, 901) (1443, 1444, 1445) (2303, 2304, 2305) (2449, 2450, 2451) \n(3599, 3600, 3601) (3871, 3872, 3873) (5183, 5184, 5185) (5617, 5618, 5619) \n(6049, 6050, 6051) (6399, 6400, 6401) (8449, 8450, 8451) (10081, 10082, 10083) \n(10403, 10404, 10405) (11663, 11664, 11665) (12481, 12482, 12483) (13447, 13448, 13449) \n(13777, 13778, 13779) (15841, 15842, 15843) (17423, 17424, 17425) (19043, 19044, 19045) \n(26911, 26912, 26913) (30275, 30276, 30277) (36863, 36864, 36865) (42631, 42632, 42633) \n(46655, 46656, 46657) (47523, 47524, 47525) (53137, 53138, 53139) (58563, 58564, 58565) \n(72961, 72962, 72963) (76175, 76176, 76177) (79523, 79524, 79525) (84099, 84100, 84101) \n(86527, 86528, 86529) (94177, 94178, 94179) (108899, 108900, 108901) (121103, 121104, 121105)\n```"
}
]
|
[
{
"role": "user",
"content": "File:Dutch flag 3.jpg\n\nThe Dutch national flag is composed of three coloured bands in the order:\n\n: : * red (top)\n * then white, and\n * lastly blue (at the bottom).\n\nThe problem posed by Edsger Dijkstra is:\n\n: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\n\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\nTask\n\n1. Generate a randomized order of balls *ensuring that they are not in the order of the Dutch national flag*.\n2. Sort the balls in a way idiomatic to your language.\n3. Check the sorted balls *are* in the order of the Dutch national flag.\n\nC.f.\n\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nHere are five ways to do it, all one liners (apart from the test apparatus).\n\n```\nenum NL <red white blue>;\nmy @colors;\n\nsub how'bout (&this-way) {\n sub show {\n say @colors;\n say \"Ordered: \", [<=] @colors;\n }\n\n @colors = NL.roll(20);\n show;\n this-way;\n show;\n say '';\n}\n\nsay \"Using functional sort\";\nhow'bout { @colors = sort *.value, @colors }\n\nsay \"Using in-place sort\";\nhow'bout { @colors .= sort: *.value }\n\nsay \"Using a Bag\";\nhow'bout { @colors = flat red, white, blue Zxx bag(@colors».key)<red white blue> }\n\nsay \"Using the classify method\";\nhow'bout { @colors = flat (.list for %(@colors.classify: *.value){0,1,2}) }\n\nsay \"Using multiple greps\";\nhow'bout { @colors = flat (.grep(red), .grep(white), .grep(blue) given @colors) }\n\n```\n\nOutput:\n\n```\nUsing functional sort\nred red white white red red red red red red red white red white red red red white white white\nOrdered: False\nred red red red red red red red red red red red red white white white white white white white\nOrdered: True\n\nUsing in-place sort\nred blue white red white blue white blue red white blue blue blue red white white red blue red blue\nOrdered: False\nred red red red red red white white white white white white blue blue blue blue blue blue blue blue\nOrdered: True\n\nUsing a Bag\nred blue blue blue white red white red white blue blue red red red red blue blue red white blue\nOrdered: False\nred red red red red red red red white white white white blue blue blue blue blue blue blue blue\nOrdered: True\n\nUsing the classify method\nblue red white blue blue white white red blue red red white red blue white white red blue red white\nOrdered: False\nred red red red red red red white white white white white white white blue blue blue blue blue blue\nOrdered: True\n\nUsing multiple greps\nred white blue white white red blue white red white red white white white white white red red blue red\nOrdered: False\nred red red red red red red white white white white white white white white white white blue blue blue\nOrdered: True\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a variable with a user-defined name.\n\nThe variable name should *not* be written in the program text, but should be taken from the user dynamically.\n\nSee also\n\n* Eval in environment is a similar task."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nYou can interpolate strings as variable names:\n\n```\nour $our-var = 'The our var';\nmy $my-var = 'The my var';\n\nmy $name = prompt 'Variable name: ';\nmy $value = $::('name'); # use the right sigil, etc\n\nput qq/Var ($name) starts with value 「$value」/;\n\n$::('name') = 137;\n\nput qq/Var ($name) ends with value 「{$::('name')}」/;\n\n```"
}
]
|
[
{
"role": "user",
"content": "When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that between some two adjacent primes will be a gap corresponding to every positive even integer.\n\n| gap | minimal starting prime | ending prime |\n| --- | --- | --- |\n| 2 | 3 | 5 |\n| 4 | 7 | 11 |\n| 6 | 23 | 29 |\n| 8 | 89 | 97 |\n| 10 | 139 | 149 |\n| 12 | 199 | 211 |\n| 14 | 113 | 127 |\n| 16 | 1831 | 1847 |\n| 18 | 523 | 541 |\n| 20 | 887 | 907 |\n| 22 | 1129 | 1151 |\n| 24 | 1669 | 1693 |\n| 26 | 2477 | 2503 |\n| 28 | 2971 | 2999 |\n| 30 | 4297 | 4327 |\n\nThis task involves locating the minimal primes corresponding to those gaps.\n\nThough every gap value exists, they don't seem to come in any particular order. For example, this table shows the gaps and minimum starting value primes for 2 through 30:\n\nFor the purposes of this task, considering only primes greater than 2, consider prime gaps that differ by exactly two to be adjacent.\n\nTask\n\nFor each order of magnitude **m** from **10¹** through **10⁶**:\n\n* Find the first two sets of minimum adjacent prime gaps where the absolute value of the difference between the prime gap start values is greater than **m**.\n\nE.G.\n\nFor an **m** of **10¹**;\n\nThe start value of gap 2 is 3, the start value of gap 4 is 7, the difference is 7 - 3 or 4. 4 < **10¹** so keep going.\n\nThe start value of gap 4 is 7, the start value of gap 6 is 23, the difference is 23 - 7, or 16. 16 > **10¹** so this the earliest adjacent gap difference > **10¹**.\n\nStretch goal\n\n* Do the same for **10⁷** and **10⁸** (and higher?) orders of magnitude\n\nNote: the earliest value found for each order of magnitude may not be unique, in fact, *is* not unique; also, with the gaps in ascending order, the minimal starting values are not strictly ascending."
},
{
"role": "assistant",
"content": "1e1 through 1e7 are pretty speedy (less than 5 seconds total). 1e8 and 1e9 take several minutes.\n\n```\nuse Math::Primesieve;\nuse Lingua::EN::Numbers;\n\nmy $iterator = Math::Primesieve::iterator.new;\nmy @gaps;\nmy $last = 2;\n\nfor 1..9 {\n my $m = exp $_, 10;\n my $this;\n loop {\n $this = (my $p = $iterator.next) - $last;\n if !@gaps[$this].defined {\n @gaps[$this]= $last;\n check-gap($m, $this, @gaps) && last\n if $this > 2 and @gaps[$this - 2].defined and (abs($last - @gaps[$this - 2]) > $m);\n }\n $last = $p;\n }\n}\n\nsub check-gap ($n, $this, @p) {\n my %upto = @p[^$this].pairs.grep: *.value;\n my @upto = (1..$this).map: { last unless %upto{$_ * 2}; %upto{$_ * 2} }\n my $key = @upto.rotor(2=>-1).first( {.sink; abs(.[0] - .[1]) > $n}, :k );\n return False unless $key;\n say \"Earliest difference > {comma $n} between adjacent prime gap starting primes:\";\n printf \"Gap %s starts at %s, gap %s starts at %s, difference is %s\\n\\n\",\n |(2 * $key + 2, @upto[$key], 2 * $key + 4, @upto[$key+1], abs(@upto[$key] - @upto[$key+1]))».,\n True\n}\n\n```\n\nOutput:\n\n```\nEarliest difference > 10 between adjacent prime gap starting primes:\nGap 4 starts at 7, gap 6 starts at 23, difference is 16\n\nEarliest difference > 100 between adjacent prime gap starting primes:\nGap 14 starts at 113, gap 16 starts at 1,831, difference is 1,718\n\nEarliest difference > 1,000 between adjacent prime gap starting primes:\nGap 14 starts at 113, gap 16 starts at 1,831, difference is 1,718\n\nEarliest difference > 10,000 between adjacent prime gap starting primes:\nGap 36 starts at 9,551, gap 38 starts at 30,593, difference is 21,042\n\nEarliest difference > 100,000 between adjacent prime gap starting primes:\nGap 70 starts at 173,359, gap 72 starts at 31,397, difference is 141,962\n\nEarliest difference > 1,000,000 between adjacent prime gap starting primes:\nGap 100 starts at 396,733, gap 102 starts at 1,444,309, difference is 1,047,576\n\nEarliest difference > 10,000,000 between adjacent prime gap starting primes:\nGap 148 starts at 2,010,733, gap 150 starts at 13,626,257, difference is 11,615,524\n\nEarliest difference > 100,000,000 between adjacent prime gap starting primes:\nGap 198 starts at 46,006,769, gap 200 starts at 378,043,979, difference is 332,037,210\n\nEarliest difference > 1,000,000,000 between adjacent prime gap starting primes:\nGap 276 starts at 649,580,171, gap 278 starts at 4,260,928,601, difference is 3,611,348,430\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nAn **eban** number is a number that has no letter **e** in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter **e** are banned.\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n**2,000,000,000** is two billion, *not* two milliard.\n\nOnly numbers less than **one sextillion** (**1021**) will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\nTask\n: : : * show all eban numbers ≤ **1,000** (in a horizontal format), and a count\n * show all eban numbers between **1,000** and **4,000** (inclusive), and a count\n * show a count of all eban numbers up and including **10,000**\n * show a count of all eban numbers up and including **100,000**\n * show a count of all eban numbers up and including **1,000,000**\n * show a count of all eban numbers up and including **10,000,000**\n * show all output here.\n\nSee also\n: * The MathWorld entry: eban numbers.\n * The OEIS entry: A6933, eban numbers.\n * Number names."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nModular approach, very little is hard coded. Change the $upto order-of-magnitude limit to adjust the search/display ranges. Change the letter(s) given to the enumerate / count subs to modify which letter(s) to disallow.\n\nWill handle multi-character 'bans'. Demonstrate for e-ban, t-ban and subur-ban.\n\nDirectly find :\n\n: * OEIS:A006933 Numbers without e: Eban\n * OEIS:A008521 Numbers without o: Oban\n * OEIS:A008523 Numbers without t: Tban\n * OEIS:A072954 Numbers without a, i, l, t: TALIban\n * OEIS:A072955 Numbers without b, r, s, u: SUBURban\n * OEIS:A072956 Numbers without r, t, u: TURban\n * OEIS:A072957 Numbers without r, u: URban\n * OEIS:A072958 Numbers without a, c, i, l: CALIban\n * OEIS:A089589 Numbers without i: Iban\n * OEIS:A089590 Numbers without u: Uban\n * *and so on...*\n\nConsidering numbers up to **1021**, as the task directions suggest.\n\n```\nuse Lingua::EN::Numbers;\n\nsub nban ($seq, $n = 'e') { ($seq).map: { next if .&cardinal.contains(any($n.lc.comb)); $_ } }\n\nsub enumerate ($n, $upto) {\n my @ban = [nban(1 .. 99, $n)],;\n my @orders;\n (2 .. $upto).map: -> $o {\n given $o % 3 { # Compensate for irregulars: 11 - 19\n when 1 { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }\n default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }\n }\n }\n ^@orders .map: -> $o {\n @ban.push: [] and next unless +@orders[$o];\n my @these;\n @orders[$o].map: -> $m {\n @these.push: $m;\n for ^@ban -> $b {\n next unless +@ban[$b];\n @these.push: $_ for (flat @ban[$b]) »+» $m ;\n }\n }\n @ban.push: @these;\n }\n @ban.unshift(0) if nban(0, $n);\n flat @ban.map: *.flat;\n}\n\nsub count ($n, $upto) {\n my @orders;\n (2 .. $upto).map: -> $o {\n given $o % 3 { # Compensate for irregulars: 11 - 19\n when 1 { @orders.push: [flat (10**($o - 1) X* 10 .. 19).map(*.&nban($n)), |(10**$o X* 2 .. 9).map: *.&nban($n)] }\n default { @orders.push: [flat (10**$o X* 1 .. 9).map: *.&nban($n)] }\n }\n }\n my @count = +nban(1 .. 99, $n);\n ^@orders .map: -> $o {\n @count.push: 0 and next unless +@orders[$o];\n my $prev = so (@orders[$o].first( { $_ ~~ /^ '1' '0'+ $/ } ) // 0 );\n my $sum = @count.sum;\n my $these = +@orders[$o] * $sum + @orders[$o];\n $these-- if $prev;\n @count[1 + $o] += $these;\n ++@count[$o] if $prev;\n }\n ++@count[0] if nban(0, $n);\n [\\+] @count;\n}\n\n#for < e o t tali subur tur ur cali i u > -> $n { # All of them\nfor < e t subur > -> $n { # An assortment for demonstration\n my $upto = 21; # 1e21\n my @bans = enumerate($n, 4);\n my @counts = count($n, $upto);\n\n # DISPLAY\n my @k = @bans.grep: * < 1000;\n my @j = @bans.grep: 1000 <= * <= 4000;\n put \"\\n============= {$n}-ban: =============\\n\" ~\n \"{$n}-ban numbers up to 1000: {+@k}\\n[{@k».&comma}]\\n\\n\" ~\n \"{$n}-ban numbers between 1,000 & 4,000: {+@j}\\n[{@j».&comma}]\\n\" ~\n \"\\nCounts of {$n}-ban numbers up to {cardinal 10**$upto}\"\n ;\n\n my $s = max (1..$upto).map: { (10**$_).&cardinal.chars };\n @counts.unshift: @bans.first: * > 10, :k;\n for ^$upto -> $c {\n printf \"Up to and including %{$s}s: %s\\n\", cardinal(10**($c+1)), comma(@counts[$c]);\n }\n}\n\n```\n\nOutput:\n\n```\n============= e-ban: =============\ne-ban numbers up to 1000: 19\n[2 4 6 30 32 34 36 40 42 44 46 50 52 54 56 60 62 64 66]\n\ne-ban numbers between 1,000 & 4,000: 21\n[2,000 2,002 2,004 2,006 2,030 2,032 2,034 2,036 2,040 2,042 2,044 2,046 2,050 2,052 2,054 2,056 2,060 2,062 2,064 2,066 4,000]\n\nCounts of e-ban numbers up to one sextillion\nUp to and including ten: 3\nUp to and including one hundred: 19\nUp to and including one thousand: 19\nUp to and including ten thousand: 79\nUp to and including one hundred thousand: 399\nUp to and including one million: 399\nUp to and including ten million: 1,599\nUp to and including one hundred million: 7,999\nUp to and including one billion: 7,999\nUp to and including ten billion: 31,999\nUp to and including one hundred billion: 159,999\nUp to and including one trillion: 159,999\nUp to and including ten trillion: 639,999\nUp to and including one hundred trillion: 3,199,999\nUp to and including one quadrillion: 3,199,999\nUp to and including ten quadrillion: 12,799,999\nUp to and including one hundred quadrillion: 63,999,999\nUp to and including one quintillion: 63,999,999\nUp to and including ten quintillion: 255,999,999\nUp to and including one hundred quintillion: 1,279,999,999\nUp to and including one sextillion: 1,279,999,999\n\n============= t-ban: =============\nt-ban numbers up to 1000: 56\n[0 1 4 5 6 7 9 11 100 101 104 105 106 107 109 111 400 401 404 405 406 407 409 411 500 501 504 505 506 507 509 511 600 601 604 605 606 607 609 611 700 701 704 705 706 707 709 711 900 901 904 905 906 907 909 911]\n\nt-ban numbers between 1,000 & 4,000: 0\n[]\n\nCounts of t-ban numbers up to one sextillion\nUp to and including ten: 7\nUp to and including one hundred: 9\nUp to and including one thousand: 56\nUp to and including ten thousand: 56\nUp to and including one hundred thousand: 56\nUp to and including one million: 57\nUp to and including ten million: 392\nUp to and including one hundred million: 785\nUp to and including one billion: 5,489\nUp to and including ten billion: 38,416\nUp to and including one hundred billion: 76,833\nUp to and including one trillion: 537,824\nUp to and including ten trillion: 537,824\nUp to and including one hundred trillion: 537,824\nUp to and including one quadrillion: 537,825\nUp to and including ten quadrillion: 3,764,768\nUp to and including one hundred quadrillion: 7,529,537\nUp to and including one quintillion: 52,706,752\nUp to and including ten quintillion: 52,706,752\nUp to and including one hundred quintillion: 52,706,752\nUp to and including one sextillion: 52,706,752\n\n============= subur-ban: =============\nsubur-ban numbers up to 1000: 35\n[1 2 5 8 9 10 11 12 15 18 19 20 21 22 25 28 29 50 51 52 55 58 59 80 81 82 85 88 89 90 91 92 95 98 99]\n\nsubur-ban numbers between 1,000 & 4,000: 0\n[]\n\nCounts of subur-ban numbers up to one sextillion\nUp to and including ten: 6\nUp to and including one hundred: 35\nUp to and including one thousand: 35\nUp to and including ten thousand: 35\nUp to and including one hundred thousand: 35\nUp to and including one million: 36\nUp to and including ten million: 216\nUp to and including one hundred million: 2,375\nUp to and including one billion: 2,375\nUp to and including ten billion: 2,375\nUp to and including one hundred billion: 2,375\nUp to and including one trillion: 2,375\nUp to and including ten trillion: 2,375\nUp to and including one hundred trillion: 2,375\nUp to and including one quadrillion: 2,375\nUp to and including ten quadrillion: 2,375\nUp to and including one hundred quadrillion: 2,375\nUp to and including one quintillion: 2,375\nUp to and including ten quintillion: 2,375\nUp to and including one hundred quintillion: 2,375\nUp to and including one sextillion: 2,375\n```\n\nNote that the limit to one sextillion is somewhat arbitrary and is just to match the task parameters.\n\nThis will quite happily count \\*-bans up to one hundred centillion. (10305) It takes longer, but still on the order of seconds, not minutes.\n\n```\nCounts of e-ban numbers up to one hundred centillion\n ...\nUp to and including one hundred centillion: 35,184,372,088,831,999,999,999,999,999,999,999,999,999,999,999,999,999,999,999\n```"
}
]
|
[
{
"role": "user",
"content": "Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from localhost (127.0.0.1 or perhaps ::1). Logging of connection information to standard output is recommended.\n\nThe implementation must be able to handle simultaneous connections from multiple clients. A multi-threaded or multi-process solution may be used. Each connection must be able to echo more than a single line.\n\nThe implementation must not stop responding to other clients if one client sends a partial line or stops reading responses."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nmy $socket = IO::Socket::INET.new:\n :localhost<localhost>,\n :localport<12321>,\n :listen;\n\nwhile $socket.accept -> $conn {\n say \"Accepted connection\";\n start {\n while $conn.recv -> $stuff {\n say \"Echoing $stuff\";\n $conn.print($stuff);\n }\n $conn.close;\n }\n}\n\n```\n\nAsync version:\n\n```\nreact {\n whenever IO::Socket::Async.listen('0.0.0.0', 12321) -> $conn {\n whenever $conn.Supply.lines -> $line {\n $conn.print( \"$line\\n\" ) ;\n }\n }\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "An **eertree** is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.\n\nThe data structure has commonalities to both *tries* and *suffix trees*.\n See links below.\n\nTask\n\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\nSee also\n\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree\n* Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n* EERTREE: An efficient data structure for processing palindromes in strings[1]"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Ring\n\n```\nmy $str = \"eertree\";\nmy @pal = ();\nmy ($strrev,$strpal);\n\nfor (1 .. $str.chars) -> $n {\n for (1 .. $str.chars) -> $m {\n $strrev = \"\";\n $strpal = $str.substr($n-1, $m);\n if ($strpal ne \"\") {\n for ($strpal.chars ... 1) -> $p {\n $strrev ~= $strpal.substr($p-1,1);\n }\n ($strpal eq $strrev) and @pal.push($strpal);\n }\n }\n}\n\nsay @pal.unique;\n\n```\n\nOutput:\n\n```\n(e ee eertree ertre r rtr t)\n\n```"
}
]
|
[
{
"role": "user",
"content": "Egyptian division is a method of dividing integers using addition and\ndoubling that is similar to the algorithm of Ethiopian multiplication\n\n**Algorithm:**\n\nGiven two numbers where the **dividend** is to be divided by the **divisor**:\n\n1. Start the construction of a table of two columns: **`powers_of_2`**, and **`doublings`**; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n2. Create the second row with columns of 2 (i.e 2^1), and 2 \\* divisor in order.\n3. Continue with successive i’th rows of 2^i and 2^i \\* divisor.\n4. Stop adding rows, and keep only those rows, where 2^i \\* divisor is less than or equal to the dividend.\n5. We now assemble two separate sums that both start as zero, called here **answer** and **accumulator**\n6. Consider each row of the table, in the *reverse* order of its construction.\n7. If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers\\_of\\_2 cell value to the answer.\n8. When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. \n (And the remainder is given by the absolute value of accumulator - dividend).\n\n**Example: 580 / 34**\n\n**Table creation:**\n\n: : : | powers\\_of\\_2 | doublings |\n | --- | --- |\n | 1 | 34 |\n | 2 | 68 |\n | 4 | 136 |\n | 8 | 272 |\n | 16 | 544 |\n\n**Initialization of sums:**\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | 1 | 34 | | |\n | 2 | 68 | | |\n | 4 | 136 | | |\n | 8 | 272 | | |\n | 16 | 544 | | |\n | | | 0 | 0 |\n\n**Considering table rows, bottom-up:**\n\nWhen a row is considered it is shown ~~crossed out~~ if it is not accumulated, or **bold** if the row causes summations.\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | 1 | 34 | | |\n | 2 | 68 | | |\n | 4 | 136 | | |\n | 8 | 272 | | |\n | **16** | **544** | 16 | 544 |\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | 1 | 34 | | |\n | 2 | 68 | | |\n | 4 | 136 | | |\n | ~~8~~ | ~~272~~ | 16 | 544 |\n | **16** | **544** | | |\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | 1 | 34 | | |\n | 2 | 68 | | |\n | ~~4~~ | ~~136~~ | 16 | 544 |\n | ~~8~~ | ~~272~~ | | |\n | **16** | **544** | | |\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | 1 | 34 | | |\n | ~~2~~ | ~~68~~ | 16 | 544 |\n | ~~4~~ | ~~136~~ | | |\n | ~~8~~ | ~~272~~ | | |\n | **16** | **544** | | |\n\n: : : | powers\\_of\\_2 | doublings | answer | accumulator |\n | --- | --- | --- | --- |\n | **1** | **34** | 17 | 578 |\n | ~~2~~ | ~~68~~ | | |\n | ~~4~~ | ~~136~~ | | |\n | ~~8~~ | ~~272~~ | | |\n | **16** | **544** | | |\n\nAnswer\n\nSo 580 divided by 34 using the Egyptian method is **`17`** remainder (578 - 580) or **`2`**.\n\nTask\n\nThe task is to create a function that does Egyptian division. The function should \nclosely follow the description above in using a list/array of powers of two, and \nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer **here, on this page**.\n\nRelated tasks\n: * Egyptian fractions\n * Ethiopian multiplication\n\nReferences\n: * Egyptian Number System"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.07\n\n### Normal version\n\nOnly works with positive real numbers, not negative or complex.\n\n```\nsub egyptian-divmod (Real $dividend is copy where * >= 0, Real $divisor where * > 0) {\n my $accumulator = 0;\n ([1, $divisor], { [.[0] + .[0], .[1] + .[1]] } … ^ *.[1] > $dividend)\n .reverse.map: { $dividend -= .[1], $accumulator += .[0] if $dividend >= .[1] }\n $accumulator, $dividend;\n}\n \n#TESTING\nfor 580,34, 578,34, 7532795332300578,235117 -> $n, $d {\n printf \"%s divmod %s = %s remainder %s\\n\",\n $n, $d, |egyptian-divmod( $n, $d )\n}\n\n```\n\nOutput:\n\n```\n580 divmod 34 = 17 remainder 2\n578 divmod 34 = 17 remainder 0\n7532795332300578 divmod 235117 = 32038497141 remainder 81\n```\n\n### More \"Egyptian\" version\n\nAs a preceding version was determined to be \"let's just say ... not Egyptian\" we submit an alternate which is hopefully more \"Egyptian\". Now only handles positive Integers up to 10 million, mostly due to limitations on Egyptian notation for numbers.\n\nNote: if the below is just a mass of \"unknown glyph\" boxes, try installing Googles free Noto Sans Egyptian Hieroglyphs font.\n\nThis is intended to be humorous and should not be regarded as good (or even sane) programming practice. That being said, 𓂽 & 𓂻 really are the ancient Egyptian symbols for addition and subtraction, and the Egyptian number notation is as accurate as possible. Everything else owes more to whimsy than rigor.\n\n```\nmy (\\𓄤, \\𓄊, \\𓎆, \\𓄰) = (0, 1, 10, 10e7);\nsub infix:<𓂽> { $^𓃠 + $^𓃟 }\nsub infix:<𓂻> { $^𓃲 - $^𓆊 }\nsub infix:<𓈝> { $^𓃕 < $^𓃢 }\nsub 𓁶 (Int \\𓆉) {\n my \\𓁢 = [«'' 𓏺 𓏻 𓏼 𓏽 𓏾 𓏿 𓐀 𓐁 𓐂»], [«'' 𓎆 𓎏 𓎐 𓎑 𓎊 𓎋 𓎌 𓎍 𓎎»],\n [«'' 𓍢 𓍣 𓍤 𓍥 𓍦 𓍧 𓍨 𓍩 𓍪»], [«'' 𓆼 𓆽 𓆾 𓆿 𓇀 𓇁 𓇂 𓇃 𓇄»],\n [«'' 𓂭 𓂮 𓂯 𓂰 𓂱 𓂲 𓂳 𓂴 𓂵»], ['𓆐' Xx ^𓎆], ['𓁨' Xx ^𓎆];\n ([~] 𓆉.polymod( 𓎆 xx * ).map( { 𓁢[$++;$_] } ).reverse) || '𓄤'\n}\n\nsub infix:<𓅓> (Int $𓂀 is copy where 𓄤 𓂻 𓄊 𓈝 * 𓈝 𓄰, Int \\𓌳 where 𓄤 𓈝 * 𓈝 𓄰) {\n my $𓎦 = 𓄤;\n ([𓄊,𓌳], { [.[𓄤] 𓂽 .[𓄤], .[𓄊] 𓂽 .[𓄊]] } … ^$𓂀 𓈝 *.[𓄊])\n .reverse.map: { $𓂀 𓂻= .[𓄊], $𓎦 𓂽= .[𓄤] if .[𓄊] 𓈝 ($𓂀 𓂽 𓄊) }\n $𓎦, $𓂀;\n}\n\n#TESTING\nfor 580,34, 578,34, 2300578,23517 -> \\𓃾, \\𓆙 {\n printf \"%s divmod %s = %s remainder %s =OR= %s 𓅓 %s = %s remainder %s\\n\",\n 𓃾, 𓆙, |(𓃾 𓅓 𓆙), (𓃾, 𓆙, |(𓃾 𓅓 𓆙))».&𓁶;\n}\n\n```\n\nOutput:\n\n```\n580 divmod 34 = 17 remainder 2 =OR= 𓍦𓎍 𓅓 𓎐𓏽 = 𓎆𓐀 remainder 𓏻\n578 divmod 34 = 17 remainder 0 =OR= 𓍦𓎌𓐁 𓅓 𓎐𓏽 = 𓎆𓐀 remainder 𓄤\n2300578 divmod 23517 = 97 remainder 19429 =OR= 𓁨𓁨𓆐𓆐𓆐𓍦𓎌𓐁 𓅓 𓂮𓆾𓍦𓎆𓐀 = 𓎎𓐀 remainder 𓂭𓇄𓍥𓎏𓐂\n```"
}
]
|
[
{
"role": "user",
"content": "An *Eisenstein integer* is a non-unit Gaussian integer a + bω where ω(1+ω) = -1, and a and b are integers.\n\nω is generally chosen as a cube root of unity: \n\nω\n=\n\n−\n1\n+\ni\n\n\n3\n2\n=\n\ne\n\ni\n2\nπ\n\n/\n3\n{\\displaystyle {\\displaystyle {\\displaystyle \\omega ={\\frac {-1+i{\\sqrt {3}}}{2}}=e^{i2\\pi /3}}}}\n\nAs with a Gaussian integer, any Eisenstein integer is either a unit (an integer with a multiplicative inverse [±1, ±ω, ±(ω^-1)]),\na prime (a number p such that if p divides xy, then p necessarily divides either x or y), or composite (a product of primes).\n\nAn Eisenstein integer a + bω is a prime if either it is a product of a unit and an integer prime p such that p % 3 == 2 or norm(a + bω) is an integer prime.\n\nEisenstein numbers can be generated by choosing any a and b such that a and b are integers. To allow generation in a relatively fixed order, such numbers can be ordered by their 2-norm or *norm*:\n\n```\n norm(eisenstein integer(a, b)) = |a + bω|² = \n \n \n \n \n \n \n a\n \n 2\n \n \n −\n a\n b\n +\n \n b\n \n 2\n \n \n \n \n \n \n {\\displaystyle {\\displaystyle a^{2}-ab+b^{2}}}\n \n\n\n```\n\nTask\n\n* Find, and show here as their complex number values, the first **100** (by norm order) Eisenstein primes nearest 0.\n\nStretch\n\n* Plot in the complex plane at least the first 2000 such numbers (again, as found with norm closest to 0).\n\nSee also\n\n* [Wikipedia entry for Eisenstein\\_integer] * [Observable entry on Eisenstein primes]"
},
{
"role": "assistant",
"content": "```\nmy \\ω = exp 2i × π/3;\n\nsub norm (@p) { @p[0]² - @p[0]×@p[1] + @p[1]² }\nsub display (@p) { (@p[0] + ω×@p[1]).reals».fmt('%+8.4f').join ~ 'i' }\n\nmy @E = gather (-10..10 X -10..10).map: -> (\\a,\\b) {\n take (a,b) if 0 == a|b || a == b ?? (.is-prime and 2 == $_ mod 3 given (a,b)».abs.max) !! norm((a,b)).is-prime\n}\n\n(@E.sort: *.&norm).head(100).map(*.&display).batch(4).join(\"\\n\").say;\n\n```\n\nOutput:\n\n```\n -1.5000 -0.8660i -0.0000 -1.7321i -1.5000 +0.8660i +1.5000 -0.8660i\n +0.0000 +1.7321i +1.5000 +0.8660i -1.0000 -1.7321i -2.0000 +0.0000i\n +1.0000 -1.7321i -1.0000 +1.7321i +2.0000 +0.0000i +1.0000 +1.7321i\n -2.0000 -1.7321i -2.5000 -0.8660i -0.5000 -2.5981i -2.5000 +0.8660i\n +0.5000 -2.5981i -2.0000 +1.7321i +2.0000 -1.7321i -0.5000 +2.5981i\n +2.5000 -0.8660i +0.5000 +2.5981i +2.5000 +0.8660i +2.0000 +1.7321i\n -2.5000 -2.5981i -3.5000 -0.8660i -1.0000 -3.4641i -3.5000 +0.8660i\n +1.0000 -3.4641i -2.5000 +2.5981i +2.5000 -2.5981i -1.0000 +3.4641i\n +3.5000 -0.8660i +1.0000 +3.4641i +3.5000 +0.8660i +2.5000 +2.5981i\n -3.5000 -2.5981i -4.0000 -1.7321i -0.5000 -4.3301i -4.0000 +1.7321i\n +0.5000 -4.3301i -3.5000 +2.5981i +3.5000 -2.5981i -0.5000 +4.3301i\n +4.0000 -1.7321i +0.5000 +4.3301i +4.0000 +1.7321i +3.5000 +2.5981i\n -2.5000 -4.3301i -5.0000 +0.0000i +2.5000 -4.3301i -2.5000 +4.3301i\n +5.0000 +0.0000i +2.5000 +4.3301i -3.5000 -4.3301i -5.5000 -0.8660i\n -2.0000 -5.1962i -5.5000 +0.8660i +2.0000 -5.1962i -3.5000 +4.3301i\n +3.5000 -4.3301i -2.0000 +5.1962i +5.5000 -0.8660i +2.0000 +5.1962i\n +5.5000 +0.8660i +3.5000 +4.3301i -5.0000 -3.4641i -5.5000 -2.5981i\n -0.5000 -6.0622i -5.5000 +2.5981i +0.5000 -6.0622i -5.0000 +3.4641i\n +5.0000 -3.4641i -0.5000 +6.0622i +5.5000 -2.5981i +0.5000 +6.0622i\n +5.5000 +2.5981i +5.0000 +3.4641i -4.0000 -5.1962i -6.5000 -0.8660i\n -2.5000 -6.0622i -6.5000 +0.8660i +2.5000 -6.0622i -4.0000 +5.1962i\n +4.0000 -5.1962i -2.5000 +6.0622i +6.5000 -0.8660i +2.5000 +6.0622i\n +6.5000 +0.8660i +4.0000 +5.1962i -6.5000 -4.3301i -7.0000 -3.4641i\n -0.5000 -7.7942i -7.0000 +3.4641i +0.5000 -7.7942i -6.5000 +4.3301i\n +6.5000 -4.3301i -0.5000 +7.7942i +7.0000 -3.4641i +0.5000 +7.7942i\n\n```"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.