messages
listlengths
2
2
[ { "role": "user", "content": "The purpose of this task is to explore working with   complex numbers.\n\nTask\n\nGiven   **n**,   find the   **n**th   roots of unity." }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku has a built-in function cis which returns a unitary complex number given its phase. Raku also defines the tau = 2\\*pi constant. Thus the k-th n-root of unity can simply be written cis(k\\*τ/n).\n\n```\nconstant n = 10;\nfor ^n -> \\k {\n say cis(k*τ/n);\n}\n\n```\n\nOutput:\n\n```\n1+0i\n0.809016994374947+0.587785252292473i\n0.309016994374947+0.951056516295154i\n-0.309016994374947+0.951056516295154i\n-0.809016994374947+0.587785252292473i\n-1+1.22464679914735e-16i\n-0.809016994374948-0.587785252292473i\n-0.309016994374948-0.951056516295154i\n0.309016994374947-0.951056516295154i\n0.809016994374947-0.587785252292473i\n```\n\nAlternately, you could use the built-in .roots method to find the nth roots of any number.\n\n```\n.say for 1.roots(9)\n\n```\n\nOutput:\n\n```\n1+0i\n0.766044443118978+0.6427876096865393i\n0.17364817766693041+0.984807753012208i\n-0.4999999999999998+0.8660254037844387i\n-0.9396926207859083+0.3420201433256689i\n-0.9396926207859084-0.34202014332566866i\n-0.5000000000000004-0.8660254037844384i\n0.17364817766692997-0.9848077530122081i\n0.7660444431189778-0.6427876096865396i\n```" } ]
[ { "role": "user", "content": "Find the total number of programming examples for each task and the total for all tasks.\n\nEssentially, count the number of occurrences of =={{header| on each task page.\n\nOutput:\n\n```\n100 doors: 20 examples.\n99 Bottles of Beer: 29 examples.\nAbstract type: 10 examples.\n\nTotal: X examples.\n```\n\nFor a full output, updated periodically, see Rosetta Code/Count examples/Full list.\n\nYou'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nRetrieves counts for both Tasks and Draft Tasks. Save / Display results as a sortable wikitable rather than a static list. Click on a column header to sort on that column. To do a secondary sort, hold down the shift key and click on a second column header. Tasks have a gray (default) background, Draft Tasks have a yellow background.\n\nThis example tracks the top 50 languages by number of examples completed but only generates reports in tiers of 10. More than 10 gets too heavy and difficult to navigate.\n\nFeed it parameters to control behaviour:\n\n* :nf or :no-fetch to use saved information to generate the different reports. Recommended for the second, third, fourth, whatever report you are generating at any one time as fetching from the site is *by far* the most time consuming part.\n* :t=1 (or :tier=1). :t=2, :t=3, whatever, up to :t=5 to control which tier of results to generate.\n\nLanguage names with spaces will have underscores inserted to make the results uniform. Some oddball languages (lookin' at you Icon and Unicon) make it very difficult to obtain accurate results. The whole \"conglomerate all of the Basic dialects together\" movement of a few years ago also complicates things, but this should be pretty close.\n\nFor a full output, see Top tier, Second tier, Third tier, Fourth tier\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\nuse Lingua::EN::Numbers :short;\n\nunit sub MAIN ( Bool :nf(:$no-fetch) = False, :t(:$tier) = 1 );\n\n# Friendlier descriptions for task categories\nmy %cat = (\n 'Programming_Tasks' => 'Task',\n 'Draft_Programming_Tasks' => 'Draft'\n);\n\nmy $client = HTTP::UserAgent.new;\n$client.timeout = 10;\n\nmy $url = 'https://rosettacode.org/w';\n\nmy $hashfile = './RC_Task_count.json';\nmy $tablefile = \"./RC_Task_count-{$tier}.txt\";\n\nmy %tasks;\n\nmy @places = <① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ㉑ ㉒ ㉓ ㉔ ㉕\n ㉖ ㉗ ㉘ ㉙ ㉚ ㉛ ㉜ ㉝ ㉞ ㉟ ㊱ ㊲ ㊳ ㊴ ㊵ ㊶ ㊷ ㊸ ㊹ ㊺ ㊺ ㊻ ㊼ ㊽ ㊾ ㊿>;\n\n# clear screen\nrun($*DISTRO.is-win ?? 'cls' !! 'clear') unless $no-fetch;\n\nmy %counts =\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle<Category:Programming Languages>,\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<categoryinfo>\n )\n .map({ .<title>.subst(/^'Category:'/, '') => .<categoryinfo><pages> || 0 });\n\nmy $per-tier = 10;\n\nmy $which = (^$per-tier) »+» $per-tier * ($tier - 1);\n\nmy @top-n = %counts.sort( {-.value, .key} )[|$which].map: *.key.trans(' ' => '_');\n\n# dump a copy to STDOUT, mostly for debugging purposes\nsay \"<pre>{tc $tier.&ord-n} {$per-tier.&card} programming languages by number of task examples completed:\";\nsay ' ', join ' ', .map( {(\"{(@places[|$which])[$_]} {@top-n[$_]}\").fmt(\"%-15s\")} ) for (^@top-n).batch(5);\nsay \"</pre>\\n\";\n\nunless $no-fetch {\n\n note 'Retrieving task information...';\n\n mkdir('./pages') unless './pages'.IO.e;\n\n @top-n = %counts.sort( {-.value, .key} )[^@places].map: *.key.trans(' ' => '_');;\n\n for %cat.keys.sort -> $cat {\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle(\"Category:$cat\"),\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<title>\n ).map({\n my $page;\n my $response;\n\n loop {\n $response = $client.get(\"{ $url }/index.php?title={ uri-escape .<title> }&action=raw\");\n if $response.is-success {\n $page = $response.content;\n last;\n } else {\n redo;\n }\n }\n\n \"./pages/{ uri-escape .<title>.subst(/' '/, '_', :g) }\".IO.spurt($page);\n my $lc = $page.lc.trans(' ' => '_');\n my $count = +$lc.comb(/ ^^'==' <-[\\n=]>* '{{header|' <-[}]>+? '}}==' \\h* $$ /);\n %tasks{.<title>} = {'cat' => %cat{$cat}, :$count};\n %tasks{.<title>}<top-n> = (^@top-n).map( {\n ($lc.contains(\"==\\{\\{header|{@top-n[$_].lc}}}\") or\n # Deal with 3 part headers - {{header|F_Sharp|F#}}, {{header|C_Sharp|C#}}, etc.\n $lc.contains(\"==\\{\\{header|{@top-n[$_].lc}|\") or\n # Icon and Unicon are their own special flowers\n $lc.contains(\"}}_and_\\{\\{header|{@top-n[$_].lc}}}==\") or\n # Language1 / Language2 for shared entries (e.g. C / C++)\n $lc.contains(rx/'}}''_'*'/''_'*'{{header|'$(@top-n[$_].lc)'}}=='/)) ??\n (@places[$_]) !!\n # Check if the task was omitted\n $lc.contains(\"\\{\\{omit_from|{@top-n[$_].lc}\") ?? 'O' !!\n # The task is neither done or omitted\n ' '\n } ).join;\n print clear, 1 + $++, ' ', %cat{$cat}, ' ', .<title>;\n })\n }\n\n print clear;\n\n note \"\\nTask information saved to local file: {$hashfile.IO.absolute}\";\n $hashfile.IO.spurt(%tasks.&to-json);\n\n}\n\n# Load information from local file\n%tasks = $hashfile.IO.e ?? $hashfile.IO.slurp.&from-json !! ( );\n\n@top-n = %counts.sort( {-.value, .key} )[|$which].map: *.key.trans(' ' => '_');\n\n# Convert saved task info to a table\nnote \"\\nBuilding table...\";\nmy $count = +%tasks;\nmy $taskcnt = +%tasks.grep: *.value.<cat> eq %cat<Programming_Tasks>;\nmy $draftcnt = $count - $taskcnt;\nmy $total = sum %tasks{*}»<count>;\n\n# Dump table to a file\nmy $out = open($tablefile, :w) or die \"$!\\n\";\n\n$out.say: \"<pre>{tc $tier.&ord-n} {$per-tier.&card} programming languages by number of task examples completed:\";\n$out.say: ' ', join ' ', .map( {(\"{(@places[|$which])[$_]} {@top-n[$_]}\").fmt(\"%-15s\")} ) for (^@top-n).batch(5);\n$out.say: \"</pre>\\n\\n<div style=\\\"height:40em;overflow:scroll;\\\">\";\n\n# Add table boilerplate and caption\n$out.say:\n '{|class=\"wikitable sortable\"', \"\\n\",\n \"|+ As of { DateTime.new(time) } :: Tasks: { $taskcnt } ::<span style=\\\"background-color:#ffd\\\"> Draft Tasks:\",\n \"{ $draftcnt } </span>:: Total Tasks: { $count } :: Total Examples: { $total }\\n\",\n \"!Count!!Task!!{(@places[|$which]).join('!!')}\"\n;\n\n# Sort tasks by count then add row\nfor %tasks.sort: { [-.value<count>, .key] } -> $task {\n $out.say:\n ( $task.value<cat> eq 'Draft'\n  ?? \"|- style=\\\"background-color: #ffc\\\"\\n\"\n  !! \"|-\\n\"\n ),\n \"| { $task.value<count> }\\n\",\n ( $task.key ~~ /\\d/\n  ?? \"|data-sort-value=\\\"{ $task.key.&naturally }\\\"| [[{uri-escape $task.key}|{$task.key}]]\\n\"\n  !! \"| [[{uri-escape $task.key}|{$task.key}]]\\n\"\n ),\n \"|{ $task.value<top-n>.comb[|$which].join('||') }\"\n}\n\n$out.say( \"|}\\n</div>\" );\n$out.close;\n\nnote \"Table file saved as: {$tablefile.IO.absolute}\";\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub uri-query-string (*%fields) { %fields.map({ \"{.key}={uri-escape .value}\" }).join(\"&\") }\n\nsub naturally ($a) { $a.lc.subst(/(\\d+)/, ->$/ {0~(65+$0.chars).chr~$0},:g) }\n\nsub clear { \"\\r\" ~ ' ' x 116 ~ \"\\r\" }\n\n```\n\nAbridged output:\n\n```\nTop ten programming language by number of task examples completed:\n① Go\n② Perl 6\n③ Kotlin\n④ Python\n⑤ Phix\n⑥ Racket\n⑦ Perl\n⑧ C\n⑨ Julia\n⑩ Tcl\n\n```\n\nAs of 2019-01-21T22:41:28Z :: Tasks: 924 :: Draft Tasks:215 :: Total Tasks: 1139 :: Total Examples: 59984\n\n| Count | Task | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| 405 | Hello world/Text | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 283 | 99 Bottles of Beer | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 276 | FizzBuzz | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 273 | 100 doors | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 251 | Fibonacci sequence | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 246 | Comments | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 239 | Factorial | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 223 | Empty program | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 222 | A+B | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |\n| 214 | Function definition | ① | ② | ③ | ④ | ⑤ | ⑥ | ⑦ | ⑧ | ⑨ | ⑩ |" } ]
[ { "role": "user", "content": "Task\n\nFind all   <lang>   tags without a language specified in the text of a page.\n\nDisplay counts by language section:\n\n```\nDescription\n\n<lang>Pseudocode</lang>\n\n=={{header|C}}==\n<lang C>printf(\"Hello world!\\n\");</lang>\n\n=={{header|Perl}}==\n<lang>print \"Hello world!\\n\"</lang>\n\n```\n\nshould display something like\n\n```\n2 bare language tags.\n\n1 in perl\n1 in no language\n\n```\n\nExtra credit\n\nAllow multiple files to be read.   Summarize all results by language:\n\n```\n5 bare language tags.\n\n2 in c ([[Foo]], [[Bar]])\n1 in perl ([[Foo]])\n2 in no language ([[Baz]])\n\n```\n\nExtra extra credit\n\nUse the   Media Wiki API   to test actual RC tasks." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\nThe only tricky thing here is the use of the ms form of match, short for m:sigspace. This causes whitespace in the regex to be considered \"significant\", that is, it matches optional whitespace at those positions, as if you'd put \\s\\* there. Of course, the regexes themselves are in Raku syntax, which is quite different from Perl 5 regex syntax (and arguably much cleaner). Regex syntax is perhaps the area in which Raku diverges most from Perl 5.\n\n```\nmy $lang = '(no language)';\nmy $total = 0;\nmy %blanks;\n\nfor lines() {\n when / '<lang>' / {\n %blanks{$lang}++;\n $total++;\n }\n when ms/ '==' '{{' 'header' '|' ( <-[}]>+? ) '}}' '==' / {\n $lang = $0.lc;\n }\n}\n\nsay \"$total bare language tag{ 's' if $total != 1 }\\n\";\nsay .value, ' in ', .key for %blanks.sort;\n\n```\n\nOutput:\n\n```\n2 bare language tags\n\n1 in (no language)\n1 in perl\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven the name of a language on Rosetta Code, find all tasks which are not implemented in that language.\n\nNote: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code.\n\nYou'll need to use the Media Wiki API, which you can find out about locally, here, or in Media Wiki's API documentation at, API:Query" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04.1\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\nuse Sort::Naturally;\n\nunit sub MAIN( Str :$lang = 'Raku' );\n\nmy $client = HTTP::UserAgent.new;\nmy $url = 'https://rosettacode.org/w';\n\nmy @total;\nmy @impl;\n\[email protected]: .&get-cat for 'Programming_Tasks', 'Draft_Programming_Tasks';\n@impl = get-cat $lang;\n\nsay \"Unimplemented tasks in $lang:\";\nmy @unimplemented = (@total (-) @impl).keys.sort: *.&naturally;\n.say for @unimplemented;\nsay \"{+@unimplemented} unimplemented tasks\";\n\nsub get-cat ($category) {\n flat mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle(\"Category:$category\"),\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<title>\n ).map({ .<title> });\n}\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub uri-query-string (*%fields) { %fields.map({ \"{.key}={uri-escape .value}\" }).join(\"&\") }\n\n```\n\nOutput:\n\n*As of Sept. 2, 2022*\n\n```\nUnimplemented tasks in Raku:\n3d turtle graphics\n15 puzzle game in 3D\nAddition-chain exponentiation\nAudio alarm\nAudio frequency generator\nAudio overlap loop\nBinary coded decimal\nBlack box\nBlackjack strategy\nBoids\nCatmull–Clark subdivision surface\nChess player\nCLI-based maze-game\nCompare sorting algorithms' performance\nCompiler/AST interpreter\nCompiler/Preprocessor\nCompiler/syntax analyzer\nCreate an executable for a program in an interpreted language\nCross compilation\nCycles of a permutation\nDiophantine linear system solving\nDominoes\nElevator simulation\nExecute Computer/Zero\nFree polyominoes enumeration\nGeneralised floating point multiplication\nHexapawn\nHoneycombs\nIRC gateway\nMorpion solitaire\nNumber triplets game\nOLE automation\nOpenGL pixel shader\nP-Adic square roots\nPlay recorded sounds\nRed black tree sort\nRemote agent/Agent interface\nRemote agent/Agent logic\nRemote agent/Simulation\nSimple turtle graphics\nSolve a Rubik's cube\nSolving coin problems\nSorting algorithms/Tree sort on a linked list\nTamagotchi emulator\nTetris\nUkkonen’s suffix tree construction\nUnicode polynomial equation\nUno (card game)\nUse a REST API\nWaveform analysis/Top and tail\nWeather routing\nWebGL rotating F\n52 unimplemented tasks\n```" } ]
[ { "role": "user", "content": "This task has been *revised* for the hosting change Rosetta Code has had in August 2022.\n\nSee the Python example for a new example to fit the revised task.\n\nTask\n\nFix Rosetta Code deprecated code tags, with these rules:\n\n```\nChange <lang %s> to <syntaxhighlight lang=%s>\nChange </lang> to </syntaxhighlight>\nChange <lang> to <syntaxhighlight lang=text>\n\n```\n\nDemonstrate the task on these examples\n\n```\n<lang AutoHotkey>; usage: > fixtags.ahk input.txt ouput.txt\nFileRead, text, %1%\nlangs = ada,awk,autohotkey,etc\nslang = /lang\nslang := \"<\" . slang . \"/>\"\nLoop, Parse, langs, `,\n{\n tag1 = <%A_LoopField%>\n tag2 = </%A_LoopField%>\n text := RegExReplace(text, tag1, \"<lang \" . A_LoopField . \">\")\n text := RegExReplace(text, tag2, slang)\n text := RegExReplace(text, \"<code (.+?)>(.*?)</code>\"\n , \"<lang $1>$2\" . slang)\n}\nFileAppend, % text, %2%\n</lang>\n\n```\n\n```\n<lang perl>my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog\nhtml4strict cil objc asm progress teraterm hq9plus genero tsql\nemail pic16 tcl apt_sources io apache vhdl avisynth winbatch\nvbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf\ncobol powershell php kixtart visualfoxpro mirc make javascript\ncpp sdlbasic cadlisp php-brief rails verilog xml csharp\nactionscript nsis bash typoscript freebasic dot applescript\nhaskell dos oracle8 cfdg glsl lotusscript mpasm latex sql klonec\nruby ocaml smarty python oracle11 caddcl robots groovy smalltalk\ndiff fortran cfm lua modula3 vb autoit java text scala\nlotusformulas pixelbender reg _div whitespace providex asp css\nlolcode lisp inno mysql plsql matlab oobas vim delphi xorg_conf\ngml prolog bf per scheme mxml d basic4gl m68k gnuplot idl abap\nintercal c_mac thinbasic java5 xpp boo klonecpp blitzbasic eiffel\npovray c gettext);\n\nmy $text = join \"\", <STDIN>;\nmy $slang=\"/lang\";\nfor (@langs) {\n $text =~ s|<$_>|<lang $_>|g;\n $text =~ s|</$_>|<$slang>|g;\n}\n\n$text =~ s|<code (.+?)>(.*?)</code>|<lang $1>$2<$slang>|sg;\n\nprint $text;</lang>\n\n```\n\n```\n<lang>HAI 1.3\n\nI HAS A bottles ITZ 99 I HAS A plural ITZ \"Z\" I HAS A lyric ITZ \"99 BOTTLZ OV BEER\"\n\nIM IN YR song\n\n VISIBLE lyric \" ON TEH WALL\"\n VISIBLE lyric\n VISIBLE \"TAEK 1 DOWN, PAZ IT AROUN\"\n bottles R DIFF OF bottles AN 1\n NOT bottles, O RLY?\n YA RLY, VISIBLE \"NO MOAR BOTTLZ OV BEER ON TEH WALL\", GTFO\n OIC\n BOTH SAEM bottles AN 1, O RLY?\n YA RLY, plural R \"\"\n OIC\n lyric R SMOOSH bottles \" BOTTL\" plural \" OV BEER\" MKAY\n VISIBLE lyric \" ON TEH WALL:)\"\nIM OUTTA YR song\n\nKTHXBYE</lang>\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @langs = <\n abap actionscript actionscript3 ada apache applescript apt_sources\n asm asp autoit avisynth bash basic4gl bf blitzbasic bnf boo c caddcl\n cadlisp cfdg cfm cil c_mac cobol cpp cpp-qt csharp css d delphi\n diff _div dos dot eiffel email fortran freebasic genero gettext\n glsl gml gnuplot groovy haskell hq9plus html4strict idl ini inno\n intercal io java java5 javascript kixtart klonec klonecpp latex lisp\n lolcode lotusformulas lotusscript lscript lua m68k make matlab mirc\n modula3 mpasm mxml mysql nsis objc ocaml ocaml-brief oobas oracle11\n oracle8 pascal per perl php php-brief pic16 pixelbender plsql povray\n powershell progress prolog providex python qbasic rails reg robots\n ruby sas scala scheme scilab sdlbasic smalltalk smarty sql tcl teraterm\n text thinbasic tsql typoscript vb vbnet verilog vhdl vim visualfoxpro\n visualprolog whitespace winbatch xml xorg_conf xpp z80\n>;\n\n$_ = slurp;\n\nfor @langs -> $l {\n s:g:i [ '<' 'lang '? $l '>' ] = \"<lang $l>\";\n s:g [ '</' $l '>' ] = '</' ~ 'lang>';\n}\n\ns:g [ '<code '(.+?) '>' (.*?) '</code>' ] = \"<lang $0>{$1}</\"~\"lang>\";\n\n.say;\n\n```\n\n```\nuse v6;\n\nconstant @langs = < abap actionscript actionscript3 ada … >;\n\nslurp().subst(\n rx:r{\n | '<' <( $<need-add-space>=<?> )> @langs '>'\n | '</' <( @langs )> '>'\n | '<' '/'? <( code )> [<.ws> @langs]? '>'\n },\n 'lang' ~ \" \" x *<need-add-space>.so,\n  :g,\n).print\n\n```" } ]
[ { "role": "user", "content": "In this task, the goal is to compile an authorship list for task descriptions. A pseudocode example (in imperative style) that should accomplish this is as follows:\n\n```\nfor each task page\n grab page source, discard everything after the first ==section==.\nCache as $previous. Note $author.\n for each revision\n grab page source, discard everything after first ==section==.\nCache as $previous2. Note $author2\n compare $previous2 to $previous. If different, record $author to $list.\n replace $previous with $previous2\n replace $author with $author2\n```\n\nThe following resources for HTTP interface information for MediaWiki may prove to be useful:\n\n* https://www.mediawiki.org/wiki/Index.php#Raw\n* https://www.mediawiki.org/wiki/Index.php#History\n* https://www.mediawiki.org/wiki/API:Main\\_page\n\nConversely, some languages have libraries which abstract these interfaces into language-native idioms. Use of these abstractions is perfectly fine.\n\nPlease **DO NOT** add a full output for *each* programming language; just show a representative sample. For an full listing, see Rosetta\\_Code/List\\_authors\\_of\\_task\\_descriptions/Full\\_list." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nThe pseudocode above is no longer really useful as the page format has changed significantly since this task was written. Rather than checking **every** edit to see if it was a change to the task description, we'll just assume the user that created the page is the task author. This isn't 100% accurate; a very few pages got renamed and recreated by someone other than the original author without preserving the history, so they are misreported (15 Puzzle Game for instance,) but is as good as it is likely to get without extensive manual intervention. Subsequent edits to the task description are not credited. As it is, we must still make *thousands* of requests and pound the server pretty hard. Checking **every** edit would make the task several of orders of magnitude more abusive of the server (and my internet connection.)\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\nuse Sort::Naturally;\n\n# Friendlier descriptions for task categories\nmy %cat = (\n 'Programming_Tasks' => 'Task',\n 'Draft_Programming_Tasks' => 'Draft'\n);\n\nmy $client = HTTP::UserAgent.new;\n\nmy $url = 'https://rosettacode.org/w';\n\nmy $tablefile = './RC_Authors.txt';\nmy $hashfile = './RC_Authors.json';\n\nmy %tasks;\n\n# clear screen\nrun($*DISTRO.is-win ?? 'cls' !! 'clear');\n\n%tasks = $hashfile.IO.e ?? $hashfile.IO.slurp.&from-json !! ( );\nsleep 1;\n\n#=begin update\n\nnote 'Retrieving task information...';\n\nmy %filter;\nfor %cat.keys.sort -> $category {\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle(\"Category:$category\"),\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<title>\n ).map( { %filter{.<title>} = %cat{$category} } )\n}\n\nmy $delete = %tasks.keys (-) %filter.keys;\n\n%tasks.delete($_) for $delete.keys; #Tasks that have changed names or been removed\n\nmy @add;\nfor %filter.keys -> $title {\n if %tasks{$title}:exists {\n %tasks{$title}<category> = %filter{$title} # update status\n } else {\n @add.push: $title => %filter{$title} # New Tasks\n }\n}\n\nif @add {\n .say for 'Adding new tasks:', |@add;\n}\n\nfor @add -> $task {\n mediawiki-query(\n $url, 'pages',\n  :titles($task.key),\n  :prop<revisions>,\n  :rvprop<user|timestamp>,\n  :rvstart<2000-01-01T01:01:01Z>,\n  :rvdir<newer>,\n  :rvlimit<1>\n ).map: {\n print clear, 1 + $++, ' ', .[0]<title>;\n %tasks{.[0]<title>}<category> = $task.value;\n %tasks{.[0]<title>}<author> = .[0]<revisions>[0]<user>;\n %tasks{.[0]<title>}<date> = .[0]<revisions>[0]<timestamp>.subst(/'T'.+$/, '')\n }\n}\n\nprint clear;\n\n# Save information to a local file\nnote \"\\nTask information saved to local file: {$hashfile.IO.absolute}\";\n$hashfile.IO.spurt(%tasks.&to-json);\n\n#=end update\n\n# Load information from local file\n%tasks = $hashfile.IO.e ?? $hashfile.IO.slurp.&from-json !! ( );\n\n# Convert saved task / author info to a table\nnote \"\\nBuilding table...\";\nmy $count = +%tasks;\nmy $taskcnt = +%tasks.grep: *.value.<category> eq %cat<Programming_Tasks>;\nmy $draftcnt = $count - $taskcnt;\n\n# Open a file handle to dump table in\nmy $out = open($tablefile, :w) or die \"$!\\n\";\n\n# Add table boilerplate and header\n$out.say:\n \"\\{|class=\\\"wikitable sortable\\\"\\n\",\n \"|+ As of { Date.today } :: Total Tasks: { $count }:: Tasks: { $taskcnt }\",\n \" ::<span style=\\\"background-color:#ffd\\\"> Draft Tasks: { $draftcnt } </span>\",\n \":: By {+%tasks{*}».<author>.unique} Authors\\n\",\n \"! Author !! Tasks !! Authored\"\n;\n\n# Get sorted unique list of task authors\nfor %tasks{*}».<author>.unique.sort(&naturally) -> $author {\n\n # Get list of tasks by this author\n my @these = %tasks.grep( { $_.value.<author> eq $author } );\n my $s = +@these == 1 ?? '' !! 's';\n\n # Add author and contributions link to the first two cells\n $out.say:\n $author ~~ /\\d/\n  ?? \"|- id=\\\"$author\\\"\\n|data-sort-value=\\\"{ sort-key $author }\\\"|[[User:$author|$author]]\\n\"~\n \"|data-sort-value=\\\"{ +@these }\\\"|[[Special:Contributions/$author|\"~\n \"{ +@these } task{ $s }]]\"\n  !! \"|- id=\\\"$author\\\"\\n|[[User:$author|$author]]\\n\"~\n \"|data-sort-value=\\\"{ +@these }\\\"|[[Special:Contributions/$author|\"~\n \"{ +@these } task{ $s }]]\"\n  ;\n\n if +@these > 2 {\n $out.say: \"|style=\\\"padding: 0px;\\\"|\\n\",\n \"\\{|class=\\\"broadtable sortable\\\" style=\\\"width: 100%;\\\"\\n\",\n \"! Task Name !! Date Added !! Status\";\n }\n else {\n $out.say: \"|style=\\\"padding: 0px;\\\"|\\n\",\n \"\\{|class=\\\"broadtable\\\" style=\\\"width: 100%;\\\"\";\n }\n\n # Tasks by this author, sorted by name\n for @these.sort({.key.&naturally}) -> $task {\n\n my $color = $task.value.<category> eq 'Draft' ?? '#ffd' !! '#fff';\n\n # add the task link, date and status to the table in the second cell\n $out.say: \"|-\\n|style=\\\"background-color: $color;\\\"\",\n ( $task.key ~~ /\\d/\n  ?? \" data-sort-value=\\\"{ sort-key $task.key }\\\"| [[{uri-escape $task.key}|{$task.key}]]\\n\"\n  !! \"| [[{uri-escape $task.key}|{$task.key}]]\\n\"\n ),\n \"|style=\\\"width: 10em; background-color: $color;\\\"| {$task.value.<date>}\\n\",\n \"|style=\\\"width: 6em; background-color: $color;\\\"| {$task.value.<category>}\",\n }\n $out.say: '|}'\n}\n$out.say( \"|}\\n\" );\n$out.close;\n\n\nnote \"Table file saved as: {$tablefile.IO.absolute}\";\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub uri-query-string (*%fields) { %fields.map({ \"{.key}={uri-escape .value}\" }).join(\"&\") }\n\nsub sort-key ($a) { $a.lc.subst(/(\\d+)/, ->$/ {0~(65+($0.chars)).chr~$0},:g) }\n\nsub clear { \"\\r\" ~ ' ' x 100 ~ \"\\r\" }\n\n```\n\nSample output:\n\nSee full output at Rosetta\\_Code/List\\_authors\\_of\\_task\\_descriptions/Full\\_list\n\nAs of 2018-04-10 :: Total Tasks: 1080:: Tasks: 871 :: Draft Tasks: 209 :: By 251 Authors\n\n| Author | Tasks | Authored |\n| --- | --- | --- |\n| 2Powers | 2 tasks | | | | | | --- | --- | --- | | Names to numbers | 2013-05-16 | Draft | | Solving coin problems | 2013-05-16 | Draft | |\n| 12.175.32.19 | 1 task | | | | | | --- | --- | --- | | Soundex | 2009-11-12 | Task | |\n| 12Me21 | 1 task | | | | | | --- | --- | --- | | Draw a rotating cube | 2015-05-04 | Task | |\n| many rows omitted... | | |\n| Zorro1024 | 2 tasks | | | | | | --- | --- | --- | | Perfect shuffle | 2015-04-16 | Task | | Vector | 2015-03-21 | Draft | |\n| Zzo38 | 1 task | | | | | | --- | --- | --- | | Thue-Morse | 2015-09-20 | Task | |\n| Русский | 3 tasks | | Task Name | Date Added | Status | | --- | --- | --- | | Main step of GOST 28147-89 | 2012-08-31 | Task | | Old Russian measure of length | 2013-01-09 | Draft | | Transportation problem | 2013-05-24 | Draft | |" } ]
[ { "role": "user", "content": "Task\n\nSort most popular programming languages based on the number of users on Rosetta Code.\n\nShow the languages with at least 100 users.\n\nA method to solve the task\n\nUsers of a computer programming language   **X**   are those referenced in the page:\n\n```\n https://rosettacode.org/wiki/Category:X_User, or preferably: \n https://rosettacode.org/mw/index.php?title=Category:X_User&redirect=no to avoid re-directions. \n\n```\n\nIn order to find the list of such categories,   it's possible to first parse the entries of:\n\n```\n http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000. \n\n```\n\nThen download and parse each computer language   *users*   category to find the number of users of that computer language.\n\nSample output on 18 February 2019:\n\n```\nLanguage Users\n--------------------------\nC 391\nJava 276\nC++ 275\nPython 262\nJavaScript 238\nPerl 171\nPHP 167\nSQL 138\nUNIX Shell 131\nBASIC 120\nC sharp 118\nPascal 116\nHaskell 102\n```\n\nA Rosetta Code user usually declares using a language with the mylang template. This template is expected to appear on the User page. However, in some cases it appears in a user Talk page. It's not necessary to take this into account. For instance, among the 373 C users in the table above, 3 are actually declared in a Talk page." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.11\n\nUse the mediawiki API rather than web scraping since it is much faster and less resource intensive. Show languages with more than 25 users since that is still a pretty short list and to demonstrate how tied rankings are handled. Change the **$minimum** parameter to adjust what the cut-off point will be.\n\nThis is all done in a single pass; ties are not detected until a language has the same count as a previous one, so ties are marked by a **T** next to the count indicating that **this** language has the same count as the **previous**.\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\n\nmy $client = HTTP::UserAgent.new;\n\nmy $url = 'https://rosettacode.org/w';\n\nmy $start-time = now;\n\nsay \"========= Generated: { DateTime.new(time) } =========\";\n\nmy $lang = 1;\nmy $rank = 0;\nmy $last = 0;\nmy $tie = ' ';\nmy $minimum = 25;\n\n.say for\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle<Category:Language users>,\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<categoryinfo>\n )\n\n .map({ %( count => .<categoryinfo><pages> || 0,\n lang => .<title>.subst(/^'Category:' (.+) ' User'/, ->$/ {$0}) ) })\n\n .sort( { -.<count>, .<syntaxhighlight lang=\"text\"> } )\n\n .map( { last if .<count> < $minimum; display(.<count>, .<syntaxhighlight lang=\"text\">) } );\n\nsay \"========= elapsed: {(now - $start-time).round(.01)} seconds =========\";\n\nsub display ($count, $which) {\n if $last != $count { $last = $count; $rank = $lang; $tie = ' ' } else { $tie = 'T' };\n sprintf \"#%3d Rank: %2d %s with %-4s users: %s\", $lang++, $rank, $tie, $count, $which;\n}\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub uri-query-string (*%fields) {\n join '&', %fields.map: { \"{.key}={uri-escape .value}\" }\n}\n\n```\n\nOutput:\n\n```\n========= Generated: 2022-09-02T20:59:20Z =========\n# 1 Rank: 1 with 441 users: C\n# 2 Rank: 2 with 321 users: Java\n# 3 Rank: 3 with 319 users: Python\n# 4 Rank: 4 with 314 users: C++\n# 5 Rank: 5 with 291 users: JavaScript\n# 6 Rank: 6 with 190 users: PHP\n# 7 Rank: 7 with 186 users: Perl\n# 8 Rank: 8 with 167 users: SQL\n# 9 Rank: 9 with 151 users: UNIX Shell\n# 10 Rank: 10 with 133 users: Pascal\n# 11 Rank: 11 with 132 users: BASIC\n# 12 Rank: 11 T with 132 users: C sharp\n# 13 Rank: 13 with 115 users: Haskell\n# 14 Rank: 14 with 107 users: Ruby\n# 15 Rank: 15 with 94 users: Fortran\n# 16 Rank: 16 with 75 users: Visual Basic\n# 17 Rank: 17 with 72 users: Scheme\n# 18 Rank: 18 with 70 users: Prolog\n# 19 Rank: 19 with 68 users: AWK\n# 20 Rank: 19 T with 68 users: Lua\n# 21 Rank: 21 with 66 users: Common Lisp\n# 22 Rank: 22 with 61 users: HTML\n# 23 Rank: 23 with 55 users: X86 Assembly\n# 24 Rank: 24 with 50 users: Forth\n# 25 Rank: 25 with 49 users: Batch File\n# 26 Rank: 26 with 47 users: Assembly\n# 27 Rank: 27 with 45 users: Bash\n# 28 Rank: 27 T with 45 users: MATLAB\n# 29 Rank: 29 with 42 users: Lisp\n# 30 Rank: 30 with 41 users: APL\n# 31 Rank: 30 T with 41 users: Erlang\n# 32 Rank: 32 with 40 users: Delphi\n# 33 Rank: 32 T with 40 users: R\n# 34 Rank: 34 with 39 users: J\n# 35 Rank: 34 T with 39 users: Visual Basic .NET\n# 36 Rank: 36 with 38 users: Go\n# 37 Rank: 36 T with 38 users: Tcl\n# 38 Rank: 38 with 37 users: COBOL\n# 39 Rank: 39 with 36 users: Smalltalk\n# 40 Rank: 40 with 35 users: Brainf***\n# 41 Rank: 40 T with 35 users: Objective-C\n# 42 Rank: 42 with 34 users: Clojure\n# 43 Rank: 43 with 33 users: Mathematica\n# 44 Rank: 44 with 30 users: OCaml\n# 45 Rank: 45 with 28 users: LaTeX\n# 46 Rank: 46 with 27 users: AutoHotkey\n# 47 Rank: 46 T with 27 users: Emacs Lisp\n# 48 Rank: 46 T with 27 users: PostScript\n# 49 Rank: 46 T with 27 users: REXX\n# 50 Rank: 50 with 26 users: Perl 6\n# 51 Rank: 50 T with 26 users: Sed\n# 52 Rank: 52 with 25 users: CSS\n# 53 Rank: 52 T with 25 users: Scala\n# 54 Rank: 52 T with 25 users: VBScript\n========= elapsed: 1.48 seconds =========\n\n========= elapsed: 1.45 seconds =========\n```" } ]
[ { "role": "user", "content": "Task\n\nSort the most popular computer programming languages based in number of members in Rosetta Code categories.\n\nSample output on 02 August 2022 at 09:50 +02\n\n```\nRank: 1 (1,565 entries) Phix\nRank: 2 (1,558 entries) Wren\nRank: 3 (1,531 entries) Julia\nRank: 4 (1,507 entries) Raku\nRank: 5 (1,500 entries) Go\nRank: 6 (1,466 entries) Perl\nRank: 7 (1,409 entries) Python\nRank: 8 (1,402 entries) Nim\nRank: 9 (1,254 entries) J\nRank: 10 (1,211 entries) C\n...\n```\n\nNotes\n\n* Each language typically demonstrates one or two methods of accessing the data:\n\n: : : * with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)\n * with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).\n\n* The scraping and API solutions can be separate subsections, see the Tcl example.\n* Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping)\n\n: : If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all **971** programming languages, updated periodically, *typically weekly*.\n\n* A complete ranked listing of all   **813**   languages (from the REXX example) is included here   ──►   output from the REXX program." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Raku: Using the API\n\nNote that this counts **only** the tasks. It does not include other non-task categories in the counts yielding more realistic, non-inflated numbers. Raku is Unicode aware and handles non-ASCII names natively. This does not attempt to 'unify' different language names that are the same behind the scenes as a result of Rosettacodes' capitalization peculiarities. (E.G. μC++, UC++ & ΜC++)\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\nuse Sort::Naturally;\n\nmy $client = HTTP::UserAgent.new;\n\nmy $url = 'https://rosettacode.org/w';\n\nmy $tablefile = './RC_Popularity.txt';\n\nmy %cat = (\n 'Programming_Tasks' => 'Task',\n 'Draft_Programming_Tasks' => 'Draft'\n);\nmy %tasks;\n\nfor %cat.keys.sort -> $cat {\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle(\"Category:$cat\"),\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<title>\n ).map({ %tasks{%cat{$cat}}++ });\n}\n\nmy %counts =\n mediawiki-query(\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle<Category:Programming Languages>,\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<categoryinfo>\n )\n .map({\n my $title = .<title>.subst(/^'Category:'/, '');\n my $tasks = (.<categoryinfo><pages> || 0);\n my $categories = (.<categoryinfo><subcats> || 0);\n my $total = (.<categoryinfo><size> || 0);\n $title => [$tasks ,$categories, $total]\n });\n\nmy $out = open($tablefile, :w) or die \"$!\\n\";\n\n# Add table boilerplate and header\n$out.say:\n \"\\{|class=\\\"wikitable sortable\\\"\\n\",\n \"|+ As of { Date.today } :: {+%counts} Languages\\n\",\n '!Rank!!Language!!Task<br>Entries!!Tasks<br>done %!!Non-task<br>Subcate-<br>gories!!Total<br>Categories'\n;\n\nmy @bg = <#fff; #ccc;>;\nmy $ff = 0;\nmy $rank = 1;\nmy $ties = 0;\n\n# Get sorted unique task counts\nfor %counts.values»[0].unique.sort: -* -> $count {\n $ff++;\n # Get list of tasks with this count\n my @these = %counts.grep( *.value[0] == $count )».keys.sort: *.&naturally;\n\n for @these {\n $ties++;\n $out.say:\n \"|- style=\\\"background-color: { @bg[$ff % 2] }\\\"\\n\"~\n \"|$rank\\n\"~\n \"|[[:Category:$_|]]\\n\"~\n \"|$count\\n\"~\n \"|{(100 * $count/%tasks<Draft Task>.sum).round(.01)} %\\n\"~\n \"|{%counts{$_}[1]}\\n\"~\n \"|{%counts{$_}[2]}\"\n }\n $rank += $ties;\n $ties = 0;\n}\n$out.say( \"|}\" );\n$out.say('=' x 5, \" query, download & processing: {(now - INIT now).round(.01)} seconds \", '=' x 5);\n$out.close;\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub uri-query-string (*%fields) {\n join '&', %fields.map: { \"{.key}={uri-escape .value}\" }\n}\n\n```\n\nAbridged output:\n\nSee full output here.\n\nAs of 2019-02-10 :: 715 Languages\n\n| Rank | Language | Task Entries | Tasks done % | Non-task Subcate- gories | Total Categories |\n| --- | --- | --- | --- | --- | --- |\n| 1 | Go | 1100 | 96.15 % | 4 | 1104 |\n| 2 | Perl 6 | 1046 | 91.43 % | 4 | 1050 |\n| 3 | Kotlin | 1029 | 89.95 % | 1 | 1030 |\n| 4 | Python | 1017 | 88.9 % | 17 | 1034 |\n| 5 | Phix | 991 | 86.63 % | 3 | 994 |\n| 6 | Racket | 986 | 86.19 % | 3 | 989 |\n| 7 | Perl | 963 | 84.18 % | 5 | 968 |\n| 8 | Julia | 958 | 83.74 % | 3 | 961 |\n| 9 | C | 940 | 82.17 % | 3 | 943 |\n| 10 | Tcl | 925 | 80.86 % | 4 | 929 |\n| 11 | Zkl | 918 | 80.24 % | 1 | 919 |\n| 12 | J | 901 | 78.76 % | 3 | 904 |\n| 13 | Java | 897 | 78.41 % | 3 | 900 |\n| 14 | REXX | 886 | 77.45 % | 4 | 890 |\n| 15 | D | 871 | 76.14 % | 3 | 874 |\n| 16 | Ruby | 866 | 75.7 % | 3 | 869 |\n| 17 | Haskell | 849 | 74.21 % | 3 | 852 |\n| 18 | Scala | 789 | 68.97 % | 3 | 792 |\n| 19 | Sidef | 787 | 68.79 % | 1 | 788 |\n| 20 | PicoLisp | 772 | 67.48 % | 3 | 775 |\n\n### Raku: Using web scraping\n\nScraping the languages and categories pages. Raku automatically handles Unicode names correctly.\n\n```\nmy $languages = qx{wget -O - 'http://rosettacode.org/wiki/Category:Programming_Languages'};\nmy $categories = qx{wget -O - 'http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000'};\n \nmy @lines = $languages.lines;\nshift @lines until @lines[0] ~~ / '<h2>Subcategories</h2>' /;\nmy \\languages = set gather for @lines {\n last if / '/bodycontent' /;\n take ~$0 if\n / '<li><a href=\"/wiki/Category:' .*? '\" title=\"Category:' .*? '\">' (.*?) '</a></li>' /;\n}\n \n@lines = $categories.lines;\nmy @results = sort -*.[0], gather for @lines {\n take [+$1.subst(',', ''), ~$0] if\n / '<li><a href=\"/wiki/Category:' .*? '\" title=\"Category:' .*? '\">'\n (.*?) <?{ ~$0 ∈ languages }>\n '</a>' .*? '(' (<[, 0..9]>+) ' member' /;\n}\n \nfor @results.kv -> $i, @l {\n printf \"%d:\\t%4d - %s\\n\", $i+1, |@l;\n}\n\n```\n\nOutput:\n\n(As of 2018-10-28) Here we show only the top 10.\n\n```\n1:\t1036 - Go\n2:\t1029 - Kotlin\n3:\t1014 - Python\n4:\t 998 - Perl 6\n5:\t 980 - Racket\n6:\t 929 - Tcl\n7:\t 926 - C\n8:\t 910 - Perl\n9:\t 904 - Zkl\n10:\t 901 - J\n```" } ]
[ { "role": "user", "content": "This task is based on an idea hatched from this C1R Implementation.\n\nWrite a program that will accept as input the name of a task from Rosetta Code and the name of a language. The program should then download the solution for the specified task in the specified language, present the source to the user and prompt the user to confirm running the example.\n\nThe program should verify that the tools needed to compile or run the solution are present before running it.\nIf the solution can not be run, a graceful exit should happen. (i.e. the program should not crash)\n\nBesides its own language, the program should support at least two other languages. (Ideally it would support most of the languages available, but that is too much to ask. Though some languages are simple, e.g. python, pike, perl, bash and several more only need the solution saved in a file and given to the language as argument to run, so it should be easy to support many languages like that).\n\nIf you know what is needed to support a particular language, please help to add support for that language to implementations in other languages.\n\nExtra credit: add a function to get a list of all solutions of a given language and run them to create a report on which solutions failed to run.\n\nMore credit: also test if the output of a solution compares to a given result. The expected output should be loaded from a file with the name of the task. (This way all implementations can share the same set of files, and anyone can add more files. In the future the content of these files could be stored directly in a section of the task on Rosetta Code itself.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nThis is a fairly comprehensive task code runner. It is set up to work for Raku by default, but has basic configurations to run Perl, Python, Tcl and Go tasks as well. It can be easily tweaked to work with other languages by adding a load-lang('whatever'){} routine similar to the Raku, Perl, Python, Tcl and Go ones. (And ensuring that the appropriate compiler is installed and accessible.) There is so much variation to the task requirements and calling conventions that it would be problematic to make a general purpose, language agnostic code runner so some configuration is necessary to make it work with other languages.\n\n(Note that there is no dependency download code nor resource hash for Python and Go, though they can run a remarkable number of tasks without.)\n\nBy default, this will download the Raku section of any (every) task that has a Raku example, extract the code blocks and attempt to run them. Many tasks require files or user interaction to proceed, others are not complete runnable code blocks (example code fragments), some tasks run forever. To try to deal with and compensate for this, this implementation can load a %resource hash that will: supply input files where necessary, skip unrunnable code fragments, limit long and/or infinite running blocks, supply user interaction code where possible, and skip blocks where user interaction is unavoidable.\n\nThere are several command line options to control its actions. See the README in the repository for details.\n\nThe complete implementation is too large and cumbersome to post in it's entirety here, only the main task retrieval and execution code is included.\n\nFor the whole ball of wax see the rc-run github repository.\n\nRun with no parameters to run every implemented task on Rosetta Code. Feed it a task name to only download / run that task. Give it command line switches to adjust its behaviour.\n\nNote: This is set up to run under Linux. It could be adapted for Windows (or OSX I suppose) fairly easily but I don't have access to those OSs, nor do I care to seek it.\n\n```\nuse HTTP::UserAgent;\nuse URI::Escape;\nuse JSON::Fast;\nuse Text::Levenshtein::Damerau;\nuse MONKEY-SEE-NO-EVAL;\n\n#####################################\nsay \"Version = 2020-03-15T12:15:31\";\n#####################################\n\nsleep 1;\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nunit sub MAIN(\n Str $run = '', #= Task or file name\n Str :$lang = 'raku', #= Language, default raku - used to load configuration settings\n Int :$skip = 0, #= Skip # to continue partially into a list\n Bool :f(:$force), #= Override any task skip parameter in %resource hash\n Bool :l(:$local), #= Only use code from local cache\n Bool :r(:$remote), #= Only use code from remote server (refresh local cache)\n Bool :q(:$quiet), #= Less verbose, don't display source code\n Bool :d(:$deps), #= Load dependencies\n Bool :p(:$pause), #= pause after each task\n Bool :b(:$broken), #= pause after each task which is broken or fails in some way\n Int  :$sleep = 0, #= sleep for $sleep after each task\n Bool :t(:$timer), #= save timing data for each task\n);\n\ndie 'You can select local or remote, but not both...' if $local && $remote;\n\n## INITIALIZATION\n\nmy $client = HTTP::UserAgent.new;\nmy $url = 'https://rosettacode.org/w';\n\nmy %c = ( # text colors\n code => \"\\e[0;92m\", # green\n delim => \"\\e[0;93m\", # yellow\n cmd => \"\\e[1;96m\", # cyan\n bad => \"\\e[0;91m\", # red\n warn => \"\\e[38;2;255;155;0m\", # orange\n dep => \"\\e[38;2;248;24;148m\", # pink\n clr => \"\\e[0m\", # clear formatting\n);\n\nmy $view = 'xdg-open'; # image viewer, this will open default under Linux\nmy %l = load-lang($lang); # load language parameters\nmy %resource = load-resources($lang);\nmy $get-tasks = True;\n\nmy @tasks;\n\nrun('clear');\n\n## FIGURE OUT WHICH TASKS TO RUN\n\nif $run {\n if $run.IO.e and $run.IO.f {# is it a file?\n @tasks = $run.IO.lines; # yep, treat each line as a task name\n } else { # must be a single task name\n @tasks = ($run); # treat it so\n }\n $get-tasks = False; # don't need to retrieve task names from web\n}\n\nif $get-tasks { # load tasks from web if cache is not found, older than one day or forced\n if !\"%l<dir>.tasks\".IO.e or (now - \"%l<dir>.tasks\".IO.modified) > 86400 or $remote {\n note 'Retrieving task list from site.';\n @tasks = mediawiki-query( # get tasks from web\n $url, 'pages',\n  :generator<categorymembers>,\n  :gcmtitle(\"Category:%l<language>\"),\n  :gcmlimit<350>,\n  :rawcontinue(),\n  :prop<title>\n )»<title>.grep( * !~~ /^'Category:'/ ).sort;\n \"%l<dir>.tasks\".IO.spurt: @tasks.sort.join(\"\\n\");\n } else {\n note 'Using cached task list.';\n @tasks = \"%l<dir>.tasks\".IO.slurp.lines; # load tasks from file\n }\n}\n\nmy $tfile;\nif $timer {\n $tfile = open :w, \"{$lang}-time.txt\";\n $tfile.close;\n}\n\nnote \"Skipping first $skip tasks...\" if $skip;\nmy $redo;\n\n## MAIN LOOP\n\nfor @tasks -> $title {\n $redo = False;\n next if $++ < $skip;\n next unless $title ~~ /\\S/; # filter blank lines (from files)\n say my $tasknum = $skip + ++$, \") $title\";\n\n my $name = $title.subst(/<-[-0..9A..Za..z]>/, '_', :g);\n my $taskdir = \"./rc/%l<dir>/$name\";\n\n my $modified = \"$taskdir/$name.txt\".IO.e ?? \"$taskdir/$name.txt\".IO.modified !! 0;\n\n my $entry;\n if $remote or !\"$taskdir/$name.txt\".IO.e or ((now - $modified) > 86400 * 7) {\n my $page = $client.get(\"{ $url }/index.php?title={ uri-escape $title }&action=raw\").content;\n\n uh-oh(\"Whoops, can't find page: $url/$title :check spelling.\\n\\n{fuzzy-search($title)}\", 'warn')\n and next if $page.elems == 0;\n say \"Getting code from: https://rosettacode.org/wiki/{ $title.subst(' ', '_', :g) }#%l<language>\";\n\n $entry = $page.comb(rx:i/'=={{header|' $(%l<header>) '}}==' .+? [<?before \\n'=='<-[={]>*'{{header'> || $] /).Str //\n uh-oh(\"No code found\\nMay be bad markup\", 'warn');\n\n if $entry ~~ /^^ 'See [[' (.+?) '/' $(%l<language>) / { # no code on main page, check sub page\n $entry = $client.get(\"{ $url }/index.php?title={ uri-escape $/[0].Str ~ '/' ~ %l<language> }&action=raw\").content;\n }\n mkdir $taskdir unless $taskdir.IO.d;\n spurt( \"$taskdir/$name.txt\", $entry );\n } else {\n if \"$taskdir/$name.txt\".IO.e {\n $entry = \"$taskdir/$name.txt\".IO.slurp;\n say \"Loading code from: $taskdir/$name.txt\";\n } else {\n uh-oh(\"Task code $taskdir/$name.txt not found, check spelling or run remote.\", 'warn');\n next;\n }\n }\n\n my @blocks = $entry.comb: %l<tag>;\n\n unless @blocks {\n uh-oh(\"No code found\\nMay be bad markup\", 'warn') unless %resource{\"$name\"}<skip> ~~ /'ok to skip'/;\n say \"Skipping $name: \", %resource{\"$name\"}<skip>, \"\\n\" if %resource{\"$name\"}<skip>\n }\n\n for @blocks.kv -> $k, $v {\n my $n = +@blocks == 1 ?? '' !! $k;\n spurt( \"$taskdir/$name$n%l<ext>\", $v );\n if %resource{\"$name$n\"}<skip> && !$force {\n dump-code (\"$taskdir/$name$n%l<ext>\");\n if %resource{\"$name$n\"}<skip> ~~ /'broken'/ {\n uh-oh(%resource{\"$name$n\"}<skip>, 'bad');\n pause if $broken;\n } else {\n say \"{%c<warn>}Skipping $name$n: \", %resource{\"$name$n\"}<skip>, \"{%c<clr>}\\n\";\n }\n next;\n }\n say \"\\nTesting $name$n\";\n run-it($taskdir, \"$name$n\", $tasknum);\n }\n say %c<delim>, '=' x 79, %c<clr>;\n redo if $redo;\n sleep $sleep if $sleep;\n pause if $pause;\n}\n\n## SUBROUTINES\n\nsub mediawiki-query ($site, $type, *%query) {\n my $url = \"$site/api.php?\" ~ uri-query-string(\n  :action<query>, :format<json>, :formatversion<2>, |%query);\n my $continue = '';\n\n gather loop {\n my $response = $client.get(\"$url&$continue\");\n my $data = from-json($response.content);\n take $_ for $data.<query>.{$type}.values;\n $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);\n }\n}\n\nsub run-it ($dir, $code, $tasknum) {\n my $current = $*CWD;\n chdir $dir;\n if %resource{$code}<file> -> $fn {\n copy \"$current/rc/resources/{$_}\", \"./{$_}\" for $fn[]\n }\n dump-code (\"$code%l<ext>\") unless $quiet;\n check-dependencies(\"$code%l<ext>\", $lang) if $deps;\n my @cmd = %resource{$code}<cmd> ?? |%resource{$code}<cmd> !! \"%l<exe> $code%l<ext>\\n\";\n if $timer {\n $tfile = open :a, \"{$current}/{$lang}-time.txt\";\n }\n my $time = 'NA: not run or killed before completion';\n for @cmd -> $cmd {\n say \"\\nCommand line: {%c<cmd>}$cmd\",%c<clr>;\n if $timer { $tfile.say: \"Command line: $cmd\".chomp }\n my $start = now;\n try shell $cmd;\n $time = (now - $start).round(.001);\n CATCH {\n when /'exit code: 137'/ { }\n default {\n .resume unless $broken;\n uh-oh($_, 'bad');\n if %resource{$code}<fail-by-design> {\n say %c<warn>, 'Fails by design, (or at least, it\\'s not unexpected).', %c<clr>;\n } else {\n if pause.lc eq 'r' {\n unlink \"$code.txt\";\n $redo = True;\n }\n }\n }\n }\n if $timer { $tfile.say(\"#$tasknum - Wallclock seconds: $time\\n\") }\n }\n chdir $current;\n say \"\\nDone task #$tasknum: $code - wallclock seconds: $time\\e[?25h\";\n $tfile.close if $timer;\n}\n\nsub pause {\n prompt \"Press enter to procede:> \";\n # or\n # sleep 5;\n}\n\nsub dump-code ($fn) {\n say \"\\n\", %c<delim>, ('vvvvvvvv' xx 7).join(' CODE '), %c<clr>, \"\\n\", %c<code>;\n print $fn.IO.slurp;\n say %c<clr>,\"\\n\\n\",%c<delim>,('^^^^^^^^' xx 7).join(' CODE '),%c<clr>;\n}\n\nsub uri-query-string (*%fields) { %fields.map({ \"{.key}={uri-escape .value}\" }).join('&') }\n\nsub clear { \"\\r\" ~ ' ' x 100 ~ \"\\r\" }\n\nsub uh-oh ($err, $class='warn') { put %c{$class}, \"{'#' x 79}\\n\\n $err \\n\\n{'#' x 79}\", %c<clr> }\n\nsub fuzzy-search ($title) {\n my @tasknames;\n if \"%l<dir>.tasks\".IO.e {\n @tasknames = \"%l<dir>.tasks\".IO.slurp.lines;\n }\n return '' unless @tasknames.elems;\n \" Did you perhaps mean:\\n\\n\\t\" ~\n @tasknames.grep( {.lc.contains($title.lc) or dld($_, $title) < (5 min $title.chars)} ).join(\"\\n\\t\");\n} # Damerau Levenshtein distance ^^^\n\nmulti check-dependencies ($fn, 'raku') {\n my @use = $fn.IO.slurp.comb(/<?after ^^ \\h* 'use '> \\N+? <?before \\h* ';'>/);\n if +@use {\n say %c<dep>, 'Checking dependencies...', %c<clr>;\n for @use -> $module {\n if $module eq any('v6', 'v6.c', 'v6.d', 'nqp', 'NativeCall', 'Test') or $module.contains('MONKEY')\n or $module.contains('experimental') or $module.starts-with('lib') or $module.contains('from<Perl5>') {\n print %c<dep>;\n say 'ok, no installation necessary: ', $module;\n print %c<clr>;\n next;\n }\n my $installed = $*REPO.resolve(CompUnit::DependencySpecification.new(:short-name($module)));\n my @mods = $module;\n if './../../../raku-modules.txt'.IO.e {\n my $fh = open( './../../../perl6-modules.txt', :r ) or die $fh;\n @mods.append: $fh.lines;\n $fh.close;\n }\n my $fh = open( './../../../raku-modules.txt', :w ) or die $fh;\n $fh.spurt: @mods.Bag.keys.sort.join: \"\\n\";\n $fh.close;\n print %c<dep>;\n if $installed {\n say 'ok, installed: ', $module\n } else {\n say 'not installed: ', $module;\n shell(\"zef install $module\");\n }\n print %c<clr>;\n }\n }\n}\n\nmulti check-dependencies ($fn, 'perl') {\n my @use = $fn.IO.slurp.comb(/<?after ^^ \\h* 'use '> \\N+? <?before \\h* ';'>/);\n if +@use {\n for @use -> $module {\n next if $module eq $module.lc;\n next if $module.starts-with(any('constant','bignum'));\n my $installed = shell( \"%l<exe> -e 'eval \\\"use {$module}\\\"; exit 1 if \\$@'\" );\n print %c<dep>;\n if $installed {\n say 'ok: ', $module\n } else {\n say 'not installed: ', $module;\n try shell(\"sudo cpan $module\");\n }\n print %c<clr>;\n }\n }\n}\n\nmulti check-dependencies ($fn, $unknown) {\n note \"Sorry, don't know how to handle dependencies for $unknown language.\"\n};\n\nmulti load-lang ('raku') { ( # Language specific variables. Adjust to suit.\n language => 'Raku', # language category name\n exe => 'raku', # executable name to run perl6 in a shell\n ext => '.raku', # file extension for perl6 code (optional, but nice to have)\n dir => 'raku', # directory to save tasks to\n header => 'Raku', # header text (=={{header|Raku}}==)\n # tags marking blocks of code - spaced out to placate wiki formatter\n # and to avoid getting tripped up when trying to run _this_ task.\n # note that this tag only selects the syntax highlighting, continue to\n # leave 'perl6' as an option, 'raku' is now live on the site.\n tag => rx/:i <?after '<syntaxhighlight lang=\"' ['perl6'|'raku'] '\"' ' line'? '>' > .*? <?before '</' 'syntaxhighlight>'>/,\n) }\n\nmulti load-lang ('perl') { (\n language => 'Perl',\n exe => 'perl',\n ext => '.pl',\n dir => 'perl',\n header => 'Perl',\n tag => rx/:i <?after '<syntaxhighlight lang=\"' 'perl' '\"' ' line'? '>' > .*? <?before '</' 'lang>'>/,\n) }\n\nmulti load-lang ('python') { (\n language => 'Python',\n exe => 'python',\n ext => '.py',\n dir => 'python',\n header => 'Python',\n tag => rx/:i <?after '<syntaxhighlight lang=\"' 'python' '\"' ' line'? '>' > .*? <?before '</' 'lang>'>/,\n) }\n\nmulti load-lang ('go') { (\n language => 'Go',\n exe => 'go run',\n ext => '.go',\n dir => 'go',\n header => 'Go',\n tag => rx/:i <?after '<syntaxhighlight lang=\"' 'go' '\"' ' line'? '>' > .*? <?before '</' 'lang>'>/,\n) }\n\nmulti load-lang ('tcl') { (\n language => 'Tcl',\n exe => 'tclsh',\n ext => '.tcl',\n dir => 'tcl',\n header => 'Tcl',\n tag => rx/:i <?after '<syntaxhighlight lang=\"' 'tcl' '\"' ' line'? '>' > .*? <?before '</' 'lang>'>/,\n) }\n\nmulti load-lang ($unknown) { die \"Sorry, don't know how to handle $unknown language.\" };\n\nmulti load-resources ($unknown) { () };\n\n```\n\nOutput:\n\nwith command line\n\n: **raku RC-run.p6 -q \"Determine if a string is numeric\"**\n\n```\nRetrieving tasks\n1) Determine if a string is numeric\nGetting code from: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Raku\n\nTesting Determine_if_a_string_is_numeric\n\nCommand line: raku Determine_if_a_string_is_numeric.p6\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\nDone task #1: Determine_if_a_string_is_numeric - wallclock seconds: 0.171\n===============================================================================\n```\n\nOr, if the full %resource hash is loaded it will automatically feed input parameters to tasks that require them: \n**raku RC-run.p6 Lucky\\_and\\_even\\_lucky\\_numbers** -q\n\n```\nRetrieving tasks\n1 Lucky_and_even_lucky_numbers\nGetting code from: http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers#Raku\n\nTesting Lucky_and_even_lucky_numbers\n\nCommand line: raku Lucky_and_even_lucky_numbers.p6 20 , lucky\n\n79\n\nCommand line: raku Lucky_and_even_lucky_numbers.p6 1 20\n\n(1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79)\n\nCommand line: raku Lucky_and_even_lucky_numbers.p6 1 20 evenlucky\n\n(2 4 6 10 12 18 20 22 26 34 36 42 44 50 52 54 58 68 70 76)\n\nCommand line: raku Lucky_and_even_lucky_numbers.p6 6000 -6100\n\n(6009 6019 6031 6049 6055 6061 6079 6093)\n\nCommand line: raku Lucky_and_even_lucky_numbers.p6 6000 -6100 evenlucky\n\n(6018 6020 6022 6026 6036 6038 6050 6058 6074 6090 6092)\n\nDone Lucky_and_even_lucky_numbers\n===============================================================================\n```\n\nTry running a Go task - Command line: **raku RC-run.p6 -q --lang=go \"Determine if a string is numeric\"**\n\nFinds two task entries, downloads both and runs each:\n\n```\n1) Determine if a string is numeric\nGetting code from: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Go\n\nTesting Determine_if_a_string_is_numeric0\n\nCommand line: go run Determine_if_a_string_is_numeric0.go\n\nAre these strings numeric?\n 1 -> true\n 3.14 -> true\n -100 -> true\n 1e2 -> true\n NaN -> true\n rose -> false\n\nDone task #1: Determine_if_a_string_is_numeric0 - wallclock seconds: 0.16\n\nTesting Determine_if_a_string_is_numeric1\n\nCommand line: go run Determine_if_a_string_is_numeric1.go\n\nAre these strings integers?\n 1 -> true\n one -> false\n\nDone task #1: Determine_if_a_string_is_numeric1 - wallclock seconds: 0.147\n===============================================================================\n```" } ]
[ { "role": "user", "content": "A RosettaCode contributor is going on a long journey.\n\nTo ease the boredom of a long flight he takes his favourite programming language manual and a list of RosettaCode tasks,   but there's a catch:   the tasks have to be description only and not include all the solutions already supplied by other programmers.\n\nTask\n: * Scrape   http://rosettacode.org/wiki/Category:Programming\\_Tasks   for all the tasks.\n * Traverse the links.\n * Extract the text or HTML between a tag with a class of   \"infobox\"   and the beginning of the table with the id of   \"toc\"." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.10\n\n```\nuse HTTP::UserAgent;\nuse Gumbo;\n\nmy $ua = HTTP::UserAgent.new;\nmy $taskfile = './RC_tasks.html';\n\n# Get list of Tasks\nsay \"Updating Programming_Tasks list...\";\nmy $page = \"https://rosettacode.org/wiki/Category:Programming_Tasks\";\nmy $html = $ua.get($page).content;\nmy $xmldoc = parse-html($html, :TAG<div>, :id<mw-pages>);\nmy @tasks = parse-html($xmldoc[0].Str, :TAG<li>).Str.comb( /'/wiki/' <-[\"]>+ / )».substr(6); #\"\nmy $f = open(\"./RC_Programming_Tasks.txt\", :w) or die \"$!\\n\";\nnote \"Writing Programming_Tasks file...\";\n$f.print( @tasks.join(\"\\n\") );\n$f.close;\n\nsleep .5;\n\nfor 'Programming_Tasks' -> $category\n{ # Scrape info from each page.\n\n note \"Loading $category file...\";\n note \"Retreiving tasks...\";\n my @entries = \"./RC_{$category}.txt\".IO.slurp.lines;\n\n for @entries -> $title {\n note $title;\n\n # Get the raw page\n my $html = $ua.get: \"https://rosettacode.org/wiki/{$title}\";\n\n # Filter out the actual task description\n $html.content ~~ m|'<div id=\"mw-content-text\" lang=\"en\" dir=\"ltr\" class=\"mw-content-ltr\"><div'\n .+? 'using any language you may know.</div>' (.+?) '<div id=\"toc\"'|;\n\n my $task = cleanup $0.Str;\n\n # save to a file\n my $fh = $taskfile.IO.open :a;\n\n $fh.put: \"<hr>\\n $title\\n<hr>\\n$task\";\n\n $fh.close;\n\n sleep 3; # Don't pound the server\n }\n}\n\nsub cleanup ( $string ) {\n $string.subst( /^.+ '</div>'/, '' )\n}\n\n```\n\nAbridged sample output:\n\n---\n\n```\n 100_doors\n\n```\n\n---\n\nThere are 100 doors in a row that are all initially closed.\n\nYou make 100 <a href=\"/wiki/Rosetta\\_Code:Multiple\\_passes\" title=\"Rosetta Code:Multiple passes\">passes</a> by the doors.\n\nThe first time through, visit every door and  *toggle*  the door  (if the door is closed,  open it;   if it is open,  close it).\n\nThe second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it.\n\nThe third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door.\n\nTask\n\nAnswer the question:   what state are the doors in after the last pass?   Which are open, which are closed?\n\n**<a href=\"/wiki/Rosetta\\_Code:Extra\\_credit\" title=\"Rosetta Code:Extra credit\">Alternate</a>:**\nAs noted in this page's   <a href=\"/wiki/Talk:100\\_doors\" title=\"Talk:100 doors\">discussion page</a>,   the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an   <a href=\"/wiki/Rosetta\\_Code:Optimization\" title=\"Rosetta Code:Optimization\">optimization</a>   that may also be expressed;\n\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n---\n\n```\n 15_Puzzle_Game\n\n```\n\n---\n\nTask\n\nImplement the <a href=\"http://en.wikipedia.org/wiki/15\\_puzzle\" class=\"extiw\" title=\"wp:15 puzzle\">Fifteen Puzzle Game</a>.\n\nRelated Task\n\n* <a href=\"/wiki/15\\_puzzle\\_solver\" title=\"15 puzzle solver\">15 Puzzle Solver</a>\n\n---\n\n```\n 15_puzzle_solver\n\n```\n\n---\n\nYour task is to write a program that finds a solution in the fewest single moves (no multimoves) possible to a random <a href=\"http://en.wikipedia.org/wiki/15\\_puzzle\" class=\"extiw\" title=\"wp:15 puzzle\">Fifteen Puzzle Game</a>. \nFor this task you will be using the following puzzle:\n\n```\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n```\n\nSolution:\n\n```\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\n```\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on. \nThere are 2 solutions with 52 moves: \nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd \nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd \nfinding either one, or both is an acceptable result. \nsee: <a rel=\"nofollow\" class=\"external text\" href=\"http://www.rosettacode.org/wiki/15\\_puzzle\\_solver/Optimal\\_solution\">Pretty Print of Optimal Solution</a>\n\nExtra credit.\n\nSolve the following problem:\n\n```\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n```\n\nRelated Task\n\n* <a href=\"/wiki/15\\_Puzzle\\_Game\" title=\"15 Puzzle Game\">15 puzzle game</a>\n\n**...and so on...**" } ]
[ { "role": "user", "content": "Task\n\nImplement a   **rot-13**   function   (or procedure, class, subroutine, or other \"callable\" object as appropriate to your programming environment).\n\nOptionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   \"standard input.\"\n\n(A number of UNIX scripting languages and utilities, such as   *awk*   and   *sed*   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python).\n\nThe   **rot-13**   encoding is commonly known from the early days of Usenet \"Netnews\" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material.\n\nMany news reader and mail user agent programs have built-in **rot-13** encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.\n\nThe definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters \"around\" the 26 letter alphabet from its normal cardinal position   (wrapping around from   **z**   to   **a**   as necessary).\n\nThus the letters   **abc**   become   **nop**   and so on.\n\nTechnically **rot-13** is a   \"mono-alphabetic substitution cipher\"   with a trivial   \"key\".\n\nA proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters\nin the input stream through without alteration.\n\nRelated tasks\n\n* Caesar cipher\n* Substitution Cipher\n* Vigenère Cipher/Cryptanalysis\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @abc = 'a'..'z';\nmy $abc = [@abc».uc, @abc];\nput .trans: $abc => $abc».rotate(13) for lines\n```\n\nInput:\n\n```\nRosetta Code\n```\n\nOutput:\n\n```\nEbfrggn Pbqr\n```\n\nAs a one-liner:\n\n```\n$ raku -pe '.=trans: {$_ => $_».rotate(13)}({[$_».uc, @$_]}(\"a\"..\"z\"))'\n```" } ]
[ { "role": "user", "content": "A round-robin tournament is also known as an all-play-all-tournament; each participant plays every other participant once.\n\nFor N participants the number of rounds is N-1 if N is an even number. When there are an odd number of participants then each round one contestor has no opponent (AKA as a \"bye\"). The number of rounds is N in that case.\n\nTask\n\nWrite a program that prints out a tournament schedule for 12 participants (represented by numbers 1 to 12).\n\nSee also\n: * **Wikipedia - Round-robin tournament**" }, { "role": "assistant", "content": "```\nmy @players = (1,0)[$_%2] .. $_ given 12;\nmy $half = +@players div 2;\nmy $round = 0;\n\nloop {\n printf \"Round %2d: %s\\n\", ++$round, \"{ zip( @players[^$half], @players[$half..*].reverse ).map: { sprintf \"(%2d vs %-2d)\", |$_ } }\";\n @players[1..*].=rotate(-1);\n last if [<] @players;\n}\n\n```\n\nOutput:\n\n```\nRound 1: ( 1 vs 12) ( 2 vs 11) ( 3 vs 10) ( 4 vs 9 ) ( 5 vs 8 ) ( 6 vs 7 )\nRound 2: ( 1 vs 11) (12 vs 10) ( 2 vs 9 ) ( 3 vs 8 ) ( 4 vs 7 ) ( 5 vs 6 )\nRound 3: ( 1 vs 10) (11 vs 9 ) (12 vs 8 ) ( 2 vs 7 ) ( 3 vs 6 ) ( 4 vs 5 )\nRound 4: ( 1 vs 9 ) (10 vs 8 ) (11 vs 7 ) (12 vs 6 ) ( 2 vs 5 ) ( 3 vs 4 )\nRound 5: ( 1 vs 8 ) ( 9 vs 7 ) (10 vs 6 ) (11 vs 5 ) (12 vs 4 ) ( 2 vs 3 )\nRound 6: ( 1 vs 7 ) ( 8 vs 6 ) ( 9 vs 5 ) (10 vs 4 ) (11 vs 3 ) (12 vs 2 )\nRound 7: ( 1 vs 6 ) ( 7 vs 5 ) ( 8 vs 4 ) ( 9 vs 3 ) (10 vs 2 ) (11 vs 12)\nRound 8: ( 1 vs 5 ) ( 6 vs 4 ) ( 7 vs 3 ) ( 8 vs 2 ) ( 9 vs 12) (10 vs 11)\nRound 9: ( 1 vs 4 ) ( 5 vs 3 ) ( 6 vs 2 ) ( 7 vs 12) ( 8 vs 11) ( 9 vs 10)\nRound 10: ( 1 vs 3 ) ( 4 vs 2 ) ( 5 vs 12) ( 6 vs 11) ( 7 vs 10) ( 8 vs 9 )\nRound 11: ( 1 vs 2 ) ( 3 vs 12) ( 4 vs 11) ( 5 vs 10) ( 6 vs 9 ) ( 7 vs 8 )\n```" } ]
[ { "role": "user", "content": "**RPG**   =   Role Playing Game.\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\nTask\n\nWrite a program that:\n\n1. Generates 4 random, whole values between 1 and 6.\n2. Saves the sum of the 3 largest values.\n3. Generates a total of 6 values this way.\n4. Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2018.04.1\n\n```\nmy ( $min_sum, $hero_attr_min, $hero_count_min ) = 75, 15, 2;\nmy @attr-names = <Str Int Wis Dex Con Cha>;\n\nsub heroic { + @^a.grep: * >= $hero_attr_min }\n\nmy @attr;\nrepeat until @attr.sum >= $min_sum\n and heroic(@attr) >= $hero_count_min {\n\n @attr = @attr-names.map: { (1..6).roll(4).sort(+*).skip(1).sum };\n}\n\nsay @attr-names Z=> @attr;\nsay \"Sum: {@attr.sum}, with {heroic(@attr)} attributes >= $hero_attr_min\";\n\n```\n\nOutput:\n\n```\n(Str => 15 Int => 16 Wis => 13 Dex => 11 Con => 15 Cha => 6)\nSum: 76, with 3 attributes >= 15\n\n```" } ]
[ { "role": "user", "content": "A daemon is a service that runs in the background independent of a users login session.\n\nDemonstrate how a program disconnects from the terminal to run as a daemon in the background.\n\nWrite a small program that writes a message roughly once a second to its stdout which should be redirected to a file.\n\nNote that in some language implementations it may not be possible to disconnect from the terminal, and instead the process needs to be started with stdout (and stdin) redirected to files before program start. If that is the case then a helper program to set up this redirection should be written in the language itself. A shell wrapper, as would be the usual solution on Unix systems, is not appropriate." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\n# Reference:\n# https://github.com/hipek8/p6-UNIX-Daemonize/\n\nuse v6;\nuse UNIX::Daemonize;\nuse File::Temp;\n\nmy ($output, $filehandle) = tempfile(:tempdir(\"/tmp\"),:!unlink) or die;\n\nsay \"Output now goes to \",$output;\n\ndaemonize();\n\nloop {\n sleep(1);\n spurt $output, DateTime.now.Str~\"\\n\", :append;\n}\n\n```\n\nOutput:\n\n```\nroot@ubuntu:~# su - david\n\ndavid@ubuntu:~$ ./dumper.p6\nOutput now goes to /tmp/x2ovx9JG8b\ndavid@ubuntu:~$ tail -f /tmp/x2ovx9JG8b\n2018-12-11T20:20:01.510484+08:00\n2018-12-11T20:20:02.513732+08:00\n2018-12-11T20:20:03.517063+08:00\n2018-12-11T20:20:04.520394+08:00\n2018-12-11T20:20:05.524871+08:00\n2018-12-11T20:20:06.528244+08:00\n2018-12-11T20:20:07.531985+08:00\n2018-12-11T20:20:08.537776+08:00\n2018-12-11T20:20:09.541606+08:00\n2018-12-11T20:20:10.545796+08:00\n2018-12-11T20:20:11.549047+08:00\n2018-12-11T20:20:12.552704+08:00\n^C\ndavid@ubuntu:~$ exit\nlogout\nroot@ubuntu:~# tail -f /tmp/x2ovx9JG8b\n2018-12-11T20:20:28.623690+08:00\n2018-12-11T20:20:29.626978+08:00\n2018-12-11T20:20:30.634309+08:00\n2018-12-11T20:20:31.637481+08:00\n2018-12-11T20:20:32.640794+08:00\n2018-12-11T20:20:33.643947+08:00\n2018-12-11T20:20:34.647146+08:00\n2018-12-11T20:20:35.651008+08:00\n^C\nroot@ubuntu:~# su - david\ndavid@ubuntu:~$ tail -f /tmp/x2ovx9JG8b\n2018-12-11T20:20:51.711357+08:00\n2018-12-11T20:20:52.715044+08:00\n2018-12-11T20:20:53.718921+08:00\n2018-12-11T20:20:54.722134+08:00\n2018-12-11T20:20:55.725970+08:00\n2018-12-11T20:20:56.729160+08:00\n2018-12-11T20:20:57.732376+08:00\n2018-12-11T20:20:58.735409+08:00\n2018-12-11T20:20:59.738886+08:00\n2018-12-11T20:21:00.743045+08:00\n2018-12-11T20:21:01.748113+08:00\n2018-12-11T20:21:02.753204+08:00\n2018-12-11T20:21:03.756665+08:00\n2018-12-11T20:21:04.759902+08:00\n^C\ndavid@ubuntu:~$ pkill -c moar\n1\n\n\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Run-length\\_encoding. 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\nGiven a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.\n\nThe output can be anything, as long as you can recreate the input with it.\n\nExample\n: Input: `WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW`\n: Output: `12W1B12W3B24W1B14W`\n\nNote: the encoding step in the above example is the same as a step of the Look-and-say sequence." }, { "role": "assistant", "content": "(formerly Perl 6)\nNote that Raku regexes don't care about unquoted whitespace, and that backrefs\ncount from 0, not from 1.\n\n```\nsub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) }\n\nsub decode($str) { $str.subst(/(\\d+) (.)/, { $1 x $0 }, :g) }\n\nmy $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW');\nsay $e;\nsay decode($e);\n```\n\nOutput:\n\n```\n12W1B12W3B24W1B14W \nWWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n```" } ]
[ { "role": "user", "content": "Given the example Differential equation:\n\n: y\n ′\n (\n t\n )\n =\n t\n ⋅\n\n\n y\n (\n t\n )\n {\\displaystyle {\\displaystyle y'(t)=t\\cdot {\\sqrt {y(t)}}}}\n\nWith initial condition:\n\n: t\n\n 0\n =\n 0\n {\\displaystyle {\\displaystyle t\\_{0}=0}}\n and \n\n y\n\n 0\n =\n y\n (\n\n t\n\n 0\n )\n =\n y\n (\n 0\n )\n =\n 1\n {\\displaystyle {\\displaystyle y\\_{0}=y(t\\_{0})=y(0)=1}}\n\nThis equation has an exact solution:\n\n: y\n (\n t\n )\n =\n\n 1\n 16\n (\n\n t\n\n 2\n +\n 4\n\n )\n\n 2\n {\\displaystyle {\\displaystyle y(t)={\\tfrac {1}{16}}(t^{2}+4)^{2}}}\n\nTask\n\nDemonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation.\n\n* Solve the given differential equation over the range \n\n t\n =\n 0\n …\n 10\n {\\displaystyle {\\displaystyle t=0\\ldots 10}}\n with a step value of \n\n δ\n t\n =\n 0.1\n {\\displaystyle {\\displaystyle \\delta t=0.1}}\n (101 total points, the first being given)\n* Print the calculated values of \n\n y\n {\\displaystyle {\\displaystyle y}}\n at whole numbered \n\n t\n {\\displaystyle {\\displaystyle t}}\n 's (\n\n 0.0\n ,\n 1.0\n ,\n …\n 10.0\n {\\displaystyle {\\displaystyle 0.0,1.0,\\ldots 10.0}}\n ) along with error as compared to the exact solution.\n\nMethod summary\n\nStarting with a given \n\ny\n\nn\n{\\displaystyle {\\displaystyle y\\_{n}}}\n and \n\nt\n\nn\n{\\displaystyle {\\displaystyle t\\_{n}}}\n calculate:\n\n: δ\n\n y\n\n 1\n =\n δ\n t\n ⋅\n\n y\n ′\n (\n\n t\n\n n\n ,\n\n y\n\n n\n )\n\n {\\displaystyle {\\displaystyle \\delta y\\_{1}=\\delta t\\cdot y'(t\\_{n},y\\_{n})\\quad }}\n: δ\n\n y\n\n 2\n =\n δ\n t\n ⋅\n\n y\n ′\n (\n\n t\n\n n\n +\n\n 1\n 2\n δ\n t\n ,\n\n y\n\n n\n +\n\n 1\n 2\n δ\n\n y\n\n 1\n )\n {\\displaystyle {\\displaystyle \\delta y\\_{2}=\\delta t\\cdot y'(t\\_{n}+{\\tfrac {1}{2}}\\delta t,y\\_{n}+{\\tfrac {1}{2}}\\delta y\\_{1})}}\n: δ\n\n y\n\n 3\n =\n δ\n t\n ⋅\n\n y\n ′\n (\n\n t\n\n n\n +\n\n 1\n 2\n δ\n t\n ,\n\n y\n\n n\n +\n\n 1\n 2\n δ\n\n y\n\n 2\n )\n {\\displaystyle {\\displaystyle \\delta y\\_{3}=\\delta t\\cdot y'(t\\_{n}+{\\tfrac {1}{2}}\\delta t,y\\_{n}+{\\tfrac {1}{2}}\\delta y\\_{2})}}\n: δ\n\n y\n\n 4\n =\n δ\n t\n ⋅\n\n y\n ′\n (\n\n t\n\n n\n +\n δ\n t\n ,\n\n y\n\n n\n +\n δ\n\n y\n\n 3\n )\n\n {\\displaystyle {\\displaystyle \\delta y\\_{4}=\\delta t\\cdot y'(t\\_{n}+\\delta t,y\\_{n}+\\delta y\\_{3})\\quad }}\n\nthen:\n\n: y\n\n n\n +\n 1\n =\n\n y\n\n n\n +\n\n 1\n 6\n (\n δ\n\n y\n\n 1\n +\n 2\n δ\n\n y\n\n 2\n +\n 2\n δ\n\n y\n\n 3\n +\n δ\n\n y\n\n 4\n )\n {\\displaystyle {\\displaystyle y\\_{n+1}=y\\_{n}+{\\tfrac {1}{6}}(\\delta y\\_{1}+2\\delta y\\_{2}+2\\delta y\\_{3}+\\delta y\\_{4})}}\n: t\n\n n\n +\n 1\n =\n\n t\n\n n\n +\n δ\n t\n\n {\\displaystyle {\\displaystyle t\\_{n+1}=t\\_{n}+\\delta t\\quad }}" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.03\n\n```\nsub runge-kutta(&yp) {\n return -> \\t, \\y, \\δt {\n my $a = δt * yp( t, y );\n my $b = δt * yp( t + δt/2, y + $a/2 );\n my $c = δt * yp( t + δt/2, y + $b/2 );\n my $d = δt * yp( t + δt, y + $c );\n ($a + 2*($b + $c) + $d) / 6;\n }\n}\n \nconstant δt = .1;\nmy &δy = runge-kutta { $^t * sqrt($^y) };\n \nloop (\n my ($t, $y) = (0, 1);\n $t <= 10;\n ($t, $y) »+=« (δt, δy($t, $y, δt))\n) {\n printf \"y(%2d) = %12f ± %e\\n\", $t, $y, abs($y - ($t**2 + 4)**2 / 16)\n if $t %% 1;\n}\n\n```\n\nOutput:\n\n```\ny( 0) = 1.000000 ± 0.000000e+00\ny( 1) = 1.562500 ± 1.457219e-07\ny( 2) = 3.999999 ± 9.194792e-07\ny( 3) = 10.562497 ± 2.909562e-06\ny( 4) = 24.999994 ± 6.234909e-06\ny( 5) = 52.562489 ± 1.081970e-05\ny( 6) = 99.999983 ± 1.659460e-05\ny( 7) = 175.562476 ± 2.351773e-05\ny( 8) = 288.999968 ± 3.156520e-05\ny( 9) = 451.562459 ± 4.072316e-05\ny(10) = 675.999949 ± 5.098329e-05\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate a language's ability for programs to execute code written in the language provided at runtime.\n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see Eval in environment." }, { "role": "assistant", "content": "(formerly Perl 6)\nAny syntactically valid sequence of statements may be run, and the snippet to be run can see its outer lexical scope at the point of the eval:\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nmy ($a, $b) = (-5, 7);\nmy $ans = EVAL 'abs($a * $b)'; # => 35\n\n```\n\nUnlike in Perl 5, eval in Raku only compiles and executes the string, but does not trap exceptions. You must say try eval to get that behavior (or supply a CATCH block within the text to be evaluated)." } ]
[ { "role": "user", "content": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a *global* variable\n\nor note that these are impossible.\n\nSee also\n\n* For more general examples and language-specific details, see Eval.\n* Dynamic variable names is a similar task." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-12-22\n\nFor security, you must explicitly allow use of 'EVAL'.\n\n```\nuse MONKEY-SEE-NO-EVAL;\nsub eval_with_x($code, *@x) { [R-] @x.map: -> \\x { EVAL $code } }\n\nsay eval_with_x('3 * x', 5, 10); # Says \"15\".\nsay eval_with_x('3 * x', 5, 10, 50); # Says \"105\".\n\n```" } ]
[ { "role": "user", "content": "A **Ruth–Aaron** pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.\n\nA **Ruth–Aaron** triple consists of ***three*** consecutive integers with the same properties.\n\nThere is a second variant of **Ruth–Aaron** numbers, one which uses prime *factors* rather than prime *divisors*. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.\n\nIt is common to refer to each **Ruth–Aaron** group by the first number in it.\n\nTask\n\n* Find and show, here on this page, the first **30** **Ruth-Aaron numbers** (factors).\n\n* Find and show, here on this page, the first **30** **Ruth-Aaron numbers** (divisors).\n\nStretch\n\n* Find and show the first **Ruth-Aaron triple** (factors).\n\n* Find and show the first **Ruth-Aaron triple** (divisors).\n\nSee also\n\n* Wikipedia: Ruth–Aaron pair * OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 * OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)" }, { "role": "assistant", "content": "```\nuse Prime::Factor;\n\nmy @pf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.sum;\nmy @upf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.unique.sum;\n\n# Task: < 1 second\nput \"First 30 Ruth-Aaron numbers (Factors):\\n\" ~\n(1..∞).grep( { @pf[$_] == @pf[$_ + 1] } )[^30];\n\nput \"\\nFirst 30 Ruth-Aaron numbers (Divisors):\\n\" ~\n(1..∞).grep( { @upf[$_] == @upf[$_ + 1] } )[^30];\n\n# Stretch: ~ 5 seconds\nput \"\\nFirst Ruth-Aaron triple (Factors):\\n\" ~\n(1..∞).first: { @pf[$_] == @pf[$_ + 1] == @pf[$_ + 2] }\n\n# Really, really, _really_ slow. 186(!) minutes... but with no cheating or \"leg up\".\nput \"\\nFirst Ruth-Aaron triple (Divisors):\\n\" ~\n(1..∞).first: { @upf[$_] == @upf[$_ + 1] == @upf[$_ + 2] }\n\n```\n\nOutput:\n\n```\nFirst 30 Ruth-Aaron numbers (Factors):\n5 8 15 77 125 714 948 1330 1520 1862 2491 3248 4185 4191 5405 5560 5959 6867 8280 8463 10647 12351 14587 16932 17080 18490 20450 24895 26642 26649\n\nFirst 30 Ruth-Aaron numbers (Divisors):\n5 24 49 77 104 153 369 492 714 1682 2107 2299 2600 2783 5405 6556 6811 8855 9800 12726 13775 18655 21183 24024 24432 24880 25839 26642 35456 40081\n\nFirst Ruth-Aaron triple (Factors):\n417162\n\nFirst Ruth-Aaron triple (Divisors):\n89460294\n```" } ]
[ { "role": "user", "content": "S-Expressions   are one convenient way to parse and store data.\n\nTask\n\nWrite a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.\n\nThe reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).\n\nNewlines and other whitespace may be ignored unless contained within a quoted string.\n\n“()”   inside quoted strings are not interpreted, but treated as part of the string.\n\nHandling escaped quotes inside a string is optional;   thus “(foo\"bar)” maybe treated as a string “foo\"bar”, or as an error.\n\nFor this, the reader need not recognize “\\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.\n\nLanguages that support it may treat unquoted strings as symbols.\n\nNote that with the exception of “()\"” (“\\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.\n\nThe reader should be able to read the following input\n\n```\n((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))\n\n```\n\nand turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.)\n\nThe writer should be able to take the produced list and turn it into a new S-Expression.\nStrings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted.\n\nExtra Credit\n\nLet the writer produce pretty printed output with indenting and line-breaks." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.02\n\nThis parses the task, but it isn't really a good lisp parser, because it always wants whitespace between lists, so `(()())` will fail ( `(() ())` wont)\n\n```\ngrammar S-Exp {\n rule TOP {^ <s-list> $};\n\n token s-list { '(' ~ ')' [ <in_list>+ % [\\s+] | '' ] }\n token in_list { <s-token> | <s-list> } \n \n proto token s-token {*}\n token s-token:sym<Num> {\\d*\\.?\\d+}\n token s-token:sym<String> {'\"' ['\\\"' |<-[\\\\\"]>]*? '\"'} #'\n token s-token:sym<Atom> {<-[()\\s]>+}\n \n}\n \n# The Actions class, for each syntactic rule there is a method\n# that stores some data in the abstract syntax tree with make\nclass S-Exp::ACTIONS {\n method TOP ($/) {make $<s-list>.ast}\n method s-list ($/) {make [$<in_list>».ast]}\n method in_list ($/) {make $/.values[0].ast}\n \n method s-token:sym<Num> ($/){make +$/}\n method s-token:sym<String> ($/){make ~$/.substr(1,*-1)}\n method s-token:sym<Atom> ($/){make ~$/}\n}\n \nmulti s-exp_writer (Positional $ary) {'(' ~ $ary.map(&s-exp_writer).join(' ') ~ ')'}\nmulti s-exp_writer (Numeric $num) {~$num}\nmulti s-exp_writer (Str $str) {\n return $str unless $str ~~ /<[(\")]>|\\s/;\n return '()' if $str eq '()';\n '\"' ~ $str.subst('\"', '\\\"' ) ~ '\"';\n}\n \n \nmy $s-exp = '((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))';\n \nmy $actions = S-Exp::ACTIONS.new();\nmy $raku_array = (S-Exp.parse($s-exp, :$actions)).ast;\n \nsay \"the expression:\\n$s-exp\\n\";\nsay \"the Raku expression:\\n{$raku_array.raku}\\n\";\nsay \"and back:\\n{s-exp_writer($raku_array)}\";\n\n```\n\nOutput:\n\n```\nthe expression:\n((data \"quoted data\" 123 4.5)\n (data (!@# (4.5) \"(more\" \"data)\")))\n\nthe Raku expression:\n[[\"data\", \"quoted data\", \"123\", 9/2], [\"data\", [\"!\\@#\", [9/2], \"(more\", \"data)\"]]]\n\nand back:\n((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))\n```" } ]
[ { "role": "user", "content": "Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.\n\nFor example, for an addition, it is the operations   +↑   and   +↓   defined as:   *a* +↓ *b* ≤ *a* + *b* ≤ *a* +↑ *b*.\n\nAdditionally it is desired that the width of the interval   (*a* +↑ *b*) - (*a* +↓ *b*)   would be about the machine epsilon after removing the exponent part.\n\nDifferently to the standard floating-point arithmetic, safe interval arithmetic is **accurate** (but still imprecise).\n\nI.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome.\n\nUsually a   FPU's   have machine   +,-,\\*,/   operations accurate within the machine precision.\n\nTo illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is **3** decimal points.\n\nIf the result of the machine addition is   1.23,   then the exact mathematical result is within the interval   ]1.22, 1.24[.\n\nWhen the machine rounds towards zero, then the exact result is within   [1.23,1.24[.   This is the basis for an implementation of safe addition.\n\nTask;\n\nShow how   +↓   and   +↑   can be implemented in your language using the standard floating-point type.\n\nDefine an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval   [*a* +↓ *b*, *a* +↑ *b*]." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nRaku uses 64 bit IEEE floating points numbers which provide 53 binary digits\nof accuracy. If you insist on using floats your answer will be accurate in the range\n± 1.1102230246251565e-16. Raku actually makes it somewhat difficult to output\nan exact stringified float with more than 15 digits of accuracy. It automatically\nrounds since it doesn't try to pretend that it is more accurate than that.\n\nIf you really DO need very high precision and accuracy, Raku has native\nbuilt-in Rational number support. Rationals are the ratio of two integers, and\nare always exact. Standard Rats are limited to 64 bits of precision in the\ndenominator. On overflow, they will downgrade to a float (Num).\nFatRats have unlimited denominators.\n\nThere is no need to load any external libraries or force the use of Rats. Unless\nyou force it otherwise, decimal number are always stored as Rats as long as they\nwill fit within the denominator limit.\n\nYou can see the two integers making up the ratio of a Rat (or FatRat) using the\n.nude method (**nu**merator, **de**nominator).\n\nRats and FatRats by default stringify to a fixed number of places for\nnon-terminating fractions and the same number of digits as the denominator for\nterminating fractions. If you need more control over stringification, load the\nmodule Rat::Precise for configurable stringification. Rat::Precise *only* affects\nstringification, not calculation. Calculations are always done at full (exact) precision.\n\n```\nsay \"Floating points: (Nums)\";\nsay \"Error: \" ~ (2**-53).Num;\n\nsub infix:<±+> (Num $a, Num $b) {\n my \\ε = (2**-53).Num;\n $a - ε + $b, $a + ε + $b,\n}\n\nprintf \"%4.16f .. %4.16f\\n\", (1.14e0 ±+ 2e3);\n\nsay \"\\nRationals:\";\n\nsay \".1 + .2 is exactly equal to .3: \", .1 + .2 === .3;\n\nsay \"\\nLarge denominators require explicit coercion to FatRats:\";\nsay \"Sum of inverses of the first 500 natural numbers:\";\nmy $sum = sum (1..500).map: { FatRat.new(1,$_) };\nsay $sum;\nsay $sum.nude;\n\n{\n say \"\\nRat stringification may not show full precision for terminating fractions by default.\";\n say \"Use a module to get full precision.\";\n use Rat::Precise; # module loading is scoped to the enclosing block\n my $rat = 1.5**63;\n say \"\\nRaku default stringification for 1.5**63:\\n\" ~ $rat; # standard stringification\n say \"\\nRat::Precise stringification for 1.5**63:\\n\" ~$rat.precise; # full precision\n}\n\n```\n\nOutput:\n\n```\nFloating points: (Nums)\nError: 1.1102230246251565e-16\n2001.1400000000000000 .. 2001.1400000000000000\n\nRationals:\n.1 + .2 is exactly equal to .3: True\n\nLarge denominators require explicit coercion to FatRats:\nSum of inverses of the first 500 natural numbers:\n6.79282342999052460298928714536797369481981381439677911664308889685435662379055049245764940373586560391756598584375065928223134688479711715030249848314807266844371012370203147722209400570479644295921001097190193214586271\n(6633384299891198065461433023874214660151383488987829406868700907802279376986364154005690172480537248349310365871218591743641116766728139494727637850449054802989613344274500453825922847052235859615378238909694581687099 976528297586037954584851660253897317730151176683856787284655867127950765610716178591036797598551026470244168088645451676177520177514977827924165875515464044694152207479405310883385229609852607806002629415184926954240)\n\nRat stringification may not show full precision for terminating fractions by default.\nUse a module to get full precision.\n\nRaku default stringification for 1.5**63:\n124093581919.64894769782737365038\n\nRat::Precise stringification for 1.5**63:\n124093581919.648947697827373650380188008224280338254175148904323577880859375\n\n```" } ]
[ { "role": "user", "content": "A prime number *p* is a Sophie Germain prime if 2*p* + 1 is also prime. \nThe number 2*p* + 1 associated with a Sophie Germain prime is called a **safe prime**.\n\nTask\n\nGenerate the first   **50**   Sophie Germain prime numbers.\n\nSee also\n\n* Wikipedia: Sophie Germain primes * OEIS:A005384 - Sophie Germain primes * Related Task: Safe\\_primes\\_and\\_unsafe\\_primes" }, { "role": "assistant", "content": "```\nput join \"\\n\", (^∞ .grep: { .is-prime && ($_*2+1).is-prime } )[^50].batch(10)».fmt: \"%4d\";\n\n```\n\nOutput:\n\n```\n 2 3 5 11 23 29 41 53 83 89\n 113 131 173 179 191 233 239 251 281 293\n 359 419 431 443 491 509 593 641 653 659\n 683 719 743 761 809 911 953 1013 1019 1031\n1049 1103 1223 1229 1289 1409 1439 1451 1481 1499\n```" } ]
[ { "role": "user", "content": "Does the language implementation allow for a \"safer mode\" of execution? Usually termed **Safe mode**, a more realistic view is probably **Safer mode** or **restricted mode**. It is one thing to place restrictions on execution, and another thing entirely to allow execution of scripts from untrusted sources and assume nothing untoward will happen.\n\nAlong with a simple yes/no answer, describe what features are restricted when running in safe mode." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n*Mostly a cut-n-paste from the Untrusted environment task.*\n\nRaku doesn't really provide a high security mode for untrusted environments. By default, Raku is sort of a walled garden. It is difficult to access memory directly, especially in locations not controlled by the Raku interpreter, so unauthorized memory access is unlikely to be a threat with default Raku commands and capabilities.\n\nIt is possible (and quite easy) to run Raku with a restricted setting which will disable many IO commands that can be used to access or modify things outside of the Raku interpreter. However, a determined bad actor could theoretically work around the restrictions, especially if the nativecall interface is available. The nativecall interface allows directly calling in to and executing code from C libraries so anything possible in C is now possible in Raku. This is great for all of the power it provides, but along with that comes the responsibility and inherent security risk. The same issue arises with unrestricted loading of modules. If modules can be loaded, especially from arbitrary locations, then any and all restriction imposed by the setting can be worked around.\n\nThe restricted setting is modifiable, but by default places restrictions on or completely disables the following things:\n\nUser Subroutines (disabled)\n\n: * sub chmod() *modify filesystem permissions*\n * sub copy() *copy a file*\n * sub link() *create a link to a file*\n * sub mkdir() *make a filesystem directory*\n * sub open() *open a filesystem location / file*\n * sub pipe() *open a pipe*\n * sub QX() *execute arbitrary code*\n * sub rename() *rename a file*\n * sub rmdir() *remove a directory*\n * sub run() *run arbitrary code*\n * sub shell() *execute code in a shell*\n * sub socket() *open a socket*\n * sub spurt() *write a file*\n * sub symlink() *create a symbolic link to a location*\n * sub unlink() *delete a file*\n\nInternal Subroutines (disabled)\n\n: * sub CHANGE-DIRECTORY *change directory*\n * sub CHMOD-PATH *change permissions*\n * sub COPY-FILE *copy a file*\n * sub MAKE-DIR *make a directory*\n * sub REMOVE-DIR *remove a directory*\n * sub RENAME-PATH *rename a directory*\n * sub SYMLINK-PATH *create a symbolic link*\n * sub UNLINK-PATH *delete a file*\n\nClasses (disabled)\n\n: * class IO::CatHandle *streaming file handle*\n * class IO::Handle *file handle*\n * class IO::Path *filesystem path*\n * class IO::Pipe *OS pipe*\n * class IO::Socket *OS socket*\n * class IO::Socket::INET *Network socket*\n * class NativeCall *Nativecall interface to foreign code (C mostly)*\n * class Proc *OS Process*\n * class Proc::Async *Asynchronous OS Process*\n\nMethod Mixins / Roles (locked down so can't be overridden)\n\n: * method FALLBACK() *handle unknown method calls*\n * method new() *create a new instance*\n * method gist() *display method*\n\nReally, if you want to lock down a Raku instance so it is \"safe\" for unauthenticated, untrusted, general access, you are better off running it in some kind of locked down virtual machine or sandbox managed by the operating system rather than trying to build an ad hoc \"safe\" environment." } ]
[ { "role": "user", "content": "Definitions\n: : * A   **safe prime**   is a prime   **p**   and where   **(p-1)/2**   is also prime.\n * The corresponding prime  **(p-1)/2**   is known as a   **Sophie Germain**   prime.\n * An   **unsafe prime**   is a prime   **p**   and where   **(p-1)/2**   *isn't*   a prime.\n * An   **unsafe prime**   is a prime that   *isn't*   a   **safe**   prime.\n\nTask\n: : * Find and display (on one line) the first   **35**   safe primes.\n * Find and display the   *count*   of the safe primes below   1,000,000.\n * Find and display the   *count*   of the safe primes below 10,000,000.\n * Find and display (on one line) the first   **40**   unsafe primes.\n * Find and display the   *count*   of the unsafe primes below   1,000,000.\n * Find and display the   *count*   of the unsafe primes below 10,000,000.\n * (Optional)   display the   *counts*   and   \"below numbers\"   with commas.\n\nShow all output here.\n\nRelated Task\n: : * strong and weak primes.\n\nAlso see\n: : * The OEIS article:     safe   primes.\n * The OEIS article:   unsafe primes." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.08\n\nRaku has a built-in method .is-prime to test for prime numbers. It's great for testing individual numbers or to find/filter a few thousand numbers, but when you are looking for millions, it becomes a drag. No fear, the Raku ecosystem has a fast prime sieve module available which can produce 10 million primes in a few seconds. Once we have the primes, it is just a small matter of filtering and formatting them appropriately.\n\n```\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nuse Math::Primesieve;\n\nmy $sieve = Math::Primesieve.new;\n\nmy @primes = $sieve.primes(10_000_000);\n\nmy %filter = @primes.Set;\n\nmy $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };\n\nfor 'safe', 35, 'unsafe', 40 -> $type, $quantity {\n say \"The first $quantity $type primes are:\";\n\n say $primes{$type}[^$quantity]».&comma;\n\n say \"The number of $type primes up to {comma $_}: \",\n comma $primes{$type}.first(* > $_, :k) // +$primes{$type} for 1e6, 1e7;\n\n say '';\n}\n\n```\n\nOutput:\n\n```\nThe first 35 safe primes are:\n(5 7 11 23 47 59 83 107 167 179 227 263 347 359 383 467 479 503 563 587 719 839 863 887 983 1,019 1,187 1,283 1,307 1,319 1,367 1,439 1,487 1,523 1,619)\nThe number of safe primes up to 1,000,000: 4,324\nThe number of safe primes up to 10,000,000: 30,657\n\nThe first 40 unsafe primes are:\n(2 3 13 17 19 29 31 37 41 43 53 61 67 71 73 79 89 97 101 103 109 113 127 131 137 139 149 151 157 163 173 181 191 193 197 199 211 223 229 233)\nThe number of unsafe primes up to 1,000,000: 74,174\nThe number of unsafe primes up to 10,000,000: 633,922\n```" } ]
[ { "role": "user", "content": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.\n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\nThe task\n\n1. Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n2. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers *are* allowed.)\n3. Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n4. Show your answers here.\n\nExtra credit (optional)\n\n* Give some indication of the number of coconuts each sailor hides during the night.\n\nNote\n\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is *not* that tale!\n\nC.f\n\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.09\n\nThere is nowhere in the spec where it explicitly states that the sailors cannot equally share zero coconuts in the morning. Actually, The On-Line Encyclopedia of Integer Sequences A002021 considers the cases for 1 and 2 sailors equally sharing zero coconuts in the morning to be the correct answer.\n\nThis will test combinations of sailors and coconuts to see if they form a valid pairing. The first 6 are done using brute force, testing every combination until a valid one is found. For cases of 7 to 15 sailors, it uses a carefully crafted filter to drastically reduce the number of trials needed to find a valid case (to one, as it happens... :-) )\n\n```\nmy @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6;\nmy @teens = 'th' xx 10;\nmy @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;\n\n# brute force the first six\nfor 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }\n\n# finesse 7 through 15\nfor 7 .. 15 -> $sailors { next if check( $sailors, coconuts( $sailors ) ) }\n\nsub is_valid ( $sailors is copy, $nuts is copy ) {\n return 0, 0 if $sailors == $nuts == 1;\n my @shares;\n for ^$sailors {\n return () unless $nuts % $sailors == 1;\n push @shares, ($nuts - 1) div $sailors;\n $nuts -= (1 + $nuts div $sailors);\n }\n push @shares, $nuts div $sailors;\n return @shares if !?($nuts % $sailors);\n}\n\nsub check ($sailors, $coconuts) {\n if my @piles = is_valid($sailors, $coconuts) {\n say \"\\nSailors $sailors: Coconuts $coconuts:\";\n for ^(@piles - 1) -> $k {\n say \"{$k+1}@suffix[$k+1] takes @piles[$k], gives 1 to the monkey.\"\n }\n say \"The next morning, each sailor takes @piles[*-1]\\nwith none left over for the monkey.\";\n return True;\n }\n False;\n}\n\nmulti sub coconuts ( $sailors where { $sailors % 2 == 0 } ) { ($sailors - 1) * ($sailors ** $sailors - 1) }\nmulti sub coconuts ( $sailors where { $sailors % 2 == 1 } ) { $sailors ** $sailors - $sailors + 1 }\n\n```\n\nOutput:\n\n```\nSailors 1: Coconuts 1:\n1st takes 0, gives 1 to the monkey.\nThe next morning, each sailor takes 0\nwith none left over for the monkey.\n\nSailors 2: Coconuts 3:\n...\n\nSailors 5: Coconuts 3121:\n1st takes 624, gives 1 to the monkey.\n2nd takes 499, gives 1 to the monkey.\n3rd takes 399, gives 1 to the monkey.\n4th takes 319, gives 1 to the monkey.\n5th takes 255, gives 1 to the monkey.\nThe next morning, each sailor takes 204\nwith none left over for the monkey.\n\nSailors 6: Coconuts 233275:\n1st takes 38879, gives 1 to the monkey.\n2nd takes 32399, gives 1 to the monkey.\n3rd takes 26999, gives 1 to the monkey.\n4th takes 22499, gives 1 to the monkey.\n5th takes 18749, gives 1 to the monkey.\n6th takes 15624, gives 1 to the monkey.\nThe next morning, each sailor takes 13020\nwith none left over for the monkey.\n\nSailors 7: Coconuts 823537:\n...\n\nSailors 15: Coconuts 437893890380859361:\n...\n\n```" } ]
[ { "role": "user", "content": "Write a routine that will compare the leaves (\"fringe\") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.\n\nAny solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.\n\nAny representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nUnlike in Perl 5, where => is just a synonym for comma, in Raku it creates a true Pair object. So here we use Pair objects for our \"cons\" cells, just as if we were doing this in Lisp. We use the gather/take construct to harvest the leaves lazily as the elements are visited with a standard recursive algorithm, using multiple dispatch to differentiate nodes from leaves. The eqv value equivalence is applied to the two lists in parallel.\n\n```\nsub fringe ($tree) {\n multi sub fringey (Pair $node) { fringey $_ for $node.kv; }\n multi sub fringey ( Any $leaf) { take $leaf; }\n\n gather fringey $tree;\n}\n\nsub samefringe ($a, $b) { fringe($a) eqv fringe($b) }\n\n# Testing:\n\nmy $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8;\nmy $b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8))));\nmy $c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8;\n\nmy $x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9;\nmy $y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8;\nmy $z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8;\n\nsay so samefringe $a, $a;\nsay so samefringe $a, $b;\nsay so samefringe $a, $c;\n\nsay not samefringe $a, $x;\nsay not samefringe $a, $y;\nsay not samefringe $a, $z;\n\n```\n\nOutput:\n\n```\nTrue\nTrue\nTrue\nTrue\nTrue\nTrue\n```" } ]
[ { "role": "user", "content": "\"Never trust user input.\" If the Super Mario Bros. 3 Wrong Warp or [Bobby Tables] have taught programmers anything, it's that user input can be dangerous in unexpected ways.\n\nIn general, the task of preventing errors such as the above are best left to the built-in security features of the language rather than a filter of your own creation. This exercise is to test your ability to think about all the possible ways user input could break your program.\n\nTask\n\nCreate a function that takes a list of 20 first and last names, and copies them to a record or struct. Ten of them must be typical input, (i.e. consist of only letters of the alphabet and punctuation), but the other ten must be deliberately chosen to cause problems with a program that expects only letters and punctuation. A few examples:\n\n* ASCII control codes such as NUL, CR, LF\n* Code for the language you are using that can result in damage (e.g. -rm -rf, delete System32, DROP TABLE, etc.)\n* Numbers, symbols, foreign languages, emojis, etc.\n\n(There were already solutions provided before the requirement that ten names are \"normal\" and ten are potentially harmful was added. Those answers satisfied the task requirements at the time they were submitted.)\n\nRelated tasks\n\n* Parametrized SQL statement" }, { "role": "assistant", "content": "It would be helpful if the task author would be a little more specific about what he is after. How user inputs must be \"sanitized\" entirely depends on how the data is going to be used.\n\nFor internal usage, in Raku, where you are simply storing data into an internal data structure, it is pretty much a non issue. Variables in Raku aren't executed without specific instructions to do so. Full stop.\n\nYour name is a string of 2.6 million null bytes? Ok. Good luck typing that in.\n\nYou're called 'rm -rf /'? Wow. sucks to be you.\n\nNow, it may be a good idea to check for a maximum permitted length; (2.6e6 null bytes) but Raku would handle it with no problem.\n\nThe problem mostly comes in when you need to interchange data with some 3rd party library / system; but every different system is going to have it's own quirks and caveats. There is no \"one size fits all\" solution.\n\nIn general, when it comes to sanitizing user input, the best way to go about it is: **don't**. It's a losing game.\n\nInstead either validate input to make sure it follows a certain format, whitelist input so only a know few commands are permitted, or if those aren't possible, use 3rd party tools the 3rd party system provides to make arbitrary input \"safe\" to run. Which one of these is used depends on what system you need to interact with.\n\nFor the case given, (Bobby Tables), where you are presumably putting names into some 3rd party data storage (nominally a database of some kind), you would use bound parameters to automatically \"make safe\" any user input. See the Raku entry under the Parametrized SQL statement task.\n\nValidating is making sure the the input matches some predetermined format, usually with some sort of regular expression. For names, you probably want to allow a fixed maximum (and minimum!) number of: any word or digit character, space and period characters and possibly some small selection of non-word characters. It is a careful balance between too restrictive and too permissive. You need to avoid falling into pre-conceived assumptions about:\nnames, time, gender, addresses, phone numbers... the list goes on.\n\nWhen passing a user command to the operating system, you probably want to use whitelisting. Only a very few commands from a predetermined list are allowed to be used.\n\n```\n if $command ∈ <ls time cd df> then { execute $command }\n\n```\n\nor some such. What the whitelist contains and how to determine if the input matches is a whole article in itself.\n\nUnfortunately, this is very vague and hand-wavey due to the vagueness of the task description. Really, any language could copy/paste 95% or better of the above, change the language name, and be done with it. But until the task description is made a little more focused, it will have to do." } ]
[ { "role": "user", "content": "Most programming languages offer support for subroutines.\nWhen execution changes between subroutines, different sets of variables and functions (\"scopes\") are available to the program.\nFrequently these sets are defined by the placement of the variable and function declarations (\"static scoping\" or \"lexical scoping\").\nThese sets may also be defined by special modifiers to the variable and function declarations.\n\nShow the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.\nIf your language has no scope modifiers, note it." }, { "role": "assistant", "content": "(formerly Perl 6)\nRaku has a system of declarators that introduce new names into various scopes.\n\n```\nmy $lexical-variable;\nour $package-variable;\nstate $persistent-lexical;\nhas $.public-attribute;\n\n```\n\nLexically scoped variables, declared with my, are the norm.\nFunction definitions are intrinsically lexical by default, but allow for forward references, unlike any other declaration.\n\nPackage variables, declared with our, are de-emphasized. Unlike in Perl 5, almost no built-ins use package declarations for anything other than type names, and most of Perl 5's global punctuational variables become dynamic variables instead, with the final recourse in the GLOBAL and PROCESS packages. The per-interpreter GLOBAL package is mainly for users; all predefined process-wide information is stored in the PROCESS symbol table instead. The our declarator actually just declares an alias to a variable of the same name in the current package, and is in a sense just permission to use that global variable in the current scope as if it were a lexical. Type and constant declarations, including enums, are intrinsically considered \"our\" declarations, since Raku considers constants to be degenerate types.\n\nState variables, declared with state, are persistent lexicals that are not re-initialized on each function entry, but retain their previous value. An initializer is run only the first time through. State variables are similar but not identical to C static variables; in Raku each closure clone gets its own state variable, since such closures are really a form of generic code.\n\nThe has declarator is for declaring items in object scope.\nMethod declarations are implicitly in \"has\" scope.\n\nIn Perl 5, dynamic scoping is done via \"local\" to temporarily change the value of a global variable. This mechanism is still specced for Raku, albeit with a different keyword, temp, that better reflects what it's doing. None of the implementations yet implement temp, since Raku does dynamic scoping via a more robust system of scanning up the call stack for the innermost dynamic declaration, which actually lives in the lexical scope of the function declaring it. We distinguish dynamic variables syntactically by introducing a \"twigil\" after the sigil. The twigil for dynamic variables is \\* to represent that we don't know how to qualify the location of the variable.\n\n```\nsub a {\n my $*dyn = 'a';\n c();\n}\nsub b {\n my $*dyn = 'b';\n c();\n}\nsub c {\n say $*dyn;\n}\na(); # says a\nb(); # says b\n\n```\n\nThe standard IO filehandles are dynamic variables $\\*IN, $\\*OUT, and $\\*ERR, which allows a program to easily redirect the input or output from any subroutine and all its children. More generally, since most process-wide variables are accessed via this mechanism, and only look in the PROCESS package as a last resort, any chunk of code can pretend to be in a different kind of process environment merely by redefining one or more of the dynamic variables in question, such as %\\*ENV.\n\nThis mechanism automatically produces thread-local storage if you declare your dynamic variable inside the lexical scope of the thread." } ]
[ { "role": "user", "content": "Task\n\nExplain or demonstrate the levels of visibility of function names and labels within the language.\n\nSee also\n\n* Variables for levels of scope relating to visibility of program variables\n* Scope modifiers for general scope modification facilities" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nFirst a little hand-wavey exposition. The lines are rather blurry in Raku between subroutines, methods, operators and functions. Methods are associated with an object and are inheritable. Subroutines and operators are not. Other than that though there is a lot of overlap. \"A function\" doesn't really have a specific definition, but is more of a generic term used when talking about code reference type of things.\n\nMethods don't have a separate scope from the object they are attached to. If the object is in scope, the method will be.\n\nA subroutine is really just another type of object. It has a code reference and has ROUTINE semantics attached to it. The same holds for operators. Operators are really just subroutines with a funny calling convention. That being the case, scoping for subroutines very closely follows scoping rules for any other Raku variable type.\n\nIn general, subroutines are \"my\" variables by default (if you don't specify, the \"my\" is implicit), meaning scoping is lexical to the enclosing block and flows inward. A subroutine defined within a block will be visible to everything inside that block, even other blocks within that block. However, any inner block can define its own subroutine with the same name and that will be used in preference to the routine from an outer block. That implies you can easily override / redefine core functions from the Raku setting. The setting is the collection of built in functions supplied by Raku, typically and somewhat incongruously referred to as \"CORE\" even though technically it is the outermost scope. ( SKIN? BARK? CRUST? ... oooo! EXOSKELETON! :-) )\n\nAlternately, subroutines may be declared as an \"our\" variable making it a package global, visible anywhere in the packages' namespace. That is somewhat discouraged though as it pollutes the namespace and reduces the granularity of control.\n\nThere are several ways to modify the relative scope of a subroutine (any item in the symbol table really) by adding modifiers to the name.\n\n```\nCALLER # Contextual symbols in the immediate caller's lexical scope\nOUTER # Symbols in the next outer lexical scope\nUNIT # Symbols in the outermost lexical scope of compilation unit\nSETTING # Lexical symbols in the unit's DSL (usually CORE)\nPARENT # Symbols in this package's parent package (or lexical scope)\n\n```\n\n```\n# call a routine before it has been defined\nsay log(); # prints: outer\n\n# define a subroutine that overrides a CORE function\nsub log { 'outer' }; \n{\n # redefine the subroutine in this block\n sub log { 'inner' };\n {\n # redefine the subroutine yet again\n sub log { 'way down inside' };\n \n # call it within this block\n say log(); # prints: way down inside\n \n # call it from the block one level out\n say &OUTER::log(); # prints: inner\n \n # call it from the block two levels out\n say &OUTER::OUTER::log(); # prints: outer\n \n # call it from the outermost block\n say &UNIT::log(); # prints: outer\n \n # call a subroutine that is post declared in outermost scope\n outersub()\n }\n\n {\n # subroutine in an inner block that doesn't redefine it\n # uses definition from nearest enclosing block\n say log(); # prints: inner\n }\n # call it within this block\n say log(); # prints: inner\n \n # call it from the block one level out\n say &OUTER::log(); # prints: outer\n}\n\nsub outersub{ \n # call subroutine within this block - gets outer sub\n say log(); # prints: outer\n \n # call subroutine from the scope of the callers block\n say &CALLER::log(); # prints: way down inside\n \n # call subroutine from the outer scope of the callers block\n say &CALLER::OUTER::log(); # prints: inner\n \n # call the original overridden CORE routine\n say &CORE::log(e); # prints: 1 ( natural log of e )\n}\n\n```\n\nLabels are less interesting and are typically useful only for control flow in looping constructs. They generally follow the same scoping rules as \"my\" variables. There is nearly always easier ways to do control flow though, so they aren't heavily used." } ]
[ { "role": "user", "content": "Definition\n\nIn object-oriented programming, a **sealed** or **final class** is one which cannot be inherited from.\n\nClasses are sometimes made non-subclassable in this way if the author feels that it would not be useful or even undesirable for subclasses to be created from them. Moreover, in a compiled language, knowing that a class cannot be subclassed, may enable optimizations to be made.\n\nRather than sealing the entire class, it may be possible to just seal certain methods for the same reasons and with the same potential benefits.\n\nTask\n\nIf your language supports the object oriented paradigm, explain what support it has for sealed classes and/or methods and, if there is no support, what if anything can be done to simulate them. If possible illustrate your answer with an example.\n\nIf your language does not support the object oriented paradigm (or its inheritance aspect), you may either simply say so, omit the task altogether or describe any equivalent structure(s) and restrictions on use which the language does have.\n\nReference\n\n* Inheritance Non-subclassable classes\n\nRelated task\n\n* Classes\n* Inheritance/Single\n* Inheritance/Multiple" }, { "role": "assistant", "content": "Raku doesn't have final class but Roles is normally used to mimic the goal.\n\n```\n# 20240626 Raku programming solution\n\nrole MovieWatcherRole { has Str $.name;\n method WatchMovie() { say \"$.name is watching the movie.\" }\n method EatPopcorn() { say \"$.name is enjoying the popcorn.\" }\n}\n\nclass MovieWatcher does MovieWatcherRole {\n method new(Str $name) { self.bless(:$name) }\n}\n\nclass ParentMovieWatcher is MovieWatcher { }\n\nrole ChildMovieWatcherRole {\n method EatPopcorn() { say \"$.name is eating too much popcorn.\" }\n}\n\nclass ChildMovieWatcher is MovieWatcher does ChildMovieWatcherRole { }\n\nrole YoungChildMovieWatcherRole {\n method WatchMovie() { \n say \"Sorry, $.name, you are too young to watch the movie.\" \n }\n}\n\nclass YoungChildMovieWatcher is ChildMovieWatcher does YoungChildMovieWatcherRole { }\n\nfor ParentMovieWatcher.new('Donald'),\n ChildMovieWatcher.new('Lisa'),\n YoungChildMovieWatcher.new('Fred')\n{ .WatchMovie and .EatPopcorn }\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Task[edit]\n\nFind the index of a string (needle) in an indexable, ordered collection of strings (haystack).\n\nRaise an exception if the needle is missing.\n\nIf there is more than one occurrence then return the smallest index to the needle.\n\nExtra credit\n\nReturn the largest index to a needle that has multiple occurrences in the haystack.\n\nSee also\n\n* Search a list of records\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo Star version 2016.07\n\n```\nmy @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;\n \nfor <Washington Bush> -> $needle {\n say \"$needle -- { @haystack.first($needle, :k) // 'not in haystack' }\";\n}\n```\n\nOutput:\n\n```\nWashington -- not in haystack\nBush -- 4\n\n```\n\nOr, including the \"extra credit\" task:\n\n**Works with**: Rakudo Star version 2016.07\n\n```\nmy Str @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;\n\nfor <Washingston Bush> -> $needle {\n my $first = @haystack.first($needle, :k);\n\n if defined $first {\n my $last = @haystack.first($needle, :k, :end);\n say \"$needle -- first at $first, last at $last\";\n }\n else {\n say \"$needle -- not in haystack\";\n }\n}\n```\n\nOutput:\n\n```\nWashingston -- not in haystack\nBush -- first at 4, last at 7\n\n```\n\nThe built-in method `.first` takes a smart-matcher, and returns the first matching list element. \nThe `:k` adverb tells it to return the key (a.k.a. list index) instead of the value of the matching element. \nThe `:end` adverb tells it to start searching from the end of the list.\n\nIf you plan to do many searches on the same large list, you might want to build a search hash first for efficient look-up:\n\n```\nmy @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;\n\nmy %index;\n%index{.value} //= .key for @haystack.pairs;\n\nfor <Washington Bush> -> $needle {\n say \"$needle -- { %index{$needle} // 'not in haystack' }\";\n}\n```" } ]
[ { "role": "user", "content": "Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. \nBut what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?\n\nTask[edit]\n\nWrite a function/method/etc. that can find the first element in a given list matching a given condition. \nIt should be as generic and reusable as possible. \n(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)\n\nThen to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.\n\nData set\n\nThe data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:\n\n```\n[\n { \"name\": \"Lagos\", \"population\": 21.0 },\n { \"name\": \"Cairo\", \"population\": 15.2 },\n { \"name\": \"Kinshasa-Brazzaville\", \"population\": 11.3 },\n { \"name\": \"Greater Johannesburg\", \"population\": 7.55 },\n { \"name\": \"Mogadishu\", \"population\": 5.85 },\n { \"name\": \"Khartoum-Omdurman\", \"population\": 4.98 },\n { \"name\": \"Dar Es Salaam\", \"population\": 4.7 },\n { \"name\": \"Alexandria\", \"population\": 4.58 },\n { \"name\": \"Abidjan\", \"population\": 4.4 },\n { \"name\": \"Casablanca\", \"population\": 3.98 }\n]\n\n```\n\nHowever, you shouldn't parse it from JSON, but rather represent it natively in your programming language.\n\n* The top-level data structure should be an **ordered** collection *(i.e. a list, array, vector, or similar)*.\n* Each element in this list should be an **associative** collection that maps from keys to values *(i.e. a struct, object, hash map, dictionary, or similar)*.\n* Each of them has two entries: One string value with key \"name\", and one numeric value with key \"population\".\n* You may rely on the list being sorted by population count, as long as you explain this to readers.\n\nIf any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.\n\nTest cases\n\n| Search | Expected result |\n| --- | --- |\n| Find the (zero-based) **index** of the first city in the list whose **name is \"Dar Es Salaam\"** | 6 |\n| Find the **name** of the first city in this list whose **population is less than 5 million** | Khartoum-Omdurman |\n| Find the **population** of the first city in this list whose **name starts with the letter \"A\"** | 4.58 |\n\nGuidance\n\nIf your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called \"find\\_index\" or similar), that takes two arguments:\n\n1. The list to search through.\n2. A function/lambda/closure (the so-called \"predicate\"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.\n\nIf this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.\n\nRelated tasks\n\n* Search a list\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe built-in method .first fulfills the requirements of this task. \nIt takes any smart-matcher as a predicate. The :k adverb makes it return the key (i.e. numerical index) instead of the value of the element.\n\n**Works with**: Rakudo version 2016.08\n\n```\nmy @cities =\n { name => 'Lagos', population => 21.0 },\n { name => 'Cairo', population => 15.2 },\n { name => 'Kinshasa-Brazzaville', population => 11.3 },\n { name => 'Greater Johannesburg', population => 7.55 },\n { name => 'Mogadishu', population => 5.85 },\n { name => 'Khartoum-Omdurman', population => 4.98 },\n { name => 'Dar Es Salaam', population => 4.7 },\n { name => 'Alexandria', population => 4.58 },\n { name => 'Abidjan', population => 4.4 },\n { name => 'Casablanca', population => 3.98 },\n;\n\nsay @cities.first(*<name> eq 'Dar Es Salaam', :k);\nsay @cities.first(*<population> < 5).<name>;\nsay @cities.first(*<name>.match: /^A/).<population>;\n\n```\n\nOutput:\n\n```\n6\nKhartoum-Omdurman\n4.58\n\n```" } ]
[ { "role": "user", "content": "The goal is to verify the presence of a word or regular expression within several paragraphs of text (structured or not) and to format the output of the relevant paragraphs before putting them on the standard output.\n\nSo here, let’s imagine that we are trying to verify the presence of a keyword \"SystemError\" within what I want to call \"the paragraphs\" \"Traceback (most recent call last):\" in the file Traceback.txt\n\n```\ncat Traceback.txt :\n\n2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.\nTraceback (most recent call last):\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py\", line 99, in run\n result = plugin.run()\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/processes.py\", line 18, in run\n for process_info in info.get_all_process_info():\n File \"/usr/lib/python3/dist-packages/landscape/lib/process.py\", line 39, in get_all_process_info\n process_info = self.get_process_info(process_id)\n File \"/usr/lib/python3/dist-packages/landscape/lib/process.py\", line 61, in get_process_info\n cmd_line = file.readline()\n File \"/usr/lib/python3.6/encodings/ascii.py\", line 26, in decode\n return codecs.ascii_decode(input, self.errors)[0]\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 152: ordinal not in range(128)\n\n2018-06-19 23:19:34,877 ERROR Processes plugin raised an exception.\nTraceback (most recent call last):\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n\n[Tue Jan 21 16:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):\n[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir\n[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n\n[Tue Jan 21 17:16:19.250245 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] Traceback (most recent call last):\n[Tue Jan 21 17:16:19.250679 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] File \"/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi\", line 5, in <module>\n[Tue Jan 21 17:16:19.251735 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] from test import app as application\n[Tue Jan 21 17:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] ImportError: cannot import name app\n\n2021-04-23 17:13:14,425 ERROR Network plugin raised an exception.\nTraceback (most recent call last):\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/sysinfo.py\", line 99, \nin run\n result = plugin.run()\n File \"/usr/lib/python3/dist-packages/landscape/sysinfo/network.py\", line 36, \nin run\n device_info = self._get_device_info()\n File \"/usr/lib/python3/dist-packages/landscape/lib/network.py\", line 163, in \nget_active_device_info\n speed, duplex = get_network_interface_speed(\n File \"/usr/lib/python3/dist-packages/landscape/lib/network.py\", line 249, in \nget_network_interface_speed\n res = status_cmd.tostring()\nAttributeError: 'array.array' object has no attribute 'tostring'\n\n11/01 18:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| TypeError: 'NoneType' object is not iterable\n\n12/01 19:24:57.726 ERROR| log:0072| post-test sysinfo error: 11/01 18:24:57.727 ERROR| traceback:0013| Traceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory\n\nTraceback (most recent call last):\n File \"/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py\", line 1492, in WaitForUpdateTask\n WaitForTask(task)\n File \"/usr/lib/vmware-vpx/pyJack/pyVim/task.py\", line 123, in WaitForTask\n raise task.info.error\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n\n```\n\nThe expected result must be formated with ---------------- for paragraph's separator AND \"Traceback (most recent call last):\" as the beginning of each relevant's paragraph :\n\n```\nTraceback (most recent call last):\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n----------------\nTraceback (most recent call last):\n[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir\n[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n----------------\nTraceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory\n----------------\nTraceback (most recent call last):\n File \"/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py\", line 1492, in WaitForUpdateTask\n WaitForTask(task)\n File \"/usr/lib/vmware-vpx/pyJack/pyVim/task.py\", line 123, in WaitForTask\n raise task.info.error\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n----------------\n\n```" }, { "role": "assistant", "content": "Generalized. Pipe in the file from the shell, user definable search term and entry point.\n\n```\nunit sub MAIN ( :$for, :$at = 0 );\n\nput slurp.split( /\\n\\n+/ ).grep( { .contains: $for } )\n .map( { .substr: .index: $at } )\n .join: \"\\n----------------\\n\"\n\n```\n\nExample output using command line:\n\n```\n raku search.raku --for='SystemError' --at='Traceback' < traceback.txt\n\n```\n\n*Matches expected except for not having a extraneous trailing paragraph separator.*\n\n```\nTraceback (most recent call last):\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n----------------\nTraceback (most recent call last):\n[Tue Jan 21 16:16:19.252221 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] SystemError: unable to access /home/dir\n[Tue Jan 21 16:16:19.249067 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Failed to exec Python script file '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n[Tue Jan 21 16:16:19.249609 2020] [wsgi:error] [pid 6515:tid 3041002528] [remote 10.0.0.12:50757] mod_wsgi (pid=6515): Exception occurred processing WSGI script '/home/pi/RaspBerryPiAdhan/www/sysinfo.wsgi'.\n----------------\nTraceback (most recent call last): 11/01 18:24:57.728 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/common_lib/log.py\", line 70, in decorated_func 11/01 18:24:57.729 ERROR| traceback:0013| fn(*args, **dargs) 11/01 18:24:57.730 ERROR| traceback:0013| File \"/tmp/sysinfo/autoserv-0tMj3m/bin/base_sysinfo.py\", line 286, in log_after_each_test 11/01 18:24:57.731 ERROR| traceback:0013| old_packages = set(self._installed_packages) 11/01 18:24:57.731 ERROR| traceback:0013| SystemError: no such file or directory\n----------------\nTraceback (most recent call last):\n File \"/usr/lib/vmware-vpx/vsan-health/pyMoVsan/VsanClusterPrototypeImpl.py\", line 1492, in WaitForUpdateTask\n WaitForTask(task)\n File \"/usr/lib/vmware-vpx/pyJack/pyVim/task.py\", line 123, in WaitForTask\n raise task.info.error\n vmodl.fault.SystemError: (vmodl.fault.SystemError) {\n dynamicType = ,\n dynamicProperty = (vmodl.DynamicProperty) [],\n msg = 'A general system error occurred: Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.',\n faultCause = ,\n faultMessage = (vmodl.LocalizableMessage) [],\n reason = 'Unable to complete Sysinfo operation. Please see the VMkernel log file for more details.: Sysinfo error: Bad parameterSee VMkernel log for details.'\n }\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a temporary file, **securely and exclusively** (opening it such that there are no possible race conditions).\n\nIt's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the \"no race conditions\" criteria).\n\nThe function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nThis is something best done with a module which is heavily tested, tries to account for all corner cases and automatically cleans up after itself.\n\nAlmost verbatim from the synopsis:\n\n```\nuse File::Temp;\n\n# Generate a temp file in a temp dir\nmy ($filename0,$filehandle0) = tempfile;\n\n# specify a template for the filename\n# * are replaced with random characters\nmy ($filename1,$filehandle1) = tempfile(\"******\");\n\n# Automatically unlink files at DESTROY (this is the default)\nmy ($filename2,$filehandle2) = tempfile(\"******\", :unlink);\n\n# Specify the directory where the tempfile will be created\nmy ($filename3,$filehandle3) = tempfile(:tempdir(\"/path/to/my/dir\"));\n\n# don't unlink this one\nmy ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink);\n\n# specify a prefix, a suffix, or both for the filename\nmy ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(\".txt\"));\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFor each number list of **6**-digit SEDOLs, calculate and append the checksum digit.\n\nThat is, given this input:\n\n```\n710889\nB0YBKJ\n406566\nB0YBLH\n228276\nB0YBKL\n557910\nB0YBKR\n585284\nB0YBKT\nB00030\n\n```\n\nProduce this output:\n\n```\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\nB000300\n\n```\n\nExtra credit\n\nCheck each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string.\n\nRelated tasks\n\n* Luhn test\n* ISIN" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: rakudo version 2015-12-17\n\n```\nsub sedol( Str $s ) {\n die 'No vowels allowed' if $s ~~ /<[AEIOU]>/;\n die 'Invalid format' if $s !~~ /^ <[0..9B..DF..HJ..NP..TV..Z]>**6 $ /;\n\n my %base36 = (flat 0..9, 'A'..'Z') »=>« ^36;\n my @weights = 1, 3, 1, 7, 3, 9;\n\n my @vs = %base36{ $s.comb };\n my $checksum = [+] @vs Z* @weights;\n my $check_digit = (10 - $checksum % 10) % 10;\n return $s ~ $check_digit;\n}\n\nsay sedol($_) for <\n 710889\n B0YBKJ\n 406566\n B0YBLH\n 228276\n B0YBKL\n 557910\n B0YBKR\n 585284\n B0YBKT\n B00030\n>;\n\n```" } ]
[ { "role": "user", "content": "In epidemiology, retrospective analyses have well-known limitations compared to prospective studies.\n\nOne such limitation is the occurrence of *selection bias* in the choice of subjects between treated\nand untreated groups about whom the data is collected. For example, a treatment may have only been\ngiven to persons who were less severely ill, which would bias the results in favor of such subjects\nappearing to have done better because of the treatment when the biased group is then compared to those\nwho who did not receive the study treatment. Or, in a retrospective study, there may a choice to place\nsubjects in a particular study group using a method which is inadvertently biased by the outcome being\nmeasured. Creating a programming example of a simulation of such selection bias in the design of a\nretrospective study is the topic of this task.\n\nThe genuine, historical example (only partially approximated in this task) is of a study done of persons who, over a course\nof 180 days, may or may not have become infected with Covid-19. Prior to becoming ill, these subjects may or may not have taken an available medication, which was actually taken on a particular schedule not used here, but is approximated by stating the medication was taken in doses of 3, 6, or 9 mg daily. The historical study then divided its subjects into three groups based on their cumulative dosage of the study medication:\n\n* Group UNTREATED were those who did not take the study medication at all before they got Covid-19, including those who exited the study period without Covid-19 and having never taken the study medication.\n\n* Group IRREGULAR is those who took the study medication but whose cumulative dose was less than a certain amount (approximated for our purposes as 100 mg) before they either came down with Covid-19 during the study or the study period ended.\n\n* Group REGULAR is those who took (our approximation is >= 100 mg) of the study medication either before they came down with Covid-19 or took >= 100 mg by the end of the study and never became infected during the study.\n\nAssumptions for the study simulation programming task\n\n* Daily risk of getting Covid-19 infection for each subject was 0.1% per day, or 18% over the 180 cumulative days of the study.\n\n* The probability of starting treatment medication for anyone not already taking it was 0.5% per day. For those who started medication, the chance of continuing the treatment was increased 50-fold to 25% each day, since most who started the medication continued to take it to some extent.\n\n* Study dose per day is random between the approximation for the simulation of 3, 6 and 9 mg. The daily cumulative dosage is used to determine the group the subject is in, unless a subject develops Covid-19. If a subject was diagnosed with Covid-19, their group at the time of that diagnosis is used in the statistical analysis of that group.\n\nTask\n\n* Create a simulation of the subjects, keeping track of their medication dosages, group membership, and Covid-19 status during the study.\n\n* Use at least 1000 subjects in the simulation over the 180 days (historically, the study size was 80,000).\n\n* Statistics used are to be the Kruskal statistic for the analysis of multiple groups, with the boolean study outcome variable whether the subject got Covid-19 during the study period, analyzed versus category. If the programming language does not have a statistical package for such a test, calculation of the Kruskal H statistic may be used, since any values of H over about 50 are considered very highly indicative of significant group difference. A description of that test is found at Kruskal-Wallis test.\n\n* You should get a statistical result highly favoring the REGULAR group.\n\nStretch task\n\n* Show monthly outcomes.\n\nA note regarding outcome: Note that by simulation design all subjects must have an IDENTICAL risk, that is 0.1 per cent or p = 0.001 per day, of developing Covid-19. Because of the design, any statistical differences between the groups CANNOT come from an influence of the treatment on that risk, but must come from some other feature of the study design.\n\nSee also\n: * Wikipedia - Selection Bias * Wikipedia - Retrospective studies * UCDavis (pdf) Challenges in Retrospective studies" }, { "role": "assistant", "content": "**Translation of**: Phix\n\n```\n# 20221025 Raku programming solution\n\nenum <UNTREATED REGULAR IRREGULAR>;\nmy \\DOSE_FOR_REGULAR = 100;\nmy ($nSubjects,$duration,$interval) = 10000, 180, 30;\nmy (@dosage,@category,@hadcovid) := (0,UNTREATED,False)>>.&{($_ xx $nSubjects).Array};\n\nsub update($pCovid=1e-3, $pStartTreatment=5e-3, $pRedose=¼, @dRange=<3 6 9>) {\n for 0 ..^ @dosage.elems -> \\i { \n unless @hadcovid[i] { \n if rand < $pCovid { \n @hadcovid[i] = True\n } else {\n my $dose = @dosage[i];\n if $dose==0 && rand < $pStartTreatment or $dose > 0 && rand < $pRedose { \n\t @dosage[i] = $dose += @dRange.roll;\n @category[i] = ($dose > DOSE_FOR_REGULAR) ?? REGULAR !! IRREGULAR\n } \n } \n } \n } \n}\n\nsub kruskal (@sets) {\n my $n = ( my @ranked = @sets>>.List.flat.sort ).elems;\n my @sr = 0 xx @sets.elems;\n my $ix = (@ranked.first: * == True, :k)+1, \n my ($arf,$art) = ($ix, $ix+$n) >>/>> 2;\n\n for @sets.kv -> \\i,@set { for @set -> $b { @sr[i] += $b ?? $art !! $arf } } \n\n my $H = [+] @sr.kv.map: -> \\i,\\s { s*s/@sets[i].elems }\n return 12/($n*($n+1)) * $H - 3 * ($n + 1)\n}\n\nsay \"Total subjects: $nSubjects\\n\";\n\nmy ($midpoint,$unt,$irr,$reg,$hunt,$hirr,$hreg,@sunt,@sirr,@sreg)=$duration div 2;\n\nfor 1 .. $duration -> \\day { \n update();\n if day %% $interval or day == $duration or day == $midpoint { \n @sunt = @hadcovid[ @category.grep: UNTREATED,:k ];\n @sirr = @hadcovid[ @category.grep: IRREGULAR,:k ]; \n @sreg = @hadcovid[ @category.grep: REGULAR,  :k ]; \n ($unt,$hunt,$irr,$hirr,$reg,$hreg)=(@sunt,@sirr,@sreg).map:{|(.elems,.sum)}\n } \n if day %% $interval {\n printf \"Day %d:\\n\",day;\n printf \"Untreated: N = %4d, with infection = %4d\\n\", $unt,$hunt;\n printf \"Irregular Use: N = %4d, with infection = %4d\\n\", $irr,$hirr;\n printf \"Regular Use: N = %4d, with infection = %4d\\n\\n\",$reg,$hreg\n } \n if day == $midpoint | $duration { \n my $stage = day == $midpoint ?? 'midpoint' !! 'study end';\n printf \"At $stage, Infection case percentages are:\\n\";\n printf \" Untreated : %f\\n\", 100*$hunt/$unt;\n printf \" Irregulars: %f\\n\", 100*$hirr/$irr;\n printf \" Regulars  : %f\\n\\n\",100*$hreg/$reg\n } \n}\n\nprintf \"Final statistics: H = %f\\n\", kruskal ( @sunt, @sirr, @sreg )\n\n```\n\nOutput:\n\n```\nTotal subjects: 10000\n\nDay 30:\nUntreated: N = 8616, with infection = 314\nIrregular Use: N = 1383, with infection = 27\nRegular Use: N = 1, with infection = 0\n\nDay 60:\nUntreated: N = 7511, with infection = 561\nIrregular Use: N = 2308, with infection = 87\nRegular Use: N = 181, with infection = 1\n\nDay 90:\nUntreated: N = 6571, with infection = 760\nIrregular Use: N = 2374, with infection = 141\nRegular Use: N = 1055, with infection = 19\n\nAt midpoint, Infection case percentages are:\n Untreated : 11.565972\n Irregulars: 5.939343\n Regulars  : 1.800948\n\nDay 120:\nUntreated: N = 5757, with infection = 909\nIrregular Use: N = 2097, with infection = 189\nRegular Use: N = 2146, with infection = 61\n\nDay 150:\nUntreated: N = 5092, with infection = 1054\nIrregular Use: N = 1832, with infection = 238\nRegular Use: N = 3076, with infection = 132\n\nDay 180:\nUntreated: N = 4530, with infection = 1172\nIrregular Use: N = 1615, with infection = 282\nRegular Use: N = 3855, with infection = 229\n\nAt study end, Infection case percentages are:\n Untreated : 25.871965\n Irregulars: 17.461300\n Regulars  : 5.940337\n\nFinal statistics: H = 248.419454\n```" } ]
[ { "role": "user", "content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nCopy part of input records to an output file.\n\nShow how file processing as known from PL/I or COBOL can be implemented in the\nlanguage of your choice.\n\nHere, a file is not 'just' a sequence of bytes or lines but a sequence of *records* (structured data).\n\nThe structure is usually described by declarations contained in an *INCLUDE* file (PL/I) or *COPY BOOK* (COBOL).\n\nThe *by name* assignment is a little extra available in PL/I.\n\nData conversions may be necessary (as shown here for data element *c* in the Go listing)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.10\n\nI have no idea how PL/I or COBOL store records and little enthusiasm to research it. If the task author can't be bothered to spell out what the format should look like, then I have no compunction about just making something up out of whole cloth. In the absence of better guidance I am going to make a binary encoded data file format with fixed sized fields consisting of a mix of ISO-8859-1 encoded text and raw binary (hex) encoded integers.\n\nThis is WAY more complicated than it could be. Could achieve the same effect in one or two lines of code, but this explicitly shows some of the possible mechanics.\n\nSince the sfc.dat file is binary encoded, I can't include it here easily as text so here is a link to an online copy instead.\n\n```\nmy @format = ( # arbitrary and made up record format\n 'field a' => { offset => 0, length => 5, type => 'Str' },\n 'field b' => { offset => 5, length => 5, type => 'Str' },\n 'field c' => { offset => 10, length => 4, type => 'Int' },\n 'field d' => { offset => 14, length => 1, type => 'Str' },\n 'field e' => { offset => 15, length => 5, type => 'Str' }\n);\n\nmy $record-length = @format[*]».value».<length>.sum;\n\nmy $in = './sfc.dat'.IO.open :r :bin;\n\nsay \"Input data as read from $in:\";\nmy @records;\[email protected]: get-record($in, $record-length) until $in.eof;\n.perl.say for @records;\n\n# not going to bother to actually write out to a file, if you really want to,\n# supply a file handle to a local file\nsay \"\\nOutput:\";\nmy $outfile = $*OUT; # or some other filename, whatever.\n\nfor @records -> $r {\n $outfile.printf( \"%-5s%s%08x%5s\\n\", flat $r.{'field a','field d','field c'}, 'xxxxx' );\n}\n\nsub get-record($fh, $bytes) {\n my $record = $fh.read($bytes);\n return ().Slip unless $record.elems == $bytes;\n my %r = @format.map: {\n .key => do given $_.value.<type> -> $type\n {\n when $type eq 'Str' { $record.subbuf($_.value.<offset>, $_.value.<length>).decode }\n when $type eq 'Int' { sum $record.subbuf($_.value.<offset>, $_.value.<length>) Z+< (24,16,8,0) }\n default { $record.subbuf($_.value.<offset>, $_.value.<length>) } # Buf\n }\n }\n}\n\n```\n\nOutput:\n\n```\nInput data as read from ./sfc.dat:\n${\"field a\" => \"A \", \"field b\" => \"bbbbB\", \"field c\" => 1, \"field d\" => \"+\", \"field e\" => \"d2345\"}\n${\"field a\" => \"AA \", \"field b\" => \"bbbBB\", \"field c\" => 2, \"field d\" => \"+\", \"field e\" => \"1d345\"}\n${\"field a\" => \"AAA \", \"field b\" => \"bbBBB\", \"field c\" => 3, \"field d\" => \"+\", \"field e\" => \"12d45\"}\n${\"field a\" => \"AAAA \", \"field b\" => \"bBBBB\", \"field c\" => 4, \"field d\" => \"-\", \"field e\" => \"123d5\"}\n${\"field a\" => \"AAAAA\", \"field b\" => \"BBBBB\", \"field c\" => 3729368837, \"field d\" => \"-\", \"field e\" => \"1234d\"}\n\nOutput:\nA +00000001xxxxx\nAA +00000002xxxxx\nAAA +00000003xxxxx\nAAAA -00000004xxxxx\nAAAAA-de49a705xxxxx\n```" } ]
[ { "role": "user", "content": "Task\n\nThis is admittedly a trivial task but I thought it would be interesting to see how succinctly (or otherwise) different languages can handle it.\n\nGiven the string: \"abracadabra\", replace programatically:\n\n* the first 'a' with 'A'\n* the second 'a' with 'B'\n* the fourth 'a' with 'C'\n* the fifth 'a' with 'D'\n* the first 'b' with 'E'\n* the second 'r' with 'F'\n\nNote that there is no replacement for the third 'a', second 'b' or first 'r'.\n\nThe answer should, of course, be : \"AErBcadCbFD\".\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": "Set up to not particularly rely on absolute structure of the word. Demonstrate with both the original 'abracadabra' and with a random shuffled instance.\n\n```\nsub mangle ($str is copy) {\n $str.match(:ex, 'a')».from.map: { $str.substr-rw($_, 1) = 'ABaCD'.comb[$++] };\n $str.=subst('b', 'E');\n $str.substr-rw($_, 1) = 'F' given $str.match(:ex, 'r')».from[1];\n $str\n}\n\nsay $_, ' -> ', .&mangle given 'abracadabra';\n\nsay $_, ' -> ', .&mangle given 'abracadabra'.comb.pick(*).join;\n\n```\n\nOutput:\n\n```\nabracadabra -> AErBcadCbFD\ncaarabadrab -> cABraECdFDb\n```" } ]
[ { "role": "user", "content": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n \nThe task is:\n\n```\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n```\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\nSee also\n\n* OEIS: A003052 - Self numbers or Colombian numbers * Wikipedia: Self numbers" }, { "role": "assistant", "content": "Translated the low memory version of the Go entry but showed only the first 50 self numbers. The machine for running this task (a Xeon E3110+8GB memory) is showing its age as, 1) took over 6 minutes to complete the Go entry, 2) not even able to run the other two Go alternative entries and 3) needed over 47 minutes to reach 1e6 iterations here. Anyway I will try this on an i5 box later to see how it goes.\n\n**Translation of**: Go\n\n```\n# 20201127 Raku programming solution\n\nmy ( $st, $count, $i, $pow, $digits, $offset, $lastSelf, $done, @selfs) =\n now, 0, 1, 10, 1, 9, 0, False;\n\n# while ( $count < 1e8 ) {\nuntil $done {\n my $isSelf = True;\n my $sum = (my $start = max ($i-$offset), 0).comb.sum;\n loop ( my $j = $start; $j < $i; $j+=1 ) {\n if $j+$sum == $i { $isSelf = False and last }\n ($j+1)%10 != 0 ?? ( $sum+=1 ) !! ( $sum = ($j+1).comb.sum ) ;\n }\n if $isSelf {\n $count+=1;\n $lastSelf = $i;\n if $count ≤ 50 {\n @selfs.append: $i;\n if $count == 50 {\n say \"The first 50 self numbers are:\\n\", @selfs;\n $done = True;\n }\n }\n }\n $i+=1;\n if $i % $pow == 0 {\n $pow *= 10;\n $digits+=1 ;\n $offset = $digits * 9\n }\n}\n\n# say \"The 100 millionth self number is \", $lastSelf;\n# say \"Took \", now - $st, \" seconds.\"\n\n```\n\nOutput:\n\n```\nThe first 50 self numbers are:\n[1 3 5 7 9 20 31 42 53 64 75 86 97 108 110 121 132 143 154 165 176 187 198 209 211 222 233 244 255 266 277 288 299 310 312 323 334 345 356 367 378 389 400 411 413 424 435 446 457 468]\n```" } ]
[ { "role": "user", "content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nThere are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example,   **2020**   is a four-digit self describing number:\n\n* position   0   has value   2   and there are two 0s in the number;\n* position   1   has value   0   and there are no 1s in the number;\n* position   2   has value   2   and there are two 2s;\n* position   3   has value   0   and there are zero 3s.\n\nSelf-describing numbers < 100.000.000  are:     1210,   2020,   21200,   3211000,   42101000.\n\nTask Description\n\n1. Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n2. As an optional stretch goal - generate and display the set of self-describing numbers.\n\nRelated tasks\n\n* Fours is the number of letters in the ...\n* Look-and-say sequence\n* Number names\n* Self-referential sequence\n* Spelling of ordinal numbers" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @values = <1210 2020 21200 3211000\n42101000 521001000 6210001000 27 115508>;\n\nfor @values -> $test {\n say \"$test is {sdn($test) ?? '' !! 'NOT ' }a self describing number.\";\n}\n\nsub sdn($n) {\n my $s = $n.Str;\n my $chars = $s.chars;\n my @a = +«$s.comb;\n my @b;\n for @a -> $i {\n return False if $i >= $chars;\n ++@b[$i];\n }\n @b[$_] //= 0 for ^$chars;\n @a eqv @b;\n}\n\n.say if .&sdn for ^9999999;\n\n```\n\nOutput:\n\n```\n1210 is a self describing number.\n2020 is a self describing number.\n21200 is a self describing number.\n3211000 is a self describing number.\n42101000 is a self describing number.\n521001000 is a self describing number.\n6210001000 is a self describing number.\n27 is NOT a self describing number.\n115508 is NOT a self describing number.\n1210\n2020\n21200\n3211000\n\n```" } ]
[ { "role": "user", "content": "This task has been flagged for clarification due to it being believed to be too difficult to implement in a reasonable amount of effort in more than one (usually very specialised) language. It may need to be divided into multiple tasks or modified substantially so that multiple implementations are practical, and that may cause code on this page in its current state to be flagged incorrect afterwards. See this page's Talk page for discussion.\n\nImplement a self-hosting compiler for your language, i.e.:   create a compiler that is implemented in the language it's supposed to compile.\n\nExtra credit for any solution that can compile in an online compiler such as Ideone.\n\nIf this isn't feasible due to language complexity, link to external projects that achieve this task." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse MONKEY-SEE-NO-EVAL;\nEVAL slurp\n\n```" } ]
[ { "role": "user", "content": "Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.\n\n**Semiprimes**   are also known as:\n\n: : : * **semi-primes**\n * **biprimes**\n * **bi-primes**\n * ***2-almost***   primes\n * or simply:   ***P2***\n\nExample\n\n```\n 1679 = 23 × 73 \n\n```\n\n(This particular number was chosen as the length of the Arecibo message).\n\nTask\n\nWrite a function determining whether a given number is semiprime.\n\nSee also\n\n* The Wikipedia article:  semiprime.\n* The Wikipedia article:  almost prime.\n* The OEIS sequence:  A001358: semiprimes  which has a shorter definition: *the product of two primes*." }, { "role": "assistant", "content": "(formerly Perl 6)\nHere is a naive, grossly inefficient implementation.\n\n```\nsub is-semiprime (Int $n --> Bool) {\n not $n.is-prime and\n .is-prime given \n $n div first $n %% *, flat grep &is-prime, 2 .. *;\n}\n\nuse Test;\nmy @primes = flat grep &is-prime, 2 .. 100;\nfor ^5 {\n nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;\n ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2;\n nok is-semiprime([*] my @f3 = @primes.roll(3)), ~@f3;\n nok is-semiprime([*] my @f4 = @primes.roll(4)), ~@f4;\n}\n\n```\n\nOutput:\n\n```\nok 1 - 17\nok 2 - 47 23\nok 3 - 23 37 41\nok 4 - 53 37 67 47\nok 5 - 5\nok 6 - 73 43\nok 7 - 13 53 71\nok 8 - 7 79 37 71\nok 9 - 41\nok 10 - 71 37\nok 11 - 37 53 43\nok 12 - 3 2 47 67\nok 13 - 17\nok 14 - 41 61\nok 15 - 71 31 79\nok 16 - 97 17 73 17\nok 17 - 61\nok 18 - 73 47\nok 19 - 13 19 5\nok 20 - 37 97 11 31\n```\n\n### More efficient example\n\nHere is a more verbose, but MUCH more efficient implementation. Demonstrating using it to find an infinite list of semiprimes and to check a range of integers to find the semiprimes.\n\n**Works with**: Rakudo version 2017.02\n\n```\nsub is-semiprime ( Int $n where * > 0 ) {\n return False if $n.is-prime;\n my $factor = find-factor( $n );\n return True if $factor.is-prime && ( $n div $factor ).is-prime;\n False;\n}\n\nsub find-factor ( Int $n, $constant = 1 ) {\n my $x = 2;\n my $rho = 1;\n my $factor = 1;\n while $factor == 1 {\n $rho *= 2;\n my $fixed = $x;\n for ^$rho {\n $x = ( $x * $x + $constant ) % $n;\n $factor = ( $x - $fixed ) gcd $n;\n last if 1 < $factor;\n }\n }\n $factor = find-factor( $n, $constant + 1 ) if $n == $factor;\n $factor;\n}\n\nINIT my $start = now;\n\n# Infinite list of semiprimes\nconstant @semiprimes = lazy gather for 4 .. * { .take if .&is-semiprime };\n\n# Show the semiprimes < 100\nsay 'Semiprimes less than 100:';\nsay @semiprimes[^ @semiprimes.first: * > 100, :k ], \"\\n\";\n\n# Check individual integers, or in this case, a range\nmy $s = 2⁹⁷ - 1;\nsay \"Is $_ semiprime?: \", .&is-semiprime for $s .. $s + 30;\n\nsay 'elapsed seconds: ', now - $start;\n\n```\n\nOutput:\n\n```\nSemiprimes less than 100:\n(4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95)\n\nIs 158456325028528675187087900671 semiprime?: True\nIs 158456325028528675187087900672 semiprime?: False\nIs 158456325028528675187087900673 semiprime?: False\nIs 158456325028528675187087900674 semiprime?: False\nIs 158456325028528675187087900675 semiprime?: False\nIs 158456325028528675187087900676 semiprime?: False\nIs 158456325028528675187087900677 semiprime?: False\nIs 158456325028528675187087900678 semiprime?: False\nIs 158456325028528675187087900679 semiprime?: False\nIs 158456325028528675187087900680 semiprime?: False\nIs 158456325028528675187087900681 semiprime?: False\nIs 158456325028528675187087900682 semiprime?: False\nIs 158456325028528675187087900683 semiprime?: False\nIs 158456325028528675187087900684 semiprime?: False\nIs 158456325028528675187087900685 semiprime?: False\nIs 158456325028528675187087900686 semiprime?: False\nIs 158456325028528675187087900687 semiprime?: False\nIs 158456325028528675187087900688 semiprime?: False\nIs 158456325028528675187087900689 semiprime?: False\nIs 158456325028528675187087900690 semiprime?: False\nIs 158456325028528675187087900691 semiprime?: False\nIs 158456325028528675187087900692 semiprime?: False\nIs 158456325028528675187087900693 semiprime?: False\nIs 158456325028528675187087900694 semiprime?: False\nIs 158456325028528675187087900695 semiprime?: False\nIs 158456325028528675187087900696 semiprime?: False\nIs 158456325028528675187087900697 semiprime?: False\nIs 158456325028528675187087900698 semiprime?: False\nIs 158456325028528675187087900699 semiprime?: False\nIs 158456325028528675187087900700 semiprime?: False\nIs 158456325028528675187087900701 semiprime?: True\nelapsed seconds: 0.0574433\n```" } ]
[ { "role": "user", "content": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: *lager* and *regal*\n\nTask\n\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as *lager* and *regal*, should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-10-26\n\n```\nmy $words = set slurp(\"unixdict.txt\").lines;\n\nmy @sems = gather for $words.flat -> $word {\n my $drow = $word.key.flip;\n take $drow if $drow ∈ $words and $drow lt $word;\n}\n\nsay $_ ~ ' ' ~ $_.flip for @sems.pick(5);\n\n```\n\nOutput:\n\n```\nabut tuba\navid diva\nbard drab\nloot tool\npart trap\n```" } ]
[ { "role": "user", "content": "Write a program in your language to solve SEND + MORE = MONEY: A Great Puzzle." }, { "role": "assistant", "content": "### Idiomatic\n\n```\nenum <D E M N O R S Y>;\n\nsub find_solution ( ) {\n for ('0'..'9').combinations(8) -> @c {\n .return with @c.permutations.first: -> @p {\n @p[M] !== 0 and\n\n @p[ S,E,N,D].join\n + @p[ M,O,R,E].join\n == @p[M,O,N,E,Y].join\n }\n }\n}\n\nmy @s = find_solution();\nsay \" {@s[ S,E,N,D].join}\";\nsay \" + {@s[ M,O,R,E].join}\";\nsay \"== { @s[M,O,N,E,Y].join}\";\n\n```\n\nOutput:\n\n```\n 9567\n + 1085\n== 10652\n\n```\n\n### Fast\n\nAlternately, a version written in 2015 by Carl Mäsak. Not very concise but quite speedy. Applying the observation that M must be 1 and S must be either 8 or 9 gets the runtime under a tenth of a second.\n\n```\nmy $s = 7;\nwhile ++$s ≤ 9 {\n my $e = -1;\n while ++$e ≤ 9 {\n next if $e == $s;\n \n my $n = -1;\n while ++$n ≤ 9 {\n next if $n == $s|$e;\n \n my $d = -1;\n while ++$d ≤ 9 {\n next if $d == $s|$e|$n;\n\n my $send = $s×10³ + $e×10² + $n×10 + $d; \n my ($m, $o) = 1, -1;\n while ++$o ≤ 9 {\n next if $o == $s|$e|$n|$d|$m;\n \n my $r = -1;\n while ++$r ≤ 9 {\n next if $r == $s|$e|$n|$d|$m|$o;\n \n my $more = $m×10³ + $o×10² + $r×10 + $e;\n my $y = -1;\n while ++$y ≤ 9 {\n next if $y == $s|$e|$n|$d|$m|$o|$r;\n\n my $money = $m×10⁴ + $o×10³ + $n×10² + $e×10 + $y;\n next unless $send + $more == $money;\n say 'SEND + MORE == MONEY' ~ \"\\n$send + $more == $money\";\n }\n }\n }\n }\n }\n }\n}\nprintf \"%.3f elapsed seconds\", now - INIT now;\n\n```\n\nOutput:\n\n```\nSEND + MORE == MONEY\n9567 + 1085 == 10652\n0.080 elapsed seconds\n```" } ]
[ { "role": "user", "content": "Task\n\nInvoke an object method where the name of the method to be invoked can be generated at run time.\n\nRelated tasks\n\n* Respond to an unknown method call.\n* Runtime evaluation" }, { "role": "assistant", "content": "(formerly Perl 6)\nJust for the fun of it, we'll mix in an anonymous role into an integer instead of defining a class.\n\n```\nmy $object = 42 but role { method add-me($x) { self + $x } }\nmy $name = 'add-me';\nsay $object.\"$name\"(5); # 47\n\n```\n\nThe double quotes are required, by the way; without them the variable would be interpreted as a hard ref to a method." } ]
[ { "role": "user", "content": "Task\n\nWrite a function to send an email.\n\nThe function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details.\n\n* If appropriate, explain what notifications of problems/success are given.\n* Solutions using libraries or functions from the language are preferred, but failing that, external programs can be used with an explanation.\n* Note how portable the solution given is between operating systems when multi-OS languages are used.\n\n(Remember to obfuscate any sensitive data used in examples)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse Email::Simple;\n\nmy $to = '[email protected]';\nmy $from = '[email protected]';\nmy $subject = 'test';\nmy $body = 'This is a test.';\n\nmy $email = Email::Simple.create(\n  :header[['To', $to], ['From', $from], ['Subject', $subject]],\n  :body($body)\n);\n\nsay ~$email;\n\n# Note that the following will fail without an actual smtp server that\n# will accept anonymous emails on port 25 (Not very common anymore).\n# Most public email servers now require authentication and encryption.\n\nmy $smtp-server = 'smtp.example.com';\nmy $smtp-port = 25;\n\nawait IO::Socket::Async.connect($smtp-server, $smtp-port).then(\n -> $smtp {\n if $smtp.status {\n given $smtp.result {\n react {\n whenever .Supply() -> $response {\n if $response ~~ /^220/ {\n .print( join \"\\r\\n\",\n \"EHLO $smtp-server\",\n \"MAIL FROM:<{$email.from}>\",\n \"RCPT TO:<{$email.to}>\",\n \"DATA\", $email.body,\n '.', ''\n )\n }\n elsif $response ~~ /^250/ {\n .print(\"QUIT\\r\\n\");\n done\n }\n else {\n say \"Send email failed with: $response\";\n done\n }\n }\n .close\n }\n }\n }\n }\n)\n\n```" } ]
[ { "role": "user", "content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nIn Germany and the Netherlands postal addresses have the form: street name, followed by the house number, in accordance with the national standards DIN 5008 respectively NEN 5825. The problem is that some street names have numbers (e.g. special years) and some house numbers have characters as an extension. It's a real life problem and difficult because in the Netherlands some street names are a tribute to our liberators. The street names have the numbers 40 and 45 indicating the years of war between 1940 and 1945.\n\nTask\n\nWrite code that correctly separates the house number from the street name and presents them both.\n*No static data must be shown, only processed data.*\n\nThe suggested approach is to either use the regular expression in the Scala entry or to devise an equivalent algorithm.\n\nThe test-set:\n\n```\nPlataanstraat 5\nStraat 12\nStraat 12 II\nDr. J. Straat 12\nDr. J. Straat 12 a\nDr. J. Straat 12-14\nLaan 1940 – 1945 37\nPlein 1940 2\n1213-laan 11\n16 april 1944 Pad 1\n1e Kruisweg 36\nLaan 1940-’45 66\nLaan ’40-’45\nLangeloërduinen 3 46\nMarienwaerdt 2e Dreef 2\nProvincialeweg N205 1\nRivium 2e Straat 59.\nNieuwe gracht 20rd\nNieuwe gracht 20rd 2\nNieuwe gracht 20zw /2\nNieuwe gracht 20zw/3\nNieuwe gracht 20 zw/4\nBahnhofstr. 4\nWertstr. 10\nLindenhof 1\nNordesch 20\nWeilstr. 6\nHarthauer Weg 2\nMainaustr. 49\nAugust-Horch-Str. 3\nMarktplatz 31\nSchmidener Weg 3\nKarl-Weysser-Str. 6\n```\n\nReference The Netherlands - Addresses" }, { "role": "assistant", "content": "(formerly Perl 6)\nAn unquestioning translation of the Scala example's regex to show how we lay out such regexes for readability in Raku, except that we take the liberty of leaving the space out of the house number.\n(Hard constants like 1940 and 1945 are a code smell,\nand the task should probably not require such constants unless there is a standard to point to that mandates them.)\nSo expect this solution to change if the task is actually defined reasonably, such as by specifying that four-digit house numbers are excluded in Europe.\n(In contrast, four- and five-digit house numbers are not uncommon\nin places such as the U.S. where each block gets a hundred house numbers\nto play with, and there are cities with hundreds of blocks along a street.)\n\n```\nsay m[\n ( .*? )\n\n [\n \\s+\n (\n | \\d+ [ \\- | \\/ ] \\d+\n | <!before 1940 | 1945> \\d+ <[ a..z I . / \\x20 ]>* \\d*\n )\n ]?\n\n $\n] for lines;\n\n```\n\nOutput:\n\n```\n「Plataanstraat 5」\n 0 => 「Plataanstraat」\n 1 => 「5」\n\n「Straat 12」\n 0 => 「Straat」\n 1 => 「12」\n\n「Straat 12 II」\n 0 => 「Straat」\n 1 => 「12 II」\n\n「Dr. J. Straat 12」\n 0 => 「Dr. J. Straat」\n 1 => 「12」\n\n「Dr. J. Straat 12 a」\n 0 => 「Dr. J. Straat」\n 1 => 「12 a」\n\n「Dr. J. Straat 12-14」\n 0 => 「Dr. J. Straat」\n 1 => 「12-14」\n\n「Laan 1940 – 1945 37」\n 0 => 「Laan 1940 – 1945」\n 1 => 「37」\n\n「Plein 1940 2」\n 0 => 「Plein 1940」\n 1 => 「2」\n\n「1213-laan 11」\n 0 => 「1213-laan」\n 1 => 「11」\n\n「16 april 1944 Pad 1」\n 0 => 「16 april 1944 Pad」\n 1 => 「1」\n\n「1e Kruisweg 36」\n 0 => 「1e Kruisweg」\n 1 => 「36」\n\n「Laan 1940-’45 66」\n 0 => 「Laan 1940-’45」\n 1 => 「66」\n\n「Laan ’40-’45」\n 0 => 「Laan ’40-’45」\n\n「Langeloërduinen 3 46」\n 0 => 「Langeloërduinen」\n 1 => 「3 46」\n\n「Marienwaerdt 2e Dreef 2」\n 0 => 「Marienwaerdt 2e Dreef」\n 1 => 「2」\n\n「Provincialeweg N205 1」\n 0 => 「Provincialeweg N205」\n 1 => 「1」\n\n「Rivium 2e Straat 59.」\n 0 => 「Rivium 2e Straat」\n 1 => 「59.」\n\n「Nieuwe gracht 20rd」\n 0 => 「Nieuwe gracht」\n 1 => 「20rd」\n\n「Nieuwe gracht 20rd 2」\n 0 => 「Nieuwe gracht」\n 1 => 「20rd 2」\n\n「Nieuwe gracht 20zw /2」\n 0 => 「Nieuwe gracht」\n 1 => 「20zw /2」\n\n「Nieuwe gracht 20zw/3」\n 0 => 「Nieuwe gracht」\n 1 => 「20zw/3」\n\n「Nieuwe gracht 20 zw/4」\n 0 => 「Nieuwe gracht」\n 1 => 「20 zw/4」\n\n「Bahnhofstr. 4」\n 0 => 「Bahnhofstr.」\n 1 => 「4」\n\n「Wertstr. 10」\n 0 => 「Wertstr.」\n 1 => 「10」\n\n「Lindenhof 1」\n 0 => 「Lindenhof」\n 1 => 「1」\n\n「Nordesch 20」\n 0 => 「Nordesch」\n 1 => 「20」\n\n「Weilstr. 6」\n 0 => 「Weilstr.」\n 1 => 「6」\n\n「Harthauer Weg 2」\n 0 => 「Harthauer Weg」\n 1 => 「2」\n\n「Mainaustr. 49」\n 0 => 「Mainaustr.」\n 1 => 「49」\n\n「August-Horch-Str. 3」\n 0 => 「August-Horch-Str.」\n 1 => 「3」\n\n「Marktplatz 31」\n 0 => 「Marktplatz」\n 1 => 「31」\n\n「Schmidener Weg 3」\n 0 => 「Schmidener Weg」\n 1 => 「3」\n\n「Karl-Weysser-Str. 6」\n 0 => 「Karl-Weysser-Str.」\n 1 => 「6」\n\n\n```" } ]
[ { "role": "user", "content": "Task\n\nShow that the following remarkable formula gives the sequence of non-square natural numbers:\n\n```\n n + floor(1/2 + sqrt(n)) \n\n```\n\n* Print out the values for   n   in the range   **1**   to   **22**\n* Show that no squares occur for   n   less than one million\n\nThis is sequence   A000037   in the **OEIS** database." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.07\n\n```\nsub nth-term (Int $n) { $n + round sqrt $n }\n\n# Print the first 22 values of the sequence\nsay (nth-term $_ for 1 .. 22);\n\n# Check that the first million values of the sequence are indeed non-square\nfor 1 .. 1_000_000 -> $i {\n say \"Oops, nth-term($i) is square!\" if (sqrt nth-term $i) %% 1;\n}\n\n```\n\nOutput:\n\n```\n(2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27)\n```" } ]
[ { "role": "user", "content": "The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime.\n\nNoting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself.\n\nTask\n\nGenerate and show here the first ten values of the sequence.\n\nOptional extended task\n\nShow the first twenty members of the series.\n\nNotes\n\n* This task asks for the primorial *indices* that create the final primorial prime numbers, so there should be no ten-or-more digit numbers in the program output (although extended precision integers *will* be needed for intermediate results).\n* There is some confusion in the references, but for the purposes of this task the **sequence begins with n = 1**.\n* Probabilistic primality tests are allowed, as long as they are good enough such that the output shown is correct.\n\nRelated tasks\n\n* Primorial numbers\n* Factorial\n\nSee also\n\n* Primorial prime Wikipedia.\n* Primorial prime from The Prime Glossary.\n* Sequence A088411 from The On-Line Encyclopedia of Integer Sequences" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nconstant @primes = |grep *.is-prime, 2..*;\nconstant @primorials = [\\*] 1, @primes;\n\nmy @pp_indexes := |@primorials.pairs.map: {\n .key if ( .value + any(1, -1) ).is-prime\n};\n\nsay ~ @pp_indexes[ 0 ^.. 20 ]; # Skipping bogus first element.\n\n```\n\nOutput:\n\n```\n1 2 3 4 5 6 11 13 24 66 68 75 167 171 172 287 310 352 384 457\n```\n\n### Alternate implementation\n\nmerged from another removed draft task.\n\n```\nmy @primorials = 1, |[\\*] (2..*).grep: &is-prime;\nsub abr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '..' ~ .substr(*-20) ~ \" ({.chars} digits)\" }\n\nmy $limit;\n\nfor ^∞ {\n my \\p = @primorials[$_];\n ++$limit and printf \"%2d: %5s - 1 = %s\\n\", $limit, \"p$_#\", abr p -1 if (p -1).is-prime;\n ++$limit and printf \"%2d: %5s + 1 = %s\\n\", $limit, \"p$_#\", abr p +1 if (p +1).is-prime;\n exit if $limit >= 30\n}\n\n```\n\nOutput:\n\n```\n 1: p0# + 1 = 2\n 2: p1# + 1 = 3\n 3: p2# - 1 = 5\n 4: p2# + 1 = 7\n 5: p3# - 1 = 29\n 6: p3# + 1 = 31\n 7: p4# + 1 = 211\n 8: p5# - 1 = 2309\n 9: p5# + 1 = 2311\n10: p6# - 1 = 30029\n11: p11# + 1 = 200560490131\n12: p13# - 1 = 304250263527209\n13: p24# - 1 = 23768741896345550770650537601358309\n14: p66# - 1 = 19361386640700823163..29148240284399976569 (131 digits)\n15: p68# - 1 = 21597045956102547214..98759003964186453789 (136 digits)\n16: p75# + 1 = 17196201054584064334..62756822275663694111 (154 digits)\n17: p167# - 1 = 19649288510530675457..35580823050358968029 (413 digits)\n18: p171# + 1 = 20404068993016374194..29492908966644747931 (425 digits)\n19: p172# + 1 = 20832554441869718052..12260054944287636531 (428 digits)\n20: p287# - 1 = 71488723083486699645..63871022000761714929 (790 digits)\n21: p310# - 1 = 40476351620665036743..10663664196050230069 (866 digits)\n22: p352# - 1 = 13372477493552802137..21698973741675973189 (1007 digits)\n23: p384# + 1 = 78244737296323701708..84011652643245393971 (1115 digits)\n24: p457# + 1 = 68948124012218025568..25023568563926988371 (1368 digits)\n25: p564# - 1 = 12039145942930719470..56788854266062940789 (1750 digits)\n26: p590# - 1 = 19983712295113492764..61704122697617268869 (1844 digits)\n27: p616# + 1 = 13195724337318102247..85805719764535513291 (1939 digits)\n28: p620# - 1 = 57304682725550803084..81581766766846907409 (1953 digits)\n29: p643# + 1 = 15034815029008301639..38987057002293989891 (2038 digits)\n30: p849# - 1 = 11632076146197231553..78739544174329780009 (2811 digits)\n```" } ]
[ { "role": "user", "content": "Calculate the sequence where each term **an** is the **nth** that has **n** divisors.\n\nTask\n\nShow here, on this page, at least the first **15** terms of the sequence.\n\nSee also\n\n: * OEIS:A073916\n\nRelated tasks\n\n: * Sequence: smallest number greater than previous term with exactly n divisors\n * Sequence: smallest number with exactly n divisors" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\nTry it online!\n\n```\nsub div-count (\\x) {\n return 2 if x.is-prime;\n +flat (1 .. x.sqrt.floor).map: -> \\d {\n unless x % d { my \\y = x div d; y == d ?? y !! (y, d) }\n }\n}\n\nmy $limit = 20;\n\nmy @primes = grep { .is-prime }, 1..*;\n@primes[$limit]; # prime the array. SCNR\n\nput \"First $limit terms of OEIS:A073916\";\nput (1..$limit).hyper(:2batch).map: -> $n {\n ($n > 4 and $n.is-prime) ??\n exp($n - 1, @primes[$n - 1]) !!\n do {\n my $i = 0;\n my $iterator = $n %% 2 ?? (1..*) !! (1..*).map: *²;\n $iterator.first: {\n next unless $n == .&div-count;\n next unless ++$i == $n;\n $_\n }\n }\n};\n\n```\n\n```\nFirst 20 terms of OEIS:A073916\n1 3 25 14 14641 44 24137569 70 1089 405 819628286980801 160 22563490300366186081 2752 9801 462 21559177407076402401757871041 1044 740195513856780056217081017732809 1520\n```" } ]
[ { "role": "user", "content": "Calculate the sequence where each term **an** is the **smallest natural number** greater than the previous term, that has exactly **n** divisors.\n\nTask\n\nShow here, on this page, at least the first **15** terms of the sequence.\n\nSee also\n: * OEIS:A069654\n\nRelated tasks\n: * Sequence: smallest number with exactly n divisors\n * Sequence: nth number with exactly n divisors‎‎" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\n```\nsub div-count (\\x) {\n return 2 if x.is-prime;\n +flat (1 .. x.sqrt.floor).map: -> \\d {\n unless x % d { my \\y = x div d; y == d ?? y !! (y, d) }\n }\n}\n\nmy $limit = 15;\n\nmy $m = 1;\nput \"First $limit terms of OEIS:A069654\";\nput (1..$limit).map: -> $n { my $ = $m = first { $n == .&div-count }, $m..Inf };\n\n```\n\nOutput:\n\n```\nFirst 15 terms of OEIS:A069654\n1 2 4 6 16 18 64 66 100 112 1024 1035 4096 4288 4624\n\n```" } ]
[ { "role": "user", "content": "Calculate the sequence where each term   **an**   is the **smallest natural number** that has exactly   **n**   divisors.\n\nTask\n\nShow here, on this page, at least the first  **15**  terms of the sequence.\n\nRelated tasks\n: * Sequence: smallest number greater than previous term with exactly n divisors\n * Sequence: nth number with exactly n divisors‎‎\n\nSee also\n: * OEIS:A005179" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\n```\nsub div-count (\\x) {\n return 2 if x.is-prime;\n +flat (1 .. x.sqrt.floor).map: -> \\d {\n unless x % d { my \\y = x div d; y == d ?? y !! (y, d) }\n }\n}\n\nmy $limit = 15;\n\nput \"First $limit terms of OEIS:A005179\";\nput (1..$limit).map: -> $n { first { $n == .&div-count }, 1..Inf };\n\n```\n\nOutput:\n\n```\nFirst 15 terms of OEIS:A005179\n1 2 4 6 16 12 64 24 36 48 1024 60 4096 192 144\n```" } ]
[ { "role": "user", "content": "A   **set**  is a collection of elements, without duplicates and without order.\n\nTask\n\nShow each of these set operations:\n\n* Set creation\n* Test m ∈ S -- \"m is an element in set S\"\n* A ∪ B -- *union*; a set of all elements either in set A or in set B.\n* A ∩ B -- *intersection*; a set of all elements in *both* set A and set B.\n* A ∖ B -- *difference*; a set of all elements in set A, except those in set B.\n* A ⊆ B -- *subset*; true if every element in set A is also in set B.\n* A = B -- *equality*; true if every element of set A is in set B and vice versa.\n\nAs an option, show some other set operations.\n \n(If A ⊆ B, but A ≠ B, then A is called a true or proper subset of B, written A ⊂ B or A ⊊ B.)\n\nAs another option, show how to modify a mutable set.\n\nOne might implement a set using an associative array (with set elements as array keys and some dummy value as the values).\n\nOne might also implement a set with a binary search tree, or with a hash table, or with an ordered array of binary bits (operated on with bit-wise binary operators).\n\nThe basic test, m ∈ S, is O(n) with a sequential list of elements, O(*log* n) with a balanced binary search tree, or (O(1) average-case, O(n) worst case) with a hash table.\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```\nuse Test;\n\nmy $a = set <a b c>;\nmy $b = set <b c d>;\nmy $c = set <a b c d e>;\n\nok 'c' ∈ $a, \"c is an element in set A\";\nnok 'd' ∈ $a, \"d is not an element in set A\";\n\nis-deeply $a ∪ $b, set(<a b c d>), \"union; a set of all elements either in set A or in set B\";\nis-deeply $a ∩ $b, set(<b c>), \"intersection; a set of all elements in both set A and set B\";\nis $a (-) $b, set(<a>), \"difference; a set of all elements in set A, except those in set B\";\n\nok $a ⊆ $c, \"subset; true if every element in set A is also in set B\";\nnok $c ⊆ $a, \"subset; false if every element in set A is not also in set B\";\nok $a ⊂ $c, \"strict subset; true if every element in set A is also in set B\";\nnok $a ⊂ $a, \"strict subset; false for equal sets\";\nok $a === set(<a b c>), \"equality; true if every element of set A is in set B and vice-versa\";\nnok $a === $b, \"equality; false for differing sets\";\n\n```\n\nOutput:\n\n```\nok 1 - c is an element in set A\nok 2 - d is not an element in set A\nok 3 - union; a set of all elements either in set A or in set B\nok 4 - intersection; a set of all elements in both set A and set B\nok 5 - difference; a set of all elements in set A, except those in set B\nok 6 - subset; true if every element in set A is also in set B\nok 7 - subset; false if every element in set A is not also in set B\nok 8 - strict subset; true if every element in set A is also in set B\nok 9 - strict subset; false for equal sets\nok 10 - equality; true if every element of set A is in set B and vice-versa\nok 11 - equality; false for differing sets\n```" } ]
[ { "role": "user", "content": "Given two sets of items then if any item is common to any set then the result of applying *consolidation* to those sets is a set of sets whose contents is:\n\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n**Example 1:**\n: Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n\n**Example 2:**\n: Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n\n**Example 3:**\n: Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n\n**Example 4:**\n: The consolidation of the five sets:\n\n : {H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n: Is the two sets:\n\n : {A, C, B, D}, and {G, F, I, H, K}\n\n**See also**\n\n* Connected component (graph theory)\n* Range consolidation" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmulti consolidate() { () }\nmulti consolidate(Set \\this is copy, *@those) {\n gather {\n for consolidate |@those -> \\that {\n if this ∩ that { this = this ∪ that }\n else { take that }\n }\n take this;\n }\n}\n\nenum Elems <A B C D E F G H I J K>;\nsay $_, \"\\n ==> \", consolidate |$_\n for [set(A,B), set(C,D)],\n [set(A,B), set(B,D)],\n [set(A,B), set(C,D), set(D,B)],\n [set(H,I,K), set(A,B), set(C,D), set(D,B), set(F,G,H)];\n\n```\n\nOutput:\n\n```\nset(A, B) set(C, D)\n ==> set(C, D) set(A, B)\nset(A, B) set(B, D)\n ==> set(A, B, D)\nset(A, B) set(C, D) set(D, B)\n ==> set(A, B, C, D)\nset(H, I, K) set(A, B) set(C, D) set(D, B) set(F, G, H)\n ==> set(A, B, C, D) set(H, I, K, F, G)\n```" } ]
[ { "role": "user", "content": "Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. \n \nThere are 81 cards in a deck.\nEach card contains a unique variation of the following four features: *color, symbol, number and shading*.\n\n* there are three colors: \n    *red, green, purple*\n\n* there are three symbols: \n    *oval, squiggle, diamond*\n\n* there is a number of symbols on the card: \n    *one, two, three*\n\n* there are three shadings: \n    *solid, open, striped*\n\nThree cards form a *set* if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped.\n\nThere are two degrees of difficulty: basic and advanced. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets.\n\nWhen creating sets you may use the same card more than once.\n\nTask\n\nWrite code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets.\n\nFor instance:\n\n**DEALT 9 CARDS:**\n\n: green, one, oval, striped\n\n: green, one, diamond, open\n\n: green, one, diamond, striped\n\n: green, one, diamond, solid\n\n: purple, one, diamond, open\n\n: purple, two, squiggle, open\n\n: purple, three, oval, open\n\n: red, three, oval, open\n\n: red, three, diamond, solid\n\n**CONTAINING 4 SETS:**\n\n: green, one, oval, striped\n\n: purple, two, squiggle, open\n\n: red, three, diamond, solid\n\n: green, one, diamond, open\n\n: green, one, diamond, striped\n\n: green, one, diamond, solid\n\n: green, one, diamond, open\n\n: purple, two, squiggle, open\n\n: red, three, oval, open\n\n: purple, one, diamond, open\n\n: purple, two, squiggle, open\n\n: purple, three, oval, open" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe trick here is to allocate three different bits for each enum, with the result that the cards of a matching set OR together to produce a 4-digit octal number that contains only the digits 1, 2, 4, or 7. This OR is done by funny looking [+|], which is the reduction form of +|, which is the numeric bitwise OR. (Because Raku stole the bare | operator for composing junctions instead.)\n\n```\nenum Color (red => 0o1000, green => 0o2000, purple => 0o4000);\nenum Count (one => 0o100, two => 0o200, three => 0o400);\nenum Shape (oval => 0o10, squiggle => 0o20, diamond => 0o40);\nenum Style (solid => 0o1, open => 0o2, striped => 0o4);\n \nmy @deck = Color.enums X Count.enums X Shape.enums X Style.enums;\n \nsub MAIN($DRAW = 9, $GOAL = $DRAW div 2) {\n sub show-cards(@c) { { printf \"%9s%7s%10s%9s\\n\", @c[$_;*]».key } for ^@c }\n\n my @combinations = [^$DRAW].combinations(3);\n\n my @draw;\n repeat until (my @sets) == $GOAL {\n @draw = @deck.pick($DRAW);\n my @bits = @draw.map: { [+] @^enums».value }\n @sets = gather for @combinations -> @c {\n take @draw[@c].item when /^ <[1247]>+ $/ given ( [+|] @bits[@c] ).base(8);\n }\n }\n\n say \"Drew $DRAW cards:\";\n show-cards @draw;\n for @sets.kv -> $i, @cards {\n say \"\\nSet {$i+1}:\";\n show-cards @cards;\n }\n}\n\n```\n\nOutput:\n\n```\nDrew 9 cards:\n purple two diamond open\n red two squiggle striped\n purple three squiggle open\n purple two squiggle striped\n red three oval striped\n red one diamond striped\n purple two oval solid\n green three diamond solid\n red two squiggle open\n\nSet 1:\n purple two diamond open\n purple two squiggle striped\n purple two oval solid\n\nSet 2:\n purple two diamond open\n red one diamond striped\n green three diamond solid\n\nSet 3:\n red two squiggle striped\n red three oval striped\n red one diamond striped\n\nSet 4:\n purple three squiggle open\n red three oval striped\n green three diamond solid\n```" } ]
[ { "role": "user", "content": "Given a left-to-right ordered collection of `e` bits, `b`, where `1 <= e <= 10000`,\nand a zero or more integer `n` :\n\n* Output the result of setting the `n` bits to the right of any set bit in `b`\n\n(if those bits are present in b and therefore also preserving the width, `e`).\n\n**Some examples:**\n\n```\n Set of examples showing how one bit in a nibble gets changed:\n \n n = 2; Width e = 4:\n \n Input b: 1000\n Result: 1110\n \n Input b: 0100\n Result: 0111\n \n Input b: 0010\n Result: 0011\n \n Input b: 0000\n Result: 0000\n \n Set of examples with the same input with set bits of varying distance apart:\n \n n = 0; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 010000000000100000000010000000010000000100000010000010000100010010\n \n n = 1; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011000000000110000000011000000011000000110000011000011000110011011\n \n n = 2; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011100000000111000000011100000011100000111000011100011100111011111\n \n n = 3; Width e = 66:\n \n Input b: 010000000000100000000010000000010000000100000010000010000100010010\n Result: 011110000000111100000011110000011110000111100011110011110111111111\n\n```\n\n**Task:**\n\n* Implement a routine to perform the setting of right-adjacent bits on representations of bits that will scale over the given range of input width `e`.\n* Use it to show, here, the results for the input examples above.\n* Print the output aligned in a way that allows easy checking by eye of the binary input vs output." }, { "role": "assistant", "content": "A left-to-right ordered collection of bits is more commonly referred to as an Integer in Raku.\n\n```\nsub rab (Int $n, Int $b = 1) {\n my $m = $n;\n $m +|= ($n +> $_) for ^ $b+1;\n $m\n}\n\nsub lab (Int $n, Int $b = 1) {\n my $m = $n;\n $m +|= ($n +< $_) for ^ $b+1;\n $m\n}\n\nsay \"Powers of 2 ≤ 8, 0 - Right-adjacent-bits: 2\";\n.&rab(2).base(2).fmt('%04s').say for <8 4 2 1 0>;\n\n# Test with a few integers.\nfor 8,4, 18455760086304825618,5, 5444684034376312377319904082902529876242,15 -> $integer, $bits {\n\n say \"\\nInteger: $integer - Right-adjacent-bits: up to $bits\";\n\n .say for ^$bits .map: -> $b { $integer.&rab($b).base: 2 };\n\n say \"\\nInteger: $integer - Left-adjacent-bits: up to $bits\";\n\n .say for ^$bits .map: -> $b { $integer.&lab($b).fmt(\"%{0~$bits+$integer.msb}b\") };\n\n}\n\n```\n\nOutput:\n\n```\nPowers of 2 ≤ 8, 0 - Right-adjacent-bits: 2\n1110\n0111\n0011\n0001\n0000\n\nInteger: 8 - Right-adjacent-bits: up to 4\n1000\n1100\n1110\n1111\n\nInteger: 8 - Left-adjacent-bits: up to 4\n0001000\n0011000\n0111000\n1111000\n\nInteger: 18455760086304825618 - Right-adjacent-bits: up to 5\n10000000000100000000010000000010000000100000010000010000100010010\n11000000000110000000011000000011000000110000011000011000110011011\n11100000000111000000011100000011100000111000011100011100111011111\n11110000000111100000011110000011110000111100011110011110111111111\n11111000000111110000011111000011111000111110011111011111111111111\n\nInteger: 18455760086304825618 - Left-adjacent-bits: up to 5\n000010000000000100000000010000000010000000100000010000010000100010010\n000110000000001100000000110000000110000001100000110000110001100110110\n001110000000011100000001110000001110000011100001110001110011101111110\n011110000000111100000011110000011110000111100011110011110111111111110\n111110000001111100000111110000111110001111100111110111111111111111110\n\nInteger: 5444684034376312377319904082902529876242 - Right-adjacent-bits: up to 15\n1000000000000001000000000000010000000000000100000000000010000000000010000000000100000000010000000010000000100000010000010000100010010\n1100000000000001100000000000011000000000000110000000000011000000000011000000000110000000011000000011000000110000011000011000110011011\n1110000000000001110000000000011100000000000111000000000011100000000011100000000111000000011100000011100000111000011100011100111011111\n1111000000000001111000000000011110000000000111100000000011110000000011110000000111100000011110000011110000111100011110011110111111111\n1111100000000001111100000000011111000000000111110000000011111000000011111000000111110000011111000011111000111110011111011111111111111\n1111110000000001111110000000011111100000000111111000000011111100000011111100000111111000011111100011111100111111011111111111111111111\n1111111000000001111111000000011111110000000111111100000011111110000011111110000111111100011111110011111110111111111111111111111111111\n1111111100000001111111100000011111111000000111111110000011111111000011111111000111111110011111111011111111111111111111111111111111111\n1111111110000001111111110000011111111100000111111111000011111111100011111111100111111111011111111111111111111111111111111111111111111\n1111111111000001111111111000011111111110000111111111100011111111110011111111110111111111111111111111111111111111111111111111111111111\n1111111111100001111111111100011111111111000111111111110011111111111011111111111111111111111111111111111111111111111111111111111111111\n1111111111110001111111111110011111111111100111111111111011111111111111111111111111111111111111111111111111111111111111111111111111111\n1111111111111001111111111111011111111111110111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\n1111111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\n1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111\n\nInteger: 5444684034376312377319904082902529876242 - Left-adjacent-bits: up to 15\n000000000000001000000000000001000000000000010000000000000100000000000010000000000010000000000100000000010000000010000000100000010000010000100010010\n000000000000011000000000000011000000000000110000000000001100000000000110000000000110000000001100000000110000000110000001100000110000110001100110110\n000000000000111000000000000111000000000001110000000000011100000000001110000000001110000000011100000001110000001110000011100001110001110011101111110\n000000000001111000000000001111000000000011110000000000111100000000011110000000011110000000111100000011110000011110000111100011110011110111111111110\n000000000011111000000000011111000000000111110000000001111100000000111110000000111110000001111100000111110000111110001111100111110111111111111111110\n000000000111111000000000111111000000001111110000000011111100000001111110000001111110000011111100001111110001111110011111101111111111111111111111110\n000000001111111000000001111111000000011111110000000111111100000011111110000011111110000111111100011111110011111110111111111111111111111111111111110\n000000011111111000000011111111000000111111110000001111111100000111111110000111111110001111111100111111110111111111111111111111111111111111111111110\n000000111111111000000111111111000001111111110000011111111100001111111110001111111110011111111101111111111111111111111111111111111111111111111111110\n000001111111111000001111111111000011111111110000111111111100011111111110011111111110111111111111111111111111111111111111111111111111111111111111110\n000011111111111000011111111111000111111111110001111111111100111111111110111111111111111111111111111111111111111111111111111111111111111111111111110\n000111111111111000111111111111001111111111110011111111111101111111111111111111111111111111111111111111111111111111111111111111111111111111111111110\n001111111111111001111111111111011111111111110111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110\n011111111111111011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110\n111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111110\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Sexy\\_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn mathematics, **sexy primes** are prime numbers that differ from each other by six.\n\nFor example, the numbers **5** and **11** are both sexy primes, because **11** minus **6** is **5**.\n\nThe term \"sexy prime\" is a pun stemming from the Latin word for six: *sex*.\n\n**Sexy prime pairs:** Sexy prime pairs are groups of two primes that differ by **6**. e.g. **(5 11), (7 13), (11 17)** \nSee sequences: OEIS:A023201 and OEIS:A046117\n\n**Sexy prime triplets:** Sexy prime triplets are groups of three primes where each differs from the next by **6**. e.g. **(5 11 17), (7 13 19), (17 23 29)** \nSee sequences: OEIS:A046118, OEIS:A046119 and OEIS:A046120\n\n**Sexy prime quadruplets:** Sexy prime quadruplets are groups of four primes where each differs from the next by **6**. e.g. **(5 11 17 23), (11 17 23 29)** \nSee sequences: OEIS:A023271, OEIS:A046122, OEIS:A046123 and OEIS:A046124\n\n**Sexy prime quintuplets:** Sexy prime quintuplets are groups of five primes with a common difference of **6**. One of the terms must be divisible by **5**, because **5** and **6** are relatively prime. Thus, the only possible sexy prime quintuplet is **(5 11 17 23 29)**\n\nTask\n\n: : * For each of pairs, triplets, quadruplets and quintuplets, Find and display the count of each group type of sexy primes less than one million thirty-five (**1,000,035**).\n * Display at most the **last** **5**, less than one million thirty-five, of each sexy prime group type.\n * Find and display the count of the unsexy primes less than one million thirty-five.\n * Find and display the **last 10** unsexy primes less than one million thirty-five.\n * Note that 1000033 **SHOULD NOT** be counted in the pair count. It is sexy, but not in a pair within the limit. However, it also **SHOULD NOT** be listed in the unsexy primes since it is sexy." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.08\n\n```\nuse Math::Primesieve;\nmy $sieve = Math::Primesieve.new;\n\nmy $max = 1_000_035;\nmy @primes = $sieve.primes($max);\n\nmy $filter = @primes.Set;\nmy $primes = @primes.categorize: &sexy;\n\nsay \"Total primes less than {comma $max}: \", comma +@primes;\n\nfor <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt {\n say \"Number of sexy prime {$sexy}s less than {comma $max}: \", comma +$primes{$sexy};\n say \" Last 5 sexy prime {$sexy}s less than {comma $max}: \",\n join ' ', $primes{$sexy}.tail(5).grep(*.defined).map:\n { \"({ $_ «+« (0,6 … 24)[^$cnt] })\" }\n say '';\n}\n\nsay \"Number of unsexy primes less than {comma $max}: \", comma +$primes<unsexy>;\nsay \" Last 10 unsexy primes less than {comma $max}: \", $primes<unsexy>.tail(10);\n\nsub sexy ($i) {\n gather {\n take 'quintuplet' if all($filter{$i «+« (6,12,18,24)});\n take 'quadruplet' if all($filter{$i «+« (6,12,18)});\n take 'triplet' if all($filter{$i «+« (6,12)});\n take 'pair' if $filter{$i + 6};\n take (($i >= $max - 6) && ($i + 6).is-prime) ||\n (so any($filter{$i «+« (6, -6)})) ?? 'sexy' !! 'unsexy';\n }\n}\n\nsub comma { $^i.flip.comb(3).join(',').flip }\n\n```\n\nOutput:\n\n```\nTotal primes less than 1,000,035: 78,500\nNumber of sexy prime pairs less than 1,000,035: 16,386\n Last 5 sexy prime pairs less than 1,000,035: (999371 999377) (999431 999437) (999721 999727) (999763 999769) (999953 999959)\n\nNumber of sexy prime triplets less than 1,000,035: 2,900\n Last 5 sexy prime triplets less than 1,000,035: (997427 997433 997439) (997541 997547 997553) (998071 998077 998083) (998617 998623 998629) (998737 998743 998749)\n\nNumber of sexy prime quadruplets less than 1,000,035: 325\n Last 5 sexy prime quadruplets less than 1,000,035: (977351 977357 977363 977369) (983771 983777 983783 983789) (986131 986137 986143 986149) (990371 990377 990383 990389) (997091 997097 997103 997109)\n\nNumber of sexy prime quintuplets less than 1,000,035: 1\n Last 5 sexy prime quintuplets less than 1,000,035: (5 11 17 23 29)\n\nNumber of unsexy primes less than 1,000,035: 48,627\n Last 10 unsexy primes less than 1,000,035: (999853 999863 999883 999907 999917 999931 999961 999979 999983 1000003)\n```" } ]
[ { "role": "user", "content": "**SHA-1** or **SHA1** is a one-way hash function;\nit computes a 160-bit message digest.\nSHA-1 often appears in security protocols; for example,\nmany HTTPS websites use RSA with SHA-1 to secure their connections.\nBitTorrent uses SHA-1 to verify downloads.\nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of octets. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\n| |\n| --- |\n| **Warning:** SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3. |" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Pure Raku\n\nA pure Raku implementation that closely follows the description of SHA-1 in FIPS 180-1. Slow.\n\n```\nsub postfix:<mod2³²> { $^x % 2**32 }\nsub infix:<⊕> { ($^x + $^y)mod2³² }\nsub S { ($^x +< $^n)mod2³² +| ($x +> (32-$n)) }\n\nmy \\f = -> \\B,\\C,\\D { (B +& C) +| ((+^B)mod2³² +& D) },\n -> \\B,\\C,\\D { B +^ C +^ D },\n -> \\B,\\C,\\D { (B +& C) +| (B +& D) +| (C +& D) },\n -> \\B,\\C,\\D { B +^ C +^ D };\n\nmy \\K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6;\n\nsub sha1-pad(Blob $msg)\n{ \n my \\bits = 8 * $msg.elems;\n my @padded = flat $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64);\n flat @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²;\n}\n\nsub sha1-block(@H, @M is copy)\n{ \n @M.push: S(1, [+^] @M[$_ «-« <3 8 14 16>] ) for 16 .. 79;\n\n my ($A,$B,$C,$D,$E) = @H;\n for 0..79 -> \\t {\n ($A, $B, $C, $D, $E) =\n S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @M[t] ⊕ K[t div 20],\n $A, S(30,$B), $C, $D;\n }\n @H »⊕=« ($A,$B,$C,$D,$E);\n}\n\nsub sha1(Blob $msg) returns Blob\n{ \n my @M = sha1-pad($msg);\n my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0;\n sha1-block(@H,@M[$_..$_+15]) for 0, 16...^ +@M;\n Blob.new: flat map { reverse .polymod(256 xx 3) }, @H;\n}\n\nsay sha1(.encode('ascii')), \" $_\"\n for 'abc',\n 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',\n 'Rosetta Code',\n 'Ars longa, vita brevis';\n\n```\n\nOutput:\n\n```\nBuf:0x<a9 99 3e 36 47 06 81 6a ba 3e 25 71 78 50 c2 6c 9c d0 d8 9d> abc\nBuf:0x<84 98 3e 44 1c 3b d2 6e ba ae 4a a1 f9 51 29 e5 e5 46 70 f1> abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\nBuf:0x<48 c9 8f 7e 5a 6e 73 6d 79 0a b7 40 df c3 f5 1a 61 ab e2 b5> Rosetta Code\nBuf:0x<e6 40 d2 85 24 28 86 eb 96 ab 80 cb f8 58 38 9b 3d f5 2f 43> Ars longa, vita brevis\n```\n\n### Library based implementation\n\nQuite speedy.\n\n```\nuse Digest::SHA1::Native;\n\n# use sha1-hex() if you want a hex string\n\nsay sha1($_), \" $_\" for\n 'abc',\n 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',\n 'Rosetta Code',\n 'Ars longa, vita brevis'\n;\n\n```\n\nOutput:\n\n```\nBlob:0x<A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D> abc\nBlob:0x<84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1> abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\nBlob:0x<48 C9 8F 7E 5A 6E 73 6D 79 0A B7 40 DF C3 F5 1A 61 AB E2 B5> Rosetta Code\nBlob:0x<E6 40 D2 85 24 28 86 EB 96 AB 80 CB F8 58 38 9B 3D F5 2F 43> Ars longa, vita brevis\n```" } ]
[ { "role": "user", "content": "**SHA-256** is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.\n\nEither by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string \"Rosetta code\" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Pure Raku\n\nThe following implementation takes all data as input. Ideally, input should be given lazily or something.\n\n```\nsay sha256 \"Rosetta code\";\n\nour proto sha256($) returns blob8 {*}\n\nmulti sha256(Str $str) { samewith $str.encode }\nmulti sha256(blob8 $data) {\n sub rotr { $^a +> $^b +| $a +< (32 - $b) }\n sub init { ^Inf .grep(&is-prime).map: { (($_ - .Int)*2**32).Int } o &^f } \n sub Ch { $^x +& $^y +^ +^$x +& $^z }\n sub Maj { $^x +& $^y +^ $x +& $^z +^ $y +& $z }\n sub Σ0 { rotr($^x, 2) +^ rotr($x, 13) +^ rotr($x, 22) }\n sub Σ1 { rotr($^x, 6) +^ rotr($x, 11) +^ rotr($x, 25) }\n sub σ0 { rotr($^x, 7) +^ rotr($x, 18) +^ $x +> 3 }\n sub σ1 { rotr($^x, 17) +^ rotr($x, 19) +^ $x +> 10 }\n\n return blob8.new: \n map |*.polymod(256 xx 3).reverse,\n\t|reduce -> $H, $block {\n\t blob32.new: $H[] Z+\n\t reduce -> $h, $j {\n\t my uint32 ($T1, $T2) =\n\t\t$h[7] + Σ1($h[4]) + Ch(|$h[4..6])\n\t\t+ (BEGIN init(* **(1/3))[^64])[$j] +\n\t\t(\n\t\t (state buf32 $w .= new)[$j] = $j < 16 ?? $block[$j] !!\n\t\t σ0($w[$j-15]) + $w[$j-7] + σ1($w[$j-2]) + $w[$j-16]\n\t\t),\n\t Σ0($h[0]) + Maj(|$h[0..2]);\n\t blob32.new: $T1 + $T2, |$h[0..2], $h[3] + $T1, |$h[4..6];\n\t }, $H, |^64;\n\t},\n\t(BEGIN init(&sqrt)[^8]),\n\t|blob32.new(\n\t blob8.new(\n\t @$data,\n\t 0x80,\n\t 0 xx (-($data + 1 + 8) mod 64),\n\t (8*$data).polymod(256 xx 7).reverse\n\t ).rotor(4)\n\t .map: { :256[@$_] }\n\t ).rotor(16)\n}\n\n```\n\nOutput:\n\n```\nBlob[uint8]:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>\n```\n\n### Native implementation\n\n```\nuse Digest::SHA256::Native;\n\n# If you want a string\nsay sha256-hex 'Rosetta code';\n\n# If you want a binary Blob\nsay sha256 'Rosetta code';\n\n```\n\nOutput:\n\n```\n764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf\nBlob:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>\n```" } ]
[ { "role": "user", "content": "As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256.\n\nSpecifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are paired up and concatenated together, and a new hash is computed from each concatenation. Then these are paired up and concatenated and hashed, and the process continues until there is only one hash left, which is the final checksum. The hexadecimal representation of this checksum is the value that must be included with the AWS API call to upload the object (or complete a multipart upload).\n\nImplement this algorithm in your language; you can use the code from the SHA-256 task for the actual hash computations. For better manageability and portability, build the tree using a smaller block size of only 1024 bytes, and demonstrate it on the RosettaCode title image with that block size. The final result should be the hexadecimal digest value a4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c." }, { "role": "assistant", "content": "```\nuse Digest::SHA256::Native;\n\nunit sub MAIN(Int :b(:$block-size) = 1024 × 1024, *@args);\n\nmy $in = @args ?? IO::CatHandle.new(@args) !! $*IN;\n\nmy @blocks = do while my $block = $in.read: $block-size { sha256 $block };\n\nwhile @blocks > 1 {\n @blocks = @blocks.batch(2).map: { $_ > 1 ?? sha256([~] $_) !! .[0] }\n}\n\nsay @blocks[0]».fmt('%02x').join;\n\n```\n\nOutput:\n\n```\n$ sha256tree --block-size=1024 title.png\na4f902cf9d51fe51eda156a6792e1445dff65edf3a217a1f3334cc9cf1495c2c\n```" } ]
[ { "role": "user", "content": "**Task**:\n\nGet user input (or store the number somewhere if the programing langauge doesn't support input) and then add 3, multiply that 0.86 and repeat that over and over again.\n\nOptionally, halt the loop when quiescence has been achieved, i.e. when the value does not change, and report that value and the corresponding number of iterations.\n\n## See Also\n\n* Esolangs.org page" }, { "role": "assistant", "content": "```\nmy $input = (+prompt()).FatRat;\nmy $previous = 0.FatRat;\nmy $count;\nmy $places = 36;\nloop {\n $input += 3;\n $input ×= .86;\n last if $previous.substr(0,$places) eq $input.substr(0,$places);\n ++$count;\n say ($previous = $input).substr(0,$places);\n}\nsay \"$count repetitions\";\n\n```\n\nOutput with a 4 fed in at the prompt:\n\n```\n4\n6.02\n7.7572\n9.251192\n10.53602512\n11.6409816032\n12.591244178752\n13.40846999372672\n14.1112841946049792\n14.715704407360282112\n15.23550579032984261632\n15.6825349796836646500352\n16.066980082527951599030272\n\n...\nmany, many lines omitted\n...\n\n18.428571428571428571428571428571416\n18.428571428571428571428571428571418\n18.428571428571428571428571428571419\n18.428571428571428571428571428571420\n18.428571428571428571428571428571421\n18.428571428571428571428571428571422\n18.428571428571428571428571428571423\n18.428571428571428571428571428571424\n512 repetitions\n\n```\n\nIn the latest iteration of the task instructions, we are to optionally \"halt the loop when quiescence has been achieved, i.e. when the value does not change\". Unless a precision is specified, \"quiescence\" will never be achieved. This operation adds more places of precision with every iteration, and will never \"quiesce\". (Unless run on a processor or with a language that is unable to handle high precision.)\n\nFor instance, the 1000th iteration, starting with 4 is exactly equal to:\n\n```\nsay (4.FatRat, (* + 3) × .86 … *)[999]\n\n```\n\nOutput:\n\n```\n18.428571428571428571428571428571428571428571428571428571428571428518562611055257476711345657046077536086307719590805662205008932637290716748623508143778473712167435511145273975385354947408188479662139937380449451942842937179508680530588633892945763008511616379084707917069957275072200539351914273993965066030011194811876547904839025263224744832595386782011862097471389181893672211696726485532183264057134602403929706908123592993235863786859888156665186026179826816128847575831458378844885123366878611593252686593421606487555134444315938261367778063531536534964127098858136548553001526656285822374662510184388742700972850063038414950295895060044238800011827580857336812976758443609296077801146559738910594736606435132635929690920618270821813108173656217015589361779205162675360527035288967300528197729261443766412283716792164777168702168039406788952779919915570541752416260293860518467707548712088056167502132216420672641269104901942501949966581723902330182247134406759443834453985391637796764689461663270662662993088449741102622767088092813554110022083926515230853581817905105492221230813528825959115645642043759816744064849863722778041272156387348996418369338438534662612609987037043047038131221189442288876209762806085696386445408093086328602555139121446610496274119187899056474561873403444794760343168250250584159942711177776533259811971409762989699214055857046134462937025863660124732727323402691866232023863821613479844954718192492032583994808226027774091320595373377362720291094591511865887665392365641680216202349251077081257991823441611723818589067580880018475492672710607080810164651535155593521646027992098574736200877274039486002214250862949227962977243520217727369412523884625435318388719886\n```\n\n(Notice that that, while very **precise**, is only **accurate** to 64 decimal places.)" } ]
[ { "role": "user", "content": "Task\n\nShow how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length.\n\nAvoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different command argument syntax, or the systems those implementations run on have different styles of shells, it would be good to show multiple examples." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #22 \"Thousand Oaks\"\n\n```\n$ raku -e 'say \"Hello, world!\"'\nHello, world!\n\n```" } ]
[ { "role": "user", "content": "Task\n\nShift list elements to left by   **3**.\n\n```\n shift = [1,2,3,4,5,6,7,8,9]\n result = [4, 5, 6, 7, 8, 9, 1, 2, 3]\n\n```" }, { "role": "assistant", "content": "```\n# 20210315 Raku programming solution\n\nsay [1..9].rotate(3)\n\n```\n\nOutput:\n\n```\n(4 5 6 7 8 9 1 2 3)\n\n```" } ]
[ { "role": "user", "content": "Given the `n + 1` vertices `x[0], y[0] .. x[N], y[N]` of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\n```\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n```\n\n(Where `abs` returns the absolute value)\n\nTask\n\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n\n```\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n```\n\nShow the answer here, on this page." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Index and mod offset\n\n**Works with**: Rakudo version 2017.07\n\n```\nsub area-by-shoelace(@p) {\n (^@p).map({@p[$_;0] * @p[($_+1)%@p;1] - @p[$_;1] * @p[($_+1)%@p;0]}).sum.abs / 2\n}\n\nsay area-by-shoelace( [ (3,4), (5,11), (12,8), (9,5), (5,6) ] );\n\n```\n\nOutput:\n\n```\n30\n```\n\n### Slice and rotation\n\n**Works with**: Rakudo version 2017.07\n\n```\nsub area-by-shoelace ( @p ) {\n my @x := @p».[0];\n my @y := @p».[1];\n\n my $s := ( @x Z* @y.rotate( 1) ).sum\n - ( @x Z* @y.rotate(-1) ).sum;\n\n return $s.abs / 2;\n}\n\nsay area-by-shoelace( [ (3,4), (5,11), (12,8), (9,5), (5,6) ] );\n\n```\n\nOutput:\n\n```\n30\n```" } ]
[ { "role": "user", "content": "Assume functions   `a`   and   `b`   return boolean values,   and further, the execution of function   `b`   takes considerable resources without side effects, and is to be minimized.\n\nIf we needed to compute the conjunction   (`and`):\n\n: : : : `x = a() and b()`\n\nThen it would be best to not compute the value of   `b()`   if the value of   `a()`   is computed as   `false`,   as the value of   `x`   can then only ever be   `false`.\n\nSimilarly, if we needed to compute the disjunction (`or`):\n\n: : : : `y = a() or b()`\n\nThen it would be best to not compute the value of   `b()`   if the value of   `a()`   is computed as   `true`,   as the value of   `y`   can then only ever be   `true`.\n\nSome languages will stop further computation of boolean equations as soon as the result is known, so-called   short-circuit evaluation   of boolean expressions\n\nTask\n\nCreate two functions named   `a`   and   `b`,   that take and return the same boolean value.\n\nThe functions should also print their name whenever they are called.\n\nCalculate and assign the values of the following equations to a variable in such a way that function   `b`   is only called when necessary:\n\n: : : : `x = a(i) and b(j)`\n : `y = a(i) or b(j)`\n\nIf the language does not have short-circuit evaluation, this might be achieved with nested     **if**     statements." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nsub a ($p) { print 'a'; $p }\nsub b ($p) { print 'b'; $p }\n\nfor 1, 0 X 1, 0 -> ($p, $q) {\n for '&&', '||' -> $op {\n my $s = \"a($p) $op b($q)\";\n print \"$s: \";\n EVAL $s;\n print \"\\n\";\n }\n}\n\n```\n\nOutput:\n\n```\na(1) && b(1): ab\na(1) || b(1): a\na(1) && b(0): ab\na(1) || b(0): a\na(0) && b(1): a\na(0) || b(1): ab\na(0) && b(0): a\na(0) || b(0): ab\n```" } ]
[ { "role": "user", "content": "The   **shortest common supersequence**   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task.\n\nTask\n\nGiven two strings \n\nu\n{\\displaystyle {\\displaystyle u}}\n and \n\nv\n{\\displaystyle {\\displaystyle v}}\n, find the shortest possible sequence \n\ns\n{\\displaystyle {\\displaystyle s}}\n, which is the shortest common super-sequence of \n\nu\n{\\displaystyle {\\displaystyle u}}\n and \n\nv\n{\\displaystyle {\\displaystyle v}}\n where both \n\nu\n{\\displaystyle {\\displaystyle u}}\n and \n\nv\n{\\displaystyle {\\displaystyle v}}\n are a subsequence of \n\ns\n{\\displaystyle {\\displaystyle s}}\n. Defined as such, \n\ns\n{\\displaystyle {\\displaystyle s}}\n is not necessarily unique.\n\nDemonstrate this by printing \n\ns\n{\\displaystyle {\\displaystyle s}}\n where \n\nu\n=\n{\\displaystyle {\\displaystyle u=}}\n“abcbdab” and \n\nv\n=\n{\\displaystyle {\\displaystyle v=}}\n“bdcaba”.\n\nAlso see\n\n* Wikipedia: shortest common supersequence" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUsing 'lcs' routine from Longest common subsequence task\n\n```\nsub lcs(Str $xstr, Str $ystr) { # longest common subsequence\n return \"\" unless $xstr && $ystr;\n my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1);\n return $x eq $y\n  ?? $x ~ lcs($xs, $ys)\n  !! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) );\n}\n\nsub scs ($u, $v) { # shortest common supersequence\n my @lcs = (lcs $u, $v).comb;\n my $pat = '(.*)' ~ join('(.*)',@lcs) ~ '(.*)';\n my $regex = \"rx/$pat/\".EVAL;\n my @u = ($u ~~ $regex).list;\n my @v = ($v ~~ $regex).list;\n my $scs = shift(@u) ~ shift(@v);\n $scs ~= $_ ~ shift(@u) ~ shift(@v) for @lcs;\n return $scs;\n}\n\nmy $u = 'abcbdab';\nmy $v = 'bdcaba';\nprintf \"Strings: %s %s\\n\", $u, $v;\nprintf \"Longest common subsequence: %s\\n\", lcs $u, $v;\nprintf \"Shortest common supersquence: %s\\n\", scs $u, $v;\n\n```\n\nOutput:\n\n```\nStrings: abcbdab bdcaba\nLongest common subsequence: bcba\nShortest common supersquence: abdcabdab\n```" } ]
[ { "role": "user", "content": "Task\n\nShow  the ASCII character set  from values   **32**   to   **127**   (decimal)   in a table format.\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\nAlternately, and perhaps more usefully, output as a wiki-table rather than ASCII art. Hover mouse over the glyph to get the name.\n\n```\nsub glyph ($_) {\n when * < 33 { (0x2400 + $_).chr } # display symbol names for invisible glyphs\n when 127 { '␡' }\n default { .chr }\n}\n\nsay '{|class=\"wikitable\" style=\"text-align:center;background-color:hsl(39, 90%, 95%)\"';\n\nfor (^128).rotor(16) -> @row {\n say '|-';\n printf(q[|%d<br>0x%02X<br><big><big title=\"%s\">%s</big></big>] ~ \"\\n\",\n $_, $_, .&glyph.uniname.subst('SYMBOL FOR ', ''),\n .&glyph.subst('|', '<nowiki>|</nowiki>')) for @row;\n}\n\nsay '|}';\n\n```\n\nOutput:\n\n| | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| 0 0x00 ␀ | 1 0x01 ␁ | 2 0x02 ␂ | 3 0x03 ␃ | 4 0x04 ␄ | 5 0x05 ␅ | 6 0x06 ␆ | 7 0x07 ␇ | 8 0x08 ␈ | 9 0x09 ␉ | 10 0x0A ␊ | 11 0x0B ␋ | 12 0x0C ␌ | 13 0x0D ␍ | 14 0x0E ␎ | 15 0x0F ␏ |\n| 16 0x10 ␐ | 17 0x11 ␑ | 18 0x12 ␒ | 19 0x13 ␓ | 20 0x14 ␔ | 21 0x15 ␕ | 22 0x16 ␖ | 23 0x17 ␗ | 24 0x18 ␘ | 25 0x19 ␙ | 26 0x1A ␚ | 27 0x1B ␛ | 28 0x1C ␜ | 29 0x1D ␝ | 30 0x1E ␞ | 31 0x1F ␟ |\n| 32 0x20 ␠ | 33 0x21 ! | 34 0x22 \" | 35 0x23 # | 36 0x24 $ | 37 0x25 % | 38 0x26 & | 39 0x27 ' | 40 0x28 ( | 41 0x29 ) | 42 0x2A \\* | 43 0x2B + | 44 0x2C , | 45 0x2D - | 46 0x2E . | 47 0x2F / |\n| 48 0x30 0 | 49 0x31 1 | 50 0x32 2 | 51 0x33 3 | 52 0x34 4 | 53 0x35 5 | 54 0x36 6 | 55 0x37 7 | 56 0x38 8 | 57 0x39 9 | 58 0x3A : | 59 0x3B ; | 60 0x3C < | 61 0x3D = | 62 0x3E > | 63 0x3F ? |\n| 64 0x40 @ | 65 0x41 A | 66 0x42 B | 67 0x43 C | 68 0x44 D | 69 0x45 E | 70 0x46 F | 71 0x47 G | 72 0x48 H | 73 0x49 I | 74 0x4A J | 75 0x4B K | 76 0x4C L | 77 0x4D M | 78 0x4E N | 79 0x4F O |\n| 80 0x50 P | 81 0x51 Q | 82 0x52 R | 83 0x53 S | 84 0x54 T | 85 0x55 U | 86 0x56 V | 87 0x57 W | 88 0x58 X | 89 0x59 Y | 90 0x5A Z | 91 0x5B [ | 92 0x5C \\ | 93 0x5D ] | 94 0x5E ^ | 95 0x5F \\_ |\n| 96 0x60 ` | 97 0x61 a | 98 0x62 b | 99 0x63 c | 100 0x64 d | 101 0x65 e | 102 0x66 f | 103 0x67 g | 104 0x68 h | 105 0x69 i | 106 0x6A j | 107 0x6B k | 108 0x6C l | 109 0x6D m | 110 0x6E n | 111 0x6F o |\n| 112 0x70 p | 113 0x71 q | 114 0x72 r | 115 0x73 s | 116 0x74 t | 117 0x75 u | 118 0x76 v | 119 0x77 w | 120 0x78 x | 121 0x79 y | 122 0x7A z | 123 0x7B { | 124 0x7C | | 125 0x7D } | 126 0x7E ~ | 127 0x7F ␡ |" } ]
[ { "role": "user", "content": "Task\n\nShow here (on this page) the decimal numbers formed by:\n\n: : (**n**   **1'**s   appended by the digit   **3**)   and then square the result,     where   **0   <=   n   <   8**\n\nSee also\n\n* oeis:A151997" }, { "role": "assistant", "content": "In an attempt to stave of terminal ennui, Find the first 8 where a(n) is semiprime.\n\n```\nsay \"$_, {.²}\" for (^∞).map({ ( 1 x $_ ~ 3)} ).grep({ .is-prime })[^8]\n\n```\n\nOutput:\n\n```\n3, 9\n13, 169\n113, 12769\n11113, 123498769\n111111113, 12345679432098769\n11111111113, 123456790165432098769\n111111111111111111111113, 12345679012345679012346098765432098765432098769\n111111111111111111111111111111111111111111111111111111111111111111111111111111111113, 12345679012345679012345679012345679012345679012345679012345679012345679012345679012765432098765432098765432098765432098765432098765432098765432098765432098765432098769\n```" } ]
[ { "role": "user", "content": "Task\n\nChoose popular date libraries used by your language and show the   epoch   those libraries use.\n\nA demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical.\n\nFor consistency's sake, show the date in UTC time where possible.\n\nRelated task\n\n* Date format" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay DateTime.new(0)\n\n```\n\nOutput:\n\n```\n1970-01-01T00:00:00Z\n\n```" } ]
[ { "role": "user", "content": "Task\n\nProduce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  **3**." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.02\n\n```\nuse SVG;\n\nrole Lindenmayer {\n has %.rules;\n method succ {\n self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)\n }\n}\n\nmy $arrow = 'X' but Lindenmayer( { X => 'YF+XF+Y', Y => 'XF-YF-X' } );\n\n$arrow++ xx 7;\n\nmy $w = 800;\nmy $h = ($w * 3**.5 / 2).round(1);\n\nmy $scale = 6;\nmy @points = (400, 15);\nmy $dir = pi/3;\n\nfor $arrow.comb {\n state ($x, $y) = @points[0,1];\n state $d = $dir;\n when 'F' { @points.append: ($x += $scale * $d.cos).round(1), ($y += $scale * $d.sin).round(1) }\n when '+' { $d += $dir }\n when '-' { $d -= $dir }\n default { }\n}\n\nmy $out = './sierpinski-arrowhead-curve-perl6.svg'.IO;\n\n$out.spurt: SVG.serialize(\n svg => [\n  :width($w), :height($h),\n  :rect[:width<100%>, :height<100%>, :fill<black>],\n  :polyline[ :points(@points.join: ','), :fill<black>, :style<stroke:#FF4EA9> ],\n ],\n);\n\n```\n\nSee: Sierpinski-arrowhead-curve-perl6.svg (offsite SVG image)" } ]
[ { "role": "user", "content": "Task\n\nProduce a graphical or ASCII-art representation of a Sierpinski carpet of order   **N**.\n\nFor example, the Sierpinski carpet of order   **3**   should look like this:\n\n```\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n### ###### ###### ###\n# # # ## # # ## # # #\n### ###### ###### ###\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n######### #########\n# ## ## # # ## ## #\n######### #########\n### ### ### ###\n# # # # # # # #\n### ### ### ###\n######### #########\n# ## ## # # ## ## #\n######### #########\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n### ###### ###### ###\n# # # ## # # ## # # #\n### ###### ###### ###\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n\n```\n\nThe use of the   #   character is not rigidly required for ASCII art.\n\nThe important requirement is the placement of whitespace and non-whitespace characters.\n\nRelated task\n\n* Sierpinski triangle" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Tcl\n\n```\nsub carpet\n{\n (['#'], -> @c {\n [ \n |@c.map({$_ x 3}), \n |@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}),\n |@c.map({$_ x 3}) \n ]\n } ... *).map: { .join(\"\\n\") };\n}\n\nsay carpet[3];\n\n# Same as above, structured as an array bound to a sequence, with a separate sub for clarity.\nsub weave ( @c ) {\n [\n |@c.map({ $_ x 3 }),\n |@c.map({ $_ ~ .trans( '#' => ' ' ) ~ $_ }),\n |@c.map({ $_ x 3 })\n ]\n}\n\nmy @carpet = ( ['#'], &weave ... * ).map: { .join: \"\\n\" };\n\nsay @carpet[3];\n\n# Output of both versions matches task example.\n```" } ]
[ { "role": "user", "content": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\nSee also\n\n* Sierpinski pentagon" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018-10\n\n5th order pentaflake\n\n```\nconstant $sides = 5;\nconstant order = 5;\nconstant $dim = 250;\nconstant scaling-factor = ( 3 - 5**.5 ) / 2;\nmy @orders = ((1 - scaling-factor) * $dim) «*» scaling-factor «**» (^order);\n\nmy $fh = open('sierpinski_pentagon.svg', :w);\n\n$fh.say: qq|<svg height=\"{$dim*2}\" width=\"{$dim*2}\" style=\"fill:blue\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">|;\n\nmy @vertices = map { cis( $_ * τ / $sides ) }, ^$sides;\n\nfor 0 ..^ $sides ** order -> $i {\n my $vector = [+] @vertices[$i.base($sides).fmt(\"%{order}d\").comb] «*» @orders;\n $fh.say: pgon ((@orders[*-1] * (1 - scaling-factor)) «*» @vertices «+» $vector)».reals».fmt(\"%0.3f\");\n};\n\nsub pgon (@q) { qq|<polygon points=\"{@q}\" transform=\"translate({$dim},{$dim}) rotate(-18)\"/>| }\n\n$fh.say: '</svg>';\n$fh.close;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nProduce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.02\n\n```\nuse SVG;\n\nrole Lindenmayer {\n has %.rules;\n method succ {\n self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules)\n }\n}\n\nmy $sierpinski = 'X' but Lindenmayer( { X => 'XF-F+F-XF+F+XF-F+F-X' } );\n\n$sierpinski++ xx 5;\n\nmy $dim = 600;\nmy $scale = 6;\n\nmy @points = (-80, 298);\n\nfor $sierpinski.comb {\n state ($x, $y) = @points[0,1];\n state $d = $scale + 0i;\n when 'F' { @points.append: ($x += $d.re).round(1), ($y += $d.im).round(1) }\n when /< + - >/ { $d *= \"{$_}1i\" }\n default { }\n}\n\nmy @t = @points.tail(2).clone;\n\nmy $out = './sierpinski-square-curve-perl6.svg'.IO;\n\n$out.spurt: SVG.serialize(\n svg => [\n  :width($dim), :height($dim),\n  :rect[:width<100%>, :height<100%>, :fill<black>],\n  :polyline[\n  :points((@points, map {(@t »+=» $_).clone}, ($scale,0), (0,$scale), (-$scale,0)).join: ','),\n  :fill<black>, :transform(\"rotate(45, 300, 300)\"), :style<stroke:#61D4FF>,\n ],\n  :polyline[\n  :points(@points.map( -> $x,$y { $x, $dim - $y + 1 }).join: ','),\n  :fill<black>, :transform(\"rotate(45, 300, 300)\"), :style<stroke:#61D4FF>,\n ],\n ],\n);\n\n```\n\nSee: Sierpinski-square-curve-perl6.svg (offsite SVG image)" } ]
[ { "role": "user", "content": "Task\n\nProduce an ASCII representation of a Sierpinski triangle of order   **N**.\n\nExample\n\nThe Sierpinski triangle of order   **4**   should look like this:\n\n```\n *\n * *\n * *\n * * * *\n * *\n * * * *\n * * * *\n * * * * * * * *\n * *\n * * * *\n * * * *\n * * * * * * * *\n * * * *\n * * * * * * * *\n * * * * * * * *\n * * * * * * * * * * * * * * * *\n\n```\n\nRelated tasks\n\n* Sierpinski triangle/Graphical for graphics images of this pattern.\n* Sierpinski carpet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub sierpinski ($n) {\n my @down = '*';\n my $space = ' ';\n for ^$n {\n @down = |(\"$space$_$space\" for @down), |(\"$_ $_\" for @down);\n $space x= 2;\n }\n return @down;\n}\n \n.say for sierpinski 4;\n```" } ]
[ { "role": "user", "content": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation.\n\nAn example of Sierpinski's triangle (order = 8) looks like this:" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis is a recursive solution. It is not really practical for more than 8 levels of recursion, but anything more than 7 is barely visible anyway.\n\n```\nmy $levels = 8;\nmy $side = 512;\nmy $height = get_height($side);\n\nsub get_height ($side) { $side * 3.sqrt / 2 }\n\nsub triangle ( $x1, $y1, $x2, $y2, $x3, $y3, $fill?, $animate? ) {\n my $svg;\n $svg ~= qq{<polygon points=\"$x1,$y1 $x2,$y2 $x3,$y3\"};\n $svg ~= qq{ style=\"fill: $fill; stroke-width: 0;\"} if $fill;\n $svg ~= $animate\n  ?? qq{>\\n <animate attributeType=\"CSS\" attributeName=\"opacity\"\\n values=\"1;0;1\" keyTimes=\"0;.5;1\" dur=\"20s\" repeatCount=\"indefinite\" />\\n</polygon>}\n  !! ' />';\n return $svg;\n}\n\nsub fractal ( $x1, $y1, $x2, $y2, $x3, $y3, $r is copy ) {\n my $svg;\n $svg ~= triangle( $x1, $y1, $x2, $y2, $x3, $y3 );\n return $svg unless --$r;\n my $side = abs($x3 - $x2) / 2;\n my $height = get_height($side);\n $svg ~= fractal( $x1, $y1-$height*2, $x1-$side/2, $y1-3*$height, $x1+$side/2, $y1-3*$height, $r);\n $svg ~= fractal( $x2, $y1, $x2-$side/2, $y1-$height, $x2+$side/2, $y1-$height, $r);\n $svg ~= fractal( $x3, $y1, $x3-$side/2, $y1-$height, $x3+$side/2, $y1-$height, $r);\n}\n\nmy $fh = open('sierpinski_triangle.svg', :w) orelse .die;\n$fh.print: qq:to/EOD/,\n<?xml version=\"1.0\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg width=\"100%\" height=\"100%\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n<defs>\n <radialGradient id=\"basegradient\" cx=\"50%\" cy=\"65%\" r=\"50%\" fx=\"50%\" fy=\"65%\">\n <stop offset=\"10%\" stop-color=\"#ff0\" />\n <stop offset=\"60%\" stop-color=\"#f00\" />\n <stop offset=\"99%\" stop-color=\"#00f\" />\n </radialGradient>\n</defs>\nEOD\n\ntriangle( $side/2, 0, 0, $height, $side, $height, 'url(#basegradient)' ),\ntriangle( $side/2, 0, 0, $height, $side, $height, '#000', 'animate' ),\n'<g style=\"fill: #fff; stroke-width: 0;\">',\nfractal( $side/2, $height, $side*3/4, $height/2, $side/4, $height/2, $levels ),\n'</g></svg>';\n\n```" } ]
[ { "role": "user", "content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nThe Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer.\n\nTask\n\nImplement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found.\n\nThat means especially that you shouldn't optimize by using pre-computed *wheels*, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes.\n\nIf there's an easy way to add such a wheel based optimization, implement it as an alternative version.\n\nNote\n\n* It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task.\n\nRelated tasks\n\n* Emirp primes\n* count in factors\n* prime decomposition\n* factors of an integer\n* extensible prime generator\n* primality by trial division\n* factors of a Mersenne number\n* trial factoring of a Mersenne number\n* partition an integer X into N primes\n* sequence of primes by Trial Division" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub sieve( Int $limit ) {\n my @is-prime = False, False, slip True xx $limit - 1;\n\n gather for @is-prime.kv -> $number, $is-prime {\n if $is-prime {\n take $number;\n loop (my $s = $number**2; $s <= $limit; $s += $number) {\n @is-prime[$s] = False;\n }\n }\n }\n}\n\n(sieve 100).join(\",\").say;\n```\n\n### A set-based approach\n\nMore or less the same as the first Python example:\n\n```\nsub eratsieve($n) {\n # Requires n(1 - 1/(log(n-1))) storage\n my $multiples = set();\n gather for 2..$n -> $i {\n unless $i (&) $multiples { # is subset\n take $i;\n $multiples (+)= set($i**2, *+$i ... (* > $n)); # union\n }\n }\n}\n\nsay flat eratsieve(100);\n```\n\nThis gives:\n\n```\n (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)\n\n```\n\n### Using a chain of filters\n\n| |\n| --- |\n| This example is **incorrect**. Please fix the code and remove this message. ***Details:*** This version uses modulo (division) testing and so is a trial division algorithm, not a sieve of Eratosthenes. |\n\n*Note: while this is \"incorrect\" by a strict interpretation of the rules, it is being left as an interesting example*\n\n```\nsub primes ( UInt $n ) {\n gather {\n # create an iterator from 2 to $n (inclusive)\n my $iterator := (2..$n).iterator;\n\n loop {\n # If it passed all of the filters it must be prime\n my $prime := $iterator.pull-one;\n # unless it is actually the end of the sequence\n last if $prime =:= IterationEnd;\n\n take $prime; # add the prime to the `gather` sequence\n\n # filter out the factors of the current prime\n $iterator := Seq.new($iterator).grep(* % $prime).iterator;\n # (2..*).grep(* % 2).grep(* % 3).grep(* % 5).grep(* % 7)…\n }\n }\n}\n\nput primes( 100 );\n```\n\nWhich prints\n\n```\n2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97\n\n```" } ]
[ { "role": "user", "content": "The Sieve of Pritchard is an algorithm for finding the prime numbers up to a given limit N, published in 1981. It considers many fewer composite numbers than the Sieve of Eratosthenes (and has a better asymptotic time complexity). However, unlike the latter, it cannot be modified to greatly reduce its space requirement, making it unsuitable for very large limits.\n\nConceptually, it works by building a wheel representing the repeating pattern of numbers not divisible by one of the first k primes, increasing k until the square of the k'th prime is at least N. Since wheels grow very quickly, the algorithm restricts attention to the initial portions of wheels up to N. (Small examples of the wheels constructed by the Sieve of Pritchard are used in the \"wheel-based optimizations\" mentioned in the Eratosthenes task.)\n\nFor example, the second-order wheel has circumference 6 (the product of the first two primes, 2 and 3) and is marked only at the numbers between 1 and 6 that are not multiples of 2 or 3, namely 1 and 5. As this wheel is rolled along the number line, it will pick up only numbers of the form 6k+1 or 6k+5 (that is, n where n mod 6 is in {1,5}). By the time it stops at 30 (2x3x5) it has added only 8 of the numbers between 6 and 30 as candidates for primality. Those that are multiples of 5 (only 2: 1\\*5 and 5\\*5) are obtained by multiplying the members of the second-order wheel. Removing them gives the next wheel, and so on.\n\nThis YouTube video presents the execution of the algorithm for N=150 in a format that permits single-stepping forward and backward through the run. In that implementation, the wheel is represented by a sparse global array s such that for each member w of the wheel, s[w] contains the next member of the wheel; along with a similar \"previous member\" value, this allows numbers to be removed in a constant number of operations. But the simple abstract algorithm is based on an ordered set, and there is plenty of scope for different implementations.\n\nTask\n\nWrite a program/subprogram that uses the Sieve of Pritchard algorithm to find all primes up to a specified limit. Show the result of running it with a limit of 150.\n\nRelated tasks\n\n* Sieve of Eratosthenes\n* Emirp primes\n* count in factors\n* prime decomposition\n* factors of an integer\n* extensible prime generator\n* primality by trial division\n* factors of a Mersenne number\n* trial factoring of a Mersenne number\n* partition an integer X into N primes\n* sequence of primes by Trial Division" }, { "role": "assistant", "content": "First, a direct translation of the implementation in the YouTube video:\n\n```\nunit sub MAIN($limit = 150);\n\nmy $maxS = 1;\nmy $length = 2;\nmy $p = 3;\nmy @s = ();\n\nwhile $p*$p <= $limit {\n if $length < $limit {\n extend-to [$p*$length, $limit].min;\n }\n delete-multiples-of($p);\n $p = next(1);\n}\nif $length < $limit {\n extend-to $limit;\n}\n\n# Done, build the list of actual primes from the array\n$p = 3;\nmy @primes = 2, |gather while $p <= $limit {\n take $p;\n $p = next($p);\n};\nsay @primes;\n\nexit;\n\nsub extend-to($n) {\n my $w = 1;\n my $x = $length + 1;\n while $x <= $n {\n append $x;\n $w = next($w);\n $x = $length + $w;\n }\n $length = $n;\n if $length == $limit {\n append $limit+2;\n }\n}\n\nsub delete-multiples-of($p) {\n my $f = $p;\n while $p*$f <= $length {\n $f = next($f);\n }\n while $f > 1 {\n $f = prev($f);\n delete($p*$f);\n }\n}\n\nsub append($w) {\n @s[$maxS-1] = $w;\n @s[$w-2] = $maxS;\n $maxS = $w;\n}\n\nsub next($w) { @s[$w-1]; }\nsub prev($w) { @s[$w-2]; }\n\nsub delete($pf) {\n my $temp1 = @s[$pf-2];\n my $temp2 = @s[$pf-1];\n @s[$temp1-1] = $temp2;\n @s[($temp2-2)%@s] = $temp1;\n}\n\n```\n\nOutput:\n\n```\n[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149\n```\n\nThen a slightly more Raku-ish implementation based on the description in the Wikipedia article:\n\n```\nunit sub MAIN($limit = 150);\n\nclass Wheel {\n has $.members is rw;\n has $.length is rw;\n method extend(*@limits) {\n my @members = $.members.keys;\n for @members -> $w {\n my $n = $w + $.length;\n while $n <= @limits.all {\n $.members.set($n);\n $n += $.length;\n }\n }\n $.length = @limits.min;\n }\n}\n\n# start with W₀=({1},1)\nmy $wheel = Wheel.new: :members(SetHash(1)), :length(1);\nmy $prime = 2;\nmy @primes = ();\n\nwhile $prime * $prime <= $limit {\n if $wheel.length < $limit {\n $wheel.extend($prime*$wheel.length, $limit);\n }\n for $wheel.members.keys.sort(-*) -> $w {\n $wheel.members.unset($prime * $w);\n }\n @primes.push: $prime;\n $prime = $prime == 2 ?? 3 !! $wheel.members.keys.grep(*>1).sort[0];\n}\n\nif $wheel.length < $limit {\n $wheel.extend($limit);\n}\[email protected]: $wheel.members.keys.grep: * != 1;\nsay @primes.sort;\n\n```\n\nThe only difference in the output is that the result of `.sort` is a list rather than an array, so it's printed in parentheses instead of square brackets:\n\nOutput:\n\n```\n(2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149)\n```" } ]
[ { "role": "user", "content": "Signum: Sign of an integer - represent the sign of an integer using a value from a set of 3 or 4 integers.\n\nTask\n\nCreate a function that takes a signed integer *x*, and returns another signed integer as follows:\n\n* if *x*<0, return -1,\n* if *x*>0, return 1 (positive 1),\n* if *x*=0, return 0.\n\nIf the integer representation used supports a signed zero, then the function should preserve the sign of the zero. That is,\n\n* if *x*=-0, return -0,\n* if *x*=+0, return +0.\n\nExample\n\n: : | input | output |\n | --- | --- |\n | -10 | -1 |\n | 42 | 1 |\n | 0 | 0 |\n\nAdditional example for integer types with a signed zero (uncommon)\n\n: : | input | output |\n | --- | --- |\n | -0 | -0 |" }, { "role": "assistant", "content": "Raku has IEEE 754 floating point numbers as part of it's numeric spectrum, so understands -0 as a concept, but does not make any attempt to keep negative zeros. Once a number is interpreted numerically, it is automatically \"narrowed\" to it's most compact form for display.\n\n```\nsay +($_ <=> 0), \": $_\" for 1, -5, 2⁷⁶, -7⁴⁴, π, Inf, -Inf, 0, -0;\n\n```\n\nOutput:\n\n```\n1: 1\n-1: -5\n1: 75557863725914323419136\n-1: -15286700631942576193765185769276826401\n1: 3.141592653589793\n1: Inf\n-1: -Inf\n0: 0\n0: 0\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a simple tool to track a small set of data.\n\nThe tool should have a command-line interface to enter at least two different values.\n\nThe entered data should be stored in a structured format and saved to disk.\n\nIt does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, baseball cards, books), a diary, an electronic organizer (birthdays/anniversaries/phone numbers/addresses), etc.\n\nYou should track the following details:\n\n* A description of the item. (e.g., title, name)\n* A category or tag (genre, topic, relationship such as “friend” or “family”)\n* A date (either the date when the entry was made or some other date that is meaningful, like the birthday); the date may be generated or entered manually\n* Other optional fields\n\nThe command should support the following Command-line arguments to run:\n\n* Add a new entry\n* Print the latest entry\n* Print the latest entry for each category\n* Print all entries sorted by a date\n\nThe category may be realized as a tag or as structure (by making all entries in that category subitems)\n\nThe file format on disk should be human readable, but it need not be standardized.   A natively available format that doesn't need an external library is preferred.   Avoid developing your own format if you can use an already existing one.   If there is no existing format available, pick one of:\n\n: : : * JSON\n * S-Expressions\n * YAML\n * others\n\nRelated task\n\n* Take notes on the command line" }, { "role": "assistant", "content": "(formerly Perl 6)\nA generic client/server JSON database. \n**server.raku:**\n\n```\n#!/usr/bin/env raku\nuse JSON::Fast ;\nsub MAIN( :$server='0.0.0.0', :$port=3333, :$dbfile='db' ) {\n my %db;\n my %index;\n my $dbdata = slurp \"$dbfile.json\" ;\n my $indexdata = slurp \"{$dbfile}_index.json\" ;\n %db = from-json($dbdata) if $dbdata ;\n %index = from-json($indexdata) if $indexdata ;\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.perl ;\n given $msg<function> { \n when 'set' {\n %db{ $msg<topic> } = $msg<message> ;\n %response<status> = 'ok' ;\n %index<last_> = $msg<topic> ;\n for %index<keys_>.keys -> $key {\n if $msg<message>{$key} {\n %index<lastkey_>{ $key }{ $msg<message>{$key} } = $msg<topic> ; \n %index<idx_>{ $key }{ $msg<message>{$key} }{ $msg<topic> } = 1 ;\n }\n }\n spurt \"$dbfile.json\", to-json(%db);\n spurt \"{$dbfile}_index.json\", to-json(%index);\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{'data'} = %db ;\n %response<status> = 'ok' ;\n }\n when 'dumpindex' {\n %response{'data'} = %index ;\n %response<status> = 'ok' ;\n }\n when 'delete' {\n %db{ $msg<topic> }:delete;\n %response<status> = 'ok' ;\n spurt \"$dbfile.json\", to-json(%db);\n reindex();\n }\n when 'addindex' {\n %response<status> = 'ok' ;\n %index<keys_>{ $msg<key>} =1 ;\n reindex();\n }\n when 'reportlast' {\n %response{'data'} = %db{%index<last_>} ;\n %response<status> = 'ok' ;\n }\n when 'reportlastindex' {\n %response<key> = $msg<key> ;\n for %index<lastkey_>{$msg<key>}.keys -> $value {\n #%response{'data'}.push: %db{ %index<lastkey_>{ $msg<key> }{ $value } } ;\n %response{'data'}{$value} = %db{ %index<lastkey_>{ $msg<key> }{ $value } } ;\n }\n %response<status> = 'ok' ;\n }\n when 'reportindex' {\n %response<status> = 'ok' ;\n for %index<idx_>{$msg<key>}.keys.sort -> $value {\n for %index<idx_>{ $msg<key> }{ $value }.keys.sort -> $topic {\n %response<data>.push: %db{ $topic }  ;\n #%response<data>{$value} = %db{ $topic }  ;\n }\n }\n }\n when 'commit' {\n spurt \"$dbfile.json\", to-json(%db);\n spurt \"{$dbfile}_index.json\", to-json(%index);\n %response<status> = 'ok' ;\n }\n default {\n %response<status> = 'error';\n %response<error> = 'no function or not supported';\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 sub reindex {\n %index<idx_>:delete;\n for %db.keys -> $topic {\n my $msg = %db{$topic} ;\n for %index<keys_>.keys -> $key {\n if $msg{$key} {\n %index<idx_>{ $key }{ $msg{$key} }{ $topic } = 1 ;\n }\n }\n }\n spurt \"{$dbfile}_index.json\", to-json(%index) ;\n }\n}\n\n```\n\n**client.raku:**\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('add', $topic, $json, :$server='localhost', :$port='3333' ) {\n my %msg = function => 'set' , topic=> $topic;\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}\nmulti MAIN('addindex', $key, :$server='localhost', :$port='3333') {\n my %msg = function => 'addindex', key => $key  ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('reportindex', $key, :$server='localhost', :$port='3333') {\n my %msg = function => 'reportindex', key => $key  ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('reportlastindex', $key, :$server='localhost', :$port='3333') {\n my %msg = function => 'reportlastindex', key => $key  ;\n sendmsg( %msg , $server, $port) ;\n}\nmulti MAIN('reportlast', :$server='localhost', :$port='3333') {\n my %msg = function => 'reportlast' ;\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\nExample:\n\n```\n./client.raku addindex constructor\n./client.raku addindex date\n\n./client.raku add 2007 '{\"date\":\"2007-11-04\",\"constructor\":\"Ducati\",\"name\":\"Casey Stoner\"}'\n./client.raku add 2008 '{\"date\":\"2008-10-26\",\"constructor\":\"Yamaha\",\"name\":\"Valentino Rossi\"}'\n./client.raku add 2009 '{\"date\":\"2009-11-08\",\"constructor\":\"Yamaha\",\"name\":\"Valentino Rossi\"}'\n./client.raku add 2010 '{\"date\":\"2010-11-17\",\"constructor\":\"Yamaha\",\"name\":\"Jorge Lorenzo\"}'\n./client.raku add 2011 '{\"date\":\"2011-11-06\",\"constructor\":\"Honda\",\"name\":\"Casey Stoner\"}'\n./client.raku add 2012 '{\"date\":\"2012-11-11\",\"constructor\":\"Yamaha\",\"name\":\"Jorge Lorenzo\"}'\n./client.raku add 2013 '{\"date\":\"2013-11-10\",\"constructor\":\"Honda\",\"name\":\"Marc Márquez\"}'\n./client.raku add 2014 '{\"date\":\"2014-11-09\",\"constructor\":\"Honda\",\"name\":\"Marc Márquez\"}'\n./client.raku add 2015 '{\"date\":\"2015-11-08\",\"constructor\":\"Yamaha\",\"name\":\"Jorge Lorenzo\"}'\n./client.raku add 2016 '{\"date\":\"2016-11-13\",\"constructor\":\"Honda\",\"name\":\"Marc Márquez\"}'\n./client.raku add 2017 '{\"date\":\"2017-11-12\",\"constructor\":\"Honda\",\"name\":\"Marc Márquez\"}'\n\n./client.raku reportlast\n./client.raku reportlastindex constructor\n./client.raku reportindex date\n```" } ]
[ { "role": "user", "content": "The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof.\n\nFor a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart.\n\nTask\n: : * Create a function (or subroutine) that uses turtle graphics to draw a house of a specified size as depicted. Optionally make it lovely by adding details such as, for example, doors and windows.\n\n: : * Create a function (or subroutine) that takes a list (array, vector) of non-negative numbers and draws a bar chart from them, scaled to fit exactly in a square of a specified size. The enclosing square need not be drawn.\n\n: : * Both functions should return the turtle to the location it was at and facing in the same direction as it was immediately before the function was executed." }, { "role": "assistant", "content": "```\n# 20250303 Raku programming solution\n\nuse Cairo;\n\nsub house(Cairo::Context $cr, $x, $y, $size) {\n $cr.save;\n $cr.rgb(1.0, 1.0, 1.0);\n\n $cr.rectangle($x, $y, $size, $size);\n $cr.stroke;\n\n $cr.move_to($x + $size / 2, $y - $size / 2);\n $cr.line_to($x, $y);\n $cr.line_to($x + $size, $y);\n $cr.close_path;\n $cr.stroke;\n\n $cr.restore;\n}\n\nsub barchart(Cairo::Context $cr, @data, $x is copy, $y, $size) {\n $cr.save;\n $cr.rgb(1.0, 1.0, 1.0);\n\n my $maxdata = @data.max || 1;\n my $bar-width = $size / (@data.elems || 1);\n my $bar-spacing = $bar-width * 0.1;\n\n for @data -> $n {\n my $bar-height = ($n / $maxdata) * $size;\n $cr.rectangle($x, $y - $bar-height, $bar-width - $bar-spacing, $bar-height);\n $cr.stroke;\n $x += $bar-width;\n }\n\n $cr.restore;\n}\n\nsub testturtle($width = 400, $height = 600) {\n my $image = Cairo::Image.create(Cairo::FORMAT_ARGB32, $width, $height);\n my $cr = Cairo::Context.new($image);\n\n $cr.rgb(0.0, 0.0, 0.0);\n $cr.paint;\n\n $cr.line_width = 2.0;\n\n barchart($cr, [15, 10, 50, 35, 20], $width * 0.6, $height, $width / 3);\n house($cr, $width / 4, $height / 3, $width / 3);\n\n $image.write_png('turtle-raku.png');\n}\n\ntestturtle();\n\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a window that has:\n\n: : 1. a label that says   \"There have been no clicks yet\"\n 2. a button that says   \"click me\"\n\nUpon clicking the button with the mouse, the label should change and show the number of times the button has been clicked." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Library:** GTK\n\n```\nuse GTK::Simple;\nuse GTK::Simple::App;\n\nmy GTK::Simple::App $app .= new(title => 'Simple Windowed Application');\n\n$app.size-request(350, 100);\n\n$app.set-content(\n GTK::Simple::VBox.new(\n my $label = GTK::Simple::Label.new( text => 'There have been no clicks yet'),\n my $button = GTK::Simple::Button.new(label => 'click me'),\n )\n);\n\n$app.border-width = 40;\n\n$button.clicked.tap: { \n state $clicks += 1;\n $label.text = \"There has been $clicks click{ 's' if $clicks != 1 }\";\n}\n\n$app.run;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nSend simulated keystrokes to a GUI window, or terminal.\n\nYou should specify whether the target may be externally created\n(i.e., if the keystrokes are going to an application\nother than the application that is creating them)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nUse libxdo bindings to send text / keystrokes to any application that will accept keystrokes from X11.\n\n```\nuse X11::libxdo;\n\nmy $xdo = Xdo.new;\n\nmy $active = $xdo.get-active-window;\n\nmy $command = $*VM.config<os> eq 'darwin' ?? 'open' !! 'xdg-open';\n\nshell \"$command https://www.google.com\";\n\nsleep 1;\n\nmy $match = rx[^'Google '];\n\nsay my $w = $xdo.search(:name($match))<ID>;\n\nsleep .25;\n\nif $w {\n $xdo.activate-window($w);\n say \"Window name: \", $xdo.get-window-name( $w );\n $xdo.type($w, 'Raku language');\n sleep .25;\n $xdo.send-sequence($w, 'Tab');\n sleep .5;\n $xdo.send-sequence($w, 'Tab');\n sleep .5;\n $xdo.send-sequence($w, 'Tab');\n sleep .5;\n $xdo.send-sequence($w, 'Return');\n}\n\n```" } ]
[ { "role": "user", "content": "Simulate the click of a mouse button by the user. Specify if the target GUI may be externally created." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nUsing bindings to libxdo so any window managed by an X11 display server can receive mouse events.\n\n```\nuse X11::libxdo;\nmy $xdo = Xdo.new;\n\nmy ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );\n\nsleep .25;\n\nfor ^$dw -> $mx {\n my $my = (($mx / $dh * τ).sin * 500).abs.Int + 200;\n $xdo.move-mouse( $mx, $my, 0 );\n my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;\n my $name = (try $xdo.get-window-name($window-id) if $window-id)\n // 'No name set';\n\n my $line = \"Mouse location: x=$x : y=$y\\nWindow under mouse:\\nWindow ID: \" ~\n $window-id ~ \"\\nWindow name: \" ~ $name ~ \"\\nScreen #: $screen\";\n\n print \"\\e[H\\e[J\", $line;\n sleep .001;\n}\n\nsay '';\n\n#`[ There are several available routines controlling mouse position and button events.\n\n.move-mouse( $x, $y, $screen ) # Move the mouse to a specific location.\n\n.move-mouse-relative( $delta-x, $delta-y ) # Move the mouse relative to it's current position.\n\n.move-mouse-relative-to-window( $x, $y, $window ) # Move the mouse to a specific location relative to the top-left corner of a window.\n\n.get-mouse-location() # Get the current mouse location (coordinates and screen ID number).\n\n.get-mouse-info() # Get all mouse location-related data.\n\n.wait-for-mouse-to-move-from( $origin-x, $origin-y ) # Wait for the mouse to move from a location.\n\n.wait-for-mouse-to-move-to( $dest-x, $dest-y ) # Wait for the mouse to move to a location.\n\n.mouse-button-down( $window, $button ) # Send a mouse press (aka mouse down) for a given button at the current mouse location.\n\n.mouse-button-up( $window, $button ) # Send a mouse release (aka mouse up) for a given button at the current mouse location.\n\n.mouse-button-click( $window, $button ) # Send a click for a specific mouse button at the current mouse location.\n\n.mouse-button-multiple( $window, $button, $repeat = 2, $delay? ) # Send a one or more clicks of a specific mouse button at the current mouse location.\n]\n\n```" } ]
[ { "role": "user", "content": "Quoted from the Wikipedia page : **Simulated annealing (SA)** is a probabilistic technique for approximating the global optimum of a given function. Simulated annealing interprets slow cooling as a slow decrease in the probability of temporarily accepting worse solutions as it explores the solution space.\n\n**Pseudo code** from Wikipedia\n\n```\nNotations :\n T : temperature. Decreases to 0.\n s : a system state\n E(s) : Energy at s. The function we want to minimize\n ∆E : variation of E, from state s to state s_next\n P(∆E , T) : Probability to move from s to s_next. \n \tif ( ∆E < 0 ) P = 1\n \t else P = exp ( - ∆E / T) . Decreases as T → 0\n \nPseudo-code:\n Let s = s0 -- initial state\n For k = 0 through kmax (exclusive):\n T ← temperature(k , kmax)\n Pick a random neighbour state , s_next ← neighbour(s)\n ∆E ← E(s) - E(s_next) \n If P(∆E , T) ≥ random(0, 1), move to the new state:\n s ← s_next\n Output: the final state s\n\n```\n\n**Problem statement**\n\nWe want to apply SA to the travelling salesman problem. There are 100 cities, numbered 0 to 99, located on a plane, at integer coordinates i,j : 0 <= i,j < 10 . The city at (i,j) has number 10\\*i + j. The cities are **all** connected : the graph is complete : you can go from one city to any other city in one step.\n\nThe salesman wants to start from city 0, visit all cities, each one time, and go back to city 0. The travel cost between two cities is the euclidian distance between them. The total travel cost is the total path length.\n\nA path **s** is a sequence (0 a b ...z 0) where (a b ..z) is a permutation of the numbers (1 2 .. 99). The path length = E(s) is the sum d(0,a) + d(a,b) + ... + d(z,0) , where d(u,v) is the distance between two cities. Naturally, we want to minimize E(s).\n\nDefinition : The neighbours of a city are the closest cities at distance 1 horizontally/vertically, or √2 diagonally. A corner city (0,9,90,99) has 3 neighbours. A center city has 8 neighbours.\n\n```\nDistances between cities\nd ( 0, 7) → 7\nd ( 0, 99) → 12.7279\nd ( 23, 78) → 7.0711\nd ( 33, 44) → 1.4142 // sqrt(2)\n\n```\n\n**Task**\n\nApply SA to the travelling salesman problem, using the following set of parameters/functions :\n\n* kT = 1 (Multiplication by kT is a placeholder, representing computing temperature as a function of 1-k/kmax):\n* temperature (k, kmax) = kT \\* (1 - k/kmax)\n* neighbour (s) : Pick a random city u > 0 . Pick a random neighbour city v > 0 of u , among u's 8 (max) neighbours on the grid. Swap u and v in s . This gives the new state *s\\_next*.\n* kmax = 1000\\_000\n* s0 = a random permutation\n\nFor k = 0 to kmax by step kmax/10 , display k, T, E(s). Display the final state s\\_final, and E(s\\_final).\n\nYou will see that the Energy may grow to a local optimum, before decreasing to a global optimum.\n\n**Illustrated example**\nTemperature charts\n\n**Numerical example**\n\n```\nkT = 1\nE(s0) = 529.9158\n\nk: 0 T: 1 Es: 529.9158\nk: 100000 T: 0.9 Es: 201.1726\nk: 200000 T: 0.8 Es: 178.1723\nk: 300000 T: 0.7 Es: 154.7069\nk: 400000 T: 0.6 Es: 158.1412 <== local optimum\nk: 500000 T: 0.5 Es: 133.856\nk: 600000 T: 0.4 Es: 129.5684\nk: 700000 T: 0.3 Es: 112.6919\nk: 800000 T: 0.2 Es: 105.799\nk: 900000 T: 0.1 Es: 102.8284\nk: 1000000 T: 0 Es: 102.2426\n\nE(s_final) = 102.2426 \nPath s_final = ( 0 10 11 21 31 20 30 40 50 60 70 80 90 91 81 71 73 83 84 74 64 54 55 65 75 76 66\n 67 77 78 68 58 48 47 57 56 46 36 37 27 26 16 15 5 6 7 17 18 8 9 19 29 28 38 39 49 59 69 \n79 89 99 98 88 87 97 96 86 85 95 94 93 92 82 72 62 61 51 41 42 52 63 53 43 32 22 12 13 \n23 33 34 44 45 35 25 24 14 4 3 2 1 0) \n\n```\n\n**Extra credit**\n\nTune the parameters kT, kmax, or use different temperature() and/or neighbour() functions to demonstrate a quicker convergence, or a better optimum." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Go\n\n```\n# simulation setup\nmy \\cities = 100; # number of cities\nmy \\kmax = 1e6; # iterations to run\nmy \\kT = 1; # initial 'temperature'\n\ndie 'City count must be a perfect square.' if cities.sqrt != cities.sqrt.Int;\n\n# locations of (up to) 8 neighbors, with grid size derived from number of cities\nmy \\gs = cities.sqrt;\nmy \\neighbors = [1, -1, gs, -gs, gs-1, gs+1, -(gs+1), -(gs-1)];\n\n# matrix of distances between cities\nmy \\D = [;];\nfor 0 ..^ cities² -> \\j {\n my (\\ab, \\cd) = (j/cities, j%cities)».Int;\n my (\\a, \\b, \\c, \\d) = (ab/gs, ab%gs, cd/gs, cd%gs)».Int;\n D[ab;cd] = sqrt (a - c)² + (b - d)²\n}\n\nsub T(\\k, \\kmax, \\kT) { (1 - k/kmax) × kT } # temperature function, decreases to 0\nsub P(\\ΔE, \\k, \\kmax, \\kT) { exp( -ΔE / T(k, kmax, kT)) } # probability to move from s to s_next\nsub Es(\\path) { sum (D[ path[$_]; path[$_+1] ] for 0 ..^ +path-1) } # energy at s, to be minimized\n\n# variation of E, from state s to state s_next\nsub delta-E(\\s, \\u, \\v) {\n my (\\a, \\b, \\c, \\d) = D[s[u-1];s[u]], D[s[u+1];s[u]], D[s[v-1];s[v]], D[s[v+1];s[v]];\n my (\\na, \\nb, \\nc, \\nd) = D[s[u-1];s[v]], D[s[u+1];s[v]], D[s[v-1];s[u]], D[s[v+1];s[u]];\n if v == u+1 { return (na + nd) - (a + d) }\n elsif u == v+1 { return (nc + nb) - (c + b) }\n else { return (na + nb + nc + nd) - (a + b + c + d) }\n}\n\n# E(s0), initial state\nmy \\s = @ = flat 0, (1 ..^ cities).pick(*), 0;\nmy \\E-min-global = my \\E-min = $ = Es(s);\n\nfor 0 ..^ kmax -> \\k {\n printf \"k:%8u T:%4.1f Es: %3.1f\\n\" , k, T(k, kmax, kT), Es(s)\n if k % (kmax/10) == 0;\n\n # valid candidate cities (exist, adjacent)\n my \\cv = neighbors[(^8).roll] + s[ my \\u = 1 + (^(cities-1)).roll ];\n next if cv ≤ 0 or cv ≥ cities or D[s[u];cv] > sqrt(2);\n\n my \\v = s[cv];\n my \\ΔE = delta-E(s, u, v);\n if ΔE < 0 or P(ΔE, k, kmax, kT) ≥ rand { # always move if negative\n (s[u], s[v]) = (s[v], s[u]);\n E-min += ΔE;\n E-min-global = E-min if E-min < E-min-global;\n }\n}\n\nsay \"\\nE(s_final): \" ~ E-min-global.fmt('%.1f');\nsay \"Path:\\n\" ~ s».fmt('%2d').rotor(20,:partial).join: \"\\n\";\n\n```\n\nOutput:\n\n```\nk: 0 T: 1.0 Es: 522.0\nk: 100000 T: 0.9 Es: 185.3\nk: 200000 T: 0.8 Es: 166.1\nk: 300000 T: 0.7 Es: 174.7\nk: 400000 T: 0.6 Es: 146.9\nk: 500000 T: 0.5 Es: 140.2\nk: 600000 T: 0.4 Es: 127.5\nk: 700000 T: 0.3 Es: 115.9\nk: 800000 T: 0.2 Es: 111.9\nk: 900000 T: 0.1 Es: 109.4\n\nE(s_final): 109.4\nPath:\n 0 10 20 30 40 50 60 84 85 86 96 97 87 88 98 99 89 79 78 77\n67 68 69 59 58 57 56 66 76 95 94 93 92 91 90 80 70 81 82 83\n73 72 71 62 63 64 74 75 65 55 54 53 52 61 51 41 31 21 22 32\n42 43 44 45 46 35 34 24 23 33 25 15 16 26 36 47 37 27 17 18\n28 38 48 49 39 29 19 9 8 7 6 5 4 14 13 12 11 2 3 1\n 0\n```" } ]
[ { "role": "user", "content": "Task\n\nGenerate a sine wave:\n\n: : 1. you choose the frequency of the wave\n 2. generate a sine wave for 5 seconds\n 3. play sound" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04.01\n\nWhat a horribly underspecified task. Ah well, gives me lots of wiggle room to cheat in various ways.\n\n```\nmy ($rows,$cols) = qx/stty size/.words;\nmy $v = floor $rows / 2;\nprint \"\\e[H\\e[J\", 'Generating sine wave of zero amplitude and zero frequency for 5 seconds...',\n \"\\e[$v;0H\", '_' x $cols;\nsleep 5;\nsay \"\\e[H\\e[J\", 'No?, ok how about this:';\n\nuse SVG;\nmy $filename = 'sine.svg';\nmy $out = open($filename, :w) orelse .die;\n$out.say: SVG.serialize(\n svg => [\n width => 400, height => 150, style => 'stroke:rgb(0,0,255)',\n  :rect[:width<100%>, :height<100%>, :fill<white>],\n  :path[ :fill<none>, :d('M0,25 C36.42,25,63.58,125,100,125 M100,125 C136.42,125,163.58,25,200,25 M200,25 C236.42,25,263.58,125,300,125 M300,125 C336.42,125,363.58,25,400,25') ],\n ],\n);\nclose $out;\nsay \"Sine wave generated to {$filename.IO.absolute}, better open it quickly...\";\nsleep 5;\nunlink $filename;\nsay 'Oops, too late.';\nsay 'Still no? Ok how about:';\nshell 'play -n -c1 synth 5.0 sin %-12';\n\n```" } ]
[ { "role": "user", "content": "A Global Singleton is a class of which only one instance exists within a program.\n\nAny attempt to use non-static members of the class involves performing operations on this one instance." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nclass Singleton {\n # We create a lexical variable in the class block that holds our single instance.\n my Singleton $instance = Singleton.bless; # You can add initialization arguments here.\n method new {!!!} # Singleton.new dies.\n method instance { $instance; }\n}\n\n```" } ]
[ { "role": "user", "content": "Define the data structure for a singly-linked list element. Said element should contain a data member capable of holding a numeric value, and the link to the next element 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#### With Pair\n\nA Pair (constructed with the `=>` operator) can be treated as a cons cell, and thus used to build a linked lists:\n\n```\nmy $elem = 42 => $nextelem;\n\n```\n\nHowever, because this is not the primary purpose of the Pair type, it suffers from the following limitations:\n\n* The naming of Pair's accessor methods is not idiomatic for this use case (`.key` for the cell's value, and `.value` for the link to the next cell).\n* A Pair (unlike an Array) does not automatically wrap its keys/values in item containers – so each cell of the list will be immutable once created, making element insertion/deletion impossible (except inserting at the front).\n* It provides no built-in convenience methods for iterating/modifying/transforming such a list.\n\n#### With custom type\n\nFor more flexibility, one would create a custom type:\n\n```\nclass Cell {\n has $.value is rw;\n has Cell $.next is rw;\n \n # ...convenience methods here...\n}\n\nsub cons ($value, $next) { Cell.new(:$value, :$next) }\n\nmy $list = cons 10, (cons 20, (cons 30, Nil));\n\n```" } ]
[ { "role": "user", "content": "Using the link element defined in Singly-Linked List (element), define a method to insert an element into a singly-linked list following a given element.\n\nUsing this method, insert an element C into a list comprised of elements A->B, following element A.\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\nExtending class Cell from Singly-linked\\_list/Element\\_definition#Raku:\n\n```\n method insert ($value) {\n $.next = Cell.new(:$value, :$.next)\n }\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDefine a method to remove an element from a singly-linked list and demonstrate its use.\n\nYou may wish to use the link element defined in Singly-Linked List (element) for the purposes of this task.\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\nExtending class Cell from Singly-linked\\_list/Element\\_definition#Raku:\n\n```\n method delete ($value --> Cell) {\n my $prev = Nil;\n my $cell = self;\n my $new-head = self;\n \n while $cell {\n my $next = $cell.next;\n if $cell.value == $value {\n $prev.next = $next if $prev;\n $cell.next = Nil;\n $new-head = $next if $cell === $new-head;\n }\n else {\n $prev = $cell;\n }\n $cell = $next;\n }\n \n return $new-head;\n }\n\n```\n\nUsage:\n\n```\nmy $list = cons 10, (cons 20, (cons 10, (cons 30, Nil)));\n\n$list = $list.delete(10);\n\n```" } ]
[ { "role": "user", "content": ": I don't even know how to reverse a linked-list, and I don't even know what that is. -- a YouTuber.\n\nReverse a linked list. Obviously you can do it by turning it into a normal list and back, but feel free to use a smarter, possibly more efficient way." }, { "role": "assistant", "content": "Extending code from the Singly-linked\\_list/Element\\_definition#Raku Task\n\n```\n# 20240220 Raku programming solution\n\nclass Cell { has ($.value, $.next) is rw;\n\n method reverse {\n my ($list, $prev) = self, Nil;\n while $list.defined {\n my $next = $list.next;\n $list.next = $prev;\n ($list, $prev) = ($next, $list)\n }\n return $prev;\n }\n\n method gist {\n my $cell = self;\n return ( gather while $cell.defined {\n take $cell.value andthen $cell = $cell.next;\n } ).Str\n }\n}\n\nsub cons ($value, $next = Nil) { Cell.new(:$value, :$next) }\n\nmy $list = cons 10, (cons 20, (cons 30, (cons 40, Nil)));\n\nsay $list = $list.reverse;\nsay $list = $list.reverse;\n\n```\n\nOutput:\n\n```\n40 30 20 10\n10 20 30 40\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "Traverse from the beginning of a singly-linked list to the end.\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### With Pair\n\nBuilt-in list processing in Raku is not specifically based on singly-linked lists,\nbut works at a higher abstraction level that encapsulates such implementation choices. Nonetheless, it's trivial to use the Pair type to build what is essentially a Lisp-style cons list, and in fact, the => pair constructor is right associative for precisely that reason.\nWe traverse such a list here using a 3-part loop:\n\n```\nmy $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu;\n\nloop (my $l = $list; $l; $l.=value) {\n say $l.key;\n}\n\n```\n\nOutput:\n\n```\n1\n2\n3\n4\n5\n6\n```\n\nIt would be pretty easy to make such lists iterable as normal Raku lists,\nif anyone really cared to...\n\nWell, shoot, let's just go ahead and do it.\nWe'll pretend the Pair type is really a list type.\n(And we show how you turn an ordinary list into a cons list using a reduction.\nNote how the [=>] reduction is also right associative,\njust like the base operator.)\n\n```\nuse MONKEY-TYPING;\naugment class Pair {\n method traverse () {\n gather loop (my $l = self; $l; $l.=value) {\n take $l.key;\n }\n }\n}\n\nmy $list = [=>] 'Ⅰ' .. 'Ⅻ', Mu;\nsay ~$list.traverse;\n\n```\n\nOutput:\n\n```\nⅠ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ Ⅶ Ⅷ Ⅸ Ⅹ Ⅺ Ⅻ\n```\n\n### With custom type\n\nExtending class Cell from Singly-linked\\_list/Element\\_definition#Raku:\n\n```\n method Seq {\n self, *.next ...^ !*\n }\n\n```\n\nUsage:\n\n```\nmy $list = (cons 10, (cons 20, (cons 30, Nil)));\n\nfor $list.Seq -> $cell {\n say $cell.value;\n}\n\n```\n\nOutput:\n\n```\n10\n20\n30\n```" } ]
[ { "role": "user", "content": "A\n{\\displaystyle {\\displaystyle A}}\n is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by \n\nX\n\n−\n1\nA\nX\n{\\displaystyle {\\displaystyle X^{-1}AX}}\n.\nThe eigenvectors in \n\nX\n{\\displaystyle {\\displaystyle X}}\n have three big problems: They are usually not orthogonal, there\nare not always enough eigenvectors, and \n\nA\nx\n{\\displaystyle {\\displaystyle Ax}}\n = \n\nλ\nx\n{\\displaystyle {\\displaystyle \\lambda x}}\n requires \n\nA\n{\\displaystyle {\\displaystyle A}}\n to be a square matrix. The\nsingular vectors of \n\nA\n{\\displaystyle {\\displaystyle A}}\n solve all those problems in a perfect way.\n\nThe Singular Value Decomposition (SVD)\n\nAccording to the web page above, for any rectangular matrix \n\nA\n{\\displaystyle {\\displaystyle A}}\n, we can decomposite it as \n\nA\n=\nU\nΣ\n\nV\n\nT\n{\\displaystyle {\\displaystyle A=U\\Sigma V^{T}}}\n\n**Task Description**\n\nFirstly, input two numbers \"m\" and \"n\".\n\nThen, input a square/rectangular matrix \n\nA\n\nm\n×\nn\n{\\displaystyle {\\displaystyle A^{m\\times n}}}\n.\n\nFinally, output \n\nU\n,\n \nΣ\n,\n \nV\n{\\displaystyle {\\displaystyle U,~\\Sigma ,\\ V}}\n with respect to \n\nA\n{\\displaystyle {\\displaystyle A}}\n.\n\n**Example**\n\n**Sample Input**\n\n```\n2 2\n3 0\n4 5\n\n```\n\nFrom the input above we can know that \n\nA\n{\\displaystyle {\\displaystyle A}}\n is a 2 by 2 matrix.\n\n**Sample Output**\n\n```\n \n0.31622776601683794 -0.9486832980505138\n0.9486832980505138 0.31622776601683794\n\n6.708203932499369 0\n0 2.23606797749979\n\n0.7071067811865475 -0.7071067811865475\n0.7071067811865475 0.7071067811865475\n\n```\n\nThe output may vary depending your choice of the data types.\n\n**Remark**\n\n1. It’s encouraged to implement the algorithm by yourself while using libraries is still acceptible.\n\n2. The algorithm should be applicable for general case(\n\nm\n×\nn\n{\\displaystyle {\\displaystyle m\\times n}}\n)." }, { "role": "assistant", "content": "```\n# 20230108 Raku programming solution\n\nuse Math::Libgsl::Matrix;\nuse Math::Libgsl::LinearAlgebra;\n\nmy @M = <3 0>, <4 5>;\nmy Math::Libgsl::Matrix \\M .= new: @M.elems, @M.first.elems;\n(^M.size1)>>.&{ M.set-row: $_, @M[$_;*] }\n\nmy (\\V,\\S) = SV-decomp M;\n\nsay \"U factor: \" and say (^M.size1)>>.&{ M.get-row($_)>>.fmt: '%.10g' }\nsay \"singular values: \" and say (^S.size )>>.&{ S.get($_)>>.fmt: '%.10g' }\nsay \"Vt factor: \" and say (^V.size1)>>.&{ V.get-row($_)>>.fmt: '%.10g' }\n\n```\n\nOutput:\n\n```\nU factor: \n([-0.316227766 -0.9486832981] [-0.9486832981 0.316227766])\nsingular values: \n((6.708203932) (2.236067977))\nVt factor: \n([-0.7071067812 -0.7071067812] [-0.7071067812 0.7071067812])\n```" } ]
[ { "role": "user", "content": "The **Sisyphus sequence** is an infinite sequence of positive integers that was devised in 2022 by Eric Angelini and Carole Dubois.\n\nThe first term is 1. Subsequent terms are found by applying the following rule:\n\n* If the previous term was even, then halve it.\n\n* If the previous term was odd, then add the smallest prime number that has not yet been added.\n\n1 is odd and so the second term is: 1 + 2 = 3, because 2 is the smallest prime not yet added.\n\n3 is odd and so the third term is: 3 + 3 = 6, because 3 is the smallest prime not yet added.\n\n6 is even and so the fourth term is : 6 ÷ 2 = 3, and so on.\n\nTask\n\nFind and show on this page (in 10 lines of 10 terms), the first 100 terms of the sequence.\n\nWhat are the **1,000**th, **10,000**th, **100,000**th and **1,000,000**th terms of the sequence and, in each case, what is the highest prime needed to reach them?\n\nIf it is difficult or impossible for your language or output device to meet all of these requirements, then just do what you reasonably can.\n\nStretch\n\nWhat are the **10 millionth** and **100 millionth** terms and the highest prime needed to reach each one?\n\nBy the time the **100 millionth** term is reached, which number(s) **under 250**:\n\n* Have not yet occurred in the sequence.\n\n* Have occurred the most times and their number of occurrences.\n\nExtreme stretch\n\nWhat is the number of the first term to equal 36?\n\nThis was originally set as a challenge by Neil Sloane who was worried by its non-appearance and found by Russ Cox.\n\nReferences\n\n* OEIS sequence A350877: The Sisyphus sequence" }, { "role": "assistant", "content": "```\nuse Math::Primesieve;\nuse Lingua::EN::Numbers;\n\nmy ($exp1, $exp2, $limit1, $limit2) = 3, 8, 100, 250;\nmy ($n, $s0, $s1, $p, @S1, %S) = 1, 1, Any, Any, 1;\nmy $iterator = Math::Primesieve::iterator.new;\nmy @Nth = ($exp1..$exp2)».exp(10);\nmy $S2 = BagHash.new;\n\nrepeat {\n $n++;\n $s1 = $s0 %% 2 ?? $s0 div 2 !! $s0 + ($p = $iterator.next);\n @S1.push: $s1 if $n ≤ $limit1;\n $S2.add: $s1 if $s1 ≤ $limit2;\n %S{$n}{'value', 'prime'} = $s1, $p if $n ∈ @Nth;\n $s0 = $s1;\n} until $n == @Nth[*-1];\n\nsay \"The first $limit1 members of the Sisyphus sequence are:\";\nsay @S1.batch(10)».fmt('%4d').join(\"\\n\") ~ \"\\n\";\nprintf \"%12sth member is: %13s with prime: %11s\\n\", ($_, %S{$_}{'value'}, %S{$_}{'prime'})».&comma for @Nth;\nsay \"\\nNumbers under $limit2 that do not occur in the first {comma @Nth[*-1]} terms:\";\nsay (1..$limit2).grep: * ∉ $S2.keys;\nsay \"\\nNumbers under $limit2 that occur the most ({$S2.values.max} times) in the first {comma @Nth[*-1]} terms:\";\nsay $S2.keys.grep({ $S2{$_} == $S2.values.max}).sort;\n\n```\n\nOutput:\n\n```\nThe first 100 members of the Sisyphus sequence are:\n 1 3 6 3 8 4 2 1 8 4\n 2 1 12 6 3 16 8 4 2 1\n 18 9 28 14 7 30 15 44 22 11\n 42 21 58 29 70 35 78 39 86 43\n 96 48 24 12 6 3 62 31 92 46\n 23 90 45 116 58 29 102 51 130 65\n 148 74 37 126 63 160 80 40 20 10\n 5 106 53 156 78 39 146 73 182 91\n 204 102 51 178 89 220 110 55 192 96\n 48 24 12 6 3 142 71 220 110 55\n\n 1,000th member is: 990 with prime: 2,273\n 10,000th member is: 24,975 with prime: 30,713\n 100,000th member is: 265,781 with prime: 392,111\n 1,000,000th member is: 8,820,834 with prime: 4,761,697\n 10,000,000th member is: 41,369,713 with prime: 55,900,829\n 100,000,000th member is: 1,179,614,168 with prime: 640,692,323\n\nNumbers under 250 that do not occur in the first 100,000,000 terms:\n36 72 97 107 115 127 144 167 194 211 214 230 232\n\nNumbers under 250 that occur the most (7 times) in the first 100,000,000 terms:\n7 14 28\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program that does the following in this order:\n\n* Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.\n* Print \"Sleeping...\"\n* Sleep the main thread for the given amount of time.\n* Print \"Awake!\"\n* End.\n\nRelated task\n\n* Nautical bell" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThe sleep function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).\n\n```\nmy $sec = prompt(\"Sleep for how many microfortnights? \") * 1.2096;\nsay \"Sleeping...\";\nsleep $sec;\nsay \"Awake!\";\n\n```\n\nNote that 1.2096 is a rational number in Raku, not floating point, so precision can be maintained even when dealing with very small powers of ten." } ]
[ { "role": "user", "content": "Background on the task\n\nIn decision theory, The Sleeping Beauty Problem\nis a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental\nsubject, named Sleeping Beauty, agrees to an experiment as follows:\nSleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.\nIf this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to\nestimate the probability that the coin toss was heads. Her estimate is recorded and she is\nthen put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.\n\nIf instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to\nestimate the probability the coin toss was heads, but is then given a drug which makes her forget\nthat she had been woken on Monday before being put back to sleep again. She then wakes only 1 day\nlater, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss\nwas heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.\n\nSome decision makers have argued that since the coin toss was fair Sleeping Beauty should always\nestimate the probability of heads as 1/2, since she does not have any additional information. Others\nhave disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice\nas likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate\nshould be 1/3 heads.\n\nTask\n\nGiven the above problem, create a Monte Carlo estimate of the actual results. The program should find the\nproportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty\nis asked the question." }, { "role": "assistant", "content": "```\nsub sleeping-beauty ($trials) {\n my $gotheadsonwaking = 0;\n my $wakenings = 0;\n ^$trials .map: {\n given <Heads Tails>.roll {\n ++$wakenings;\n when 'Heads' { ++$gotheadsonwaking }\n when 'Tails' { ++$wakenings }\n }\n }\n say \"Wakenings over $trials experiments: \", $wakenings;\n $gotheadsonwaking / $wakenings\n}\n\nsay \"Results of experiment: Sleeping Beauty should estimate a credence of: \", sleeping-beauty(1_000_000);\n\n```\n\nOutput:\n\n```\nWakenings over 1000000 experiments: 1500040\nResults of experiment: Sleeping Beauty should estimate a credence of: 0.333298\n```" } ]
[ { "role": "user", "content": "The **smallest enclosing circle problem** (aka **minimum covering circle problem**, **bounding circle problem**) is a mathematical problem of computing the smallest circle that contains all of a given set of points in the Euclidean plane.\n\nInitially it was proposed by the English mathematician James Joseph Sylvester in 1857.\n\nTask\n\nFind circle of smallest radius containing all of given points.\n\n* Circle is defined by it's center and radius;\n* Points are defined by their coordinates in n-dimensional space;\n* Circle (sphere) contains point when *distance between point and circle center <= circle radius*." }, { "role": "assistant", "content": "**Translation of**: Go\n\n```\nclass P { has ($.x, $.y) is rw; # Point\n method gist { \"({$.x~\", \"~$.y})\" }\n}\n\nclass C { has (P $.c, Numeric $.r); # Circle\n method gist { \"Center = \" ~$.c.gist ~ \" and Radius = $.r\\n\" }\n\n # tests whether a circle contains the point 'p'\n method contains(P \\p --> Bool) { distSq($.c, p) ≤ $.r² }\n\n # tests whether a circle contains a slice of point\n method encloses(@ps --> Bool) { [and] @ps.map: { $.contains($_) } } \n}\n\nsub infix:<−> (P \\a, P \\b) { a.x - b.x, a.y - b.y } # note: Unicode 'minus'\n\n# returns the square of the distance between two points\nsub distSq (P \\a, P \\b) { [+] (a − b)»² }\n\nsub getCenter (\\bx, \\by, \\cx, \\cy --> P) {\n my (\\b,\\c,\\d) = bx²+by², cx²+cy², bx*cy - by*cx;\n P.new: x => (cy*b - by*c) / (2 * d), y => (bx*c - cx*b) / (2 * d)\n} # returns the center of a circle defined by 3 points\n\nsub circleFrom3 (P \\a, P \\b, P \\c --> C) {\n my \\k = $ = getCenter |(b − a), |(c − a);\n k.x, k.y Z[+=] a.x, a.y;\n C.new: c => k, r => distSq(k, a).sqrt\n} # returns a unique circle that intersects 3 points\n\nsub circleFrom2 (P \\a, P \\b --> C ) {\n my \\center = P.new: x => ((a.x + b.x) / 2), y => ((a.y + b.y) / 2) ;\n C.new: c => center, r => (distSq(a, b).sqrt / 2)\n} # returns smallest circle that intersects 2 points\n\nsub secTrivial( @rs --> C ) {\n given @rs {\n when * == 0 { return C.new: c => (P.new: x => 0, y => 0), r => 0 }\n when * == 1 { return C.new: c => @rs[0], r => 0 }\n when * == 2 { return circleFrom2 |@rs }\n when * == 3 { #`{ no-op } }\n when * > 3 { die \"There shouldn't be more than 3 points.\" }\n }\n for 0, 1 X 1, 2 -> ( \\i, \\j ) {\n return $_ if .encloses(@rs) given circleFrom2 |@rs[i,j]\n }\n circleFrom3 |@rs\n} # returns smallest enclosing circle for n ≤ 3\n\nsub Welzl-helper( @ps is copy, @rs is copy , \\n --> C ) {\n return secTrivial(@rs) if n == 0 or @rs == 3;\n my \\p = @ps.shift;\n return $_ if .contains(p) given Welzl-helper @ps, @rs, n-1;\n Welzl-helper @ps, @rs.append(p), n-1\n} # helper function for Welzl method\n\n# applies the Welzl algorithm to find the SEC\nsub welzl(@ps --> C) { Welzl-helper @ps.pick(*), [], @ps }\n\nmy @tests = (\n [ (0,0), (0,1), (1,0) ],\n [ (5,-2), (-3,-2), (-2,5), (1,6), (0,2) ]\n).map: {\n @_.map: { P.new: x => $_[0], y => $_[1] }\n}\n\nsay \"Solution for smallest circle enclosing {$_.gist} :\\n\", welzl $_ for @tests;\n\n```\n\nOutput:\n\n```\nSolution for smallest circle enclosing ((0, 0) (0, 1) (1, 0)) :\nCenter = (0.5, 0.5) and Radius = 0.7071067811865476\n\nSolution for smallest circle enclosing ((5, -2) (-3, -2) (-2, 5) (1, 6) (0, 2)) :\nCenter = (1, 1) and Radius = 5\n```" } ]
[ { "role": "user", "content": "Task\n\nTask description is taken from Project Euler\n \n(https://projecteuler.net/problem=5)\n \n2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.\n \nWhat is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?\n\nRelated\n\n* Least common multiple" }, { "role": "assistant", "content": "Exercise with some larger values as well.\n\n```\nsay \"$_: \", [lcm] 2..$_ for <10 20 200 2000>\n\n```\n\nOutput:\n\n```\n10: 2520\n20: 232792560\n200: 337293588832926264639465766794841407432394382785157234228847021917234018060677390066992000\n2000: 151117794877444315307536308337572822173736308853579339903227904473000476322347234655122160866668946941993951014270933512030194957221371956828843521568082173786251242333157830450435623211664308500316844478617809101158220672108895053508829266120497031742749376045929890296052805527212315382805219353316270742572401962035464878235703759464796806075131056520079836955770415021318508272982103736658633390411347759000563271226062182345964184167346918225243856348794013355418404695826256911622054015423611375261945905974225257659010379414787547681984112941581325198396634685659217861208771400322507388161967513719166366839894214040787733471287845629833993885413462225294548785581641804620417256563685280586511301918399010451347815776570842790738545306707750937624267501103840324470083425714138183905657667736579430274197734179172691637931540695631396056193786415805463680000\n```" } ]
[ { "role": "user", "content": "Generate the sequence of numbers **a(k)**, where each **k** is the smallest positive integer such that **k + 2m** is composite for every positive integer **m** less than **k**.\n\nFor example\n\nSuppose k == 7; test m == 1 through m == 6. If any are prime, the test fails.\n\nIs 7 + 21 (9) prime? False\n\nIs 7 + 22 (11) prime? True\n\nSo 7 is not an element of this sequence.\n\nIt is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite.\n\nTask\n\nFind and display, here on this page, the first **5** elements of this sequence.\n\nSee also\n\nOEIS:A033919 - Odd k for which k+2^m is composite for all m < k" }, { "role": "assistant", "content": "```\nput (1..∞).hyper(:250batch).map(* × 2 + 1).grep( -> $k { !(1 ..^ $k).first: ($k + 1 +< *).is-prime } )[^5]\n\n```\n\nOutput:\n\n```\n773 2131 2491 4471 5101\n```" } ]
[ { "role": "user", "content": "Task\n\nSmallest positive integer   **k**   such that the decimal expansion of   **kk**   contains   **n**,   where   **n  <  51**" }, { "role": "assistant", "content": "```\nsub smallest ( $n ) {\n state @powers = '', |map { $_ ** $_ }, 1 .. *;\n\n return @powers.first: :k, *.contains($n);\n}\n\n.say for (^51).map(&smallest).batch(10)».fmt('%2d');\n\n```\n\nOutput:\n\n```\n( 9 1 3 5 2 4 4 3 7 9)\n(10 11 5 19 22 26 8 17 16 19)\n( 9 8 13 7 17 4 17 3 11 18)\n(13 5 23 17 18 7 17 15 9 18)\n(16 17 9 7 12 28 6 23 9 24)\n(23)\n\n```" } ]
[ { "role": "user", "content": "Task\n\nShow the smallest (non-negative integer) power of   **6**   whose decimal expansion contains   **n,**     where   **n   <   22**" }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\n\nmy @po6 = ^Inf .map: *.exp: 6;\n\nput join \"\\n\", (flat ^22, 120).map: -> $n {\n sprintf \"%3d: 6%-4s %s\", $n, .&super, comma @po6[$_]\n given @po6.first: *.contains($n), :k\n};\n\n```\n\nOutput:\n\n```\n 0: 6⁹ 10,077,696\n 1: 6⁰ 1\n 2: 6³ 216\n 3: 6² 36\n 4: 6⁶ 46,656\n 5: 6⁶ 46,656\n 6: 6¹ 6\n 7: 6⁵ 7,776\n 8: 6¹² 2,176,782,336\n 9: 6⁴ 1,296\n 10: 6⁹ 10,077,696\n 11: 6¹⁶ 2,821,109,907,456\n 12: 6⁴ 1,296\n 13: 6¹³ 13,060,694,016\n 14: 6²⁸ 6,140,942,214,464,815,497,216\n 15: 6¹⁸ 101,559,956,668,416\n 16: 6³ 216\n 17: 6¹⁰ 60,466,176\n 18: 6¹⁵ 470,184,984,576\n 19: 6²¹ 21,936,950,640,377,856\n 20: 6²⁶ 170,581,728,179,578,208,256\n 21: 6³ 216\n120: 6¹⁴⁷ 2,444,746,349,972,956,194,083,608,044,935,243,159,422,957,210,683,702,349,648,543,934,214,737,968,217,920,868,940,091,707,112,078,529,114,392,164,827,136\n```" } ]