messages
listlengths 2
2
|
---|
[
{
"role": "user",
"content": "Task[edit]\n\nWrite a function or program that can split a string at each non-escaped occurrence of a separator character.\n\nIt should accept three input parameters:\n\n: : : * The **string**\n * The **separator character**\n * The **escape character**\n\nIt should output a list of strings.\n\nDetails\n\nRules for splitting:\n\n* The fields that were separated by the separators, become the elements of the output list.\n* Empty fields should be preserved, even at the start and end.\n\nRules for escaping:\n\n* \"Escaped\" means preceded by an occurrence of the escape character that is not already escaped itself.\n* When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).\n* Each occurrence of the escape character that was used to escape something, should **not** become part of the output.\n\nTest case\n\nDemonstrate that your function satisfies the following test-case:\n\n| Input | Output |\n| --- | --- |\n| | | | | --- | --- | | string: | ``` one^|uno||three^^^^|four^^^|^cuatro| ``` | | separator character: | ``` | ``` | | escape character: | ``` ^ ``` | | | | | --- | | ``` one|uno ``` | | | | ``` three^^ ``` | | ``` four^|cuatro ``` | | | |\n\n(Print the output list in any format you like, as long as it is it easy to see what the fields are.)\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string ย (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff ย (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub tokenize ($string,ย :$sep!,ย :$esc!) {\n return $string.match(/([ <!before $sep | $esc> . | $esc . ]*)+ย % $sep/)\\\n .[0].map(*.subst: /$esc )> ./, '',ย :g);\n}\n\nsay \"'$_'\" for tokenize 'one^|uno||three^^^^|four^^^|^cuatro|', sep => '|', esc => '^';\n\n```\n\nOutput:\n\n```\n'one|uno'\n''\n'three^^'\n'four^|cuatro'\n''\n\n```\n\nNotable Raku innovations that make this different from the equivalent #Perl solution:\n\n* string variables can be safely interpolated into regexes without having to 'quotemeta' them\n* regexes matches return a nested `Match` object which allows retrieving *all* results for a given capture group *(rather than just the last thing that it matched)*, thus getting rid of the need for repeated global matching\n* the `<field>+ย % <delimiter>` regex construct allows handling the delimiters in a more idiomatic way\n* the `)>` regex construct can be used to exclude anything that follows it from the returned match result"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn computational number theory, the TonelliโShanks algorithm is a technique for solving for **x** in a congruence of the form:\n\n: : x2 โก n (mod p)\n\nwhere **n** is an integer which is a quadratic residue (mod p), **p** is an odd prime, and **x,n โ Fp** where Fp = {0, 1, ..., p - 1}.\n\nIt is used in cryptography techniques.\n\nTo apply the algorithm, we need the Legendre symbol:\n\nThe Legendre symbol **(a | p)** denotes the value of a(p-1)/2 (mod p).\n\n* **(a | p) โก 1** ย ย if **a** is a square (mod p)\n* **(a | p) โก -1** ย ย if **a** is not a square (mod p)\n* **(a | p) โก 0** ย ย if **a** โก 0 (mod p)\n\nAlgorithm pseudo-code\n\nAll โก are taken to mean (mod p) unless stated otherwise.\n\n* Input: **p** an odd prime, and an integer **n** .\n* Step 0: Check that **n** is indeed a square: (n | p) must be โก 1 .\n* Step 1: By factoring out powers of 2 from p - 1, find **q** and **s** such that p - 1 = q2s with **q** odd .\n + If p โก 3 (mod 4) (i.e. s = 1), output the two solutions r โก ยฑ n(p+1)/4 .\n* Step 2: Select a non-square **z** such that (z | p) โก -1 and set c โก zq .\n* Step 3: Set r โก n(q+1)/2, t โก nq, m = s .\n* Step 4: Loop the following:\n + If t โก 1, output **r** and **p - r** .\n + Otherwise find, by repeated squaring, the lowest **i**, 0 < i < m , such that t2i โก 1 .\n + Let b โก c2(m - i - 1), and set r โก rb, t โก tb2, c โก b2 and m = i .\n\nTask\n\nImplement the above algorithm.\n\nFind solutions (if any) for\n\n* n = 10 p = 13\n* n = 56 p = 101\n* n = 1030 p = 10009\n* n = 1032 p = 10009\n* n = 44402 p = 100049\n\nExtra credit\n\n* n = 665820697 p = 1000000009\n* n = 881398088036 p = 1000000000039\n* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577\n\nSee also\n\n* Modular exponentiation\n* Cipolla's algorithm"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04\n\nTranslation of the Wikipedia pseudocode, heavily influenced by Sidef and Python.\n\n```\n# Legendre operator (๐โ๐)\nsub infix:<โ> (Int \\๐, Int \\๐ where ๐.is-prime && (๐ย != 2)) {\n given ๐.expmod( (๐-1) div 2, ๐ ) {\n when 0 { 0 }\n when 1 { 1 }\n default { -1 }\n }\n}\n\nsub tonelli-shanks ( \\๐, \\๐ where (๐โ๐) > 0 ) {\n my $๐ = ๐ - 1;\n my $๐ = 0;\n $๐ +>= 1 and $๐++ while $๐ย %% 2;\n return ๐.expmod((๐+1) div 4, ๐) if $๐ == 1;\n my $๐ = ((2..๐).first: (*โ๐) < 0).expmod($๐, ๐);\n my $๐
= ๐.expmod( ($๐+1) +> 1, ๐ );\n my $๐ก = ๐.expmod( $๐, ๐ );\n while ($๐ก-1)ย % ๐ {\n my $b;\n my $๐ก2 = $๐กยฒย % ๐;\n for 1 .. $๐ {\n if ($๐ก2-1)ย %% ๐ {\n $b = $๐.expmod(1 +< ($๐-1-$_), ๐);\n $๐ = $_;\n last;\n }\n $๐ก2 = $๐ก2ยฒย % ๐;\n }\n $๐
= ($๐
* $b)ย % ๐;\n $๐ = $bยฒย % ๐;\n $๐ก = ($๐ก * $๐)ย % ๐;\n }\n $๐
;\n}\n\nmy @tests = (\n (10, 13),\n (56, 101),\n (1030, 10009),\n (1032, 10009),\n (44402, 100049),\n (665820697, 1000000009),\n (881398088036, 1000000000039),\n (41660815127637347468140745042827704103445750172002,\n 100000000000000000000000000000000000000000000000577)\n);\n\n for @tests -> ($n, $p) {\n try my $t = tonelli-shanks($n, $p);\n say \"No solution for ({$n}, {$p}).\" and next ifย !$t or ($tยฒ - $n)ย % $p;\n say \"Roots of $n are ($t, {$p-$t}) mod $p\";\n}\n\n```\n\nOutput:\n\n```\nRoots of 10 are (7, 6) mod 13\nRoots of 56 are (37, 64) mod 101\nRoots of 1030 are (1632, 8377) mod 10009\nNo solution for (1032, 10009).\nRoots of 44402 are (30468, 69581) mod 100049\nRoots of 665820697 are (378633312, 621366697) mod 1000000009\nRoots of 881398088036 are (791399408049, 208600591990) mod 1000000000039\nRoots of 41660815127637347468140745042827704103445750172002 are (32102985369940620849741983987300038903725266634508, 67897014630059379150258016012699961096274733366069) mod 100000000000000000000000000000000000000000000000577\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nFind the top ย *N* ย salaries in each department, ย where ย *N* ย is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\n```\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nWe use whitespace-separated fields here from a heredoc; q:to/---/ begins the heredoc. The Z=> operator zips two lists into a list of pairs.\nIn MAIN, the classify method generates pairs where each key is a different department, and each value all the entries in that department. We then sort the pairs and process each department separately. Within each department, we sort on salary (negated to reverse the order). The last statement is essentially a list comprehension that uses a slice subscript with the ^ \"up to\" operator to take the first N elements of the sorted employee list. The :v modifier returns only valid values. The .<Name> form is a slice hash subscript with literals strings. That in turn is just the subscript form of the <...> (\"quote words\") form, which is more familar to Perl 5 programmers as\nqw/.../. We used that form earlier to label the initial data set.\n\nThis program also makes heavy use of method calls that start with dot. In Raku this means a method call on the current topic, $\\_, which is automatically set by any for or map construct that doesn't declare an explicit formal parameter on its closure.\n\n```\nmy @data = do for q:to/---/.lines -> $line {\n E10297 32000 D101 Tyler Bennett\n E21437 47000 D050 John Rappl\n E00127 53500 D101 George Woltman\n E63535 18000 D202 Adam Smith\n E39876 27800 D202 Claire Buckman\n E04242 41500 D101 David McClellan\n E01234 49500 D202 Rich Holcomb\n E41298 21900 D050 Nathan Adams\n E43128 15900 D101 Richard Potter\n E27002 19250 D202 David Motsinger\n E03033 27000 D101 Tim Sampair\n E10001 57000 D190 Kim Arlich\n E16398 29900 D190 Timothy Grove\n ---\n\n $%( < Id Salary Dept Name >\n Z=>\n $line.split(/ \\s\\s+ /)\n )\n}\n\nsub MAIN(Int $N = 3) {\n for @data.classify({ .<Dept> }).sortยป.value {\n my @es = .sort: { -.<Salary> }\n say '' if (state $bline)++;\n say .< Dept Id Salary Name > for @es[^$N]:v;\n }\n}\n\n```\n\nOutput:\n\n```\nD050 E21437 47000 John Rappl\nD050 E41298 21900 Nathan Adams\n\nD101 E00127 53500 George Woltman\nD101 E04242 41500 David McClellan\nD101 E10297 32000 Tyler Bennett\n\nD190 E10001 57000 Kim Arlich\nD190 E16398 29900 Timothy Grove\n\nD202 E01234 49500 Rich Holcomb\nD202 E39876 27800 Claire Buckman\nD202 E27002 19250 David Motsinger\n```"
}
]
|
[
{
"role": "user",
"content": "Several programming languages offer syntax shortcuts to deal with the notion of \"current\" or \"topic\" variable.\n\nA topic variable is a special variable with a very short name which can also often be omitted.\n\nDemonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.\n\nFor instance you can (but you don't have to) show how the topic variable can be used by assigning the number \n\n3\n{\\displaystyle {\\displaystyle 3}}\n to it and then computing its square and square root."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nAs in Perl, in Raku the topic variable is $\\_. In addition to a direct assigment, it can be set with the 'given' or 'with' keywords, or by some iteration operator ('for', 'map' etc). A method can be called from it with an implicit call:\n\n```\n$_ = 'Outside';\nfor <3 5 7 10> {\n print $_;\n .ยณ.map: { say join \"\\t\", '', $_, .ยฒ, .sqrt, .log(2), OUTER::<$_>, UNIT::<$_> }\n}\n\n```\n\nOutput:\n\n```\n3\t27\t729\t5.196152422706632\t4.754887502163469\t3\tOutside\n5\t125\t15625\t11.180339887498949\t6.965784284662088\t5\tOutside\n7\t343\t117649\t18.520259177452136\t8.422064766172811\t7\tOutside\n10\t1000\t1000000\t31.622776601683793\t9.965784284662087\t10\tOutside\n```\n\nNote: that the $\\_ inside the 'map' block is different than the $\\_ set in the 'for' block. The scope of the $\\_ variable is always lexical in Raku, though a function can access topics in other scopes by specifying the scope: `CALLER::<$_>` from within a subroutine, `OUTER::<$_>` for the next enclosing block, `UNIT::<$_>` for the outermost block in a compilation unit, etc. The scope modifiers may be stacked: `CALLER::OUTER::<$_>` would be the topic variable of the next outer block of the current subroutines caller block.\n\nThe scope modifiers can only flow outward. There is no way to access the topic of a block enclosed within the current scope or in a separate scope 'branch'.\n\nAlso note: **Any** variable in other scopes can be accessed this way. This is just pointing out that the default (topic) variable also has this property."
}
]
|
[
{
"role": "user",
"content": "Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.\n\nThe compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.\n\nA tool exists that extracts library dependencies.\n\nTask\n\nWrite a function that will return a valid compile order of VHDL libraries from their dependencies.\n\n* Assume library names are single words.\n* Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.\n* Any self dependencies should be ignored.\n* Any un-orderable dependencies should be flagged.\n\nUse the following data as an example:\n\n```\nLIBRARY LIBRARY DEPENDENCIES\n======= ====================\ndes_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\ndw01 ieee dw01 dware gtech\ndw02 ieee dw02 dware\ndw03 std synopsys dware dw03 dw02 dw01 ieee gtech\ndw04 dw04 ieee dw01 dware gtech\ndw05 dw05 ieee dware\ndw06 dw06 ieee dware\ndw07 ieee dware\ndware ieee dware\ngtech ieee gtech\nramlib std ieee\nstd_cell_lib ieee std_cell_lib\nsynopsys\n\n```\n\nNote: the above data would be un-orderable if, for example, `dw04` is added to the list of dependencies of `dw01`.\n\nC.f.\n: * Topological sort/Extracted top item.\n\nThere are two popular algorithms for topological sorting:\n\n: * Kahn's 1962 topological sort [1]\n * depth-first search [2] [3]"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: rakudo version 2016.01\n\n```\nsub print_topo_sort ( %deps ) {\n my %ba;\n for %deps.kv -> $before, @afters {\n for @afters -> $after {\n %ba{$before}{$after} = 1 if $before ne $after;\n %ba{$after} //= {};\n }\n }\n\n while %ba.grep( not *.value )ยป.key -> @afters {\n say [email protected];\n %ba{@afters}:delete;\n for %ba.values { .{@afters}:delete }\n }\n\n say %baย ?? \"Cycle found! {%ba.keys.sort}\"ย !! '---';\n}\n\nmy %deps =\n des_system_lib => < std synopsys std_cell_lib des_system_lib dw02\n dw01 ramlib ieee >,\n dw01 => < ieee dw01 dware gtech >,\n dw02 => < ieee dw02 dware >,\n dw03 => < std synopsys dware dw03 dw02 dw01 ieee gtech >,\n dw04 => < dw04 ieee dw01 dware gtech >,\n dw05 => < dw05 ieee dware >,\n dw06 => < dw06 ieee dware >,\n dw07 => < ieee dware >,\n dware => < ieee dware >,\n gtech => < ieee gtech >,\n ramlib => < std ieee >,\n std_cell_lib => < ieee std_cell_lib >,\n synopsys => < >;\n\nprint_topo_sort(%deps);\n%deps<dw01> = <ieee dw01 dware gtech dw04>; # Add unresolvable dependency\nprint_topo_sort(%deps);\n\n```\n\nOutput:\n\n```\nieee std synopsys\ndware gtech ramlib std_cell_lib\ndw01 dw02 dw05 dw06 dw07\ndes_system_lib dw03 dw04\n---\nieee std synopsys\ndware gtech ramlib std_cell_lib\ndw02 dw05 dw06 dw07\nCycle found! des_system_lib dw01 dw03 dw04\n```\n\nSome differences from the Perl 5 version include use of\nformal parameters; use of ยป as a \"hyper\" operator, that is, a parallelizable implicit loop; and use of normal lambda-like notation to bind loop parameters, so we can have multiple loop parameters bound on each iteration. Also,\nsince => is now a real pair composer rather than a synonym for comma, the data can be represented with real pair notation that points to quoted word lists delimited by angle brackets rather than [qw(...)]."
}
]
|
[
{
"role": "user",
"content": "Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.\n\nThe compiling of a design in the VHDL language has the constraint that a file must be compiled after any file containing definitions it depends on. A tool exists that extracts file dependencies.\n\n* Assume the file names are single words, given without their file extensions.\n* Files mentioned as only dependants, have no dependants of their own, but their order of compiling must be given.\n* Any self dependencies should be ignored.\n\nA top level file is defined as a file that:\n\n1. Has dependents.\n2. Is not itself the dependent of another file\n\n**Task Description**\n\nGiven the following file dependencies as an example:\n\n```\nFILE FILE DEPENDENCIES\n==== =================\ntop1 des1 ip1 ip2\ntop2 des1 ip2 ip3\nip1 extra1 ip1a ipcommon\nip2 ip2a ip2b ip2c ipcommon\ndes1 des1a des1b des1c\ndes1a des1a1 des1a2\ndes1c des1c1 extra1\n```\n\nThe task is to create a program that given a graph of the dependency:\n\n1. Determines the top levels from the dependencies and show them.\n2. Extracts a compile order of files to compile any given (usually top level) file.\n3. Give a compile order for file top1.\n4. Give a compile order for file top2.\n\nYou may show how to compile multiple top levels as a stretch goal\n\nNote: this task differs from task Topological sort in that the order for compiling any file might not include all files; and that checks for dependency cycles are not mandated.\n\nRelated task\n\n* Topological sort"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub top_topos ( %deps, *@top ) {\n my %ba;\n for %deps.kv -> $after, @befores {\n for @befores -> $before {\n %ba{$after}{$before} = 0 if $before ne $after;\n %ba{$before} //= {};\n }\n }\n\n if @top {\n\tmy @want = @top;\n\tmy %care;\n\t%care{@want} = 1 xx *;\n\trepeat while @want {\n\t my @newwant;\n\t for @want -> $before {\n\t\tif %ba{$before} {\n\t\t for %ba{$before}.keys -> $after {\n\t\t\tif not %ba{$before}{$after} {\n\t\t\t %ba{$before}{$after}++;\n\t\t\t push @newwant, $after;\n\t\t\t}\n\t\t }\n\t\t}\n\t }\n\t @want = @newwant;\n\t %care{@want} = 1 xx *;\n\t}\n\n\tfor %ba.keys -> $before {\n\t %ba{$before}:delete unless %care{$before};\n\t}\n }\n \n my @levels;\n while %ba.grep( not *.value )ยป.key -> @befores {\n\tpush @levels, [email protected];\n %ba{@befores}:delete;\n for %ba.values { .{@befores}:delete }\n }\n if @top {\n\tsay \"For top-level-modules: \", @top;\n\tsay \" $_\" for @levels;\n }\n else {\n\tsay \"Top levels are: @levels[*-1]\";\n }\n \n say \"Cycle found! {%ba.keys.sort}\" if %ba;\n say ''; \n}\n\nmy %deps =\n top1 => <des1 ip1 ip2>,\n top2 => <des1 ip2 ip3>,\n ip1 => <extra1 ip1a ipcommon>,\n ip2 => <ip2a ip2b ip2c ipcommon>,\n des1 => <des1a des1b des1c>,\n des1a => <des1a1 des1a2>,\n des1c => <des1c1 extra1>;\n \ntop_topos(%deps);\ntop_topos(%deps, 'top1');\ntop_topos(%deps, 'top2');\ntop_topos(%deps, 'ip1');\ntop_topos(%deps, 'top1', 'top2');\n\n```\n\nOutput:\n\n```\nTop levels are: top1 top2\n\nFor top-level-modules: top1\n des1a1 des1a2 des1b des1c1 extra1 ip1a ip2a ip2b ip2c ipcommon\n des1a des1c ip1 ip2\n des1\n top1\n\nFor top-level-modules: top2\n des1a1 des1a2 des1b des1c1 extra1 ip2a ip2b ip2c ip3 ipcommon\n des1a des1c ip2\n des1\n top2\n\nFor top-level-modules: ip1\n extra1 ip1a ipcommon\n ip1\n\nFor top-level-modules: top1 top2\n des1a1 des1a2 des1b des1c1 extra1 ip1a ip2a ip2b ip2c ip3 ipcommon\n des1a des1c ip1 ip2\n des1\n top1 top2\n\n```"
}
]
|
[
{
"role": "user",
"content": "Topswops is a card game created by John Conway in the 1970's.\n\nAssume you have a particular permutation of a set of ย n ย cards numbered ย 1..n ย on both of their faces, for example the arrangement of four cards given by ย [2, 4, 1, 3] ย where the leftmost card is on top.\n\nA round is composed of reversing the first ย m ย cards where ย m ย is the value of the topmost card.\n\nRounds are repeated until the topmost card is the number ย 1 ย and the number of swaps is recorded.\n\nFor our example the swaps produce:\n\n```\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n```\n\nFor a total of four swaps from the initial ordering to produce the terminating case where ย 1 ย is on top.\n\nFor a particular number ย `n` ย of cards, ย `topswops(n)` ย is the maximum swaps needed for any starting permutation of the ย `n` ย cards.\n\nTask\n\nThe task is to generate and show here a table of ย `n` ย vs ย `topswops(n)` ย for ย `n` ย in the range ย 1..10 ย inclusive.\n\nNote\n\nTopswops ย is also known as ย Fannkuch ย from the German word ย *Pfannkuchen* ย meaning ย pancake.\n\nRelated tasks\n\n* Number reversal game\n* Sorting algorithms/Pancake sort"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub swops(@a is copy) {\n my int $count = 0;\n until @a[0] == 1 {\n @a[ ^@a[0] ] .= reverse;\n ++$count;\n }\n $count\n}\n\nsub topswops($n) { max (1..$n).permutations.race.map: &swops }\n\nsay \"$_ {topswops $_}\" for 1 .. 10;\n\n```\n\nOutput:\n\n```\n1 0\n2 1\n3 2\n4 4\n5 7\n6 10\n7 16\n8 22\n9 30\n10 38\n```\n\nAlternately, using string manipulation instead. Much faster, though honestly, still not very fast.\n\n```\nsub swops($a is copy) {\n my int $count = 0;\n while (my \\l = $a.ord) > 1 {\n $a = $a.substr(0, l).flip ~ $a.substr(l);\n ++$count;\n }\n $count\n}\n\nsub topswops($n) { max (1..$n).permutations.map: { .chrs.join.&swops } }\n\nsay \"$_ {topswops $_}\" for 1 .. 10;\n\n```\n\nSame output"
}
]
|
[
{
"role": "user",
"content": "Example circles\n\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once.\n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the **x** and **y** coordinates of the centers of the disks and their radii ย (11 disks are fully contained inside other disks):\n\n```\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n```\n\nThe result is ย 21.56503660... .\n\nRelated task\n\n* Circles of given radius through two points.\n\nSee also\n\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012\\_challenge\\_96\\_difficult\\_water\\_droplets/\n* http://stackoverflow.com/a/1667789/10562"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThis subdivides the outer rectangle repeatedly into subrectangles, and classifies them into wet, dry, or unknown. The knowns are summed to provide an inner bound and an outer bound, while the unknowns are further subdivided. The estimate is the average of the outer bound and the inner bound. Not the simplest algorithm, but converges fairly rapidly because it can treat large areas sparsely, saving the fine subdivisions for the circle boundaries. The number of unknown rectangles roughly doubles each pass, but the area of those unknowns is about half.\n\n```\nclass Point {\n has Real $.x;\n has Real $.y;\n has Int $!cbits;\t# bitmap of circle membership\n\n method cbits { $!cbits //= set_cbits(self) }\n method gist { $!x ~ \"\\t\" ~ $!y }\n}\n\nmulti infix:<to>(Point $p1, Point $p2) {\n sqrt ($p1.x - $p2.x) ** 2 + ($p1.y - $p2.y) ** 2;\n}\n\nmulti infix:<mid>(Point $p1, Point $p2) {\n Point.new(x => ($p1.x + $p2.x) / 2, y => ($p1.y + $p2.y) / 2);\n}\n\nclass Circle {\n has Point $.center;\n has Real $.radius;\n\n has Point $.north = Point.new(x => $!center.x, y => $!center.y + $!radius);\n has Point $.west = Point.new(x => $!center.x - $!radius, y => $!center.y);\n has Point $.south = Point.new(x => $!center.x, y => $!center.y - $!radius);\n has Point $.east = Point.new(x => $!center.x + $!radius, y => $!center.y);\n\n multi method contains(Circle $c) { $!center to $c.center <= $!radius - $c.radius }\n multi method contains(Point $p) { $!center to $p <= $!radius }\n method gist { $!center.gist ~ \"\\t\" ~ $.radius }\n}\n\nclass Rect {\n has Point $.nw;\n has Point $.ne;\n has Point $.sw;\n has Point $.se;\n\n method diag { $!ne to $!se }\n method area { ($!ne.x - $!nw.x) * ($!nw.y - $!sw.y) }\n method contains(Point $p) {\n\t$!nw.x < $p.x < $!ne.x and\n\t$!sw.y < $p.y < $!nw.y;\n }\n}\n\nmy @rawcircles = sort -*.radius,\n map -> $x, $y, $radius { Circle.new(:center(Point.new(:$x,ย :$y)),ย :$radius) },\n <\n\t 1.6417233788 1.6121789534 0.0848270516\n\t-1.4944608174 1.2077959613 1.1039549836\n\t 0.6110294452 -0.6907087527 0.9089162485\n\t 0.3844862411 0.2923344616 0.2375743054\n\t-0.2495892950 -0.3832854473 1.0845181219\n\t 1.7813504266 1.6178237031 0.8162655711\n\t-0.1985249206 -0.8343333301 0.0538864941\n\t-1.7011985145 -0.1263820964 0.4776976918\n\t-0.4319462812 1.4104420482 0.7886291537\n\t 0.2178372997 -0.9499557344 0.0357871187\n\t-0.6294854565 -1.3078893852 0.7653357688\n\t 1.7952608455 0.6281269104 0.2727652452\n\t 1.4168575317 1.0683357171 1.1016025378\n\t 1.4637371396 0.9463877418 1.1846214562\n\t-0.5263668798 1.7315156631 1.4428514068\n\t-1.2197352481 0.9144146579 1.0727263474\n\t-0.1389358881 0.1092805780 0.7350208828\n\t 1.5293954595 0.0030278255 1.2472867347\n\t-0.5258728625 1.3782633069 1.3495508831\n\t-0.1403562064 0.2437382535 1.3804956588\n\t 0.8055826339 -0.0482092025 0.3327165165\n\t-0.6311979224 0.7184578971 0.2491045282\n\t 1.4685857879 -0.8347049536 1.3670667538\n\t-0.6855727502 1.6465021616 1.0593087096\n\t 0.0152957411 0.0638919221 0.9771215985\n >ยป.Num;\n\n# remove redundant circles\nmy @circles;\nwhile @rawcircles {\n my $c = @rawcircles.shift;\n next if @circles.any.contains($c);\n push @circles, $c;\n}\n\nsub set_cbits(Point $p) {\n my $cbits = 0;\n for @circles Z (1,2,4...*) -> ($c, $b) {\n\t$cbits += $b if $c.contains($p);\n }\n $cbits;\n}\n\nmy $xmin = min @circles.map: { .center.x - .radius }\nmy $xmax = max @circles.map: { .center.x + .radius }\nmy $ymin = min @circles.map: { .center.y - .radius }\nmy $ymax = max @circles.map: { .center.y + .radius }\n\nmy $min-radius = @circles[*-1].radius;\n\nmy $outer-rect = Rect.new:\n nw => Point.new(x => $xmin, y => $ymax),\n ne => Point.new(x => $xmax, y => $ymax),\n sw => Point.new(x => $xmin, y => $ymin),\n se => Point.new(x => $xmax, y => $ymin);\n\nmy $outer-area = $outer-rect.area;\n\nmy @unknowns = $outer-rect;\nmy $known-dry = 0e0;\nmy $known-wet = 0e0;\nmy $div = 1;\n\n# divide current rects each into four rects, analyze each\nsub divide(@old) {\n\n $div *= 2;\n\n # rects too small to hold circle?\n my $smallish = @old[0].diag < $min-radius;\n\n my @unk;\n for @old {\n\tmy $center = .nw mid .se;\n\tmy $north = .nw mid .ne;\n\tmy $south = .sw mid .se;\n\tmy $west = .nw mid .sw;\n\tmy $east = .ne mid .se;\n\n\tfor Rect.new(nw => .nw, ne => $north, sw => $west, se => $center),\n\t Rect.new(nw => $north, ne => .ne, sw => $center, se => $east),\n\t Rect.new(nw => $west, ne => $center, sw => .sw, se => $south),\n\t Rect.new(nw => $center, ne => $east, sw => $south, se => .se)\n\t{\n\t my @bits = .nw.cbits, .ne.cbits, .sw.cbits, .se.cbits;\n\n\t # if all 4 points wet by same circle, guaranteed wet\n\t if [+&] @bits {\n\t\t$known-wet += .area;\n\t\tnext;\n\t }\n\n\t # if all 4 corners are dry, must check further\n\t if not [+|] @bits and $smallish {\n\n\t\t# check that no circle bulges into this rect\n\t\tmy $ok = True;\n\t\tfor @circles -> $c {\n\t\t if .contains($c.east) or .contains($c.west) or\n\t\t\t.contains($c.north) or .contains($c.south)\n\t\t {\n\t\t\t$ok = False;\n\t\t\tlast;\n\t\t }\n\t\t}\n\t\tif $ok {\n\t\t $known-dry += .area;\n\t\t next;\n\t\t}\n\t }\n\t push @unk, $_;\t# dunno yet\n\t}\n }\n @unk;\n}\n\nmy $delta = 0.001;\nrepeat until my $diff < $delta {\n @unknowns = divide(@unknowns);\n\n $diff = $outer-area - $known-dry - $known-wet;\n say 'div: ', $div.fmt('%-5d'),\n\t' unk: ', (+@unknowns).fmt('%-6d'),\n\t' est: ', ($known-wet + $diff/2).fmt('%9.6f'),\n\t' wet: ', $known-wet.fmt('%9.6f'),\n\t' dry: ', ($outer-area - $known-dry).fmt('%9.6f'),\n\t' diff: ', $diff.fmt('%9.6f'),\n\t' error: ', ($diff - @unknowns * @unknowns[0].area).fmt('%e');\n}\n\n```\n\nOutput:\n\n```\ndiv: 2 unk: 4 est: 14.607153 wet: 0.000000 dry: 29.214306 diff: 29.214306 error: 0.000000e+000\ndiv: 4 unk: 15 est: 15.520100 wet: 1.825894 dry: 29.214306 diff: 27.388411 error: 0.000000e+000\ndiv: 8 unk: 39 est: 20.313072 wet: 11.411838 dry: 29.214306 diff: 17.802467 error: 7.105427e-015\ndiv: 16 unk: 107 est: 23.108972 wet: 17.003639 dry: 29.214306 diff: 12.210667 error: -1.065814e-014\ndiv: 32 unk: 142 est: 21.368667 wet: 19.343066 dry: 23.394268 diff: 4.051203 error: 8.881784e-014\ndiv: 64 unk: 290 est: 21.504182 wet: 20.469985 dry: 22.538380 diff: 2.068396 error: 1.771916e-013\ndiv: 128 unk: 582 est: 21.534495 wet: 21.015613 dry: 22.053377 diff: 1.037764 error: -3.175238e-013\ndiv: 256 unk: 1169 est: 21.557898 wet: 21.297343 dry: 21.818454 diff: 0.521111 error: -2.501332e-013\ndiv: 512 unk: 2347 est: 21.563415 wet: 21.432636 dry: 21.694194 diff: 0.261558 error: -1.046996e-012\ndiv: 1024 unk: 4700 est: 21.564111 wet: 21.498638 dry: 21.629584 diff: 0.130946 error: 1.481315e-013\ndiv: 2048 unk: 9407 est: 21.564804 wet: 21.532043 dry: 21.597565 diff: 0.065522 error: 1.781700e-012\ndiv: 4096 unk: 18818 est: 21.564876 wet: 21.548492 dry: 21.581260 diff: 0.032768 error: 1.098372e-011\ndiv: 8192 unk: 37648 est: 21.564992 wet: 21.556797 dry: 21.573187 diff: 0.016389 error: -1.413968e-011\ndiv: 16384 unk: 75301 est: 21.565017 wet: 21.560920 dry: 21.569115 diff: 0.008195 error: -7.683898e-011\ndiv: 32768 unk: 150599 est: 21.565031 wet: 21.562982 dry: 21.567080 diff: 0.004097 error: -1.247991e-010\ndiv: 65536 unk: 301203 est: 21.565035 wet: 21.564010 dry: 21.566059 diff: 0.002049 error: -2.830591e-010\ndiv: 131072 unk: 602411 est: 21.565036 wet: 21.564524 dry: 21.565548 diff: 0.001024 error: -1.607121e-010\n```\n\nHere the \"diff\" is calculated by subtracting the known wet and dry areas from the total area, and the \"error\" is the difference between that and the sum of the areas of the unknown blocks, to give a rough idea of how much floating point roundoff error we've accumulated."
}
]
|
[
{
"role": "user",
"content": "The ย **totient** ย function is also known as:\n\n: : * Euler's totient function\n * Euler's phi totient function\n * phi totient function\n * ฮฆ ย function ย (uppercase Greek phi)\n * ฯย ย function ย (lowercase Greek phi)\n\nDefinitions ย (as per number theory)\n\nThe totient function:\n\n: : * counts the integers up to a given positive integer ย **n** ย that are relatively prime to ย **n**\n * counts the integers ย **k** ย in the range ย **1 โค k โค n** ย for which the greatest common divisor ย **gcd(n,k)** ย is equal to ย **1**\n * counts numbers ย **โค n** ย and ย prime to ย **n**\n\nIf the totient number ย (for **N**) ย is one less than ย **N**, ย then ย **N** ย is prime.\n\nTask\n\nCreate a ย **totient** ย function and:\n\n: : * Find and display ย (1 per line) ย for the 1st ย **25** ย integers:\n\n : : * the integer ย (the index)\n * the totient number for that integer\n * indicate if that integer is prime\n\n * Find and display the ย *count* ย of the primes up to ย ย ย ย ย 100\n * Find and display the ย *count* ย of the primes up to ย ย ย 1,000\n * Find and display the ย *count* ย of the primes up to ย ย 10,000\n * Find and display the ย *count* ย of the primes up to ย 100,000 ย ย (optional)\n\nShow all output here.\n\nRelated task\n: : * Perfect totient numbers\n\nAlso see\n: : * Wikipedia: Euler's totient function.\n * MathWorld: totient function.\n * OEIS: Euler totient function phi(n)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\nThis is an *incredibly* inefficient way of finding prime numbers.\n\n```\nuse Prime::Factor;\n\nmy \\๐ = 0, |(1..*).hyper.map: -> \\t { t * [*] t.&prime-factors.squish.map: { 1 - 1/$_ } }\n\nprintf \"๐(%2d) = %3d %s\\n\", $_, ๐[$_], $_ - ๐[$_] - 1ย ?? ''ย !! 'Prime' for 1 .. 25;\n\n(1e2, 1e3, 1e4, 1e5).map: -> $limit {\n say \"\\nCount of primes <= $limit: \" ~ +(^$limit).grep: {$_ == ๐[$_] + 1}\n}\n\n```\n\nOutput:\n\n```\n๐( 1) = 1\n๐( 2) = 1 Prime\n๐( 3) = 2 Prime\n๐( 4) = 2\n๐( 5) = 4 Prime\n๐( 6) = 2\n๐( 7) = 6 Prime\n๐( 8) = 4\n๐( 9) = 6\n๐(10) = 4\n๐(11) = 10 Prime\n๐(12) = 4\n๐(13) = 12 Prime\n๐(14) = 6\n๐(15) = 8\n๐(16) = 8\n๐(17) = 16 Prime\n๐(18) = 6\n๐(19) = 18 Prime\n๐(20) = 8\n๐(21) = 12\n๐(22) = 10\n๐(23) = 22 Prime\n๐(24) = 8\n๐(25) = 20\n\nCount of primes <= 100: 25\n\nCount of primes <= 1000: 168\n\nCount of primes <= 10000: 1229\n\nCount of primes <= 100000: 9592\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSolve the ย Towers of Hanoi ย problem with recursion."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsubset Peg of Int where 1|2|3;\n\nmulti hanoi (0, Peg $a, Peg $b, Peg $c) { }\nmulti hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) {\n hanoi $n - 1, $a, $c, $b;\n say \"Move $a to $b.\";\n hanoi $n - 1, $c, $b, $a;\n}\n```"
}
]
|
[
{
"role": "user",
"content": "The TPK algorithm is an early example of a programming chrestomathy.\nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.\nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n```\nask for 11 numbers to be read into a sequence S\nreverse sequence S\nfor each item in sequence S\n result := call a function to do an operation\n if result overflows\n alert user\n else\n print result\n\n```\n\nThe task is to implement the algorithm:\n\n1. Use the function: ย ย \n\n f\n (\n x\n )\n =\n\n |\n x\n\n\n |\n\n 0.5\n +\n 5\n\n x\n\n 3\n {\\displaystyle {\\displaystyle f(x)=|x|^{0.5}+5x^{3}}}\n2. The overflow condition is an answer of greater than 400.\n3. The 'user alert' should not stop processing of other items of the sequence.\n4. Print a prompt before accepting **eleven**, textual, numeric inputs.\n5. You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n6. The sequence ย ***S*** ย may be 'implied' and so not shown explicitly.\n7. *Print and show the program in action from a typical run here*. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy @nums = prompt(\"Please type 11 space-separated numbers: \").words\n until @nums == 11;\nfor @nums.reverse -> $n {\n my $r = $n.abs.sqrt + 5 * $n ** 3;\n say \"$n\\t{ $r > 400ย ?? 'Urk!'ย !! $r }\";\n}\n\n```\n\nOutput:\n\n```\nPlease type 11 space-separated numbers: 10 -1 1 2 3 4 4.3 4.305 4.303 4.302 4.301\n4.301\t399.88629974772681\n4.302\tUrk!\n4.303\tUrk!\n4.305\tUrk!\n4.3\t399.60864413533278\n4\t322\n3\t136.73205080756887\n2\t41.414213562373092\n1\t6\n-1\t-4\n10\tUrk!\n```"
}
]
|
[
{
"role": "user",
"content": "Rules\n\nA rather silly little task intended as a bit of fun as well as a simple exercise in text substitution. So, if you're a Greek speaker or an expert in ancient Greek, please don't take it too seriously!\n\nAs there isn't a one-to-one correspondence between the English and Greek alphabets, we need some rules:\n\n| Greek letter | Corresponding English letter(s) |\n| --- | --- |\n| alpha | a |\n| beta | b or v |\n| gamma | g |\n| delta | d |\n| epsilon | e (but not ee) |\n| zeta | z |\n| eta | h or ee (but not ch, kh, ph, rh or th) |\n| theta | th |\n| iota | i or j |\n| kappa | c, k, q or ck (but not ch and kh) |\n| lambda | l |\n| mu | m |\n| nu | n |\n| xi | x |\n| omicron | o (but not oo) |\n| pi | p (but not ph or ps) |\n| rho | r or rh |\n| sigma | s (but not ps) |\n| tau | t (but not th) |\n| upsilon | u or y |\n| phi | f or ph |\n| chi | ch or kh |\n| psi | ps |\n| omega | w or oo |\n\nIn the case of lower-case sigma, use **ฯ** when **s** is the final letter of an English word or **ฯ** otherwise.\n\nIgnore Greek diacritics (accents and breathings) but use the same capitalization, spacing and punctuation as in the English text.\n\nExample\n\nEnglish: The quick brown fox jumped over the lazy dog.\n\nGreek: ฮฮต ฮบฯ
ฮนฮบ ฮฒฯฮฟฯฮฝ ฯฮฟฮพ ฮนฯ
ฮผฯฮตฮด ฮฟฮฒฮตฯ ฮธฮต ฮปฮฑฮถฯ
ฮดฮฟฮณ.\n\nTask\n\nTransliterate the following English text into Greek using the above rules:\n\n```\nI was looking at some rhododendrons in my back garden,\ndressed in my khaki shorts, when the telephone rang.\n\nAs I answered it, I cheerfully glimpsed that the July sun\ncaused a fragment of black pine wax to ooze on the velvet quilt\nlaying in my patio.\n\n```\n\nIf your language does not support the printing of non-ascii characters, then you can instead transliterate the following lower-case pangram:\n\n```\nsphinx of black quartz, judge my vow.\n\n```\n\nJust represent the Greek letters by their names in angle brackets. For example:\n\n```\nthe dog => <theta><epsilon> <delta><omicron><gamma>\n```\n\nReference\n\n* Wikipedia: Greek alphabet\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": "```\nsub to-Greek (Str $string is copy) {\n my %pre = ย :Ph<F>, :ck<k>,ย :ee<h>, :J<I>,ย :rh<r>,:oo<w>,ย :ph<f>, :ch<ฯ>,\n ย :th<ฮธ>, :ps<ฯ>,ย :Ch<ฮง>, :Th<ฮ>,ย :Ps<ฮจ>, :kh<ฯ>, 's ' => 'ฯ ';\n my %post =ย :a<ฮฑ>, :b<ฮฒ>,ย :d<ฮด>, :e<ฮต>,ย :f<ฯ>, :g<ฮณ>,ย :h<ฮท>, :i<ฮน>,ย :j<ฮน>,\n :k<ฮบ>,ย :l<ฮป>, :m<ฮผ>,ย :n<ฮฝ>, :o<ฮฟ>,ย :p<ฯ>, :q<ฮบ>,ย :r<ฯ>, :s<ฯ>,\n ย :t<ฯ>, :u<ฯ
>,ย :v<ฮฒ>, :w<ฯ>,ย :x<ฮพ>, :y<ฯ
>,ย :z<ฮถ>, :A<ฮ>,ย :B<ฮ>,\n :D<ฮ>,ย :E<ฮ>, :F<ฮฆ>,ย :G<ฮ>, :H<ฮ>,ย :I<ฮ>, :L<ฮ>,ย :M<ฮ>, :N<ฮ>,\n ย :O<ฮ>, :P<ฮ >,ย :Q<ฮ>,ย :R<ฮก>, :S<ฮฃ>,ย :T<ฮค>, :U<ฮฅ>,ย :W<ฮฉ>, :X<ฮ>,\n ย :Z<ฮ>;\n\n $string.=subst(:g, .key, .value ) for flat %pre, %post;\n $string\n}\n\nmy $text = chomp q:to/ENGLISH/;\n The quick brown fox jumped over the lazy dog.\n\n I was looking at some rhododendrons in my back garden,\n dressed in my khaki shorts, when the telephone rang.\n\n As I answered it, I cheerfully glimpsed that the July sun\n caused a fragment of black pine wax to ooze on the velvet quilt\n laying in my patio.\n\n sphinx of black quartz, judge my vow.\n ENGLISH\n\nsay \"English:\\n\\n\" ~ $text ~ \"\\n\" ~ '=' x 80;\n\nsay \"\\\"Greek\\\":\\n\\n\" ~ $text.&to-Greek ~ \"\\n\" ~ '=' x 80;\n\nsay \"Or, to named characters:\\n\\n$_\\n\" ~\n .&to-Greek.comb.map({ .match(/\\W/)ย ?? $_ย !!\n '<' ~ .uniname.subst( /.+<?after LETTER\\s>/).lc ~ '>'\n }).join\n given 'sphinx of black quartz, judge my vow.';\n\n```\n\nOutput:\n\n```\nEnglish:\n\nThe quick brown fox jumped over the lazy dog.\n\nI was looking at some rhododendrons in my back garden,\ndressed in my khaki shorts, when the telephone rang.\n\nAs I answered it, I cheerfully glimpsed that the July sun\ncaused a fragment of black pine wax to ooze on the velvet quilt\nlaying in my patio.\n\nsphinx of black quartz, judge my vow.\n================================================================================\n\"Greek\":\n\nฮฮต ฮบฯ
ฮนฮบ ฮฒฯฮฟฯฮฝ ฯฮฟฮพ ฮนฯ
ฮผฯฮตฮด ฮฟฮฒฮตฯ ฮธฮต ฮปฮฑฮถฯ
ฮดฮฟฮณ.\n\nฮ ฯฮฑฯ ฮปฯฮบฮนฮฝฮณ ฮฑฯ ฯฮฟฮผฮต ฯฮฟฮดฮฟฮดฮตฮฝฮดฯฮฟฮฝฯ ฮนฮฝ ฮผฯ
ฮฒฮฑฮบ ฮณฮฑฯฮดฮตฮฝ,\nฮดฯฮตฯฯฮตฮด ฮนฮฝ ฮผฯ
ฯฮฑฮบฮน ฯฮทฮฟฯฯฯ, ฯฮทฮตฮฝ ฮธฮต ฯฮตฮปฮตฯฮฟฮฝฮต ฯฮฑฮฝฮณ.\n\nฮฯ ฮ ฮฑฮฝฯฯฮตฯฮตฮด ฮนฯ, ฮ ฯฮทฯฯฯ
ฮปฮปฯ
ฮณฮปฮนฮผฯฮตฮด ฮธฮฑฯ ฮธฮต ฮฯ
ฮปฯ
ฯฯ
ฮฝ\ncฮฑฯ
ฯฮตฮด ฮฑ ฯฯฮฑฮณฮผฮตฮฝฯ ฮฟฯ ฮฒฮปฮฑฮบ ฯฮนฮฝฮต ฯฮฑฮพ ฯฮฟ ฯฮถฮต ฮฟฮฝ ฮธฮต ฮฒฮตฮปฮฒฮตฯ ฮบฯ
ฮนฮปฯ\nฮปฮฑฯ
ฮนฮฝฮณ ฮนฮฝ ฮผฯ
ฯฮฑฯฮนฮฟ.\n\nฯฯฮนฮฝฮพ ฮฟฯ ฮฒฮปฮฑฮบ ฮบฯ
ฮฑฯฯฮถ, ฮนฯ
ฮดฮณฮต ฮผฯ
ฮฒฮฟฯ.\n================================================================================\nOr, to named characters:\n\nsphinx of black quartz, judge my vow.\n<sigma><phi><iota><nu><xi> <omicron><phi> <beta><lamda><alpha><kappa> <kappa><upsilon><alpha><rho><tau><zeta>, <iota><upsilon><delta><gamma><epsilon> <mu><upsilon> <beta><omicron><omega>.\n```"
}
]
|
[
{
"role": "user",
"content": "The **transportation problem** in linear programming is to find the optimal transportation plan for certain volumes of resources from suppliers to consumers, taking into account the cost of transportation. The plan is a table (matrix), whose rows and columns correspond to the suppliers and consumers, the cells are placed in cargo volume.\n\nExample of the transportation problem:\n\n: : : : : : | | *Consumer 1*, need 20 kg | *Consumer 2*, need 30 kg | *Consumer 3*, need 10 kg |\n | --- | --- | --- | --- |\n | *Supplier 1*, supply 25 kg | $3 per kg | $5 per kg | $7 per kg |\n | *Supplier 2*, supply 35 kg | $3 per kg | $2 per kg | $5 per kg |\n\nThe object is to solve the classical transport problem using the method of potentials (with redistributive cycle) with the preparation of the initial transportation plan by the north-west corner of the features to be implemented in this task. The input is the number of suppliers and customers, inventory levels, needs and cost matrix transport cargo. The output of the program is the optimal plan. If necessary, enter a fictitious vendor or customer.\n\nThe solution for the above example would be the plan:\n\n: : : : : : | | *Consumer 1* | *Consumer 2* | *Consumer 3* |\n | --- | --- | --- | --- |\n | *Supplier 1* | 20 kg | - | 5 kg |\n | *Supplier 2* | - | 30 kg | 5 kg |\n\nSee also\n\n* The Transportation Problem\n* Transportation model - Concepts (youtube)\n\nRelated tasks\n\n* Vogel's approximation method"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03.1\n\nUsing Vogel's approximation method:\n\n```\nmy %costs =ย :S1{:3C1,ย :5C2,ย :7C3},ย :S2{:3C1,ย :2C2,ย :5C3};\nmy %demand =ย :20C1,ย :30C2,ย :10C3;\nmy %supply =ย :25S1,ย :35S2;\n\nmy @cols = %demand.keys.sort;\n\nmy %res;\nmy %g = (|%supply.keys.map: -> $x { $x => [%costs{$x}.sort(*.value)ยป.key]}),\n (|%demand.keys.map: -> $x { $x => [%costs.keys.sort({%costs{$_}{$x}})]});\n\nwhile (+%g) {\n my @d = %demand.keys.map: -> $x\n {[$x, my $z = %costs{%g{$x}[0]}{$x},%g{$x}[1]ย ?? %costs{%g{$x}[1]}{$x} - $zย !! $z]}\n\n my @s = %supply.keys.map: -> $x\n {[$x, my $z = %costs{$x}{%g{$x}[0]},%g{$x}[1]ย ?? %costs{$x}{%g{$x}[1]} - $zย !! $z]}\n\n @d = |@d.grep({ (.[2] == max @dยป.[2]) }).&min:ย :by(*.[1]);\n @s = |@s.grep({ (.[2] == max @sยป.[2]) }).&min:ย :by(*.[1]);\n\n my ($t, $f) = @d[2] == @s[2]ย ?? (@s[1],@d[1])ย !! (@d[2],@s[2]);\n my ($d, $s) = $t > $fย ?? (@d[0],%g{@d[0]}[0])ย !! (%g{@s[0]}[0], @s[0]);\n\n my $v = %supply{$s} min %demand{$d};\n\n %res{$s}{$d} += $v;\n %demand{$d} -= $v;\n\n if (%demand{$d} == 0) {\n %supply.grep( *.valueย != 0 )ยป.key.map: -> $v\n { %g{$v}.splice((%g{$v}.first: * eq $d,ย :k),1) };\n %g{$d}:delete;\n %demand{$d}:delete;\n }\n\n %supply{$s} -= $v;\n\n if (%supply{$s} == 0) {\n %demand.grep( *.valueย != 0 )ยป.key.map: -> $v\n { %g{$v}.splice((%g{$v}.first: * eq $s,ย :k),1) };\n %g{$s}:delete;\n %supply{$s}:delete;\n }\n}\n\nsay join \"\\t\", flat '', @cols;\nmy $total;\nfor %costs.keys.sort -> $g {\n print \"$g\\t\";\n for @cols -> $col {\n print %res{$g}{$col} // '-', \"\\t\";\n $total += (%res{$g}{$col} // 0) * %costs{$g}{$col};\n }\n print \"\\n\";\n}\nsay \"\\nTotal cost: $total\";\n\n```\n\nOutput:\n\n```\n\tC1\tC2\tC3\nS1\t20\t-\t5\t\nS2\t-\t30\t5\t\n```"
}
]
|
[
{
"role": "user",
"content": "The following shows a tree of data with nesting denoted by visual levels of indentation:\n\n```\nRosettaCode\n rocks\n code\n comparison\n wiki\n mocks\n trolling\n```\n\nA common datastructure for trees is to define node structures having a name and a, (possibly empty), list of child nodes. The nesting of nodes captures the indentation of the tree. Lets call this **the nest form**.\n\n```\n# E.g. if child nodes are surrounded by brackets\n# and separated by commas then:\nRosettaCode(rocks(code, ...), ...)\n# But only an _example_\n```\n\nAnother datastructure for trees is to construct from the root an ordered list of the nodes level of indentation and the name of that node. The indentation for the root node is zero; node 'rocks is indented by one level from the left, and so on. Lets call this **the indent form**.\n\n```\n0 RosettaCode\n1 rocks\n2 code\n...\n```\n\nTask\n\n1. Create/use a nest datastructure format and textual representation for arbitrary trees.\n2. Create/use an indent datastructure format and textual representation for arbitrary trees.\n3. Create methods/classes/proceedures/routines etc to:\n 1. Change from a nest tree datastructure to an indent one.\n 2. Change from an indent tree datastructure to a nest one\n4. Use the above to encode the example at the start into the nest format, and show it.\n5. transform the initial nest format to indent format and show it.\n6. transform the indent format to final nest format and show it.\n7. Compare initial and final nest formats which should be the same.\n\nNote\n\n* It's all about showing aspects of the contrasting datastructures as they hold the tree.\n* Comparing nested datastructures is secondary - saving formatted output as a string then a string compare would suffice for this task, if its easier.\n\nShow all output on this page."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nCode golf is a entertaining passtime, even if it isn't appropriate for this site. To a large extent, I agree with Hout, I am not really on board with mocking anybody, especially espousing it as an official RosettaCode position. So, feel free to mark this incorrect.\n\n```\n#`(\nSort of vague as to what we are trying to accomplish here. If we are just\ntrying to transform from one format to another, probably easiest to just\nperform string manipulations.\n)\n\nmy $level = ' ';\n\nmy $trees = q:to/END/;\n RosettaCode\n encourages\n code\n diversity\n comparison\n discourages\n golfing\n trolling\n emphasising execution speed\n code-golf.io\n encourages\n golfing\n discourages\n comparison\n END\n\nsub nested-to-indent { $^str.subst: / ^^ ($($level))* /, -> $/ { \"{+$0} \" },ย :g }\nsub indent-to-nested { $^str.subst: / ^^ (\\d+) \\s* /, -> $/ { \"{$level x +$0}\" },ย :g }\n\nsay $trees;\nsay my $indent = $trees.&nested-to-indent;\nsay my $nest = $indent.&indent-to-nested;\n\nuse Test;\nis($trees, $nest, 'Round-trip equals original');\n\n#`(\nIf, on the other hand, we want perform more complex transformations; better to\nload it into a native data structure which will then allow us to manipulate it\nhowever we like.\n)\n\n# Import outline paragraph into native data structure\nsub import (Str $trees, $level = ' ') {\n my $forest;\n my $last = -Inf;\n\n for $trees.lines -> $branch {\n $branch ~~ / ($($level))* /;\n my $this = +$0;\n $forest ~= do {\n given $this cmp $last {\n when More { \"\\['{esc $branch.trim}', \" }\n when Same { \"'{esc $branch.trim}', \" }\n when Less { \"{']' x $last - $this}, '{esc $branch.trim}', \" }\n }\n }\n $last = $this;\n }\n\n sub esc { $^s.subst( /(<['\\\\]>)/, -> $/ { \"\\\\$0\" },ย :g) }\n\n $forest ~= ']' x 1 + $last;\n $forest.EVAL;\n}\n\nmy $forest = import $trees;\n\nsay \"\\nNative data structure:\\n\", $forest.raku;\n\n{\n use JSON::Fast;\n say \"\\nJSON:\\n\", $forest.&to-json;\n}\n\n{\n use YAML;\n say \"\\nYAML:\\n\", $forest.&dump;\n}\n\n```\n\nOutput:\n\n```\nRosettaCode\n encourages\n code\n diversity\n comparison\n discourages\n golfing\n trolling\n emphasising execution speed\ncode-golf.io\n encourages\n golfing\n discourages\n comparison\n\n0 RosettaCode\n1 encourages\n2 code\n3 diversity\n3 comparison\n1 discourages\n2 golfing\n2 trolling\n2 emphasising execution speed\n0 code-golf.io\n1 encourages\n2 golfing\n1 discourages\n2 comparison\n\nRosettaCode\n encourages\n code\n diversity\n comparison\n discourages\n golfing\n trolling\n emphasising execution speed\ncode-golf.io\n encourages\n golfing\n discourages\n comparison\n\nok 1 - Round-trip equals original\n\nNative data structure:\n$[\"RosettaCode\", [\"encourages\", [\"code\", [\"diversity\", \"comparison\"]], \"discourages\", [\"golfing\", \"trolling\", \"emphasising execution speed\"]], \"code-golf.io\", [\"encourages\", [\"golfing\"], \"discourages\", [\"comparison\"]]]\n\nJSON:\n[\n \"RosettaCode\",\n [\n \"encourages\",\n [\n \"code\",\n [\n \"diversity\",\n \"comparison\"\n ]\n ],\n \"discourages\",\n [\n \"golfing\",\n \"trolling\",\n \"emphasising execution speed\"\n ]\n ],\n \"code-golf.io\",\n [\n \"encourages\",\n [\n \"golfing\"\n ],\n \"discourages\",\n [\n \"comparison\"\n ]\n ]\n]\n\nYAML:\n---\n- RosettaCode\n- - encourages\n - - code\n - - diversity\n - comparison\n - discourages\n - - golfing\n - trolling\n - emphasising execution speed\n- code-golf.io\n- - encourages\n - - golfing\n - discourages\n - - comparison\n...\n```"
}
]
|
[
{
"role": "user",
"content": "Given a flat list of integers greater than zero, representing object nesting\nlevels, e.g. `[1, 2, 4]`,\ngenerate a tree formed from nested lists of those nesting level integers where:\n\n* Every int appears, in order, at its depth of nesting.\n* If the next level int is greater than the previous then it appears in a sub-list of the list containing the previous item\n\nThe generated tree data structure should ideally be in a languages nested list format that can\nbe used for further calculations rather than something just calculated for printing.\n\nAn input of `[1, 2, 4]` should produce the equivalent of: `[1, [2, [[4]]]]`\nwhere 1 is at depth1, 2 is two deep and 4 is nested 4 deep.\n\n`[1, 2, 4, 2, 2, 1]` should produce `[1, [2, [[4]], 2, 2], 1]`. \nAll the nesting integers are in the same order but at the correct nesting\nlevels.\n\nSimilarly `[3, 1, 3, 1]` should generate `[[[3]], 1, [[3]], 1]`\n\nTask\n\nGenerate and show here the results for the following inputs:\n\n: * `[]`\n * `[1, 2, 4]`\n * `[3, 1, 3, 1]`\n * `[1, 2, 3, 1]`\n * `[3, 2, 1, 3]`\n * `[3, 3, 3, 1, 1, 3, 3, 3]`"
},
{
"role": "assistant",
"content": "### Iterative\n\n**Translation of**: Python\n\n```\nsub new_level ( @stack --> Nil ) {\n my $e = [];\n push @stack.tail, $e;\n push @stack, $e;\n}\nsub to_tree_iterative ( @xs --> List ) {\n my $nested = [];\n my @stack = $nested;\n\n for @xs -> Int $x {\n new_level(@stack) while $x > @stack;\n pop @stack while $x < @stack;\n push @stack.tail, $x;\n }\n\n return $nested;\n}\nmy @tests = (), (1, 2, 4), (3, 1, 3, 1), (1, 2, 3, 1), (3, 2, 1, 3), (3, 3, 3, 1, 1, 3, 3, 3);\nsay .Str.fmt( '%15s => ' ), .&to_tree_iterative for @tests;\n\n```\n\nOutput:\n\n```\n => []\n 1 2 4 => [1 [2 [[4]]]]\n 3 1 3 1 => [[[3]] 1 [[3]] 1]\n 1 2 3 1 => [1 [2 [3]] 1]\n 3 2 1 3 => [[[3] 2] 1 [[3]]]\n3 3 3 1 1 3 3 3 => [[[3 3 3]] 1 1 [[3 3 3]]]\n\n```\n\n### Recursive\n\n**Translation of**: Python\n\n```\nsub to_tree_recursive ( @list, $index is copy, $depth ) {\n my @so_far = gather while $index <= @list.end {\n my $t = @list[$index];\n\n given $t <=> $depth {\n when Order::Same {\n take $t;\n }\n when Order::More {\n ( $index, my $n1 ) = to_tree_recursive( @list, $index, $depth+1 );\n take $n1;\n }\n when Order::Less {\n $index--;\n last;\n }\n }\n $index++;\n }\n\n my $i = ($depth > 1)ย ?? $indexย !! -1;\n return $i, @so_far;\n}\nmy @tests = (), (1, 2, 4), (3, 1, 3, 1), (1, 2, 3, 1), (3, 2, 1, 3), (3, 3, 3, 1, 1, 3, 3, 3);\nsay .Str.fmt( '%15s => ' ), to_tree_recursive( $_, 0, 1 ).[1] for @tests;\n\n```\n\nOutput:\n\n```\n => []\n 1 2 4 => [1 [2 [[4]]]]\n 3 1 3 1 => [[[3]] 1 [[3]] 1]\n 1 2 3 1 => [1 [2 [3]] 1]\n 3 2 1 3 => [[[3] 2] 1 [[3]]]\n3 3 3 1 1 3 3 3 => [[[3 3 3]] 1 1 [[3 3 3]]]\n\n```\n\n### String Eval\n\n**Translation of**: Perl\n\n```\nuse MONKEY-SEE-NO-EVAL;\nsub to_tree_string_eval ( @xs --> Array ) {\n my @gap = [ |@xs, 0 ] Z- [ 0, |@xs ];\n\n my @open = @gap.map( '[' x * );\n my @close = @gap.map( ']' x -* );\n\n my @wrapped = [Z~] @open, @xs, @close.skip;\n\n return EVAL @wrapped.join(',').subst(:g, ']]', '],]') || '[]';\n}\nmy @tests = (), (1, 2, 4), (3, 1, 3, 1), (1, 2, 3, 1), (3, 2, 1, 3), (3, 3, 3, 1, 1, 3, 3, 3);\nsay .Str.fmt( '%15s => ' ), .&to_tree_string_eval for @tests;\n\n```\n\nOutput:\n\n```\n => []\n 1 2 4 => [1 [2 [[4]]]]\n 3 1 3 1 => [[[3]] 1 [[3]] 1]\n 1 2 3 1 => [1 [2 [3]] 1]\n 3 2 1 3 => [[[3] 2] 1 [[3]]]\n3 3 3 1 1 3 3 3 => [[[3 3 3]] 1 1 [[3 3 3]]]\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a binary tree where each node carries an integer, ย and implement:\n\n: : : * pre-order,\n * in-order,\n * post-order, ย ย and\n * level-order ย traversal.\n\nUse those traversals to output the following tree:\n\n```\n 1\n / \\\n / \\\n / \\\n 2 3\n / \\ /\n 4 5 6\n / / \\\n 7 8 9\n\n```\n\nThe correct output should look like this:\n\n```\npreorder: 1 2 4 7 5 3 6 8 9\ninorder: 7 4 2 5 1 8 6 9 3\npostorder: 7 4 5 2 8 9 6 3 1\nlevel-order: 1 2 3 4 5 6 7 8 9\n\n```\n\nSee also\n\n* Wikipedia article: ย Tree traversal."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nclass TreeNode {\n has TreeNode $.parent;\n has TreeNode $.left;\n has TreeNode $.right;\n has $.value;\n\n method pre-order {\n flat gather {\n take $.value;\n take $.left.pre-order if $.left;\n take $.right.pre-order if $.right\n }\n }\n\n method in-order {\n flat gather {\n take $.left.in-order if $.left;\n take $.value;\n take $.right.in-order if $.right;\n }\n }\n\n method post-order {\n flat gather {\n take $.left.post-order if $.left;\n take $.right.post-order if $.right;\n take $.value;\n }\n }\n\n method level-order {\n my TreeNode @queue = (self);\n flat gather while @queue.elems {\n my $n = @queue.shift;\n take $n.value;\n @queue.push($n.left) if $n.left;\n @queue.push($n.right) if $n.right;\n }\n }\n}\n\nmy TreeNode $root .= new( value => 1,\n left => TreeNode.new( value => 2,\n left => TreeNode.new( value => 4, left => TreeNode.new(value => 7)),\n right => TreeNode.new( value => 5)\n ),\n right => TreeNode.new( value => 3, \n left => TreeNode.new( value => 6, \n left => TreeNode.new(value => 8),\n right => TreeNode.new(value => 9)\n )\n )\n );\n\nsay \"preorder: \",$root.pre-order.join(\" \");\nsay \"inorder: \",$root.in-order.join(\" \");\nsay \"postorder: \",$root.post-order.join(\" \");\nsay \"levelorder:\",$root.level-order.join(\" \");\n\n```\n\nOutput:\n\n```\npreorder: 1 2 4 7 5 3 6 8 9\ninorder: 7 4 2 5 1 8 6 9 3\npostorder: 7 4 5 2 8 9 6 3 1\nlevelorder:1 2 3 4 5 6 7 8 9\n```"
}
]
|
[
{
"role": "user",
"content": "A triangular number is a count of objects arranged into an equilateral triangle.\nMuch like how a square number is a count of objects arranged into a square.\n\nThe *nth* triangular number is the sum of the first **n** non-negative integers. \n\nT\n\nn\n=\n\nโ\n\nk\n=\n1\n\nn\nk\n=\n1\n+\n2\n+\n3\n+\nโฏ\n+\nn\n{\\displaystyle {\\displaystyle T\\_{n}=\\sum \\_{k=1}^{n}k=1+2+3+\\dotsb +n}}\n\nTriangular numbers may be calculated by the explicit formulas: \n\nT\n\nn\n=\n\nn\n(\nn\n+\n1\n)\n2\n=\n\n(\n\n\nn\n+\n1\n2\n\n)\n{\\displaystyle {\\displaystyle T\\_{n}={\\frac {n(n+1)}{2}}={n+1 \\choose 2}}}\n\nwhere \n\n(\n\n\nn\n+\n1\n2\n\n)\n{\\displaystyle {\\displaystyle \\textstyle {n+1 \\choose 2}}}\n is the binomial coefficient \"n plus one choose two\".\n\nAnalogous to square roots, we may also calculate a triangular root. Numbers that have an integer triangular\nroot are triangular numbers.\n\nThe real triangular root of a number *x* may be found using: \n\nn\n=\n\n8\nx\n+\n1\nโ\n1\n2\n{\\displaystyle {\\displaystyle n={\\frac {{\\sqrt {8x+1}}-1}{2}}}}\n\nSimilar to how cubic numbers are square numbers extended into a third dimension,\ntriangular numbers extended into a third dimension are known as tetrahedral numbers.\n\nThe *nth* tetrahedral number is the sum of the first **n** triangular numbers. \n\nT\n\ne\n\nn\n=\n\nโ\n\nk\n=\n1\n\nn\n\nT\n\nk\n{\\displaystyle {\\displaystyle Te\\_{n}=\\sum \\_{k=1}^{n}T\\_{k}}}\n\nOr, may be calculated directly: \n\nT\n\ne\n\nn\n=\n\nn\n(\nn\n+\n1\n)\n(\nn\n+\n2\n)\n6\n=\n\nn\n\n\n3\nยฏ\n\n3\n!\n=\n\n(\n\n\nn\n+\n2\n3\n\n)\n{\\displaystyle {\\displaystyle Te\\_{n}={\\frac {n(n+1)(n+2)}{6}}={\\frac {n^{\\overline {3}}}{3!}}={\\binom {n+2}{3}}}}\n (Binomial \"n plus two choose three\".)\n\nOne may find the real tetrahedral root of *x* using the formula: \n\nn\n=\n\n3\nx\n+\n\n\n9\n\n\nx\n\n2\nโ\n\n\n1\n27\n\n3\n+\n\n3\nx\nโ\n\n\n9\n\n\nx\n\n2\nโ\n\n\n1\n27\n\n3\nโ\n1\n{\\displaystyle {\\displaystyle n={\\sqrt[{3}]{3x+{\\sqrt {9{x^{2}}-{\\frac {1}{27}}}}}}+{\\sqrt[{3}]{3x-{\\sqrt {9{x^{2}}-{\\frac {1}{27}}}}}}-1}}\n \n*Depending on the math precision of your particular language, may need to be rounded to the nearest 1e-16 or so.*\n\nExtending into a fourth dimension we get pentatopic numbers.\n\nAgain, the *nth* pentatope is the sum of the first **n** tetrahedral numbers, \n\nP\n\nn\n=\n\nโ\n\nk\n=\n1\n\nn\nT\n\ne\n\nk\n{\\displaystyle {\\displaystyle P\\_{n}=\\sum \\_{k=1}^{n}Te\\_{k}}}\n\nor explicitly: \n\nP\n\nn\n=\n\nn\n(\nn\n+\n1\n)\n(\nn\n+\n2\n)\n(\nn\n+\n3\n)\n24\n=\n\n(\n\n\nn\n+\n3\n4\n\n)\n{\\displaystyle {\\displaystyle P\\_{n}={\\frac {n(n+1)(n+2)(n+3)}{24}}={\\binom {n+3}{4}}}}\n (Binomial \"n plus three choose four\".)\n\nThe pentatopic real root of *x* may be found using: \n\nn\n=\n\n5\n+\n4\n\n\n24\nx\n+\n1\nโ\n3\n2\n.\n{\\displaystyle {\\displaystyle n={\\frac {{\\sqrt {5+4{\\sqrt {24x+1}}}}-3}{2}}.}}\n\nIn general, these all belong to the class figurate numbers as they are\nbased on **r** dimensional geometric figures. Sometimes they are referred to as **r-simplex**\nnumbers. In geometry a simplex is the simplest possible **r-dimensional**\nobject.\n\nYou may easily extend to an arbitrary dimension **r** using binomials. Each term **n** in dimension **r** is \n\nr\n\nn\n=\n\n(\n\n\nn\n+\nr\nโ\n1\nr\n\n)\n{\\displaystyle {\\displaystyle r\\_{n}={\\binom {n+r-1}{r}}}}\n\nThere is no known general formula to find higher r-simplex roots.\n\nTask\n\n* Find and display the first 30 triangular numbers (**r** = 2).\n* Find and display the first 30 tetrahedral numbers (**r** = 3).\n* Find and display the first 30 pentatopic numbers (**r** = 4).\n* Find and display the first 30 12-simplex numbers (**r** = 12).\n* Find and display the triangular root, the tetrahedral root, and the pentatopic root for the integers:\n + 7140\n + 21408696\n + 26728085384\n + 14545501785001\n\nSee also\n\n* Wikipedia: Triangular numbers * Wikipedia: Tetrahedral numbers * Wikipedia: Pentatopic numbers * Wikipedia: Figurate numbers * Wikipedia: Simplex(geometry) * OEIS:A000217 - Triangular numbers: a(n) = binomial(n+1,2) * OEIS:A000292 - Tetrahedral numbers: a(n) = binomial(n+2,3) * OEIS:A000332 - Pentatope numbers: a(n) = binomial(n+3,4) * Related task: Evaluate binomial coefficients * Related task: Pascal's triangle"
},
{
"role": "assistant",
"content": "```\nuse Math::Root:ver<0.0.4>;\n\nsub binomial { [ร] ($^n โฆ 0) Z/ 1 .. $^p }\n\nsub polytopic (Int $r, @range) { @range.map: { binomial $_ + $r - 1, $r } }\n\nsub display (@values) {\n my $c = @values.max.chars;\n @values.batch(6)ยป.fmt(\"%{$c}d\").join: \"\\n\";\n}\n\nfor 2, 'triangular', 3, 'tetrahedral', 4, 'pentatopic', 12, '12-simplex'\n -> $r, $name { say \"\\nFirst 30 $name numbers:\\n\" ~ display polytopic $r, ^30 }\n\nsay '';\n\nmy \\ฮต = FatRat.new: 1, 10**24;\n\nfor 7140, 21408696, 26728085384, 14545501785001 {\n say qq:to/R/;\n Roots of $_:\n triangular-root: {.&triangular-root.round: ฮต}\n tetrahedral-root: {.&tetrahedral-root.round: ฮต}\n pentatopic-root: {.&pentatopic-root.round: ฮต}\n R\n}\n\n```\n\nOutput:\n\n```\nFirst 30 triangular numbers:\n 0 1 3 6 10 15\n 21 28 36 45 55 66\n 78 91 105 120 136 153\n171 190 210 231 253 276\n300 325 351 378 406 435\n\nFirst 30 tetrahedral numbers:\n 0 1 4 10 20 35\n 56 84 120 165 220 286\n 364 455 560 680 816 969\n1140 1330 1540 1771 2024 2300\n2600 2925 3276 3654 4060 4495\n\nFirst 30 pentatopic numbers:\n 0 1 5 15 35 70\n 126 210 330 495 715 1001\n 1365 1820 2380 3060 3876 4845\n 5985 7315 8855 10626 12650 14950\n17550 20475 23751 27405 31465 35960\n\nFirst 30 12-simplex numbers:\n 0 1 13 91 455 1820\n 6188 18564 50388 125970 293930 646646\n 1352078 2704156 5200300 9657700 17383860 30421755\n 51895935 86493225 141120525 225792840 354817320 548354040\n 834451800 1251677700 1852482996 2707475148 3910797436 5586853480\n\nRoots of 7140:\n triangular-root: 119\n tetrahedral-root: 34\n pentatopic-root: 18.876646615928006607901783\n\nRoots of 21408696:\n triangular-root: 6543\n tetrahedral-root: 503.56182697463651404819613\n pentatopic-root: 149.060947375265867484387575\n\nRoots of 26728085384:\n triangular-root: 231205.405565255836957291031961\n tetrahedral-root: 5432\n pentatopic-root: 893.442456751684869888466212\n\nRoots of 14545501785001:\n triangular-root: 5393607.158145172316497304724655\n tetrahedral-root: 44355.777384073256052620916903\n pentatopic-root: 4321\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nIf your language has a library or built-in functions for trigonometry, show examples of:\n\n: : * sine\n * cosine\n * tangent\n * inverses ย (of the above)\n\nusing the same angle in radians and degrees.\n\nFor the non-inverse functions, ย each radian/degree pair should use arguments that evaluate to the same angle ย (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).\n\nFor the inverse functions, ย use the same number and convert its answer to radians and degrees.\n\nIf your language does not have trigonometric functions available or only has some available, ย write functions to calculate the functions based on any ย known approximation or identity."
},
{
"role": "assistant",
"content": "(formerly Perl 6) Borrow the degree to radian routine from here.\n\n**Works with**: Rakudo version 2020.12\n\n```\n# 20210212 Updated Raku programming solution\n\nsub postfix:<ยฐ> (\\แต) { แต ร ฯ / 360 }\n\nsub postfix:<ใญ๐กยฐ> (\\แถ) { แถ / ฯ ร 180 }\n\nsay sin ฯ/3ย ;\nsay sin 60ยฐย ;\n\nsay cos ฯ/4ย ;\nsay cos 45ยฐย ;\n\nsay tan ฯ/6ย ;\nsay tan 30ยฐย ;\n\n( asin(3.sqrt/2), acos(1/sqrt 2), atan(1/sqrt 3) )ยป.&{ .say and .ใญ๐กยฐ.say }\n\n```\n\nOutput:\n\n```\n0.8660254037844386\n0.8660254037844386\n0.7071067811865476\n0.7071067811865476\n0.5773502691896257\n0.5773502691896257\n1.0471975511965976\n60\n0.7853981633974484\n45.00000000000001\n0.5235987755982989\n30.000000000000004\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nNumbers ย **n** ย such that the three numbers ย **n-1**, ย **n+3**, ย and ย **n+5** ย are all prime, ย where ย **n < 6,000.**"
},
{
"role": "assistant",
"content": "A weird combination of Cousin primes and Twin primes that are siblings, but known by their neighbor.... I shall dub these Alabama primes.\n\n```\nsay \"{.[0]+1}: \",$_ for grep *.all.is-prime, ^6000 .race.map: { $_-1, $_+3, $_+5 };\n\n```\n\nOutput:\n\n```\n8: (7 11 13)\n14: (13 17 19)\n38: (37 41 43)\n68: (67 71 73)\n98: (97 101 103)\n104: (103 107 109)\n194: (193 197 199)\n224: (223 227 229)\n278: (277 281 283)\n308: (307 311 313)\n458: (457 461 463)\n614: (613 617 619)\n824: (823 827 829)\n854: (853 857 859)\n878: (877 881 883)\n1088: (1087 1091 1093)\n1298: (1297 1301 1303)\n1424: (1423 1427 1429)\n1448: (1447 1451 1453)\n1484: (1483 1487 1489)\n1664: (1663 1667 1669)\n1694: (1693 1697 1699)\n1784: (1783 1787 1789)\n1868: (1867 1871 1873)\n1874: (1873 1877 1879)\n1994: (1993 1997 1999)\n2084: (2083 2087 2089)\n2138: (2137 2141 2143)\n2378: (2377 2381 2383)\n2684: (2683 2687 2689)\n2708: (2707 2711 2713)\n2798: (2797 2801 2803)\n3164: (3163 3167 3169)\n3254: (3253 3257 3259)\n3458: (3457 3461 3463)\n3464: (3463 3467 3469)\n3848: (3847 3851 3853)\n4154: (4153 4157 4159)\n4514: (4513 4517 4519)\n4784: (4783 4787 4789)\n5228: (5227 5231 5233)\n5414: (5413 5417 5419)\n5438: (5437 5441 5443)\n5648: (5647 5651 5653)\n5654: (5653 5657 5659)\n5738: (5737 5741 5743)\n```"
}
]
|
[
{
"role": "user",
"content": "In algebra, a max tropical semiring (also called a max-plus algebra) is the semiring\n(โ โช -Inf, โ, โ) containing the ring of real numbers โ augmented by negative infinity,\nthe max function (returns the greater of two real numbers), and addition.\n\nIn max tropical algebra, x โ y = max(x, y) and x โ y = x + y. The identity for โ\nis -Inf (the max of any number with -infinity is that number), and the identity for โ is 0.\n\nTask\n\n* Define functions or, if the language supports the symbols as operators, operators for โ and โ that fit the above description. If the language does not support โ and โ as operators but allows overloading operators for a new object type, you may instead overload + and \\* for a new min tropical albrbraic type. If you cannot overload operators in the language used, define ordinary functions for the purpose.\n\nShow that 2 โ -2 is 0, -0.001 โ -Inf is -0.001, 0 โ -Inf is -Inf, 1.5 โ -1 is 1.5, and -0.5 โ 0 is -0.5.\n\n* Define exponentiation as serial โ, and in general that a to the power of b is a \\* b, where a is a real number and b must be a positive integer. Use either โ or similar up arrow or the carat ^, as an exponentiation operator if this can be used to overload such \"exponentiation\" in the language being used. Calculate 5 โ 7 using this definition.\n\n* Max tropical algebra is distributive, so that\n\n```\n a โ (b โ c) equals a โ b โ b โ c, \n\n```\n\nwhere โ has precedence over โ. Demonstrate that 5 โ (8 โ 7) equals 5 โ 8 โ 5 โ 7.\n\n* If the language used does not support operator overloading, you may use ordinary function names such as tropicalAdd(x, y) and tropicalMul(x, y).\n\nSee also\n: * [Tropical algebra] * [Tropical geometry review article] * [Operator overloading]"
},
{
"role": "assistant",
"content": "No need to overload, define our own operators with whatever precedence level we want. Here we're setting precedence equivalent to existing operators.\n\n```\nsub infix:<โ> (Real $a, Real $b) is equiv(&[+]) { $a max $b }\nsub infix:<โ> (Real $a, Real $b) is equiv(&[ร]) { $a + $b }\nsub infix:<โ> (Real $a, Int $b where * โฅ 0) is equiv(&[**]) { [โ] $a xx $b }\n \nuse Test;\n \nis-deeply( 2 โ -2, 0, '2 โ -2 == 0' );\nis-deeply( -0.001 โ -Inf, -0.001, '-0.001 โ -Inf == -0.001' );\nis-deeply( 0 โ -Inf, -Inf, '0 โ -Inf == -Inf' );\nis-deeply( 1.5 โ -1, 1.5, '1.5 โ -1 == 1.5' );\nis-deeply( -0.5 โ 0, -0.5, '-0.5 โ 0 == -0.5' );\nis-deeply( 5 โ 7, 35, '5 โ 7 == 35' );\nis-deeply( 5 โ (8 โ 7), 5 โ 8 โ 5 โ 7, '5 โ (8 โ 7) == 5 โ 8 โ 5 โ 7');\nis-deeply( 5 โ 7 โ 6 โ 6, 36, '5 โ 7 โ 6 โ 6 == 36');\n\n```\n\nOutput:\n\n```\nok 1 - 2 โ -2 == 0\nok 2 - -0.001 โ -Inf == -0.001\nok 3 - 0 โ -Inf == -Inf\nok 4 - 1.5 โ -1 == 1.5\nok 5 - -0.5 โ 0 == -0.5\nok 6 - 5 โ 7 == 35\nok 7 - 5 โ (8 โ 7) == 5 โ 8 โ 5 โ 7\nok 8 - 5 โ 7 โ 6 โ 6 == 36\n```"
}
]
|
[
{
"role": "user",
"content": "A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.\n\nExamples\n\nThe number **997** is called a *left-truncatable prime* as the numbers **997**, **97**, and **7** are all prime.\n\nThe number **7393** is a *right-truncatable prime* as the numbers **7393**, **739**, **73**, and **7** formed by removing digits from its right are also prime.\n\nNo zeroes are allowed in truncatable primes.\n\nTask\n\nThe task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).\n\nRelated tasks\n\n* Find largest left truncatable prime in a given base\n* Sieve of Eratosthenes\n\nSee also\n\n* Truncatable Prime from MathWorld.]"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2024.12\n\nYou May Attempt This Online.\n\n```\nconstant ltp = [2, 3, 5, 7], {\n last if .not;\n [ ((1..9) X~ @$_).grep: &is-prime ]\n} ... *;\n\nconstant rtp = [2, 3, 5, 7], {\n last if .not;\n [ (@$_ X~ (1,3,7,9)).grep: &is-prime ]\n} ... *;\n\nsay \"Largest ltp < 1e6 = \", ltp[5][*-1];\nsay \"Largest rtp < 1e6 = \", rtp[5][*-1];\nsay \"Largest possible ltp = \", ltp.eager.flat.tail;\nsay \"Largest possible rtp = \", rtp.eager.flat.tail;\n\n```\n\nOutput:\n\n```\nLargest ltp < 1e6 = 998443\nLargest rtp < 1e6 = 739399\nLargest possible ltp = 357686312646216567629137\nLargest possible rtp = 73939133\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nTruncate a file to a specific length. ย This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. ย The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition.\n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file.\n\nThis task permits the use of such facilities. ย However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.07\n\n```\nuse NativeCall;\n\nsub truncate(Str, int32 --> int32) is native {*}\n\nsub MAIN (Str $file, Int $to) {\n given $file.IO { \n .e or die \"$file doesn't exist\";\n .w or die \"$file isn't writable\";\n .s >= $to or die \"$file is not big enough to truncate\";\n }\n truncate($file, $to) == 0 or die \"Truncation was unsuccessful\";\n}\n\n```\n\nThe external `truncate` routine could be replaced with the following line (in which case no need for `NativeCall`):\n\n```\nspurt $file, slurp($file).substr($to);\n\n```"
}
]
|
[
{
"role": "user",
"content": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\nTask\n\n1. Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. \n (One can assume that the user input is correct).\n2. Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function.\n3. Either reverse-polish or infix notation expressions are allowed.\n\nRelated tasks\n\n* Boolean values\n* Ternary logic\n\nSee also\n\n* Wolfram MathWorld entry on truth tables.\n* some \"truth table\" examples from Google."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.01\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nsub MAIN ($x) {\n my @n = $x.comb(/<ident>/);\n my &fun = EVAL \"-> {('\\\\' ยซ~ยซย @n).join(',')} \\{ [{ (|@n,\"so $x\").join(',') }] \\}\";\n\n say (|@n,$x).join(\"\\t\");\n .join(\"\\t\").say for map &fun, flat map { .fmt(\"\\%0{+@n}b\").combยป.Intยป.so }, 0 ..^ 2**@n;\n say '';\n}\n\n```\n\nOutput:\n\n```\n$ truthtable 'A ^ B'\nA B A ^ B\nFalse False False\nFalse True True\nTrue False True\nTrue True False\n\n$ truthtable 'foo & bar | baz'\nfoo bar baz foo & bar | baz\nFalse False False False\nFalse False True True\nFalse True False False\nFalse True True True\nTrue False False False\nTrue False True True\nTrue True False True\nTrue True True True\n\n$ truthtable 'Jim & (Spock ^ Bones) | Scotty'\nJim Spock Bones Scotty Jim & (Spock ^ Bones) | Scotty\nFalse False False False False\nFalse False False True True\nFalse False True False False\nFalse False True True True\nFalse True False False False\nFalse True False True True\nFalse True True False False\nFalse True True True True\nTrue False False False False\nTrue False False True True\nTrue False True False True\nTrue False True True True\nTrue True False False True\nTrue True False True True\nTrue True True False False\nTrue True True True True\n```"
}
]
|
[
{
"role": "user",
"content": "Introduction\n\nJeff Tupper, in his 2001 paper \"Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables\", shows a set of methods to graph equations and inequalities with two variables in the cartesian plane.\n\nOne of the examples of the paper, refers to the inequality:\n\n1\n2\n<\n\nโ\n\n\nm\no\nd\n\n(\n\n\nโ\n\n\ny\n17\nโ\n\n2\n\nโ\n17\nโ\nx\nโ\nโ\n\nm\no\nd\n\n(\n\nโ\ny\nโ\n,\n17\n)\n,\n2\n)\nโ\n{\\displaystyle {\\frac {1}{2}}<\\left\\lfloor \\mathrm {mod} \\left(\\left\\lfloor {\\frac {y}{17}}\\right\\rfloor 2^{-17\\lfloor x\\rfloor -\\mathrm {mod} \\left(\\lfloor y\\rfloor ,17\\right)},2\\right)\\right\\rfloor }\n\nThat inequality, once plotted in the range 0 โค x โค 106 and k โค y โค k + 17 for k = 960, 939, 379, 918, 958, 884, 971, 672, 962, 127, 852, 754, 715, 004, 339, 660, 129, 306, 651, 505, 519, 271, 702, 802, 395, 266, 424, 689, 642, 842, 174, 350, 718, 121, 267, 153, 782, 770, 623, 355, 993, 237, 280, 874, 144, 307, 891, 325, 963, 941, 337, 723, 487, 857, 735, 749, 823, 926, 629, 715, 517, 173, 716, 995, 165, 232, 890, 538, 221, 612, 403, 238, 855, 866, 184, 013, 235, 585, 136, 048, 828, 693, 337, 902, 491, 454, 229, 288, 667, 081, 096, 184, 496, 091, 705, 183, 454, 067, 827, 731, 551, 705, 405, 381, 627, 380, 967, 602, 565, 625, 016, 981, 482, 083, 418, 783, 163, 849, 115, 590, 225, 610, 003, 652, 351, 370, 343, 874, 461, 848, 378, 737, 238, 198, 224, 849, 863, 465, 033, 159, 410, 054, 974, 700, 593, 138, 339, 226, 497, 249, 461, 751, 545, 728, 366, 702, 369, 745, 461, 014, 655, 997, 933, 798, 537, 483, 143, 786, 841, 806, 593, 422, 227, 898, 388, 722, 980, 000, 748, 404, 719 produces a drawing that visually mimics the inequality itself, hence it is called self-referential.\n\nAlthough the inequality is intended to be drawn on the continuum of the cartesian plane, the drawing can be performed iterating over the integer values of both the horizontal and vertical ranges.\n\nTask\n\nMake a drawing of the Tupper's formula, either using text, a matrix or creating an image.\n\nThis task requires arbitrary precision integer operations. If your language does not intrinsically support that, you can use a library.\n\nEpilogue\n\nThe value of k is an encoding of the bitmap of the image, therefore any 17-width bitmap can be produced, using its associated encoded value as k.\n\nReferences\n\n: * Wikipedia: Tupper's self-referential formula\n * Tupper, Jeff. \"Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables\""
},
{
"role": "assistant",
"content": "```\n# 20240802 Raku programming solution\n\nmy ( \\H, \\W, \\N ) = 17, 106, 4858450636189713423582095962494202044581400587983244549483093085061934704708809928450644769865524364849997247024915119110411605739177407856919754326571855442057210445735883681829823754139634338225199452191651284348332905131193199953502413758765239264874613394906870130562295813219481113685339535565290850023875092856892694555974281546386510730049106723058933586052544096664351265349363643957125565695936815184334857605266940161251266951421550539554519153785457525756590740540157929001765967965480064427829131488548259914721248506352686630476300;\n\nfor N+H-1 ... N -> \\y {\n say [~] ^W .map: { (y div H) div 2**(H * $_ + yย % H)ย % 2ย ?? 'โ'ย !! ' ' }\n}\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "This puzzle is borrowed from ย math-frolic.blogspot.\n\nGiven the following twelve statements, which of them are true?\n\n```\n 1. This is a numbered list of twelve statements.\n 2. Exactly 3 of the last 6 statements are true.\n 3. Exactly 2 of the even-numbered statements are true.\n 4. If statement 5 is true, then statements 6 and 7 are both true.\n 5. The 3 preceding statements are all false.\n 6. Exactly 4 of the odd-numbered statements are true.\n 7. Either statement 2 or 3 is true, but not both.\n 8. If statement 7 is true, then 5 and 6 are both true.\n 9. Exactly 3 of the first 6 statements are true.\n10. The next two statements are both true.\n11. Exactly 1 of statements 7, 8 and 9 are true.\n12. Exactly 4 of the preceding statements are true.\n\n```\n\nTask\n\nWhen you get tired of trying to figure it out in your head,\nwrite a program to solve it, and print the correct answer or answers.\n\nExtra credit\n\nPrint out a table of near misses, that is, solutions that are contradicted by only a single statement."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.07\n\n```\nsub infix:<โ> ($protasis, $apodosis) {ย !$protasis or $apodosis }\n \nmy @tests =\n { .end == 12 and all(.[1..12]) === any(True, False) },\n { 3 == [+] .[7..12] },\n { 2 == [+] .[2,4...12] },\n { .[5] โ all .[6,7] },\n { none .[2,3,4] },\n { 4 == [+] .[1,3...11] },\n { one .[2,3] },\n { .[7] โ all .[5,6] },\n { 3 == [+] .[1..6] },\n { all .[11,12] },\n { one .[7,8,9] },\n { 4 == [+] .[1..11] },\n;\n\nmy @solutions;\nmy @misses;\n\nfor [X] (True, False) xx 12 {\n my @assert = Nil, |$_;\n my @result = Nil, |@tests.map({ย ?.(@assert) });\n my @true = @assert.grep(?*, :k);\n my @cons = (@assert Z=== @result).grep(!*, :k);\n given @cons {\n when 0 { push @solutions, \"<{@true}> is consistent.\"; }\n when 1 { push @misses, \"<{@true}> implies { \"ยฌ\" ifย !@result[~$_] }$_.\" }\n }\n}\n\n.say for @solutions;\nsay \"\";\nsay \"Near misses:\";\n.say for @misses;\n\n```\n\nOutput:\n\n```\n<1 3 4 6 7 11> is consistent.\n\nNear misses:\n<1 2 4 7 8 9> implies ยฌ8.\n<1 2 4 7 9 10> implies ยฌ10.\n<1 2 4 7 9 12> implies ยฌ12.\n<1 3 4 6 7 9> implies ยฌ9.\n<1 3 4 8 9> implies 7.\n<1 4 6 8 9> implies ยฌ6.\n<1 4 8 10 11 12> implies ยฌ12.\n<1 4> implies 8.\n<1 5 6 9 11> implies 8.\n<1 5 8 10 11 12> implies ยฌ12.\n<1 5 8 11> implies 12.\n<1 5 8> implies 11.\n<1 5> implies 8.\n<4 8 10 11 12> implies 1.\n<5 8 10 11 12> implies 1.\n<5 8 11> implies 1.\n```"
}
]
|
[
{
"role": "user",
"content": "Twin primes are pairs of natural numbers ย (P1 ย andย P2) ย that satisfy the following:\n\n: : 1. P1 ย and ย P2 ย are primes\n 2. P1 ย +ย **2** ย = ย P2\n\nTask\n\nWrite a program that displays the number of **pairs of twin primes** that can be found under a user-specified number\n \n(P1 < *user-specified number* & P2 < *user-specified number*).\n\nExtension\n: : 1. Find all twin prime pairs under 100000, 10000000 and 1000000000.\n 2. What is the time complexity of the program? Are there ways to reduce computation time?\n\nExamples\n\n```\n> Search Size: 100\n> 8 twin prime pairs.\n\n```\n\n```\n> Search Size: 1000\n> 35 twin prime pairs.\n\n```\n\nAlso see\n\n* The OEIS entry: A001097: Twin primes.\n* The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.\n* The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.\n* The OEIS entry: A007508: Number of twin prime pairs below 10^n."
},
{
"role": "assistant",
"content": "**Works with**: Rakudo version 2020.07\n\n```\nuse Lingua::EN::Numbers;\n\nuse Math::Primesieve;\n\nmy $p = Math::Primesieve.new;\n\nprintf \"Twin prime pairs less than %17s: %s\\n\", comma(10**$_), comma $p.count(10**$_,ย :twins) for 1 .. 12;\nsay (now - INIT now).round(.01) ~ ' seconds';\n\n```\n\nOutput:\n\n```\nTwin prime pairs less than 10: 2\nTwin prime pairs less than 100: 8\nTwin prime pairs less than 1,000: 35\nTwin prime pairs less than 10,000: 205\nTwin prime pairs less than 100,000: 1,224\nTwin prime pairs less than 1,000,000: 8,169\nTwin prime pairs less than 10,000,000: 58,980\nTwin prime pairs less than 100,000,000: 440,312\nTwin prime pairs less than 1,000,000,000: 3,424,506\nTwin prime pairs less than 10,000,000,000: 27,412,679\nTwin prime pairs less than 100,000,000,000: 224,376,048\nTwin prime pairs less than 1,000,000,000,000: 1,870,585,220\n6.89 seconds\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program that displays twin primes under 10.000.000 whose sum is a square number."
},
{
"role": "assistant",
"content": "Updated for updated task requirements. Trivial to find the squares that are sums of twin primes less than 1e7. (First 69.) Also find the largest square less than 1e12 (#4288) (Not sure why, but that seems to be a popular \"stretch\" task, and the largest matching *root* less than 1e7, that when squared is a sum of two twin primes. (#29,996) Added some timing info as well. Timing is going to be system dependent. This task is ridiculously parallelizable. Run on a 16 core Ryzen 7950X.\n\n```\nuse List::Divvy;\n\nmy @tps = lazy (^Inf).hyper(:1000batch).map({next if $_%2; (my $s = .ยฒ, $_, $s+>1)}).grep:\n {(.[2]-1).is-prime && (.[2]+1).is-prime};\n\n{\n state $c;\n say \"{++$c}: {.[1]}ยฒ ({.[0]}) == {.[2]-1} + {.[2]+1}\"\n} for @tps.&before({.[2] > 1e7});\n\nsay \"{(now - INIT now).round(.001)} seconds elapsed\\n\";\n\n{\n my $s = @tps[$_];\n say \"{1+$_}: {$s[1]}ยฒ ({$s[0]}) == {$s[2]-1} + {$s[2]+1}\";\n} for @tps.&before({.[0] > 1e12}).elems - 1, @tps.first({.[1] > 1e7},:k) - 1;\n\nsay \"\\n{(now - INIT now).round(.001)} total seconds elapsed\\n\";\n\n```\n\nOutput:\n\n```\n1: 6ยฒ (36) == 17 + 19\n2: 12ยฒ (144) == 71 + 73\n3: 42ยฒ (1764) == 881 + 883\n4: 48ยฒ (2304) == 1151 + 1153\n5: 72ยฒ (5184) == 2591 + 2593\n6: 84ยฒ (7056) == 3527 + 3529\n7: 90ยฒ (8100) == 4049 + 4051\n8: 174ยฒ (30276) == 15137 + 15139\n9: 204ยฒ (41616) == 20807 + 20809\n10: 264ยฒ (69696) == 34847 + 34849\n11: 306ยฒ (93636) == 46817 + 46819\n12: 372ยฒ (138384) == 69191 + 69193\n13: 408ยฒ (166464) == 83231 + 83233\n14: 456ยฒ (207936) == 103967 + 103969\n15: 474ยฒ (224676) == 112337 + 112339\n16: 546ยฒ (298116) == 149057 + 149059\n17: 594ยฒ (352836) == 176417 + 176419\n18: 600ยฒ (360000) == 179999 + 180001\n19: 642ยฒ (412164) == 206081 + 206083\n20: 750ยฒ (562500) == 281249 + 281251\n21: 852ยฒ (725904) == 362951 + 362953\n22: 882ยฒ (777924) == 388961 + 388963\n23: 936ยฒ (876096) == 438047 + 438049\n24: 972ยฒ (944784) == 472391 + 472393\n25: 978ยฒ (956484) == 478241 + 478243\n26: 1038ยฒ (1077444) == 538721 + 538723\n27: 1140ยฒ (1299600) == 649799 + 649801\n28: 1212ยฒ (1468944) == 734471 + 734473\n29: 1272ยฒ (1617984) == 808991 + 808993\n30: 1386ยฒ (1920996) == 960497 + 960499\n31: 1470ยฒ (2160900) == 1080449 + 1080451\n32: 1512ยฒ (2286144) == 1143071 + 1143073\n33: 1518ยฒ (2304324) == 1152161 + 1152163\n34: 1584ยฒ (2509056) == 1254527 + 1254529\n35: 1770ยฒ (3132900) == 1566449 + 1566451\n36: 1836ยฒ (3370896) == 1685447 + 1685449\n37: 1902ยฒ (3617604) == 1808801 + 1808803\n38: 1980ยฒ (3920400) == 1960199 + 1960201\n39: 1986ยฒ (3944196) == 1972097 + 1972099\n40: 2130ยฒ (4536900) == 2268449 + 2268451\n41: 2196ยฒ (4822416) == 2411207 + 2411209\n42: 2256ยฒ (5089536) == 2544767 + 2544769\n43: 2262ยฒ (5116644) == 2558321 + 2558323\n44: 2316ยฒ (5363856) == 2681927 + 2681929\n45: 2382ยฒ (5673924) == 2836961 + 2836963\n46: 2652ยฒ (7033104) == 3516551 + 3516553\n47: 2688ยฒ (7225344) == 3612671 + 3612673\n48: 2718ยฒ (7387524) == 3693761 + 3693763\n49: 2772ยฒ (7683984) == 3841991 + 3841993\n50: 2814ยฒ (7918596) == 3959297 + 3959299\n51: 2886ยฒ (8328996) == 4164497 + 4164499\n52: 2946ยฒ (8678916) == 4339457 + 4339459\n53: 2988ยฒ (8928144) == 4464071 + 4464073\n54: 3012ยฒ (9072144) == 4536071 + 4536073\n55: 3096ยฒ (9585216) == 4792607 + 4792609\n56: 3282ยฒ (10771524) == 5385761 + 5385763\n57: 3366ยฒ (11329956) == 5664977 + 5664979\n58: 3498ยฒ (12236004) == 6118001 + 6118003\n59: 3558ยฒ (12659364) == 6329681 + 6329683\n60: 3582ยฒ (12830724) == 6415361 + 6415363\n61: 3738ยฒ (13972644) == 6986321 + 6986323\n62: 3786ยฒ (14333796) == 7166897 + 7166899\n63: 3936ยฒ (15492096) == 7746047 + 7746049\n64: 3948ยฒ (15586704) == 7793351 + 7793353\n65: 4032ยฒ (16257024) == 8128511 + 8128513\n66: 4170ยฒ (17388900) == 8694449 + 8694451\n67: 4200ยฒ (17640000) == 8819999 + 8820001\n68: 4314ยฒ (18610596) == 9305297 + 9305299\n69: 4416ยฒ (19501056) == 9750527 + 9750529\n0.027 seconds elapsed\n\n4288: 999684ยฒ (999368099856) == 499684049927 + 499684049929\n29996: 9999450ยฒ (99989000302500) == 49994500151249 + 49994500151251\n\n71.494 total seconds elapsed\n\n```"
}
]
|
[
{
"role": "user",
"content": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n> A revolver handgun has a revolving cylinder with six chambers for bullets.\n>\n> It is loaded with the following procedure:\n>\n> 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n> is seen, the cylinder is rotated one chamber clockwise and the next chamber\n> checked until an empty chamber is found.\n>\n> 2. A cartridge containing a bullet is placed in the empty chamber.\n>\n> 3. The cylinder is then rotated one chamber clockwise.\n>\n> To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n> a random position from 1 to 6 chamber rotations clockwise from its starting position.\n>\n> When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n> counterclockwise from the loading position.\n>\n> The gun is unloaded by removing all cartridges from the cylinder.\n>\n> According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n> roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n> If the gun fires with a trigger pull, this is considered a successful suicide.\n>\n> The cylinder is always spun before the first shot, but it may or may not be spun after putting\n> in the first bullet and may or may not be spun after taking the first shot.\n>\n> Which of the following situations produces the highest probability of suicide?\n>\n> A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n>\n> B. Spinning the cylinder after loading the first bullet only.\n>\n> C. Spinning the cylinder after firing the first shot only.\n>\n> D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n>\n> E. The probability is the same for all cases.\n\nTask\n\n1. Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n2. Show the results as a percentage of deaths for each type of scenario.\n3. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question.\n\nReference\n\nYoutube video on the Russian 1895 Nagant revolver [[1]]"
},
{
"role": "assistant",
"content": "```\nunit sub MAIN ($shots = 6);\n\nmy @cyl;\n\nsub load () {\n @cyl.=rotate(-1) while @cyl[1];\n @cyl[1] = 1;\n @cyl.=rotate(-1);\n}\n\nsub spin () { @cyl.=rotate: (^@cyl).pick }\n\nsub fire () { @cyl.=rotate; @cyl[0] }\n\nsub LSLSFSF {\n @cyl = 0 xx $shots;\n load, spin, load, spin;\n return 1 if fire;\n spin;\n fire\n}\n\nsub LSLSFF {\n @cyl = 0 xx $shots;\n load, spin, load, spin;\n fire() || fire\n}\n\nsub LLSFSF {\n @cyl = 0 xx $shots;\n load, load, spin;\n return 1 if fire;\n spin;\n fire\n}\n\nsub LLSFF {\n @cyl = 0 xx $shots;\n load, load, spin;\n fire() || fire\n}\n\nmy %revolver;\nmy $trials = 100000;\n\nfor ^$trials {\n %revolver<LSLSFSF> += LSLSFSF;\n %revolver<LSLSFF> += LSLSFF;\n %revolver<LLSFSF> += LLSFSF;\n %revolver<LLSFF> += LLSFF;\n}\n\nsay \"{.fmt('%7s')}:ย %{(%revolver{$_} / $trials ร 100).fmt('%.2f')}\"\n for <LSLSFSF LSLSFF LLSFSF LLSFF>\n\n```\n\nSample output (default; 6 shooter):\n\n```\nLSLSFSF: %55.37\n LSLSFF: %58.30\n LLSFSF: %55.42\n LLSFF: %50.29\n\n```\n\nThough if you go and look at the Wikipedia article for the 1895 Nagant revolver mentioned in the task reference section, you'll see it is actually a **7** shot revolver... so, run again with 7 chambers:\n\n`raku roulette.raku 7`\n\nSample output (7 shooter):\n\n```\nLSLSFSF: %49.29\n LSLSFF: %51.14\n LLSFSF: %48.74\n LLSFF: %43.08\n```\n\nOr, how about a Ruger GP100 10 round revolver?\n\n`raku roulette.raku 10`\n\nSample output (10 shooter):\n\n```\nLSLSFSF: %36.00\n LSLSFF: %37.00\n LLSFSF: %36.13\n LLSFF: %29.77\n```\n\nDoesn't change the answers, B (LSLSFF) is definitely the worst most likely choice in all cases."
}
]
|
[
{
"role": "user",
"content": "Task\n\nFind and display ย (here on this page) ย positive integers, n, whose base 2 representation is the concatenation of two identical binary strings,\n \nwhere ย **n** < ย 1,00010 **(one thousand).**\n\nFor each such integer, show its decimal and binary forms."
},
{
"role": "assistant",
"content": "```\nmy @cat = (1..*).map: {ย :2([~] .base(2) xx 2) };\nsay \"{+$_} matching numbers\\n{.batch(5)ยป.map({$_ ~ .base(2).fmt('(%s)')})ยป.fmt('%15s').join: \"\\n\"}\\n\"\n given @cat[^(@cat.first: * > 1000,ย :k)];\n\n```\n\nOutput:\n\n```\n30 matching numbers\n 3(11) 10(1010) 15(1111) 36(100100) 45(101101)\n 54(110110) 63(111111) 136(10001000) 153(10011001) 170(10101010)\n 187(10111011) 204(11001100) 221(11011101) 238(11101110) 255(11111111)\n528(1000010000) 561(1000110001) 594(1001010010) 627(1001110011) 660(1010010100)\n693(1010110101) 726(1011010110) 759(1011110111) 792(1100011000) 825(1100111001)\n858(1101011010) 891(1101111011) 924(1110011100) 957(1110111101) 990(1111011110)\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nTask\n\nGiven a sorted array of integers (with possibly duplicates), is it possible to find a pair of integers from that array that sum up to a given sum? If so, return indices of the two integers or an empty array if not. The solution is not necessarily unique.\n\nExample\n\nGiven numbers = [0, 2, 11, 19, 90], sum = 21, \nBecause numbers[1] + numbers[3] = 2 + 19 = 21, \nreturn [1, 3].\n\nSource\n\nStack Overflow: Find pair of numbers in array that add to given sum"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Procedural\n\n**Translation of**: zkl\n\n```\nsub two_sum ( @numbers, $sum ) {\n die '@numbers is not sorted' unless [<=] @numbers;\n\n my ( $i, $j ) = 0, @numbers.end;\n while $i < $j {\n given $sum <=> @numbers[$i,$j].sum {\n when Order::More { $i += 1 }\n when Order::Less { $j -= 1 }\n when Order::Same { return $i, $j }\n }\n }\n return;\n}\n\nsay two_sum ( 0, 2, 11, 19, 90 ), 21;\nsay two_sum ( 0, 2, 11, 19, 90 ), 25;\n\n```\n\nOutput:\n\n```\n(1 3)\nNil\n```\n\n### Functional\n\nThe two versions differ only in how one 'reads' the notional flow of processing: left-to-right versus right-to-left.\nBoth return all pairs that sum to the target value, not just the first (e.g. for input of `0 2 10 11 19 90` would get indices 1/4 and 2/3).\n\n```\nsub two-sum-lr (@a, $sum) {\n # (((^@a X ^@a) Z=> (@a X+ @a)).grep($sum == *.value)>>.keys.map:{ .split(' ').sort.join(' ')}).unique\n (\n (\n (^@a X ^@a) Z=> (@a X+ @a)\n ).grep($sum == *.value)>>.keys\n .map:{ .split(' ').sort.join(' ')}\n ).unique\n}\n\nsub two-sum-rl (@a, $sum) {\n # unique map {.split(' ').sort.join(' ')}, keysย %(grep {.value == $sum}, ((^@a X ^@a) Z=> (@a X+ @a)))\n unique\n map {.split(' ').sort.join(' ')},\n keysย %(\n grep {.value == $sum}, (\n (^@a X ^@a) Z=> (@a X+ @a)\n )\n )\n}\n\nmy @a = <0 2 11 19 90>;\nfor 21, 25 {\n say two-sum-rl(@a, $_);\n say two-sum-lr(@a, $_);\n}\n\n```\n\nOutput:\n\n```\n(1 3)\n(1 3)\n()\n()\n```"
}
]
|
[
{
"role": "user",
"content": "Two's complement is an important concept in representing negative numbers. To turn a positive integer negative, flip the bits and add one.\n\nTask\n\nShow how to calculate the two's complement of an integer. (It doesn't necessarily need to be a 32 bit integer.)"
},
{
"role": "assistant",
"content": "By default Rakus integers are arbitrary sized, theoretically of infinite length. You can't really take the twos complement of an infinitely long number; so, we need to specifically use fixed size integers.\n\nThere is a module available from the Raku ecosystem that provides fixed size integer support, named (appropriately enough.) FixedInt.\n\nFixedInt supports fixed bit size integers, not only 8 bit, 16 bit, 32 bit or 64 bit, but *ANY* integer size. 22 bit, 35 bit, 191 bit, whatever.\n\nHere we'll demonstrate twos complement on a 57 bit integer.\n\n```\nuse FixedInt;\n\n# Instantiate a new 57(!) bit fixed size integer\nmy \\fixedint = FixedInt.new:ย :57bits;\n\nfixedint = (2ยณโท / 72 - 5ยนโท); # Set it to a large value\n\nsay fixedint; # Echo the value to the console in decimal format\nsay fixedint.bin; # Echo the value to the console in binary format\n\nfixedint.=C2; # Take the twos complement\n\nsay fixedint; # Echo the value to the console in decimal format\nsay fixedint.bin; # Echo the value to the console in binary format\n\n```\n\nOutput:\n\n```\n144114427045277101\n0b111111111111111110100111011001111000010101110110110101101\n761030578771\n0b000000000000000001011000100110000111101010001001001010011\n```"
}
]
|
[
{
"role": "user",
"content": "This draft task needs a purpose, a description and some way to tell whether examples satisfy or do not satisfy it.\n\nTask\n\nShow a function/procedure that processes a block of text by printing it.\n\nThe function takes one parameter (ideally) that describes the text.\n\nDemonstrate by calling the function twice, each time passing in a different type.\n\nThis can be done with pattern matching, multi-methods, dynamic type detection, structure(s) with a tag, etc.\n\nThe objective is write a [e.g. library] function that processes text from multiple sources (such as a string/char \\*, socket, file, etc).\n\nIf not practical, show how the caller would coerce a type that can be passed to the library function."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nRaku is a dynamic language that has gradual, duck typing. It provides introspection methods through its comprehensive MOP (Meta Object Protocol) making it easy to do type detection, subroutine signatures and multi-dispatch. Raku types have two general flavors: content types and container types. Different container types have varying restrictions on what sort of content they can contain and in return provide specialized methods to operate on those contents. Content types give the compiler hints on how to best handle the information, what storage requirements it may have, what operators will work with it, etc.\n\nThis is really a very broad and kind of hand-wavey overview of Raku types. For much more in-depth coverage see: https://docs.raku.org/type.html\n\n```\nsub type ($t) { say $t.raku, \"\\tis type: \", $t.WHAT }\n\n# some content types\n.&type for 1, 2.0, 3e0, 4i, ฯ, Inf, NaN, 'String';\n\n# some primitive container types\n.&type for $, [ ], @, { },ย %, (5 .. 7), (8 ... 10), /0/, {;}, sub {}, ( );\n\n# undefined things\n.&type for Any, Nil;\n\n# user defined types\nclass my-type { };\n\nmy my-type $object;\n\n$object.&type;\n\n```\n\nOutput:\n\n```\n1\tis type: (Int)\n2.0\tis type: (Rat)\n3e0\tis type: (Num)\n<0+4i>\tis type: (Complex)\n3.14159265358979e0\tis type: (Num)\nInf\tis type: (Num)\nNaN\tis type: (Num)\n\"String\"\tis type: (Str)\nAny\tis type: (Any)\n$[]\tis type: (Array)\n$[]\tis type: (Array)\n{}\tis type: (Hash)\n{}\tis type: (Hash)\n5..7\tis type: (Range)\n(8, 9, 10).Seq\tis type: (Seq)\n/0/\tis type: (Regex)\n->ย ;; $_? is raw { #`(Block|61385680) ... }\tis type: (Block)\nsub () { #`(Sub|62948936) ... }\tis type: (Sub)\n$()\tis type: (List)\nAny\tis type: (Any)\nNil\tis type: Nil\nmy-type\tis type: (my-type)\n```"
}
]
|
[
{
"role": "user",
"content": "With the following initial conditions:\n\n```\n u1 = 1 \n u2 = 2 \n\n```\n\nWe define the ย nth ย Ulam number ย un ย as the smallest number that is greater than ย un-1 ย ย and\n \nis the unique sum of two different Ulam numbers ย uiย (<n) ย and ย ujย (<n).\n\nTask\n\nWrite a function to generate the ย nth ย Ulam number.\n\nReferences\n\n* OEIS Ulam numbers"
},
{
"role": "assistant",
"content": "```\nmy @ulams = 1, 2, &next-ulam โฆ *;\n\nsub next-ulam {\n state $i = 1;\n state @sums = 0,1,1;\n my $last = @ulams[$i];\n (^$i).map: { @sums[@ulams[$_] + $last]++ };\n ++$i;\n quietly ($last ^.. *).first: { @sums[$_] == 1 };\n}\n\nfor 1 .. 4 {\n say \"The {10**$_}th Ulam number is: \", @ulams[10**$_ - 1]\n}\n\n```\n\nOutput:\n\n```\nThe 10th Ulam number is: 18\nThe 100th Ulam number is: 690\nThe 1000th Ulam number is: 12294\nThe 10000th Ulam number is: 132788\n```"
}
]
|
[
{
"role": "user",
"content": "An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at **1**), ย constructed on a square grid, starting at the \"center\".\n\nAn Ulam spiral is also known as a ย *prime spiral*.\n\nThe first grid (green) is shown with sequential integers, ย starting at ย **1**.\n\nIn an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk), ย and all non-primes as shown as a blank ย (or some other whitespace).\n\nOf course, the grid and border are not to be displayed (but they are displayed here when using these Wiki HTML tables).\n\nNormally, the spiral starts in the \"center\", ย and the ย 2nd ย number is to the viewer's right and the number spiral starts from there in a counter-clockwise direction.\n\nThere are other geometric shapes that are used as well, including clock-wise spirals.\n\nAlso, some spirals (for the ย 2nd ย number) ย is viewed upwards from the ย 1st ย number instead of to the right, but that is just a matter of orientation.\n\nSometimes, the starting number can be specified to show more visual striking patterns (of prime densities).\n\n[A larger than necessary grid (numbers wise) is shown here to illustrate the pattern of numbers on the diagonals ย (which may be used by the method to orientate the direction of spiral-construction algorithm within the example computer programs)].\n\nThen, in the next phase in the transformation of the Ulam prime spiral, ย the non-primes are translated to blanks.\n\nIn the orange grid below, ย the primes are left intact, ย and all non-primes are changed to blanks.\n\nThen, in the final transformation of the Ulam spiral (the yellow grid), ย translate the primes to a glyph such as a ย **โข** ย or some other suitable glyph.\n\n| | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| **65** | **64** | **63** | **62** | **61** | **60** | **59** | **58** | **57** |\n| **66** | **37** | **36** | **35** | **34** | **33** | **32** | **31** | **56** |\n| **67** | **38** | **17** | **16** | **15** | **14** | **13** | **30** | **55** |\n| **68** | **39** | **18** | **5** | **4** | **3** | **12** | **29** | **54** |\n| **69** | **40** | **19** | **6** | **1** | **2** | **11** | **28** | **53** |\n| **70** | **41** | **20** | **7** | **8** | **9** | **10** | **27** | **52** |\n| **71** | **42** | **21** | **22** | **23** | **24** | **25** | **26** | **51** |\n| **72** | **43** | **44** | **45** | **46** | **47** | **48** | **49** | **50** |\n| **73** | **74** | **75** | **76** | **77** | **78** | **79** | **80** | **81** |\n\n| | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | | | | **61** | | **59** | | |\n| | **37** | | | | | | **31** | |\n| **67** | | **17** | | | | **13** | | |\n| | | | **5** | | **3** | | **29** | |\n| | | **19** | | | **2** | **11** | | **53** |\n| | **41** | | **7** | | | | | |\n| **71** | | | | **23** | | | | |\n| | **43** | | | | **47** | | | |\n| **73** | | | | | | **79** | | |\n\n| | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | | | | **โข** | | **โข** | | |\n| | **โข** | | | | | | **โข** | |\n| **โข** | | **โข** | | | | **โข** | | |\n| | | | **โข** | | **โข** | | **โข** | |\n| | | **โข** | | | **โข** | **โข** | | **โข** |\n| | **โข** | | **โข** | | | | | |\n| **โข** | | | | **โข** | | | | |\n| | **โข** | | | | **โข** | | | |\n| **โข** | | | | | | **โข** | | |\n\nThe Ulam spiral becomes more visually obvious as the grid increases in size.\n\nTask\n\nFor any sized ย **N ร N** ย grid, ย construct and show an Ulam spiral (counter-clockwise) of primes starting at some specified initial number ย (the default would be **1**), ย with some suitably ย *dotty* ย (glyph) representation to indicate primes, ย and the absence of dots to indicate non-primes.\n\nYou should demonstrate the generator by showing at Ulam prime spiral large enough to (almost) fill your terminal screen.\n\nRelated tasks\n\n* Spiral matrix\n* Zig-zag matrix\n* Identity matrix\n* Sequence of primes by Trial Division\n\nSee also\n\n* Wikipedia entry: ย Ulam spiral\n* MathWorldโข entry: ย Prime Spiral"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub MAIN($max = 160, $start = 1) {\n (my %world){0}{0} = 0;\n my ($n, $dir, $side, $loc) = $start, 1, 0, 0+0i;\n\n while ++$side < $max {\n\tstep for ^$side; turn-left;\n\tstep for ^$side; turn-left;\n }\n\n braille-graphics %world;\n\n sub step {\n\t$loc += $dir;\n\t%world{$loc.im}{$loc.re} = $n if (++$n).is-prime;\n }\n\n sub turn-left { $dir ร= -i }\n sub turn-right { $dir ร= i }\n}\n\nsub braille-graphics (%a) {\n my ($y-lo, $y-hi, $x-lo, $x-hi);\n for %a.keys.map(+*) -> \\y {\n for %a{y}.keys.map(+*) -> \\x {\n $y-lo min= y; $y-hi max= y;\n $x-lo min= x; $x-hi max= x;\n }\n }\n\n for $y-lo, $y-lo + 4 ...^ $y-hi -> \\y {\n\tfor $x-lo, $x-lo + 2 ...^ $x-hi -> \\x {\n\t my $cell = 0x2800;\n $cell += 2โฐ if %a{y + 0}{x + 0};\n $cell += 2ยน if %a{y + 1}{x + 0};\n $cell += 2ยฒ if %a{y + 2}{x + 0};\n $cell += 2ยณ if %a{y + 0}{x + 1};\n $cell += 2โด if %a{y + 1}{x + 1};\n $cell += 2โต if %a{y + 2}{x + 1};\n $cell += 2โถ if %a{y + 3}{x + 0};\n $cell += 2โท if %a{y + 3}{x + 1};\n print chr($cell);\n\t}\n\tprint \"\\n\";\n }\n}\n\n```\n\nOutput:\n\n```\nโ โ โ โ โขโ โ โ โ โ โขโ โ โขโ โ โ โ โขโ โ โ
โขโ โข
โขโ โขโ โ โ โ โ โขโขโ โ โ โ โขโขโ โ โขโ โขโ โ โขโ โ โ โขโ โ โ โ โขโ โ โ โ โ โ โ โ โ โขโ โ โ โ โขโขโ โ โ โ โขโ \nโ โ โ โ โ โ โขโ โ โ โ โ โขโขโ โ โ โ โขโ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ
โ โ โขโขโ โ โ โ โ โขโ โ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โขโ โ โ โ \nโ โ โขโ โขโ โ โขโ โ โ โ โ
โขโ โ โ โ โ โ โ โ โ โขโ โขโ โ โขโ โ โ โขโ โขโ โ โขโ โ โขโ โ โ โ โ โ โขโ โ โ โ โ โขโ โขโ โ โ โ โ โ โ โ โขโ โ โ โขโ โขโ โ
โ โ โ
โขโ โ โ \nโ
โขโ โ โ โ โ
โ โ โขโ โ โ โ โ โขโ โ โขโขโ โ โ โ โ โขโ โ โ โ โขโ โ โขโ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โ \nโ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โขโขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โขโ โ
โขโ โ โ โ โ โ
โขโ โขโขโ โ โ โ โ โ โ โ โขโ โ
โ โ โขโ โ โ
โ โ โขโ โขโ โขโ โ โ โขโ โ \nโขโ โ โขโ โ โ โ โขโ โ โ โ โขโขโ โ โ โ โ โขโ โ โ โ โขโ โ โขโ โ โ โขโ โ โขโ โ โขโ โขโ โ โ โขโ โ โขโ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โ โขโ โขโขโ โ โขโ โ โขโ โขโ โ โ \nโ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โขโ โ โ โขโ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โขโ โ โขโ โข
โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \nโ โ โ โ โ โขโขโ โขโ โ โขโ โ โ โ โ โ
โ โขโ โ โขโ โขโ โ โ โ โ โขโ โ โขโ โ โ โขโ โ โ โ โ โขโ โขโ โ โข
โ โ โ
โ โ โ โขโ โขโ โ โขโ โ โ โ โขโขโ โขโ โ โ
โ โขโ โ โ โ โขโข\nโขโ โ โ โ โขโ โ โ โ โ โ
โ โ โขโขโข
โ โ โขโ โ โ โ โ
โ โขโ โขโ โ โขโ โ โ โ โ โ โขโ โขโ โ โ โขโ โขโ โ โขโ โ โ โขโ โขโ โ โ โ โ โ โ โ โ โ โ โขโขโ โ โ โ โ โ โ โขโขโ โ \nโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โขโ โ โ โ โขโ โ โขโ โ โขโ โ โขโขโ โ
โขโ โ โ โ โขโ โ โขโ โ โ โขโ โ โขโ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \nโขโ โขโขโ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โขโ โ โ โขโ โ โ โขโ โขโ โ โ โ โ โ โขโ โ
โขโ
โ โ โ
โ โ โ โ โ โ โ โ โ โขโ โ โขโ โขโขโขโขโขโขโ โ โขโ โ โขโขโ โขโขโ โ โ โ โ \nโ โ โ
โ โ โ
โ โขโ โ โ โขโ โขโ โ โ โขโ โ โข
โขโ โ โ โขโขโ โ โ โ โ โขโ โ โขโ โ โ โ โ โ โ โขโ โ โขโขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โข
โ โ โ โ โ โ
โขโ โ โ โ โ \nโ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โขโขโ โ
โ โ โขโ โ โ โ โ โ โ โ โ
โขโ โ โขโ โขโ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ \nโขโ โ โ โ โขโขโ โ โขโ โขโ โ โ โขโ โ โ โ โขโขโ โ โขโ โขโ โ โ โ โขโ โขโ โ โขโ โ โขโ โ
โ โขโ โขโขโ โ โ โ โ โ โ โ โ โขโขโ โ โ โ โ โ โ โ โขโขโ โ โ โขโ โ โ โ โ โขโ โ \nโ โ โ โขโ โ โขโ โ โ โ โ โขโ โ โ โ
โ โขโขโ โ โขโ โ โ
โขโขโ โขโ โขโ โ โ โ โ โ โขโ โขโ โ โ โขโ
โขโ โ โ โ โ โขโ โ โขโ โ โขโขโ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ \nโ โ โ โ โ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โขโขโ โ โขโ โขโ โ โ โ โ โขโ โ โข
โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ \nโ โ โ โ โ โขโ โ โขโขโ โขโ โ โขโ โ โ โ โ โ โขโ โ โ โ โขโ โ โขโขโ โขโขโ โ โขโขโ โ โขโ
โ
โขโ โ โ โ โ โขโ โ โ โ โ โขโ
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โขโขโ โ โ โข\nโขโขโ โ โ โ โขโ โ โ โ โ โ โขโ โขโ โ โ โ โขโ โขโ โขโ โ โ โขโขโขโขโ โ โ โขโ โ โขโ โ โ โ โขโขโ
โขโ โ โขโขโ โ โขโ โ โ โ โ โ โ โขโ โ โขโ โ โ โขโ
โขโ โ โขโ โ
โ โ โ โ \nโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ
โ โ โขโขโ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โขโ \nโ โ โ โขโ โ โขโ โขโขโ โขโขโ โ โ โ โขโ โ โ โ โ โขโขโ โขโ โ โขโ โ โ โ โ โ โขโ โขโ โฃโข
โขโขโ โขโขโข
โ โ โขโ โ โ โขโขโข
โขโ โ โ โ โ โ โขโ โขโขโ โขโ โขโ โ โขโขโขโข
โขโ \nโขโ โ โ โ โ โ โขโขโ โ โ โ โ โ
โ โ โขโขโ โ โ โขโขโ โขโ โขโ
โ
โขโ โ โขโ โขโ โขโ
โ โขโ โ โขโขโ โขโ โ โ โขโ โ โขโ โ โขโ โขโขโ โ โ โ โ โขโ โขโ โ โขโขโ โขโขโ โ โ โ โข\nโ โขโ โ โ โ โ โ โ โ โขโ โ
โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โขโ โ โขโ โ โขโ โขโขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \nโ โ โขโ โ โ โ โ โขโ โ โขโขโ โ โขโ โ โ โ โขโขโ โ โขโ โ โขโ โ โขโ โขโขโ โ โขโ โ โขโ โขโขโ โ โ โ โ โขโ โ โขโ โขโขโขโ โ โขโขโ โ โ โ โขโ โขโ โ โ โ โ โ โ โขโขโ โ โขโข\nโ โขโ โ โขโ โ โ
โ โ โ
โ โ โ โขโขโขโ โ โ
โ โขโ โ โ โขโ โ โ โขโ โ โ โขโขโ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โขโ โ โขโ โขโ โ โ โขโ โ โ โ โ โขโ โ โ โ
โ โ โ โ โขโ โ \nโ โขโ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ
โ โ โ โขโ โ โ โ โ โขโ โ
โ โ
โ โ โ โ โขโ โ โขโ โขโขโ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โขโ \nโขโ โขโ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โขโ โ โขโ โขโขโ โ โขโ โขโ โ โขโ โ โ โ โ โ โ โขโขโขโขโ โขโ โ โ โ โขโขโ โ โขโขโ โ โ โขโ โ \nโขโขโ โ โขโข
โขโขโขโขโ
โ โ โ โขโขโขโขโขโข
โขโ โ โขโขโ โ
โ โ โ โขโ โ โขโ โ โ โขโ โขโ โ
โ โขโ โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ \nโ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โขโ โ โขโขโ โ โ โ โ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โ โ โ โ โ โขโ \nโ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โข
โ โ โ โ โ โขโ โ โขโขโ โ โ โ โ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โขโ โ โ โ โ โ โขโขโ โ โ โขโ โ โ โ โ โขโขโ โ โขโ โ โ \nโ โ
โ โขโ โ โ โ โ โ โ โขโ โขโขโ โ โขโ โขโ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โขโ โ โ โ โ โ โ โ โขโ โขโขโ โ โ โ โ โขโขโ โข
โ โ โ โ โ
โ โ โ โขโ โ โ
โ โ โข\nโ โ โ โ โ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ
โ โ โ โขโ โ โขโ โขโขโ โขโ โ โ โ โ
โ โ โ
โขโ โ โขโ โ โ โ โ โขโ โ โขโ โ โ โ โ โขโ โ โขโ โ โขโ โ โ โ \nโ โ โขโขโ โ โขโ โ โ โ โ โ โ โขโ โ โ
โขโ โขโ โ โ โ โ โ
โขโ โขโขโ โ
โขโ โ โ โ โ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โ โขโ โ
โขโ โ โขโ โ โ โขโขโ โขโ โขโ โ
โ โ โ โ โ โ โ โ \nโ โ โขโ โ โขโ โ โ โ โขโขโ โ โ โ โ โ โ โ โ โขโขโ โ โ โ โขโ โ โ โขโ โ โ โ โ โ โ โขโ โ โขโ โ โ โขโ โ โขโ โ โ โ โขโ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โขโขโ โ โ โ โ โ โ โข\nโ โ โ โ โขโ โ โ โ โ โ โ โขโ โ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โขโ โ
โขโ โ โ โ
โขโ โ โ โขโ โ โ โ
โ โ โ โ โขโ โขโ โ โ โ โ โ โขโ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \nโ โ โขโ โ โ โขโ โ โ โ โ โ โ โ โขโ โขโ โ โขโ โ โขโขโ โ โขโ โข
โขโ โ โ โ โ โ โ โ โ โ โ โ โ โขโขโ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โ โขโขโ โข
โ โ โขโ โขโ โขโขโ โ โ โขโขโข\nโ โ โ
โขโ โ โ โ
โ โ โขโ โ โ โ โขโ โ โ โ โ โ โ โ โขโ โ โขโ โ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โ โ โ โ โ โ โ โ โขโ โขโ โ โ โ โ โขโ โ โ โ โ โขโขโ โ โ โ โ โขโ โ
โ โ โ โ \nโ โ โ โ โขโ โ โขโ โ โ โ โ โ โ โ โ โ โ โขโ โ โ โ โขโ โ โ โขโ โ โ โ โ โขโ โ โ โ โขโ โ โ โ โ โข
โ โ โขโ โ โ โ โ โขโ โ โ โ โ โข
โ โ โขโ โ โ โขโ โ โ โ โ โ โ โ โ โ โ โ \nโ โ โขโ โ โ โขโ โ โ โ โขโขโ โขโ โ โ
โ โ โ โ โ โขโ โ โ โขโ โ
โ โ โขโ โ โ โขโ โ โ โ โ โขโ โขโ โ โ
โ โ โ
โ โ โขโขโ โ โ โ โ โ โ โ โขโ โ โ โ โขโขโ โขโขโ โขโ โขโ โ โ \nโ โ โ โ โ โ โ โขโ โ โ โ โขโ โ โ โ โ โขโขโ โขโ โ โ โ โ โ โขโ โ โ โ โขโ โ โขโ โ โขโ โ โขโ โ โ โ โ โ โ โ โขโ โ โ โ โ โขโขโ โ โ โ โ โ โ
โ โ โ โ โ โ โขโ โ โ โ โ โ โ \nโ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ
โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ โ \n\n```"
}
]
|
[
{
"role": "user",
"content": "An **ultra-useful prime** is a member of the sequence where each **a(n)** is the smallest positive integer **k** such that **2(2n) - k** is prime.\n\n***k** must always be an odd number since 2 to any power is always even.*\n\nTask\n\n* Find and show here, on this page, the first **10** elements of the sequence.\n\nStretch\n\n* Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.)\n\nSee also\n\n* OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime"
},
{
"role": "assistant",
"content": "The first 10 take less than a quarter second. 11 through 13, a little under 30 seconds. Drops off a cliff after that.\n\n```\nsub useful ($n) {\n (|$n).map: {\n my $p = 1 +< ( 1 +< $_ );\n ^$p .first: ($p - *).is-prime\n }\n}\n\nput useful 1..10;\n\nput useful 11..13;\n\n```\n\nOutput:\n\n```\n1 3 5 15 5 59 159 189 569 105\n1557 2549 2439\n```"
}
]
|
[
{
"role": "user",
"content": "Given a weighted one-bit generator of random numbers where the probability of a one occurring,\n\nP\n\n1\n{\\displaystyle {\\displaystyle P\\_{1}}}\n\n, is not the same as\n\nP\n\n0\n{\\displaystyle {\\displaystyle P\\_{0}}}\n\n, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is\n\nP\n\n1\n{\\displaystyle {\\displaystyle P\\_{1}}}\n\nร\n\nP\n\n0\n{\\displaystyle {\\displaystyle P\\_{0}}}\n\n, assuming independence. This is the same as the probability of a zero followed by a one:\n\nP\n\n0\n{\\displaystyle {\\displaystyle P\\_{0}}}\n\nร\n\nP\n\n1\n{\\displaystyle {\\displaystyle P\\_{1}}}\n\n.\n\nTask details\n\n* Use your language's random number generator to create a function/method/subroutine/... **randN** that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function **unbiased** that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: Rakudo version 2020.08.1\n\n```\nsub randN ( $n where 3..6 ) {\n return ( $n.rand / ($n - 1) ).Int;\n}\n\nsub unbiased ( $n where 3..6 ) {\n my $n1;\n repeat { $n1 = randN($n) } until $n1ย != randN($n);\n return $n1;\n}\n\nmy $iterations = 1000;\nfor 3 .. 6 -> $n {\n my ( @raw, @fixed );\n for ^$iterations {\n @raw[ randN($n) ]++;\n @fixed[ unbiased($n) ]++;\n }\n printf \"N=%d randN: %s, %4.1f%% unbiased: %s, %4.1f%%\\n\",\n $n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;\n}\n\n```\n\nOutput:\n\n```\nN=3 randN: [676, 324], 32.4% unbiased: [517, 483], 48.3%\nN=4 randN: [734, 266], 26.6% unbiased: [489, 511], 51.1%\nN=5 randN: [792, 208], 20.8% unbiased: [494, 506], 50.6%\nN=6 randN: [834, 166], 16.6% unbiased: [514, 486], 48.6%\n```"
}
]
|
[
{
"role": "user",
"content": "For languages which have an explicit notion of an undefined value, identify and exercise those language's mechanisms for identifying and manipulating a variable's value's status as being undefined."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nRaku has \"interesting\" values of undef, but unlike Perl 5, doesn't actually have a value named undef. Instead, several very different meanings of undefinedness are distinguished. First, Nil represents the absence of a value. The absence of a value cannot be stored. Instead, an attempt to assign Nil to a storage location causes that location to revert to its uninitialized state, however that is defined.\n\n```\nmy $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()\n\n```\n\nThis Any is an example of another kind of undefined type, which is a typed undef. All reference types have an undefined value representing the type. You can think of it as a sort of \"type gluon\" that carries a type charge without being a \"real\" particle. Hence there are undefined values whose names represent types, such as Int, Num, Str, and all the other object types in Raku. As generic objects, such undefined values carry the same metaobject pointer that a real object of the type would have, without being instantiated as a real object. As such, these types are in the type hierarchy. For example, Int derives from Cool, Cool derives from Any, and Any derives from Mu, the most general undefined object (akin to Object in other languages). Since they are real objects of the type, even if undefined, they can be used in reasoning about the type. You don't have to instantiate a Method object in order to ask if Method is derived from Routine, for instance.\n\n```\nsay Method ~~ Routine; # Bool::True\n\n```\n\nVariables default to Any, unless declared to be of another type:\n\n```\nmy $x; say $x.WHAT; # Any()\nmy Int $y; say $y.WHAT; # Int()\nmy Str $z; say $z.WHAT; # Str()\n\n```\n\nThe user-interface for definedness are type smilies and the with-statement.\n\n```\nmy Int:D $i = 1; # if $i has to be defined you must provide a default value\nmulti sub foo(Int:D $i where *ย != 0){ (0..100).roll / $i } # we will never divide by 0\nmulti sub foo(Int:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly\n\nwith $i { say 'defined' } # as \"if\" is looking for Bool::True, \"with\" is looking for *.defined\nwith 0 { say '0 may not divide but it is defined' }\n\n```\n\nThere are further some operators for your convenience.\n\n```\nmy $is-defined = 1;\nmy $ain't-defined = Any;\nmy $doesn't-matter;\nmy Any:D $will-be-defined = $ain't-defined // $is-defined // $doesn't-matter;\n\nmy @a-mixed-list = Any, 1, Any, 'a';\n$will-be-defined = [//] @a-mixed-list; # [//] will return the first defined value\n\nmy @a = Any,Any,1,1;\nmy @b = 2,Any,Any,2;\nmy @may-contain-any = @a >>//<< @b; # contains: [2, Any, 1, 1]\n\nsub f1(){Failure.new('WELP!')};\nsub f2(){ $_ ~~ Failure }; # orelse will kindly set the topic for us\nmy $s = (f1() orelse f2()); # Please note the parentheses, which are needed because orelse is\n # much looser then infix:<=> .\ndd $s; # this be Bool::False\n\n```\n\nFinally, another major group of undefined values represents failures. Raku is designed with the notion that throwing exceptions is bad for parallel processing, so exceptions are thrown lazily; that is, they tend to be returned in-band instead as data, and are only thrown for real if not properly handled as exception data. (In which case, the exception is required to report the original difficulty accurately.) In order not to disrupt control flow and the synchronicity of event ordering, such failures are returned in-band as a normal values. And in order not to subvert the type system when it comes to return types, failure may be mixed into any reference type which produces an undefined, typed value which is also indicates the nature of the failure.\n\nNative storage types work under different rules, since most native types cannot represent failure, or even undefinedness. Any attempt to assign a value to a storage location that cannot represent a failure will cause an exception to be thrown."
}
]
|
[
{
"role": "user",
"content": "An **Undulating number** in some base is a number which has the digit form ABABAB... where A and B are digits in that base.\n\nFor the purposes of this task, we shall only consider a number to be undulating if it has at least 3 digits in a given base and Aย != B.\n\nExamples\n\nThe numbers: 101 and 9898 are undulating numbers in base 10.\n\nThe numbers: 50 and 2350 are undulating numbers in base 7 because their base 7 representations are: 101 and 6565 respectively.\n\nTask\n\nFor base 10, find and show on this page:\n\n1. All three digit undulating numbers.\n\n2. All four digit undulating numbers.\n\n3. All three digit undulating numbers which are primes.\n\n4. The 600th undulating number.\n\n5. How many undulating numbers are less than 2^53 and the largest such number.\n\nBonus\n\nDo the same for base 7 expressing the results in base 10 apart from 4. and 5. which should be expressed in base 7 also.\n\nNote that undulating numbers with a given number of digits in base 7 may, of course, have less digits when expressed in base 10 and are unlikely to be still undulating. However, 121 (or 232 in base 7) is an exception to this.\n\nReferences\n\n* Wikipedia article : Undulating number\n* OEIS sequence A046075: Non-trivial undulants"
},
{
"role": "assistant",
"content": "**Translation of**: Wren\n\n```\n# 20230602 Raku programming solution\n\nsub undulating ($base, \\n) {\n my \\limit = 2**(my \\mpow = 53) - 1;\n my (\\bsquare,@u3,@u4) = $base*$base; \n for 1..^$base X 0..^$base -> (\\a,\\b) {\n next if b == a;\n @u3.push(a * bsquare + b * $base + a);\n @u4.push((my \\v = a * $base + b) * bsquare + v)\n }\n say \"\\nAll 3 digit undulating numbers in base $base:\";\n .fmt('%3d').say for @u3.rotor: 9;\n say \"\\nAll 4 digit undulating numbers in base $base:\";\n .fmt('%4d').say for @u4.rotor: 9; \n say \"\\nAll 3 digit undulating numbers which are primes in base $base:\";\n my @primes = @u3.grep: *.is-prime; \n .fmt('%3d').say for @primes.rotor: 10,ย :partial;\n my \\unc = (my @un = @u3.append: @u4).elems;\n my ($j, $done) = 0, False;\n loop {\n for 0..^unc {\n my \\u = @un[$j * unc + $_] * bsquare + @un[$j * unc + $_]ย % bsquare;\n\t u > limitย ?? ( $done = True and last )ย !! ( @un.push: u );\n }\n $doneย ?? ( last )ย !! $j++ \n }\n say \"\\nThe {n} undulating number in $base $base is: @un[n-1]\";\n say \"or expressed in base $baseย : {@un[n-1].base($base)}\" unless $base == 10;\n say \"\\nTotal number of undulating numbers in base $base < 2**{mpow} = {+@un}\";\n say \"of which the largest is: \", @un[*-1];\n say \"or expressed in base $baseย : {@un[*-1].base($base)}\" unless $base == 10;\n}\n\nundulating $_, 600 for 10, 7;\n\n```\n\nYou may Try it online!"
}
]
|
[
{
"role": "user",
"content": "Within a string, an escape sequence gives special meaning to otherwise ordinary characters.\n\nFor example, in the C programming language, the string literal `\"a\\nb\"`, containing the escape sequence `\\n`, would be interpreted by the compiler as the bytes `61 0a 62`, not `61 5c 6e 62`.\n\nIn JavaScript Object Notation, the string value `\"a\\u263Ac\"`, containing the escape sequence `\\u263A`, would be parsed into `\"aโบc\"`.\n\nTask\n\nWrite a function (or routine, subroutine, procedure, etc.) that, when given a UTF-8 encoded string, returns a new string, also encoded in UTF-8, with all escape sequences replaced with equivalent Unicode code points.\n\nFor this task we'll follow JSON string semantics, defined in Section 7 of RFC 8259. In summary:\n\n* Allowed two-character escapes are `\\\\`, `\\\"`, `\\/`, `\\b`, `\\f`, `\\n`, `\\r`, `\\t`.\n* `\"`, `\\` and control characters (U+0000 through U+001F) must be escaped.\n* Any \"character\" in the Basic Multilingual Plane may be escaped with a `\\uXXXX` sequence, where `XXXX` are hexadecimal digits encoding the character's code point\n* Characters outside the Basic Multilingual Plane may be escaped with a `\\uXXXX\\uXXXX` sequence, where `XXXX` are hexadecimal digits encoding the code point using UTF-16.\n\nAlthough not required by RFC 8259, we'll treat strings containing invalid `\\u` escape sequences (those that can't be decoded to a Unicode code point) as an error condition.\n\nTest your program with the following inputs and display the string before and after unescaping. It's OK to display bytes rather than \"characters\" if it's more convenient for your language, or both, if you prefer.\n\nTest cases\n\n| Input string | Expected result | Comment |\n| --- | --- | --- |\n| `abc` | `abc` | No escape sequences |\n| `aโบc` | `aโบc` | No escape sequences, extended unicode |\n| `a\\\"c` | `a\"c` | Two-character escape |\n| `\\u0061\\u0062\\u0063` | `abc` | Just escape sequences |\n| `a\\\\c` | `a\\c` | Two-character escape for reverse solidus |\n| `a\\u263Ac` | `aโบc` | `\\u` escape, basic multilingual plane |\n| `a\\\\u263Ac` | `a\\u263Ac` | Escaped `\\` before `u` |\n| `a\\uD834\\uDD1Ec` | `a๐c` | `\\u` escape, surrogate pair |\n| `a\\ud834\\udd1ec` | `a๐c` | Lower case hex digits |\n| `a\\u263` | *error* | Incomplete escape sequence |\n| `a\\u263Xc` | *error* | Invalid hexadecimal digit |\n| `a\\uDD1Ec` | *error* | Lone low surrogate |\n| `a\\uD834c` | *error* | Lone high surrogate |\n| `a\\uD834\\u263Ac` | *error* | High surrogate followed by non-surrogate |\n\nRelated tasks\n\n* Literals/String\n* Special characters\n* UTF-8 encode and decode"
},
{
"role": "assistant",
"content": "Implement a JSON string unescape Grammar.\n\n```\n# 20240816 Raku programming solution\n\ngrammar JSON-Unescape {\n token TOP { ^ <value> $ }\n token value { [ <str> | \\\\ <str=.str_escape> ]* }\n token str { <-[\"\\\\\\t\\x[0A]]>+ }\n token str_escape { <[\"\\\\/bfnrt]> | 'u' <utf16_codepoint>+ย % '\\u' }\n token utf16_codepoint { <.xdigit>**4 }\n}\n\nclass JSON-Unescape-Actions {\n method TOP($/) { make $<value>.made }\n method str($/) { make ~$/ }\n method value($/) { make $<str>ยป.made.join }\n method str_escape($/) {\n make $<utf16_codepoint>.Bool \n ย ?? utf16.new( $<utf16_codepoint>.map({:16(~$_)}) ).decode()\n ย !!ย %(< \\\\ / b n t f r \" > Z=> < \\\\ / \\b \\n \\t \\f \\r \" >).{~$/}\n }\n}\n\nfor < abc aโบc a\\\"c \\u0061\\u0062\\u0063 a\\\\\\c a\\u263Ac a\\\\\\u263Ac\n a\\uD834\\uDD1Ec a\\ud834\\udd1ec a\"c a\\\\u263 a\\\\u263Xc \n a\\\\uDD1Ec a\\\\uD834c a\\\\uD834\\\\u263Ac > -> $input {\n printf \"%20s => \", $input;\n my $o = JSON-Unescape.parse($input, actions => JSON-Unescape-Actions.new).made;\n fail \"Invalid JSON string\" unless $o.defined;\n say $o;\n CATCH { default { say \"Error: $_\" } }\n}\n\n```\n\nYou may Attempt This Online!\n\nOutput:\n\n```\n abc => abc\n aโบc => aโบc\n a\\\"c => a\"c\n \\u0061\\u0062\\u0063 => abc\n a\\\\c => a\\c\n a\\u263Ac => aโบc\n a\\\\u263Ac => a\\u263Ac\n a\\uD834\\uDD1Ec => a๐c\n a\\ud834\\udd1ec => a๐c\n a\"c => Error: Invalid JSON string\n a\\u263 => Error: Invalid JSON string\n a\\u263Xc => Error: Invalid JSON string\n a\\uDD1Ec => Error: Malformed UTF-16; unexpected low surrogate\n a\\uD834c => Error: Malformed UTF-16; incomplete surrogate pair\n a\\uD834\\u263Ac => Error: Malformed UTF-16; incomplete surrogate pair\n```"
}
]
|
[
{
"role": "user",
"content": "As the world gets smaller each day, internationalization becomes more and more important. ย For handling multiple languages, Unicode is your best friend.\n\nIt is a very capable and remarquable tool, but also quite complex compared to older single- and double-byte character encodings.\n\nHow well prepared is your programming language for Unicode?\n\nTask\n\nDiscuss and demonstrate its unicode awareness and capabilities.\n\nSome suggested topics:\n\n: * How easy is it to present Unicode strings in source code?\n * Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n * How well can the language communicate with the rest of the world?\n * Is it good at input/output with Unicode?\n * Is it convenient to manipulate Unicode strings in the language?\n * How broad/deep does the language support Unicode?\n * What encodings (e.g. UTF-8, UTF-16, etc) can be used?\n * Does it support normalization?\n\nNote\n\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\nSee also\n\n* Unicode variable names\n* Terminal control/Display an extended character"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku programs and strings are all in Unicode and operate at a grapheme abstraction level, which is agnostic to underlying encodings. (These are generally handled at program boundaries.) Opened files default to UTF-8 encoding. All Unicode character properties are in play, so any appropriate characters may be used as parts of identifiers, whitespace, or user-defined operators. For instance:\n\n```\nsub prefix:<โ> (\\๐) { ๐ ** โ
}\nsay โ27; # prints 3\n\n```\n\nNon-Unicode strings are represented as Buf types rather than Str types, and Unicode operations may not be applied to Buf types without some kind of explicit conversion. Only ASCIIish operations are allowed on buffers.\n\nRaku tracks the Unicode consortium standards releases and is generally up to the latest standard within a few months or so of its release. (currently at 15.0 as of February 2023)\n\n* Supports the normalized forms NFC, NFD, NFKC, and NFKD, and character equivalence as specified in Unicode technical report #15.\n* Built-in routines provide access to character classifications (Letter, Numeric. White-space, etc) and sub-classifications: (Letter-lowercase, Letter-uppercase, Numeric-digit, etc.)\n* Allows users to use any Unicode character that has a Numeric property **as** that numeric value.\n* Provides Unicode aware upper-case, lower-case and fold-case routines.\n* Implements the Unicode technical standard #10 collation algorithm, (though not all optional mappings are supported yet).\n* Provides built-in routines to access character names, do name-to-character character-to-ordinal and ordinal-to-character conversions.\n* Works seamlessly with upper plane and private use plane character codepoints.\n* Provides tools to deal with strings that contain invalid Unicode characters.\n\nIn general, it tries to make dealing with Unicode \"just work\".\n\nRaku intends to support Unicode even better than Perl 5, which already does a great job in recent versions of accessing large swaths of Unicode spec. functionality. Raku improves on Perl 5 primarily by offering explicitly typed strings that always know which operations are sensical and which are not.\n\nA very important distinctive characteristic of Raku to keep in mind is that it applies normalization (Unicode NFC form (Normalization Form Canonical)) automatically by default to all strings as showcased and explained on the String comparison page."
}
]
|
[
{
"role": "user",
"content": "Task\n\n1. Describe, and give a pointer to documentation on your languages use of characters *beyond* those of the ASCII character set in the naming of variables.\n2. Show how to:\n\n: * Set a variable with a name including the 'ฮ', (delta *character*), to 1\n * Increment it\n * Print its value.\n\nRelated task\n\n* Case-sensitivity of identifiers"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nRaku is written in Unicode so, with narrow restrictions, nearly any Unicode letter can be used in identifiers.\n\nSee the current Raku documentation on the topic here: https://docs.raku.org/language/syntax#Identifiers\n\n```\nmy $ฮ = 1;\n$ฮ++;\nsay $ฮ;\n\n```\n\nFunction and subroutine names can also use Unicode characters: (as can methods, classes, packages, whatever...)\n\n```\nmy @แ = (0, 45, 60, 90);\n\nsub ฯ { pi };\n\nsub postfix:<ยฐ>($degrees) { $degrees * ฯ / 180 };\n\nfor @แ -> $เฒ _เฒ { say sin $เฒ _เฒ ยฐ };\n\nsub cออฬอฬฬฬฬฝhฬฅฬชออฃอฬaอจอฃฬอฦกฬฑอฬอฬฬฝศฬปฬฅอฌฬฬอฉ { 'HE COMES' }\n\n```\n\n**See Also:** \nEgyptian division"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven a list of strings, ย find characters appearing only in one string and once only.\n\nThe result should be given in alphabetical order.\n\nUse the following list for this task:\n\n```\n [\"133252abcdeeffd\", \"a6789798st\", \"yxcdfgxcyz\"]\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string ย (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff ย (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "One has to wonder where the digits 0 through 9 come in the alphabet... ๐ค For that matter, What alphabet should they be in order of? Most of these entries seem to presuppose ASCII order but that isn't specified anywhere. What to do with characters outside of ASCII (or Latin-1)? Unicode ordinal order? Or maybe DUCET Unicode collation order? It's all very vague.\n\n```\nmy @list = <133252abcdeeffd a6789798st yxcdfgxcyz>;\n\nfor @list, (@list, 'AะฮSรคaoรถูฅ๐ค๐จโ๐ฉโ๐งโ๐ง') {\n say \"$_\\nSemi-bogus \\\"Unicode natural sort\\\" order: \",\n .map( *.comb ).Bag.grep( *.value == 1 )ยป.key.sort( { .unival, .NFKD[0], .fc } ).join,\n \"\\n (DUCET) Unicode collation order: \",\n .map( *.comb ).Bag.grep( *.value == 1 )ยป.key.collate.join, \"\\n\";\n}\n\n```\n\nOutput:\n\n```\n133252abcdeeffd a6789798st yxcdfgxcyz\nSemi-bogus \"Unicode natural sort\" order: 156bgstz\n (DUCET) Unicode collation order: 156bgstz\n\n133252abcdeeffd a6789798st yxcdfgxcyz AะฮSรคaoรถูฅ๐ค๐จโ๐ฉโ๐งโ๐ง\nSemi-bogus \"Unicode natural sort\" order: 15ูฅ6ASรคbgoรถstzฮะ๐จโ๐ฉโ๐งโ๐ง๐ค\n (DUCET) Unicode collation order: ๐จโ๐ฉโ๐งโ๐ง๐ครค15ูฅ6AbรถgosStzฮะ\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven a list of strings, find the characters appearing exactly once in each string.\n\nThe result should be in alphabetical order.\n\nUse the following list for this task:\n\n```\n [\"1a3c52debeffd\", \"2b6178c97a938stf\", \"3ycxdb1fgxa2yz\"]\n\n```\n\nFor this list, the result would be:\n1 2 3 a b c\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string ย (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff ย (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "```\nmy $strings = <1a3c52debeffd 2b6178c97a938stf 3ycxdb1fgxa2yz>;\n\nput sort keys [โฉ] $strings.map: *.comb.Bag.grep: *.value == 1\n\n```\n\nOutput:\n\n```\n1 2 3 a b c\n```"
}
]
|
[
{
"role": "user",
"content": "Demonstrate any support for Unit testing built into the language implementation.\n\nSee https://en.wikipedia.org/wiki/Unit\\_testing and Test a function for more information.\n\nClearly state whether this support is internal, or external to the interpreter or compiler used."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nRaku does not really have a mechanism built into the compiler to do unit testing, (It **does** have design-by-contract capabilities built in, but that is more for run-time, not really for unit testing.) Raku, and Perl in general **does** have unit testing built into the community. The Test-Anything-Protocol was invented and developed specifically to do unit testing on the original version of Perl, is still heavily used for modern versions, and has become a major standard for unit testing in many different languages other than Perl.\n\nTesting is such a basic value in Raku, that a suite of unit tests **is** the language specification. As decreed by Larry Wall, the original author of Perl and the lead designer of Raku, anything that can pass \"roast\", the official Raku test suite, or at least majority portions of it, can call itself Raku.\n\nUnit testing tools are not built in to the base compiler. Basic tools are distributed with the compiler as loadable modules. Many more complex toolkits and test harnesses are available through the Raku ecosystem. In general, it is uncommon to include testing code in with run-time code; not unheard-of and not forbidden, but uncommon. Instead Raku modules by convention and community pressure tend to have a test suite that is automatically run when the module is installed. Again, there is no rule that a module that is released for public consumption **must** have a test suite, but the community tends to favour modules that have them and discourage/avoid those without."
}
]
|
[
{
"role": "user",
"content": "One of the foundational mathematical constructs behind computer science\nis the universal Turing Machine.\n\n(Alan Turing introduced the idea of such a machine in 1936โ1937.)\n\nIndeed one way to definitively prove that a language\nis turing-complete\nis to implement a universal Turing machine in it.\n\nTask\n\nSimulate such a machine capable\nof taking the definition of any other Turing machine and executing it.\n\nOf course, you will not have an infinite tape,\nbut you should emulate this as much as is possible.\n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language\nis Turing complete!), you should execute the following two Turing machines\nbased on the following definitions.\n\n**Simple incrementer**\n\n* **States:** q0, qf\n* **Initial state:** q0\n* **Terminating states:** qf\n* **Permissible symbols:** B, 1\n* **Blank symbol:** B\n* **Rules:**\n + (q0, 1, 1, right, q0)\n + (q0, B, 1, stay, qf)\n\nThe input for this machine should be a tape of `1 1 1`\n\n**Three-state busy beaver**\n\n* **States:** a, b, c, halt\n* **Initial state:** a\n* **Terminating states:** halt\n* **Permissible symbols:** 0, 1\n* **Blank symbol:** 0\n* **Rules:**\n + (a, 0, 1, right, b)\n + (a, 1, 1, left, c)\n + (b, 0, 1, left, a)\n + (b, 1, 1, right, b)\n + (c, 0, 1, left, b)\n + (c, 1, 1, stay, halt)\n\nThe input for this machine should be an empty tape.\n\n**Bonus:**\n\n**5-state, 2-symbol probable Busy Beaver machine from Wikipedia**\n\n* **States:** A, B, C, D, E, H\n* **Initial state:** A\n* **Terminating states:** H\n* **Permissible symbols:** 0, 1\n* **Blank symbol:** 0\n* **Rules:**\n + (A, 0, 1, right, B)\n + (A, 1, 1, left, C)\n + (B, 0, 1, right, C)\n + (B, 1, 1, right, B)\n + (C, 0, 1, right, D)\n + (C, 1, 0, left, E)\n + (D, 0, 1, left, A)\n + (D, 1, 1, left, D)\n + (E, 0, 1, stay, H)\n + (E, 1, 0, left, A)\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: Rakudo version 2018.03\n\n```\nsub run_utm(:$state! is copy,ย :$blank!,ย :@rules!,ย :@tape = [$blank],ย :$halt,ย :$pos is copy = 0) {\n $pos += @tape if $pos < 0;\n die \"Bad initial position\" unless $pos ~~ ^@tape;\n\nSTEP: loop {\n print \"$state\\t\";\n for ^@tape {\n my $v = @tape[$_];\n print $_ == $posย ?? \"[$v]\"ย !! \" $v \";\n }\n print \"\\n\";\n\n last if $state eq $halt;\n\n for @rules -> @rule {\n my ($s0, $v0, $v1, $dir, $s1) = @rule;\n next unless $s0 eq $state and @tape[$pos] eq $v0;\n\n @tape[$pos] = $v1;\n\n given $dir {\n when 'left' {\n if $pos == 0 { unshift @tape, $blank }\n else { $pos-- }\n }\n when 'right' {\n push @tape, $blank if ++$pos >= @tape;\n }\n }\n\n $state = $s1;\n next STEP;\n\n }\n die 'No matching rules';\n }\n\n}\n\nsay \"incr machine\";\nrun_utm\t:halt<qf>,\n ย :state<q0>,\n ย :tape[1,1,1],\n ย :blank<B>,\n :rules[\n [< q0 1 1 right q0 >],\n [< q0 B 1 stay qf >]\n ];\n\nsay \"\\nbusy beaver\";\nrun_utm :halt<halt>,\n ย :state<a>,\n :blank<0>,\n ย :rules[\n [< a 0 1 right b >],\n [< a 1 1 left c >],\n [< b 0 1 left a >],\n [< b 1 1 right b >],\n [< c 0 1 left b >],\n [< c 1 1 stay halt >]\n ];\n\nsay \"\\nsorting test\";\nrun_utmย :halt<STOP>,\n ย :state<A>,\n :blank<0>,\n ย :tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >],\n ย :rules[\n [< A 1 1 right A >],\n [< A 2 3 right B >],\n [< A 0 0 left E >],\n [< B 1 1 right B >],\n [< B 2 2 right B >],\n [< B 0 0 left C >],\n [< C 1 2 left D >],\n [< C 2 2 left C >],\n [< C 3 2 left E >],\n [< D 1 1 left D >],\n [< D 2 2 left D >],\n [< D 3 1 right A >],\n [< E 1 1 left E >],\n [< E 0 0 right STOP >]\n ];\n\n```\n\nOutput:\n\n```\nincr machine\nq0\t[1] 1 1\nq0\t 1 [1] 1\nq0\t 1 1 [1]\nq0\t 1 1 1 [B]\nqf\t 1 1 1 [1]\n\nbusy beaver\na\t[0]\nb\t 1 [0]\na\t[1] 1\nc\t[0] 1 1\nb\t[0] 1 1 1\na\t[0] 1 1 1 1\nb\t 1 [1] 1 1 1\nb\t 1 1 [1] 1 1\nb\t 1 1 1 [1] 1\nb\t 1 1 1 1 [1]\nb\t 1 1 1 1 1 [0]\na\t 1 1 1 1 [1] 1\nc\t 1 1 1 [1] 1 1\nhalt\t 1 1 1 [1] 1 1\n\nsorting test\nA\t[2] 2 2 1 2 2 1 2 1 2 1 2 1 2\nB\t 3 [2] 2 1 2 2 1 2 1 2 1 2 1 2\nB\t 3 2 [2] 1 2 2 1 2 1 2 1 2 1 2\nB\t 3 2 2 [1] 2 2 1 2 1 2 1 2 1 2\nB\t 3 2 2 1 [2] 2 1 2 1 2 1 2 1 2\nB\t 3 2 2 1 2 [2] 1 2 1 2 1 2 1 2\nB\t 3 2 2 1 2 2 [1] 2 1 2 1 2 1 2\nB\t 3 2 2 1 2 2 1 [2] 1 2 1 2 1 2\nB\t 3 2 2 1 2 2 1 2 [1] 2 1 2 1 2\nB\t 3 2 2 1 2 2 1 2 1 [2] 1 2 1 2\nB\t 3 2 2 1 2 2 1 2 1 2 [1] 2 1 2\nB\t 3 2 2 1 2 2 1 2 1 2 1 [2] 1 2\nB\t 3 2 2 1 2 2 1 2 1 2 1 2 [1] 2\nB\t 3 2 2 1 2 2 1 2 1 2 1 2 1 [2]\nB\t 3 2 2 1 2 2 1 2 1 2 1 2 1 2 [0]\nC\t 3 2 2 1 2 2 1 2 1 2 1 2 1 [2] 0\nC\t 3 2 2 1 2 2 1 2 1 2 1 2 [1] 2 0\nD\t 3 2 2 1 2 2 1 2 1 2 1 [2] 2 2 0\nD\t 3 2 2 1 2 2 1 2 1 2 [1] 2 2 2 0\nD\t 3 2 2 1 2 2 1 2 1 [2] 1 2 2 2 0\nD\t 3 2 2 1 2 2 1 2 [1] 2 1 2 2 2 0\nD\t 3 2 2 1 2 2 1 [2] 1 2 1 2 2 2 0\nD\t 3 2 2 1 2 2 [1] 2 1 2 1 2 2 2 0\nD\t 3 2 2 1 2 [2] 1 2 1 2 1 2 2 2 0\nD\t 3 2 2 1 [2] 2 1 2 1 2 1 2 2 2 0\nD\t 3 2 2 [1] 2 2 1 2 1 2 1 2 2 2 0\nD\t 3 2 [2] 1 2 2 1 2 1 2 1 2 2 2 0\nD\t 3 [2] 2 1 2 2 1 2 1 2 1 2 2 2 0\nD\t[3] 2 2 1 2 2 1 2 1 2 1 2 2 2 0\nA\t 1 [2] 2 1 2 2 1 2 1 2 1 2 2 2 0\nB\t 1 3 [2] 1 2 2 1 2 1 2 1 2 2 2 0\nB\t 1 3 2 [1] 2 2 1 2 1 2 1 2 2 2 0\nB\t 1 3 2 1 [2] 2 1 2 1 2 1 2 2 2 0\nB\t 1 3 2 1 2 [2] 1 2 1 2 1 2 2 2 0\nB\t 1 3 2 1 2 2 [1] 2 1 2 1 2 2 2 0\nB\t 1 3 2 1 2 2 1 [2] 1 2 1 2 2 2 0\nB\t 1 3 2 1 2 2 1 2 [1] 2 1 2 2 2 0\nB\t 1 3 2 1 2 2 1 2 1 [2] 1 2 2 2 0\nB\t 1 3 2 1 2 2 1 2 1 2 [1] 2 2 2 0\nB\t 1 3 2 1 2 2 1 2 1 2 1 [2] 2 2 0\nB\t 1 3 2 1 2 2 1 2 1 2 1 2 [2] 2 0\nB\t 1 3 2 1 2 2 1 2 1 2 1 2 2 [2] 0\nB\t 1 3 2 1 2 2 1 2 1 2 1 2 2 2 [0]\nC\t 1 3 2 1 2 2 1 2 1 2 1 2 2 [2] 0\nC\t 1 3 2 1 2 2 1 2 1 2 1 2 [2] 2 0\nC\t 1 3 2 1 2 2 1 2 1 2 1 [2] 2 2 0\nC\t 1 3 2 1 2 2 1 2 1 2 [1] 2 2 2 0\nD\t 1 3 2 1 2 2 1 2 1 [2] 2 2 2 2 0\nD\t 1 3 2 1 2 2 1 2 [1] 2 2 2 2 2 0\nD\t 1 3 2 1 2 2 1 [2] 1 2 2 2 2 2 0\nD\t 1 3 2 1 2 2 [1] 2 1 2 2 2 2 2 0\nD\t 1 3 2 1 2 [2] 1 2 1 2 2 2 2 2 0\nD\t 1 3 2 1 [2] 2 1 2 1 2 2 2 2 2 0\nD\t 1 3 2 [1] 2 2 1 2 1 2 2 2 2 2 0\nD\t 1 3 [2] 1 2 2 1 2 1 2 2 2 2 2 0\nD\t 1 [3] 2 1 2 2 1 2 1 2 2 2 2 2 0\nA\t 1 1 [2] 1 2 2 1 2 1 2 2 2 2 2 0\nB\t 1 1 3 [1] 2 2 1 2 1 2 2 2 2 2 0\nB\t 1 1 3 1 [2] 2 1 2 1 2 2 2 2 2 0\nB\t 1 1 3 1 2 [2] 1 2 1 2 2 2 2 2 0\nB\t 1 1 3 1 2 2 [1] 2 1 2 2 2 2 2 0\nB\t 1 1 3 1 2 2 1 [2] 1 2 2 2 2 2 0\nB\t 1 1 3 1 2 2 1 2 [1] 2 2 2 2 2 0\nB\t 1 1 3 1 2 2 1 2 1 [2] 2 2 2 2 0\nB\t 1 1 3 1 2 2 1 2 1 2 [2] 2 2 2 0\nB\t 1 1 3 1 2 2 1 2 1 2 2 [2] 2 2 0\nB\t 1 1 3 1 2 2 1 2 1 2 2 2 [2] 2 0\nB\t 1 1 3 1 2 2 1 2 1 2 2 2 2 [2] 0\nB\t 1 1 3 1 2 2 1 2 1 2 2 2 2 2 [0]\nC\t 1 1 3 1 2 2 1 2 1 2 2 2 2 [2] 0\nC\t 1 1 3 1 2 2 1 2 1 2 2 2 [2] 2 0\nC\t 1 1 3 1 2 2 1 2 1 2 2 [2] 2 2 0\nC\t 1 1 3 1 2 2 1 2 1 2 [2] 2 2 2 0\nC\t 1 1 3 1 2 2 1 2 1 [2] 2 2 2 2 0\nC\t 1 1 3 1 2 2 1 2 [1] 2 2 2 2 2 0\nD\t 1 1 3 1 2 2 1 [2] 2 2 2 2 2 2 0\nD\t 1 1 3 1 2 2 [1] 2 2 2 2 2 2 2 0\nD\t 1 1 3 1 2 [2] 1 2 2 2 2 2 2 2 0\nD\t 1 1 3 1 [2] 2 1 2 2 2 2 2 2 2 0\nD\t 1 1 3 [1] 2 2 1 2 2 2 2 2 2 2 0\nD\t 1 1 [3] 1 2 2 1 2 2 2 2 2 2 2 0\nA\t 1 1 1 [1] 2 2 1 2 2 2 2 2 2 2 0\nA\t 1 1 1 1 [2] 2 1 2 2 2 2 2 2 2 0\nB\t 1 1 1 1 3 [2] 1 2 2 2 2 2 2 2 0\nB\t 1 1 1 1 3 2 [1] 2 2 2 2 2 2 2 0\nB\t 1 1 1 1 3 2 1 [2] 2 2 2 2 2 2 0\nB\t 1 1 1 1 3 2 1 2 [2] 2 2 2 2 2 0\nB\t 1 1 1 1 3 2 1 2 2 [2] 2 2 2 2 0\nB\t 1 1 1 1 3 2 1 2 2 2 [2] 2 2 2 0\nB\t 1 1 1 1 3 2 1 2 2 2 2 [2] 2 2 0\nB\t 1 1 1 1 3 2 1 2 2 2 2 2 [2] 2 0\nB\t 1 1 1 1 3 2 1 2 2 2 2 2 2 [2] 0\nB\t 1 1 1 1 3 2 1 2 2 2 2 2 2 2 [0]\nC\t 1 1 1 1 3 2 1 2 2 2 2 2 2 [2] 0\nC\t 1 1 1 1 3 2 1 2 2 2 2 2 [2] 2 0\nC\t 1 1 1 1 3 2 1 2 2 2 2 [2] 2 2 0\nC\t 1 1 1 1 3 2 1 2 2 2 [2] 2 2 2 0\nC\t 1 1 1 1 3 2 1 2 2 [2] 2 2 2 2 0\nC\t 1 1 1 1 3 2 1 2 [2] 2 2 2 2 2 0\nC\t 1 1 1 1 3 2 1 [2] 2 2 2 2 2 2 0\nC\t 1 1 1 1 3 2 [1] 2 2 2 2 2 2 2 0\nD\t 1 1 1 1 3 [2] 2 2 2 2 2 2 2 2 0\nD\t 1 1 1 1 [3] 2 2 2 2 2 2 2 2 2 0\nA\t 1 1 1 1 1 [2] 2 2 2 2 2 2 2 2 0\nB\t 1 1 1 1 1 3 [2] 2 2 2 2 2 2 2 0\nB\t 1 1 1 1 1 3 2 [2] 2 2 2 2 2 2 0\nB\t 1 1 1 1 1 3 2 2 [2] 2 2 2 2 2 0\nB\t 1 1 1 1 1 3 2 2 2 [2] 2 2 2 2 0\nB\t 1 1 1 1 1 3 2 2 2 2 [2] 2 2 2 0\nB\t 1 1 1 1 1 3 2 2 2 2 2 [2] 2 2 0\nB\t 1 1 1 1 1 3 2 2 2 2 2 2 [2] 2 0\nB\t 1 1 1 1 1 3 2 2 2 2 2 2 2 [2] 0\nB\t 1 1 1 1 1 3 2 2 2 2 2 2 2 2 [0]\nC\t 1 1 1 1 1 3 2 2 2 2 2 2 2 [2] 0\nC\t 1 1 1 1 1 3 2 2 2 2 2 2 [2] 2 0\nC\t 1 1 1 1 1 3 2 2 2 2 2 [2] 2 2 0\nC\t 1 1 1 1 1 3 2 2 2 2 [2] 2 2 2 0\nC\t 1 1 1 1 1 3 2 2 2 [2] 2 2 2 2 0\nC\t 1 1 1 1 1 3 2 2 [2] 2 2 2 2 2 0\nC\t 1 1 1 1 1 3 2 [2] 2 2 2 2 2 2 0\nC\t 1 1 1 1 1 3 [2] 2 2 2 2 2 2 2 0\nC\t 1 1 1 1 1 [3] 2 2 2 2 2 2 2 2 0\nE\t 1 1 1 1 [1] 2 2 2 2 2 2 2 2 2 0\nE\t 1 1 1 [1] 1 2 2 2 2 2 2 2 2 2 0\nE\t 1 1 [1] 1 1 2 2 2 2 2 2 2 2 2 0\nE\t 1 [1] 1 1 1 2 2 2 2 2 2 2 2 2 0\nE\t[1] 1 1 1 1 2 2 2 2 2 2 2 2 2 0\nE\t[0] 1 1 1 1 1 2 2 2 2 2 2 2 2 2 0\nSTOP\t 0 [1] 1 1 1 1 2 2 2 2 2 2 2 2 2 0\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program that will list everything in the current folder, ย similar to:\n\n: : : * the Unix utility ย โlsโ ย [1] ย ย ย or\n * the Windows terminal command ย โDIRโ\n\nThe output must be sorted, but printing extended details and producing multi-column output is not required.\n\nExample output\n\nFor the list of paths:\n\n```\n/foo/bar\n/foo/bar/1\n/foo/bar/2\n/foo/bar/a\n/foo/bar/b\n\n```\n\nWhen the program is executed in ย `/foo`, ย it should print:\n\n```\nbar\n\n```\n\nand when the program is executed in ย `/foo/bar`, ย it should print:\n\n```\n1\n2\na\nb\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThere is a dir builtin command which returns a list of IO::Path objects. We stringify them all with a hyperoperator before sorting the strings.\n\n```\n.say for sort ~ยซdir\n\n```"
}
]
|
[
{
"role": "user",
"content": "Definitions\n\nAs used here, all unprimeable numbers ย (positive integers) ย are always expressed in base ten.\n\nโโโโโ Definition from OEIS โโโโโ:\n \nUnprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed.\n\nโโโโโ Definition from Wiktionary ย (referenced from Adam Spencer's book) โโโโโ:\n \n(*arithmetic*) ย that cannot be turned into a prime number by changing just one of its digits to any other\ndigit. ย (sic)\n\n**Unprimeable** numbers are also spelled: ย **unprimable**.\n\nAll oneโ and twoโdigit numbers can be turned into primes by changing a single decimal digit.\n\nExamples\n\n**190** ย isn't unprimeable, ย because by changing the zero digit into a three yields ย **193**, ย which is a prime.\n\nThe number ย **200** ย is unprimeable, ย since none of the numbers ย **201, 202, 203, ยทยทยท 209** ย are\nprime, and all the other numbers obtained by changing a single digit to\nproduce ย **100, 300, 400, ยทยทยท 900**, ย or ย **210, 220, 230, ยทยทยท 290** ย which are all even.\n\nIt is valid to change ย **189** ย into ย **089** ย by changing the ย **1** ย (one) ย into\na ย **0** ย (zero), ย which then the leading zero can be removed, ย and then treated as if\nthe ย \"new\" ย number is ย **89**.\n\nTask\n: : * show the first ย **35** ย unprimeable numbers ย (horizontally, on one line, preferably with a title)\n * show the ย **600th** ย unprimeable number\n * (optional) show the lowest unprimeable number ending in a specific decimal digit ย (**0, 1, 2, 3, 4, 5, 6, 7, 8, 9**)\n * (optional) use commas in the numbers where appropriate\n\nShow all output here, on this page.\n\nAlso see\n: * the ย ย OEIS ย ย entry: ย A118118 (unprimeable)\n * with some useful counts to compare unprimeable number\n * the Wiktionary entry (reference from below): ย (arithmetic definition) unprimeable\n * from the Adam Spencer book ย (page 200): ย *Adam Spencer's World of Numbers* ย ย ย (Xoum Publishing)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Library:** ntheory\n\n```\nuse ntheory:from<Perl5> <is_prime>;\nuse Lingua::EN::Numbers;\n\nsub is-unprimeable (\\n) {\n return False if n.&is_prime;\n my \\chrs = n.chars;\n for ^chrs -> \\place {\n my \\pow = 10**(chrs - place - 1);\n my \\this = n.substr(place, 1) ร pow;\n ^10 .map: -> \\dgt {\n next if this == dgt;\n return False if is_prime(n - this + dgt ร pow)\n }\n }\n True\n}\n\nmy @ups = lazy ^โ .grep: { .&is-unprimeable };\n\nsay \"First 35 unprimeables:\\n\" ~ @ups[^35];\n\nsay \"\\n{ordinal-digit(600, :u)} unprimeable: \" ~ comma( @ups[599] ) ~ \"\\n\";\n\n^10 .map: -> \\n {\n print \"First unprimeable that ends with {n}: \" ~\n sprintf \"%9s\\n\", comma (n, *+10 โฆ *).race.first: { .&is-unprimeable }\n}\n\n```\n\nOutput:\n\n```\nFirst 35 unprimeables:\n200 204 206 208 320 322 324 325 326 328 510 512 514 515 516 518 530 532 534 535 536 538 620 622 624 625 626 628 840 842 844 845 846 848 890\n\n600แตสฐ unprimeable: 5,242\n\nFirst unprimeable that ends with 0: 200\nFirst unprimeable that ends with 1: 595,631\nFirst unprimeable that ends with 2: 322\nFirst unprimeable that ends with 3: 1,203,623\nFirst unprimeable that ends with 4: 204\nFirst unprimeable that ends with 5: 325\nFirst unprimeable that ends with 6: 206\nFirst unprimeable that ends with 7: 872,897\nFirst unprimeable that ends with 8: 208\nFirst unprimeable that ends with 9: 212,159\n```"
}
]
|
[
{
"role": "user",
"content": "Definitions\n: * *Untouchable numbers* ย are also known as ย *nonaliquot numbers*.\n\n: * An ย untouchable number ย is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer. ย (From Wikipedia)\n\n: * The ย *sum of all the proper divisors* ย is also known as ย the ย *aliquot sum*.\n\n: * An ย untouchable ย are those numbers that are not in the image of the aliquot sum function. ย (From Wikipedia)\n\n: * Untouchable numbers: ย impossible values for the sum of all aliquot parts function. ย (From OEIS: ย The On-line Encyclopedia of Integer Sequencesยฎ)\n\n: * An untouchable number is a positive integer that is not the sum of the proper divisors of any number. ย (From MathWorldโข)\n\nObservations and conjectures\n\nAll untouchable numbers ย >ย **5**ย are composite numbers.\n\nNo untouchable number is perfect.\n\nNo untouchable number is sociable.\n\nNo untouchable number is a Mersenne prime.\n\nNo untouchable number is ย one more ย than a prime number, ย since if ย **p** ย is prime, ย then\nthe sum of the proper divisors of ย **p2** ย isย ย **pย +ย 1**.\n\nNo untouchable number is ย three more ย than an odd prime number, ย since if ย **p** ย is an odd prime, ย then the\nsum of the proper divisors of ย **2p** ย isย ย **pย +ย 3**.\n\nThe number ย **5**ย is believed to be the only odd untouchable number, ย but this has not been proven: ย it would follow from a\nslightly stronger version of the ย Goldbach'sย conjecture, ย since the sum of the\nproper divisors of ย **pq** ย (with ย **p**, **q** ย being\ndistinct primes) ย isย ย **1ย +ย pย +ย q**.\n\nThere are infinitely many untouchable numbers, ย a fact that was proven\nby ย Paul Erdลs.\n\nAccording to Chen & Zhao, ย their natural density is at least ย **d > 0.06**.\n\nTask\n: * show ย (in a grid format)ย all untouchable numbers ย โคย 2,000.\n * show (for the above) ย the ย *count* ย of untouchable numbers.\n * show the ย *count* ย of untouchable numbers from unity up to ย (inclusive):\n\n : : : * 10\n * 100\n * 1,000\n * 10,000\n * 100,000\n * ... or as high as is you think is practical.\n\n * all output is to be shown here, on this page.\n\nSee also\n: * Wolfram MathWorld: ย untouchable number.\n * OEIS: ย A005114 untouchable numbers.\n * OEIS: ย a list of all untouchable numbers below 100,000 ย (inclusive).\n * Wikipedia: untouchable number.\n * Wikipedia: Goldbach's conjecture."
},
{
"role": "assistant",
"content": "Borrow the proper divisors routine from here.\n\n**Translation of**: Wren\n\n```\n# 20210220 Raku programming solution\n\nsub propdiv (\\x) {\n my @l = 1 if x > 1;\n (2 .. x.sqrt.floor).map: -> \\d {\n unless xย % d { @l.push: d; my \\y = x div d; @l.push: y if yย != d }\n }\n @l\n}\n\nsub sieve (\\n) {\n my %s;\n for (0..(n+1)) -> \\k {\n given ( [+] propdiv k ) { %s{$_} = True if $_ โค (n+1) }\n }\n %s;\n}\n\nmy \\limit = 1e5;\nmy %c = ( grep {ย !.is-prime }, 1..limit ).Set; # store composites\nmy %s = sieve(14 * limit);\nmy @untouchable = 2, 5;\n\nloop ( my \\n = $ = 6ย ; n โค limitย ; n += 2 ) {\n @untouchable.append(n) if (!%s{n} && %c{n-1} && %c{n-3})\n}\n\nmy ($c, $last) = 0, False; \nfor @untouchable.rotor(10) { \n say [~] @_ยป.&{$c++ย ; $_ > 2000ย ?? ( $last = True and last )ย !! .fmt: \"%6d \"}\n $c-- and last if $last\n}\n\nsay \"\\nList of untouchable numbers โค 2,000ย : $c \\n\"; \n\nmy ($p, $count) = 10,0;\nBREAK: for @untouchable -> \\n {\n $count++;\n if (n > $p) {\n printf \"%6d untouchable numbers were found โค %7d\\n\", $count-1, $p;\n last BREAK if limit == ($p *= 10)\n }\n}\nprintf \"%6d untouchable numbers were found โค %7d\\n\", +@untouchable, limit\n\n```\n\nOutput:\n\n```\n 2 5 52 88 96 120 124 146 162 188\n 206 210 216 238 246 248 262 268 276 288\n 290 292 304 306 322 324 326 336 342 372\n 406 408 426 430 448 472 474 498 516 518\n 520 530 540 552 556 562 576 584 612 624\n 626 628 658 668 670 708 714 718 726 732\n 738 748 750 756 766 768 782 784 792 802\n 804 818 836 848 852 872 892 894 896 898\n 902 926 934 936 964 966 976 982 996 1002\n 1028 1044 1046 1060 1068 1074 1078 1080 1102 1116\n 1128 1134 1146 1148 1150 1160 1162 1168 1180 1186\n 1192 1200 1212 1222 1236 1246 1248 1254 1256 1258\n 1266 1272 1288 1296 1312 1314 1316 1318 1326 1332\n 1342 1346 1348 1360 1380 1388 1398 1404 1406 1418\n 1420 1422 1438 1476 1506 1508 1510 1522 1528 1538\n 1542 1566 1578 1588 1596 1632 1642 1650 1680 1682\n 1692 1716 1718 1728 1732 1746 1758 1766 1774 1776\n 1806 1816 1820 1822 1830 1838 1840 1842 1844 1852\n 1860 1866 1884 1888 1894 1896 1920 1922 1944 1956\n 1958 1960 1962 1972 1986 1992\n\nList of untouchable numbers โค 2,000ย : 196\n\n 2 untouchable numbers were found โค 10\n 5 untouchable numbers were found โค 100\n 89 untouchable numbers were found โค 1000\n 1212 untouchable numbers were found โค 10000\n 13863 untouchable numbers were found โค 100000\n\n```"
}
]
|
[
{
"role": "user",
"content": "Sometimes it is useful to run code with inputs from untrusted users, untrusted code, etc. Explain and demonstrate the features your language uses for dealing with untrusted input and untrusted code. Explain possible compromises, weaknesses and exploits that may be available through the language (for example forcing execution of something outside of the application) as a result of using untrusted data sources.\n\nThe intention is that the definition is to be interpreted broadly; different languages will solve this task in very different ways and with (generally) incomparable results."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\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.\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": "Goal\n\nConvert UPC bar codes to decimal.\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards...\n\nHere, ย in this task, ย we will focus on some of the data format standards, ย with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII ย (with spaces and ย **#** ย characters representing the presence or absence of ink).\n\nSample input\n\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n```\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\n```\n\nSome of these were entered upside down, ย and one entry has a timing error.\n\nTask\n\nImplement code to find the corresponding decimal representation of each, rejecting the error.\n\nExtra credit for handling the rows entered upside down ย (the other option is to reject them).\n\nNotes\n\nEach digit is represented by 7 bits:\n\n```\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\n```\n\nOn the left hand side of the bar code a space represents a **0** and a **#** represents a **1**.\n \nOn the right hand side of the bar code, a **#** represents a **0** and a space represents a **1**\n \nAlternatively (for the above): ย spaces always represent zeros and **#** characters always represent ones, but the representation is logically negated -- **1**s and **0**s are flipped -- on the right hand side of the bar code.\n\nThe UPC-A bar code structure\n: : * It begins with at least 9 spaces ย (which our imaginary bar code reader unfortunately doesn't always reproduce properly),\n * then has a ย ย **# #** ย ย sequence marking the start of the sequence,\n * then has the six \"left hand\" digits,\n * then has a ย **# #** ย sequence in the middle,\n * then has the six \"right hand digits\",\n * then has another ย **# #** ย (end sequence), ย and finally,\n * then ends with nine trailing spaces ย (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\nFinally, the last digit is a checksum digit which may be used to help detect errors.\n\nVerification\n\nMultiply each digit in the represented 12 digit sequence by the corresponding number in ย (3,1,3,1,3,1,3,1,3,1,3,1) ย and add the products.\n\nThe sum (mod 10) must be **0** ย (must have a zero as its last digit) ย if the UPC number has been read correctly."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub decode_UPC ( Str $line ) {\n constant @patterns1 = ' ## #', ' ## #', ' # ##', ' #### #', ' # ##',\n ' ## #', ' # ####', ' ### ##', ' ## ###', ' # ##';\n constant @patterns2 = @patterns1ยป.trans( '#' => ' ', ' ' => '#' );\n\n constant %pattern_to_digit_1 = @patterns1.antipairs;\n constant %pattern_to_digit_2 = @patterns2.antipairs;\n\n constant $re = / ^ '# #' (@patterns1) ** 6\n ' # # ' (@patterns2) ** 6\n '# #' $ /;\n\n $line.trim ~~ $re\n orelse return;\n\n my @digits = flat %pattern_to_digit_1{ $0ยป.Str },\n %pattern_to_digit_2{ $1ยป.Str };\n\n return unless ( @digits Z* ( |(3,1) xx * ) ).sumย %% 10;\n\n return @digits.join;\n}\n\nmy @lines =\n ' # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ',\n ' # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ',\n ' # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ',\n ' # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ',\n ' # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ',\n ' # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ',\n ' # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ',\n ' # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ',\n ' # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ',\n ' # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ',\n;\nfor @lines -> $line {\n say decode_UPC($line)\n // decode_UPC($line.flip)\n // 'Invalid';\n}\n\n```\n\nOutput:\n\n```\n924773271019\n403944441050\n834999676706\n939825158811\nInvalid\n316313718717\n214575875608\n818778841813\n706466743030\n653483540435\n```"
}
]
|
[
{
"role": "user",
"content": "We have a configuration file as follows:\n\n```\n# This is a configuration file in standard configuration file format\n#\n# Lines begininning with a hash or a semicolon are ignored by the application\n# program. Blank lines are also ignored by the application program.\n\n# The first word on each non comment line is the configuration option.\n# Remaining words or numbers on the line are configuration parameter\n# data fields.\n\n# Note that configuration option names are not case sensitive. However,\n# configuration parameter data is case sensitive and the lettercase must\n# be preserved.\n\n# This is a favourite fruit\nFAVOURITEFRUIT banana\n\n# This is a boolean that should be set\nNEEDSPEELING\n\n# This boolean is commented out\n; SEEDSREMOVED\n\n# How many bananas we have\nNUMBEROFBANANAS 48\n\n```\n\nThe task is to manipulate the configuration file as follows:\n\n* Disable the needspeeling option (using a semicolon prefix)\n* Enable the seedsremoved option by removing the semicolon and any leading whitespace\n* Change the numberofbananas parameter to 1024\n* Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000\n\nNote that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case.\n\nOptions should always be disabled by prefixing them with a semicolon.\n\nLines beginning with hash symbols should not be manipulated and left unchanged in the revised file.\n\nIf a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry.\n\nFor the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.)\n\nThe update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons).\n\nAny lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single\nspace, and any non-ASCII extended characters, tabs characters, or control codes\n(other than end of line markers), should also be removed.\n\nRelated tasks\n\n* Read a configuration file"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nImplemented as a command-line script which can make arbitrary in-place updates to such config files.\n\nAssuming that the script is saved as conf-update and the config file as test.cfg, the four changes required by the task description could be performed with the command:\n\n```\nconf-update --/needspeeling --seedsremoved --numberofbananas=1024 --numberofstrawberries=62000 test.cfg\n```\n\nThe script:\n\n```\nuse File::Temp;\n\nmy ($tmpfile, $out) = tempfile;\n\nsub MAIN ($file, *%changes) {\n %changes.=map({; .key.uc => .value });\n my %seen;\n\n for $file.IO.lines {\n when /:s ^ ('#' .* | '') $/ {\n say $out: ~$0;\n }\n when /:s ^ (';'+)? [(\\w+) (\\w+)?]? $/ {\n next ifย !$1 or %seen{$1.uc}++;\n my $new = %changes{$1.uc}:delete;\n say $out: format-line $1, |(ย !defined($new) ย ?? ($2,ย !$0) ย !!\n $new ~~ Bool ย ?? ($2, $new)ย !! ($new, True) );\n }\n default {\n note \"Malformed line: $_\\nAborting.\";\n exit 1;\n }\n }\n\n say $out: format-line .key, |(.value ~~ Boolย ?? (Nil, .value)ย !! (.value, True))\n for %changes;\n\n $out.close;\n\n copy $tmpfile, $file;\n}\n\nsub format-line ($key, $value, $enabled) {\n (\"; \" ifย !$enabled) ~ $key.uc ~ (\" $value\" if defined $value);\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "An upside-down number is a positive base 10 integer whose ***i***-th leftmost and ***i***-th rightmost digits are complements, i.e., their sum is 10.\n\nFor example\n\n```\n 7165493 is an upside-down number.\n 7 + 3 = 10\n 1 + 9 = 10\n 6 + 4 = 10\n 5 + 5 = 10\n\n```\n\nFrom that definition it follows that an upside-down number cannot contain any zeros, and if there is an odd number of digits, then the center digit must be a 5.\n\nTask\n\n* Write a routine to find (or generate) upside-down numbers.\n* Find and show the first 50 upside-down numbers.\n* Find and show the five hundredth upside-down number.\n* Find and show the five thousandth upside-down number.\n\nStretch\n\n* Find and show the fifty thousandth, five hundred thousandth, five millionth upside-down number.\n\nSee also\n\n* Numbers-A-Plenty: Upside-down number * OEIS:A299539 - Upside-down numbers"
},
{
"role": "assistant",
"content": "```\nuse Lingua::EN::Numbers;\n\nsub udgen (@r) {\n my @u = @r.hyper.map: { next if .contains: 0; ($_, (10 ยซ-ยซย .flip.comb).join) };\n @uยป.join, @uยป.join(5)\n}\n\nmy @upside-downs = lazy flat 5, (^โ).map({ udgen exp($_,10) .. exp(1+$_,10) });\n\nsay \"First fifty upside-downs:\\n\" ~ @upside-downs[^50].batch(10)ยป.fmt(\"%4d\").join: \"\\n\";\n\nsay '';\n\nfor 5e2, 5e3, 5e4, 5e5, 5e6 {\n say \"{.Int.&ordinal.tc}: \" ~ comma @upside-downs[$_-1]\n}\n\n```\n\nOutput:\n\n```\nFirst fifty upside-downs:\n 5 19 28 37 46 55 64 73 82 91\n 159 258 357 456 555 654 753 852 951 1199\n1289 1379 1469 1559 1649 1739 1829 1919 2198 2288\n2378 2468 2558 2648 2738 2828 2918 3197 3287 3377\n3467 3557 3647 3737 3827 3917 4196 4286 4376 4466\n\nFive hundredth: 494,616\nFive thousandth: 56,546,545\nFifty thousandth: 6,441,469,664\nFive hundred thousandth: 729,664,644,183\nFive millionth: 82,485,246,852,682\n```"
}
]
|
[
{
"role": "user",
"content": "This task ย (the reverse of ย URL encoding ย and distinct from ย URL parser) ย is to provide a function\nor mechanism to convert an URL-encoded string into its original unencoded form.\n\nTest cases\n\n* The encoded string ย \"`http%3A%2F%2Ffoo%20bar%2F`\" ย should be reverted to the unencoded form ย \"`http://foo bar/`\".\n\n* The encoded string ย \"`google.com/search?q=%60Abdu%27l-Bah%C3%A1`\" ย should revert to the unencoded form ย \"`google.com/search?q=`Abdu'l-Bahรก`\".\n\n* The encoded string ย \"`%25%32%35`\" ย should revert to the unencoded form ย \"`%25`\" and **not** \"`%`\"."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy @urls = < http%3A%2F%2Ffoo%20bar%2F\n google.com/search?q=%60Abdu%27l-Bah%C3%A1 >;\n\nsay .subst( :g,\n / [ '%' ( <xdigit> ** 2 ) ]+ / ,\n { Blob.new((:16(~$_) for $0)).decode }\n ) for @urls;\n\n```\n\nOutput:\n\n```\nhttp://foo bar/\ngoogle.com/search?q=`Abdu'l-Bahรก\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nProvide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters\nare converted into a percent symbol followed by a two digit hexadecimal code,\nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\nExample\n\nThe string \"`http://foo bar/`\" would be encoded as \"`http%3A%2F%2Ffoo%20bar%2F`\".\n\nVariations\n\n* Lowercase escapes are legal, as in \"`http%3a%2f%2ffoo%20bar%2f`\".\n* Special characters have different encodings for different standards:\n + RFC 3986, *Uniform Resource Identifier (URI): Generic Syntax*, section 2.3, says to preserve \"-.\\_~\".\n + HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-.\\_\\*\", and to encode space \" \" to \"+\".\n + encodeURI function in Javascript will preserve \"-.\\_~\" (RFC 3986) and \";,/?:@&=+$!\\*'()#\".\n\nOptions\n\nIt is permissible to use an exception string (containing a set of symbols\nthat do not need to be converted).\nHowever, this is an optional feature and is not a requirement of this task.\n\nRelated tasks\n\n* URL decoding\n* URL parser"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $url = 'http://foo bar/';\n\nsay $url.subst(/<-alnum>/, *.ord.fmt(\"%%%02X\"),ย :g);\n\n```\n\nOutput:\n\n```\nhttp%3A%2F%2Ffoo%20bar%2F\n```"
}
]
|
[
{
"role": "user",
"content": "URLs are strings with a simple syntax:\n\n```\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n```\n\nTask\n\nParse a well-formed URL to retrieve the relevant information: ย **scheme**, **domain**, **path**, ...\n\nNote: ย this task has nothing to do with URL encoding or URL decoding.\n\nAccording to the standards, the characters:\n\n: : : : ! \\* ' ( )ย ;ย : @ & = + $ , /ย ?ย % # [ ]\n\nonly need to be percent-encoded ย (**%**) ย in case of possible confusion.\n\nAlso note that the **path**, **query** and **fragment** are case sensitive, even if the **scheme** and **domain** are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...)\nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* Here is the official standard: ย ย https://tools.ietf.org/html/rfc3986,\n* and here is a simpler ย BNF: ย ย http://www.w3.org/Addressing/URL/5\\_URI\\_BNF.html.\n\nTest cases\n\nAccording to T. Berners-Lee\n\n**foo://example.com:8042/over/there?name=ferret#nose** ย ย should parse into:\n\n: : * scheme = foo\n * domain = example.com\n * port = :8042\n * path = over/there\n * query = name=ferret\n * fragment = nose\n\n**urn:example:animal:ferret:nose** ย ย should parse into:\n\n: : * scheme = urn\n * path = example:animal:ferret:nose\n\n**other URLs that must be parsed include:**\n\n: * jdbc:mysql://test\\_user:ouupppssss@localhost:3306/sakila?profileSQL=true\n * ftp://ftp.is.co.za/rfc/rfc1808.txt\n * http://www.ietf.org/rfc/rfc2396.txt#header1\n * ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\n * mailto:[email protected]\n * news:comp.infosystems.www.servers.unix\n * tel:+1-816-555-1212\n * telnet://192.0.2.16:80/\n * urn:oasis:names:specification:docbook:dtd:xml:4.1.2"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-02\n\nUses the URI library which implements a Raku grammar based on the RFC 3986 BNF grammar.\n\n```\nuse URI;\nuse URI::Escape;\n\nmy @test-uris = <\n foo://example.com:8042/over/there?name=ferret#nose\n urn:example:animal:ferret:nose\n jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\n ftp://ftp.is.co.za/rfc/rfc1808.txt\n http://www.ietf.org/rfc/rfc2396.txt#header1\n ldap://[2001:db8::7]/c=GB?objectClass?one\n mailto:[email protected]\n news:comp.infosystems.www.servers.unix\n tel:+1-816-555-1212\n telnet://192.0.2.16:80/\n urn:oasis:names:specification:docbook:dtd:xml:4.1.2\n ssh://[email protected]\n https://bob:[email protected]/place\n http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\n>;\n\nmy $u = URI.new;\n\nfor @test-uris -> $uri {\n say \"URI:\\t\", $uri;\n $u.parse($uri);\n for <scheme host port path query frag> -> $t {\n my $token = try {$u.\"$t\"()} || '';\n say \"$t:\\t\", uri-unescape $token.Str if $token;\n }\n say '';\n}\n\n```\n\nOutput:\n\n```\nURI:\tfoo://example.com:8042/over/there?name=ferret#nose\nscheme:\tfoo\nhost:\texample.com\nport:\t8042\npath:\t/over/there\nquery:\tname=ferret\nfrag:\tnose\n\nURI:\turn:example:animal:ferret:nose\nscheme:\turn\npath:\texample:animal:ferret:nose\n\nURI:\tjdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\nscheme:\tjdbc\npath:\tmysql://test_user:ouupppssss@localhost:3306/sakila\nquery:\tprofileSQL=true\n\nURI:\tftp://ftp.is.co.za/rfc/rfc1808.txt\nscheme:\tftp\nhost:\tftp.is.co.za\nport:\t21\npath:\t/rfc/rfc1808.txt\n\nURI:\thttp://www.ietf.org/rfc/rfc2396.txt#header1\nscheme:\thttp\nhost:\twww.ietf.org\nport:\t80\npath:\t/rfc/rfc2396.txt\nfrag:\theader1\n\nURI:\tldap://[2001:db8::7]/c=GB?objectClass?one\nscheme:\tldap\nhost:\t[2001:db8::7]\nport:\t389\npath:\t/c=GB\nquery:\tobjectClass?one\n\nURI:\tmailto:[email protected]\nscheme:\tmailto\npath:\[email protected]\n\nURI:\tnews:comp.infosystems.www.servers.unix\nscheme:\tnews\nport:\t119\npath:\tcomp.infosystems.www.servers.unix\n\nURI:\ttel:+1-816-555-1212\nscheme:\ttel\npath:\t 1-816-555-1212\n\nURI:\ttelnet://192.0.2.16:80/\nscheme:\ttelnet\nhost:\t192.0.2.16\nport:\t80\npath:\t/\n\nURI:\turn:oasis:names:specification:docbook:dtd:xml:4.1.2\nscheme:\turn\npath:\toasis:names:specification:docbook:dtd:xml:4.1.2\n\nURI:\tssh://[email protected]\nscheme:\tssh\nhost:\texample.com\nport:\t22\npath:\t\n\nURI:\thttps://bob:[email protected]/place\nscheme:\thttps\nhost:\texample.com\nport:\t443\npath:\t/place\n\nURI:\thttp://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\nscheme:\thttp\nhost:\texample.com\nport:\t80\npath:\t/\nquery:\ta=1&b=2 2&c=3&c=4&d=encoded\n```"
}
]
|
[
{
"role": "user",
"content": "The job of a URL shortener is to take a long URL (e.g. \"https://www.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb.html\") and turn it into something shorter (e.g. \"https://bit.ly/2QLUQIu\").\n\nA simple URL shortener with no special rules is very simple and consists of 2 endpoints:\n\n* One to generate a short version of a URL given a long version of a URL.\n* One to handle a call to the short version of a URL and redirect the user to the long (original) version of the URL.\n\nCreate a simple URL shortening API with the following endpoints:\n\n**POST /**\n\nA POST endpoint that accepts a JSON body describing the URL to shorten. Your URL shortener should generate a short version of the URL and keep track of the mapping between short and long URLs. For example:\n\n```\n $ curl -X POST 'localhost:8080' \\\n -H 'Content-Type: application/json' \\\n -d '{\n \"long\": \"https://www.cockroachlabs.com/docs/stable/build-a-go-app-with-cockroachdb.html\"\n }'\n\n```\n\nShould returning something similar to:\n\n```\n http://localhost:8080/9eXmFnuj\n\n```\n\n**GET /:short**\n\nA GET endpoint that accepts a short version of the URL in the URL path and redirects the user to the original URL. For example:\n\n```\n $ curl -L http://localhost:3000/9eXmFnuj\n\n```\n\nShould redirect the user to the original URL:\n\n```\n <!DOCTYPE html>\n <html lang=\"en\">\n ...\n\n```\n\n**Rules**:\n\n* Store the short -> long mappings in any way you like. In-memory is fine.\n* There are no auth requirements. Your API can be completely open."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\nAs there is no requirement to obfuscate the shortened urls, I elected to just use a simple base 36 incremental counter starting at \"0\" to \"shorten\" the urls.\n\nSets up a micro web service on the local computer at port 10000. Run the service, then access it with any web browser at address localhost:10000 . Any saved urls will be displayed with their shortened id. Enter a web address in the text field to assign a shortened id. Append that id to the web address to automatically be redirected to that url. The url of **this** page is entered as id 0, so the address: \" localhost:10000/0 \" will redirect to here, to this page.\n\nThe next saved address would be accessible at localhost:10000/1 . And so on.\n\nSaves the shortened urls in a local json file called urls.json so saved urls will be available from session to session. No provisions to edit or delete a saved url. If you want to edit the saved urls, edit the urls.json file directly with some third party editor then restart the service.\n\nThere is **NO** security or authentication on this minimal app. Not recommended to run this as-is on a public facing server. It would not be too difficult to *add* appropriate security, but it isn't a requirement of this task. Very minimal error checking and recovery.\n\n```\n# Persistent URL storage\nuse JSON::Fast;\n\nmy $urlfile = './urls.json'.IO;\nmy %urls = ($urlfile.e and $urlfile.f and $urlfile.s)ย ??\n ( $urlfile.slurp.&from-json )ย !!\n ( index => 1, url => { 0 => 'http://rosettacode.org/wiki/URL_shortener#Raku' } );\n\n$urlfile.spurt(%urls.&to-json);\n\n# Setup parameters\nmy $host = 'localhost';\nmy $port = 10000;\n\n# Micro HTTP service\nuse Cro::HTTP::Router;\nuse Cro::HTTP::Server;\n\nmy $application = route {\n post -> 'add_url' {\n redirectย :see-other, '/';\n request-body -> (:$url) {\n %urls<url>{ %urls<index>.base(36) } = $url;\n ++%urls<index>;\n $urlfile.spurt(%urls.&to-json);\n }\n }\n\n get -> {\n content 'text/html', qq:to/END/;\n <form action=\"http://$host:$port/add_url\" method=\"post\">\n URL to add:</br><input type=\"text\" name=\"url\"></br>\n <input type=\"submit\" value=\"Submit\"></form></br>\n Saved URLs:\n <div style=\"background-color:#eeeeee\">\n { %urls<url>.sort( +(*.key.parse-base(36)) ).join: '</br>' }\n </div>\n END\n }\n\n get -> $short {\n if my $link = %urls<url>{$short} {\n redirectย :permanent, $link\n }\n else {\n not-found\n }\n }\n}\n\nmy Cro::Service $shorten = Cro::HTTP::Server.new:\n ย :$host,ย :$port,ย :$application;\n\n$shorten.start;\n\nreact whenever signal(SIGINT) { $shorten.stop; exit; }\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\nThis task is inverse to the task Call foreign language function. Consider the following C program:\n\n```\n#include <stdio.h>\n\nextern int Query (char * Data, size_t * Length);\n\nint main (int argc, char * argv [])\n{\n char Buffer [1024];\n size_t Size = sizeof (Buffer);\n \n if (0 == Query (Buffer, &Size))\n {\n printf (\"failed to call Query\\n\");\n }\n else\n {\n char * Ptr = Buffer;\n while (Size-- > 0) putchar (*Ptr++);\n putchar ('\\n');\n }\n}\n\n```\n\nImplement the missing `Query` function in your language, and let this C program call it. The function should place the string *Here am I* into the buffer which is passed to it as the parameter `Data`. The buffer size in bytes is passed as the parameter `Length`. When there is no room in the buffer, `Query` shall return 0. Otherwise it overwrites the beginning of `Buffer`, sets the number of overwritten bytes into `Length` and returns 1."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThis SO answer, by JJ Merelo, explained the difficulty on providing a simple solution.ย So this attempt takes the same approach as PicoLisp by summoning the interpreter at run time.\n\n**Translation of**: PicoLisp\n\nquery.raku\n\n```\n#!/usr/bin/env raku\n\nsub MAIN (Intย :l(:len(:$length))) {\n my Str $String = \"Here am I\";\n $*OUT.print: $String if $String.codes โค $length\n}\n\n```\n\nquery.c\n\n```\n#include<stdio.h>\n#include<stddef.h>\n#include<string.h>\n\nint Query(char *Data, size_t *Length) {\n FILE *fp;\n char buf[64];\n\n sprintf(buf, \"/home/user/query.raku --len=%zu\", *Length);\n if (!(fp = popen(buf, \"r\")))\n return 0;\n fgets(Data, *Length, fp);\n *Length = strlen(Data);\n return pclose(fp) >= 0 && *Length != 0;\n}\n\n```\n\nOutput:\n\n```\ngcc -Wall -o main main.c query.c\n./main\nHere am I\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShowcase an instruction or function built into the language, that is made redundant by another instruction also built into the language. It can be limited to a specific way that function is used, e.g. printing a null string, but try not to make it that obvious.\n\n`NOP` and any instructions or functions that are intended to do nothing do not count."
},
{
"role": "assistant",
"content": "I disagree with the whole premise. There are pretty darn few instructions that are completely useless in *any* language unless *you are using them in ways not intended*, or are *deliberately structuring them to be useless*; and most of the existing examples point that out.\n\n.oO( This chainsaw is crap at driving screws in... ) Well duh.\n\n.oO( I've multiplied this numeric value by 1 millions of times and it still hasn't changed! ) Thanks for your contribution, Captain Oblivious.\n\nRedundant instructions / operations on the other hand... Syntactically different operations that *can* be used to achieve the same result abound in higher level languages. In general they are intended to be used in slightly different circumstances, or are just syntactic sugar to condense a multi-step operation down to a more compact representation. Raku is just **full** of syntactic sugar operations.\n\nProgramming languages aren't for computers, they are for people. If they were for computers, we would be programming in binary code. Having an expressive language that helps the programmer transform his thoughts into code leads to \"redundancies\" due to allowing for shades of meaning that make sense to people though may be insignificant to computers.\n\nSome examples: Say you have a variable $x that holds an integer, and you want to add 1 to it.\n\n```\nmy $x = 1;\n\n$x = $x + 1; # classic\n$x += 1; # classic abbreviated\n++$x; # pre-increment\n$x++; # post-increment\n$x.=succ; # method, find successor\n\n```\n\n*Raku is by no means unique in that regard.* Each one of those nominally accomplishes the same thing, though they go about it in slightly different ways, and are intended for slightly different purposes. Redundant on the face of it, but different reasons for each.\n\nThere may be different operations that essentially perform the same function that have been retained for historical compatibility and / or ease for crossover programmers. the `for next` construct really only exists in Raku for programmer convenience. Internally it is converted to a map operation. Programmers can use map directly, but if they come from a language that doesn't provide map, and aren't used to it, `for next` is a easy stepping stone.\n\n```\nfor 1..10 { next if $_ย %% 2; say '_' x $_ }; # for next\nmap { next if $_ย %% 2; say '_' x $_ }, 1..10; # equivalent map\n\n```\n\nSyntactic sugar (typically) replaces some longer expression with a shorter, more easily typed one. Raku abounds with them.\n\n```\nmy @a1 = Q:w[one two three]; # list of strings using the Q sublanguage\nmy @a2 = <one two three>; # syntactic sugar for the same operation\n\nsay (1,2,3,4,5,6,7).reduce(&infix:<*>); # multiply all of the items in a list together \nsay [*] (1,2,3,4,5,6,7); # same operation, sweeter syntax\n\n```"
}
]
|
[
{
"role": "user",
"content": "If the language supports operator definition, then:\n\n* create \"user defined\" the equivalents of the Unix shell \"<\", \"|\", \">\", \"<<\", \">>\" and $(cmd) operators.\n* Provide simple equivalents of: cat, tee, grep, & uniq, but as filters/procedures native to the specific language.\n* Replicate the below sample shell script, but in the specific language\n* Specifically *do not* cache the entire stream before the subsequent filter/procedure starts. Pass each record on as soon as available through each of the filters/procedures in the chain.\n\n**Alternately:** if the language does not support operator definition then replace with:\n\n* define the procedures: input(cmd,stream), pipe(stream,cmd), output(stream, stream), whereis(array), append(stream)\n\nFor bonus Kudos: Implement the shell \"&\" concept as a dyadic operator in the specific language. e.g.:\n\n```\n( head x & tail x & wait ) | grep test\n\n```\n\n**Sample shell script:** *ยข draft - pending a better (more interesting) suggestion ยข*\n\n```\naa=\"$(\n (\n head -4 < List_of_computer_scientists.lst;\n cat List_of_computer_scientists.lst | grep ALGOL | tee ALGOL_pioneers.lst;\n tail -4 List_of_computer_scientists.lst\n ) | sort | uniq | tee the_important_scientists.lst | grep aa\n);\necho \"Pioneer: $aa\"\n\n```\n\n**Input Records:**\n\nA test sample of scientists from wikipedia's \"List of computer scientists\"\n\n| Name | Areas of interest |\n| --- | --- |\n| Wil van der Aalst | business process management, process mining, Petri nets |\n| Hal Abelson | intersection of computing and teaching |\n| Serge Abiteboul | database theory |\n| Samson Abramsky | game semantics |\n| Leonard Adleman | RSA, DNA computing |\n| Manindra Agrawal | polynomial-time primality testing |\n| Luis von Ahn | human-based computation |\n| Alfred Aho | compilers book, the 'a' in AWK |\n| Stephen R. Bourne | Bourne shell, portable ALGOL 68C compiler |\n| Kees Koster | ALGOL 68 |\n| Lambert Meertens | ALGOL 68, ABC (programming language) |\n| Peter Naur | BNF, ALGOL 60 |\n| Guido van Rossum | Python (programming language) |\n| Adriaan van Wijngaarden | Dutch pioneer; ARRA, ALGOL |\n| Dennis E. Wisnosky | Integrated Computer-Aided Manufacturing (ICAM), IDEF |\n| Stephen Wolfram | Mathematica |\n| William Wulf | compilers |\n| Edward Yourdon | Structured Systems Analysis and Design Method |\n| Lotfi Zadeh | fuzzy logic |\n| Arif Zaman | Pseudo-random number generator |\n| Albert Zomaya | Australian pioneer of scheduling in parallel and distributed systems |\n| Konrad Zuse | German pioneer of hardware and software |\n\nThese records can be declared in any format appropriate to the specific language. eg table, array, list, table or text file etc.\n\n**Output:**\n\n```\nPioneer: Adriaan van Wijngaarden - Dutch pioneer; ARRA, ALGOL\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nImplementing cat, redirect(<), head, tail and tee. I share the same general lack of enthusiasm as the Perl example author to implement the other shell ops. Many of the ops already exist in some form in Raku, though they may have slightly different syntax and precedence as the shell ops. I didn't bother implementing pipe (|) as Raku pretty much has chaining semantics built in.\n\nThe less than '<' operator is very low level in Raku and would be troublesome to override, so is implemented as 'redirect'. The sort and unique directives don't really have any effect on the final result string, it would be the same without them, but it is following the task example.\n\nThis assumes that the data is in a tab separated file \"List\\_of\\_computer\\_scientists.lst\" in the current directory.\n\n```\nsub cat ($fname) { lazy $fname.IO.lines };\nsub head ($count, @positional) { @positional.head($count) }\nsub redirect ($fname) { cat($fname) }\nsub tail (Int $count, Str $fname) { $fname.IO.lines.tail($count) }\nsub infix:<tee> ($stream, $fname) {\n # need to reify the lazy list to write to a file\n my @values = @$stream[^Inf].grep: *.defined;\n # meh. not really going to write the files\n # $fname.IO.put @values.join(\"\\n\")\n # just pass the reified values along\n @values.List\n}\n\nmy $aa = ((\n (head 4, redirect 'List_of_computer_scientists.lst'),\n cat('List_of_computer_scientists.lst') .grep( /'ALGOL'/ ) tee 'ALGOL_pioneers.lst',\n tail 4, 'List_of_computer_scientists.lst'\n).flat .sort .unique tee 'the_important_scientists.lst') .grep: /'aa'/;\n\nsay \"Pioneer: $aa\";\n\n```\n\nOutput:\n\n```\nPioneer: Adriaan van Wijngaarden\tDutch pioneer; ARRA, ALGOL\n```"
}
]
|
[
{
"role": "user",
"content": "In this task, the goal is to input a string and the integer 75000, from graphical user interface.\n\nSee also: User input/Text"
},
{
"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 => 'User Interaction' );\n\n$app.border-width = 20;\n\n$app.set-content(\n GTK::Simple::VBox.new(\n my $ = GTK::Simple::Label.new( text => 'Enter a string.' ),\n my $str = GTK::Simple::Entry.new,\n my $string = GTK::Simple::Label.new,\n my $ = GTK::Simple::Label.new( text => 'Enter the number 75000' ),\n my $val = GTK::Simple::Entry.new,\n my $correct = GTK::Simple::Label.new,\n )\n);\n\n$str.changed.tap: {\n $string.text = \"You entered: { $str.text }\"\n}\n\n$val.changed.tap: {\n $correct.text = \"That's { 'not' unless $val.text ~~ / ^^ <ws> 75000 <ws> $$ / } 75000!\"\n}\n\n$app.run;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nInput a string and the integer ย **75000** ย from the text console.\n\nSee also: User input/Graphical\n\nWhy doesn't syntax highlighting work on this pageย ?\n\nCurrently, there is a limit on how many <syntaxhighlight> tags can appear on a page, so only the first few languages get highlighting, the rest are shown in monochrome. \nYou could try \"manual highlighting\", possibly using one of the highlighters on Syntax highlighting using Mediawiki formatting or something similar."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $str = prompt(\"Enter a string: \");\nmy $int = prompt(\"Enter a integer: \");\n```"
}
]
|
[
{
"role": "user",
"content": "Display a piece of text and produce spoken output via a speech engine.\n\nAs each word is being spoken, highlight the word on the display.\n\nIn languages where cursor control and highlighting are not possible, it is permissible to output each word as it is spoken.\n\nRelated task\n: * speech synthesis"
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n```\n# 20200826 Raku programming solution\n\nmy \\s = \"Actions speak louder than words.\";\nmy \\prev = $ = \"\";\nmy \\prevLen = $ = 0;\nmy \\bs = $ = \"\";\n\nfor s.split(' ',ย :skip-empty) {\n run \"/usr/bin/espeak\", $_ or die;\n bs = \"\\b\" x prevLen if prevLen > 0;\n printf \"%s%s%s \", bs, prev, $_.uc;\n prev = \"$_ \";\n prevLen = $_.chars + 1\n}\n\nprintf \"%s%s\\n\", \"\\b\" x prevLen, prev;\n\n```"
}
]
|
[
{
"role": "user",
"content": "As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1โ4 bytes representing that character in the UTF-8 encoding.\n\nThen you have to write the corresponding decoder that takes a sequence of 1โ4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n```\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\nรถ LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nะ CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nโฌ EURO SIGN U+20AC E2 82 AC\n๐ MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n```\n\nProvided below is a reference implementation in Common Lisp."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.02\n\nPretty much all built in to the language.\n\n```\nsay sprintf(\"%-18sย %-36s|%8s| %7s |%14s | %s\\n\", 'Character|', 'Name', 'Ordinal', 'Unicode', 'UTF-8 encoded', 'decoded'), '-' x 100;\n\nfor < A รถ ะ โฌ ๐ ๐ ๐จโ๐ฉโ๐งโ๐ฆ> -> $char {\n printf \" ย %-5s |ย %-43s | %6s |ย %-7s | %12s |%4s\\n\", $char, $char.uninames.join(','), $char.ords.join(' '),\n ('U+' X~ $char.ordsยป.base(16)).join(' '), $char.encode('UTF8').listยป.base(16).Str, $char.encode('UTF8').decode;\n}\n\n```\n\nOutput:\n\n```\nCharacter| Name | Ordinal| Unicode | UTF-8 encoded | decoded\n----------------------------------------------------------------------------------------------------\n A | LATIN CAPITAL LETTER A | 65 | U+41 | 41 | A\n รถ | LATIN SMALL LETTER O WITH DIAERESIS | 246 | U+F6 | C3 B6 | รถ\n ะ | CYRILLIC CAPITAL LETTER ZHE | 1046 | U+416 | D0 96 | ะ\n โฌ | EURO SIGN | 8364 | U+20AC | E2 82 AC | โฌ\n ๐ | MUSICAL SYMBOL G CLEF | 119070 | U+1D11E | F0 9D 84 9E | ๐\n ๐ | FACE WITH STUCK-OUT TONGUE AND WINKING EYE | 128540 | U+1F61C | F0 9F 98 9C | ๐\n ๐จโ๐ฉโ๐งโ๐ฆ | MAN,ZERO WIDTH JOINER,WOMAN,ZERO WIDTH JOINER,GIRL,ZERO WIDTH JOINER,BOY | 128104 8205 128105 8205 128103 8205 128102 | U+1F468 U+200D U+1F469 U+200D U+1F467 U+200D U+1F466 | F0 9F 91 A8 E2 80 8D F0 9F 91 A9 E2 80 8D F0 9F 91 A7 E2 80 8D F0 9F 91 A6 | ๐จโ๐ฉโ๐งโ๐ฆ\n\n```"
}
]
|
[
{
"role": "user",
"content": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond.\n\nTask\n\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ย *and* ย the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\nDetails\n\nThe format of an ISIN is as follows:\n\nโโโโโโโโโโโโโโ a 2-character ISO country code (A-Z)\n\nโย โโโโโโโโโโโโ a 9-character security code (A-Z, 0-9)\n\nโย โย ย ย ย ย ย ย ย โโโ a checksum digit (0-9)\n\nAU0000XVGZA3\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n\n1. **Replace letters with digits**, by converting each character from base 36 to base 10, e.g. `AU0000XVGZA3` โ`1030000033311635103`.\n2. **Perform the Luhn test on this base-10 number.** \n There is a separate task for this test: *Luhn test of credit card numbers*. \n You don't have to replicate the implementation of this test here ย โโโ ย you can just call the existing function from that task. ย (Add a comment stating if you did this.)\n\nTest cases\n\n: : : : | ISIN | Validity | Comment |\n | --- | --- | --- |\n | US0378331005 | valid | |\n | US0373831005 | not valid | The transposition typo is caught by the checksum constraint. |\n | U50378331005 | not valid | The substitution typo is caught by the format constraint. |\n | US03378331005 | not valid | The duplication typo is caught by the format constraint. |\n | AU0000XVGZA3 | valid | |\n | AU0000VXGZA3 | valid | Unfortunately, not *all* transposition typos are caught by the checksum constraint. |\n | FR0000988040 | valid | |\n\n(The comments are just informational. ย Your function should simply return a Boolean result. ย See #Raku for a reference solution.)\n\nRelated task:\n\n* Luhn test of credit card numbers\n\nAlso see\n\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nUsing the luhn-test function from the *Luhn test of credit card numbers* task.\n\n```\nmy $ISIN = /\n ^ <[A..Z]>**2 <[A..Z0..9]>**9 <[0..9]> $\n <?{ luhn-test $/.comb.map({ย :36($_) }).join }>\n/;\n\nsub luhn-test ($number --> Bool) {\n my @digits = $number.comb.reverse;\n my $sum = @digits[0,2...*].sum\n + @digits[1,3...*].map({ |($_ * 2).comb }).sum;\n return $sumย %% 10;\n}\n\n# Testing:\n\nsay \"$_ is { m/$ISIN/ย ?? \"valid\"ย !! \"not valid\"}\" for <\nUS0378331005\nUS0373831005\nU50378331005\nUS03378331005\nAU0000XVGZA3\nAU0000VXGZA3\nFR0000988040\n>;\n\n```\n\nOutput:\n\n```\nUS0378331005 is valid\nUS0373831005 is not valid\nU50378331005 is not valid\nUS03378331005 is not valid\nAU0000XVGZA3 is valid\nAU0000VXGZA3 is valid\nFR0000988040 is valid\n\n```"
}
]
|
[
{
"role": "user",
"content": "A vampire number is a natural decimal number with an even number of digits, ย that can be factored into two integers.\n\nThese two factors are called the ย *fangs*, ย and must have the following properties:\n\n: : * they each contain half the number of the decimal digits of the original number\n * together they consist of exactly the same decimal digits as the original number\n * at most one of them has a trailing zero\n\nAn example of a vampire number and its fangs: ย `1260ย : (21, 60)`\n\nTask\n\n1. Print the first ย **25** ย vampire numbers and their fangs.\n2. Check if the following numbers are vampire numbers and, ย if so, ย print them and their fangs:\n\n`16758243290880, 24959017348650, 14593825548650`\n\nNote that a vampire number can have more than one pair of fangs.\n\nSee also\n\n* numberphile.com.\n* vampire search algorithm\n* vampire numbers on OEIS"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nuse Prime::Factor;\n\nsub is_vampire (Int $num) {\n return Empty unless $numย % 9 == 0|4;\n my $digits = $num.comb.sort;\n my @fangs;\n my @divs = $num.&divisors(:s).grep({.chars == $num.chars div 2});\n return Empty unless @divs >= 2;\n @divs.map: -> $this {\n my $that = $num div $this;\n next if $thisย %% 10 && $thatย %% 10;\n last if $this > $that;\n @fangs.push(\"$this x $that\") if ($this ~ $that).comb.sort eq $digits;\n }\n @fangs\n}\n\nconstant @vampires = flat (3..*).map: -> $s, $e {\n (flat (10**$s div 9 .. 10**$e div 9).map({my $v = $_ * 9, $v + 4})).hyper.map: -> $n {\n next unless my @fangs = is_vampire($n);\n \"$n: { @fangs.join(', ') }\"\n }\n}\n\nsay \"\\nFirst 25 Vampire Numbers:\\n\";\n\n.say for @vampires[^25];\n\nsay \"\\nIndividual tests:\\n\";\n\n.say for (16758243290880, 24959017348650, 14593825548650).hyper(:1batch).map: {\n \"$_: \" ~ (is_vampire($_).join(', ') || 'is not a vampire number.')\n}\n\n```\n\n```\nFirst 25 Vampire Numbers:\n\n1260: 21 x 60\n1395: 15 x 93\n1435: 35 x 41\n1530: 30 x 51\n1827: 21 x 87\n2187: 27 x 81\n6880: 80 x 86\n102510: 201 x 510\n104260: 260 x 401\n105210: 210 x 501\n105264: 204 x 516\n105750: 150 x 705\n108135: 135 x 801\n110758: 158 x 701\n115672: 152 x 761\n116725: 161 x 725\n117067: 167 x 701\n118440: 141 x 840\n120600: 201 x 600\n123354: 231 x 534\n124483: 281 x 443\n125248: 152 x 824\n125433: 231 x 543\n125460: 204 x 615, 246 x 510\n125500: 251 x 500\n\nIndividual tests:\n\n16758243290880: 1982736 x 8452080, 2123856 x 7890480, 2751840 x 6089832, 2817360 x 5948208\n24959017348650: 2947050 x 8469153, 2949705 x 8461530, 4125870 x 6049395, 4129587 x 6043950, 4230765 x 5899410\n14593825548650: is not a vampire number.\n```"
}
]
|
[
{
"role": "user",
"content": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of \n\n2\n\n0\n{\\displaystyle {\\displaystyle 2^{0}}}\n; the digit in the next column to the left has a multiplier of \n\n2\n\n1\n{\\displaystyle {\\displaystyle 2^{1}}}\n; and so on.\n\nSo in the following table:\n\n```\n 0.\n 1.\n 10.\n 11.\n ...\n```\n\nthe binary number \"`10`\" is \n\n1\nร\n\n2\n\n1\n+\n0\nร\n\n2\n\n0\n{\\displaystyle {\\displaystyle 1\\times 2^{1}+0\\times 2^{0}}}\n.\n\nYou can also have binary digits to the right of the โpointโ, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of \n\n2\n\nโ\n1\n{\\displaystyle {\\displaystyle 2^{-1}}}\n, or \n\n1\n\n/\n2\n{\\displaystyle {\\displaystyle 1/2}}\n.\nThe weight for the second column to the right of the point is \n\n2\n\nโ\n2\n{\\displaystyle {\\displaystyle 2^{-2}}}\n or \n\n1\n\n/\n4\n{\\displaystyle {\\displaystyle 1/4}}\n. And so on.\n\nIf you take the integer binary count of the first table, and *reflect* the digits about the binary point, you end up with **the van der Corput sequence of numbers in base 2**.\n\n```\n .0\n .1\n .01\n .11\n ...\n```\n\nThe third member of the sequence, binary `0.01`, is therefore \n\n0\nร\n\n2\n\nโ\n1\n+\n1\nร\n\n2\n\nโ\n2\n{\\displaystyle {\\displaystyle 0\\times 2^{-1}+1\\times 2^{-2}}}\n or \n\n1\n\n/\n4\n{\\displaystyle {\\displaystyle 1/4}}\n.\n\nDistribution of 2500 points each: Van der Corput (top) vs pseudorandom\n\nMembers of the sequence lie within the interval\n\n0\nโค\nx\n<\n1\n{\\displaystyle {\\displaystyle 0\\leq x<1}}\n\n. Points within the sequence tend to be evenly distributed which is a useful trait to have for Monte Carlo simulations.\n\nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n**Hint**\n\nA *hint* at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n\n```\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\n\n```\n\nthe above showing that `11` in decimal is \n\n1\nร\n\n2\n\n3\n+\n0\nร\n\n2\n\n2\n+\n1\nร\n\n2\n\n1\n+\n1\nร\n\n2\n\n0\n{\\displaystyle {\\displaystyle 1\\times 2^{3}+0\\times 2^{2}+1\\times 2^{1}+1\\times 2^{0}}}\n. \nReflected this would become `.1101` or \n\n1\nร\n\n2\n\nโ\n1\n+\n1\nร\n\n2\n\nโ\n2\n+\n0\nร\n\n2\n\nโ\n3\n+\n1\nร\n\n2\n\nโ\n4\n{\\displaystyle {\\displaystyle 1\\times 2^{-1}+1\\times 2^{-2}+0\\times 2^{-3}+1\\times 2^{-4}}}\n\nTask description\n\n* Create a function/method/routine that given *n*, generates the *n'*th term of the van der Corput sequence in base 2.\n* Use the function to compute *and display* the first ten members of the sequence. (The first member of the sequence is for *n*=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\nSee also\n\n* The Basic Low Discrepancy Sequences\n* Non-decimal radices/Convert\n* Van der Corput sequence"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\nFirst a cheap implementation in base 2, using string operations.\n\n```\nconstant VdC = map {ย :2(\"0.\" ~ .base(2).flip) }, ^Inf;\n.say for VdC[^16];\n\n```\n\nHere is a more elaborate version using the polymod built-in integer method:\n\n```\nsub VdC($base = 2) {\n map {\n [+] $_ && .polymod($base xx *) Z/ [\\*] $base xx *\n }, ^Inf\n}\n\n.say for VdC[^10];\n\n```\n\nOutput:\n\n```\n0\n0.5\n0.25\n0.75\n0.125\n0.625\n0.375\n0.875\n0.0625\n0.5625\n```\n\nHere is a fairly standard imperative version in which we mutate three variables in parallel:\n\n```\nsub vdc($num, $base = 2) {\n my $n = $num;\n my $vdc = 0;\n my $denom = 1;\n while $n {\n $vdc += $n mod $base / ($denom *= $base);\n $n div= $base;\n }\n $vdc;\n}\n\nfor 2..5 -> $b {\n say \"Base $b\";\n say ( vdc($_,$b).Rat.nude.join('/') for ^10 ).join(', ');\n say '';\n}\n\n```\n\nOutput:\n\n```\nBase 2\n0, 1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16\n\nBase 3\n0, 1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27\n\nBase 4\n0, 1/4, 1/2, 3/4, 1/16, 5/16, 9/16, 13/16, 1/8, 3/8\n\nBase 5\n0, 1/5, 2/5, 3/5, 4/5, 1/25, 6/25, 11/25, 16/25, 21/25\n```\n\nHere is a functional version that produces the same output:\n\n```\nsub vdc($value, $base = 2) {\n my @values = $value, { $_ div $base } ... 0;\n my @denoms = $base, { $_ * $base } ... *;\n [+] do for (flat @values Z @denoms) -> $v, $d {\n $v mod $base / $d;\n }\n}\n\n```\n\nWe first define two sequences, one finite, one infinite.\nWhen we zip those sequences together, the finite sequence terminates the loop (which, since a Raku loop returns all its values, is merely another way of writing a map).\nWe then sum with [+], a reduction of the + operator.\n(We could have in-lined the sequences or used a traditional map operator, but this way seems more readable than the typical FP solution.)\nThe do is necessary to introduce a statement where a term is expected, since Raku distinguishes \"sentences\" from \"noun phrases\" as a natural language might."
}
]
|
[
{
"role": "user",
"content": "The sequence is generated by following this pseudo-code:\n\n```\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n```\n\nExample\n\nUsing A:\n\n: `0`\n\nUsing B:\n\n: `0 0`\n\nUsing C:\n\n: `0 0 1`\n\nUsing B:\n\n: `0 0 1 0`\n\nUsing C: (zero last occurred two steps back - before the one)\n\n: `0 0 1 0 2`\n\nUsing B:\n\n: `0 0 1 0 2 0`\n\nUsing C: (two last occurred two steps back - before the zero)\n\n: `0 0 1 0 2 0 2 2`\n\nUsing C: (two last occurred one step back)\n\n: `0 0 1 0 2 0 2 2 1`\n\nUsing C: (one last appeared six steps back)\n\n: `0 0 1 0 2 0 2 2 1 6`\n\n...\n\nTask\n\n1. Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n2. Use it to display here, on this page:\n\n: 1. The first ten terms of the sequence.\n 2. Terms 991 - to - 1000 of the sequence.\n\nReferences\n\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThere is not **a** Van Eck sequence, rather a series of related sequences that differ in their starting value. This task is nominally for the sequence starting with the value 0. This Raku implementation will handle any integer starting value.\n\nSpecifically handles:\n\n* OEIS:A181391 - Van Eck sequence starting with 0\n* OEIS:A171911 - Van Eck sequence starting with 1\n* OEIS:A171912 - Van Eck sequence starting with 2\n* OEIS:A171913 - Van Eck sequence starting with 3\n* OEIS:A171914 - Van Eck sequence starting with 4\n* OEIS:A171915 - Van Eck sequence starting with 5\n* OEIS:A171916 - Van Eck sequence starting with 6\n* OEIS:A171917 - Van Eck sequence starting with 7\n* OEIS:A171918 - Van Eck sequence starting with 8\n\namong others.\n\nImplemented as lazy, extendable lists.\n\n```\nsub n-van-ecks ($init) {\n $init, -> $i, {\n state %v;\n state $k;\n $k++;\n my $t = %v{$i}.definedย ?? $k - %v{$i}ย !! 0;\n %v{$i} = $k;\n $t\n } ... *\n}\n\nfor <\n A181391 0\n A171911 1\n A171912 2\n A171913 3\n A171914 4\n A171915 5\n A171916 6\n A171917 7\n A171918 8\n> -> $seq, $start {\n\n my @seq = n-van-ecks($start);\n\n # The task\n put qq:to/END/\n\n Van Eck sequence OEIS:$seq; with the first term: $start\n First 10 terms: {@seq[^10]}\n Terms 991 through 1000: {@seq[990..999]}\n END\n}\n\n```\n\nOutput:\n\n```\nVan Eck sequence OEIS:A181391; with the first term: 0\n First 10 terms: 0 0 1 0 2 0 2 2 1 6\nTerms 991 through 1000: 4 7 30 25 67 225 488 0 10 136\n\n\nVan Eck sequence OEIS:A171911; with the first term: 1\n First 10 terms: 1 0 0 1 3 0 3 2 0 3\nTerms 991 through 1000: 0 6 53 114 302 0 5 9 22 71\n\n\nVan Eck sequence OEIS:A171912; with the first term: 2\n First 10 terms: 2 0 0 1 0 2 5 0 3 0\nTerms 991 through 1000: 8 92 186 0 5 19 41 413 0 5\n\n\nVan Eck sequence OEIS:A171913; with the first term: 3\n First 10 terms: 3 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 5 5 1 17 192 0 6 34 38 179\n\n\nVan Eck sequence OEIS:A171914; with the first term: 4\n First 10 terms: 4 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 33 410 0 6 149 0 3 267 0 3\n\n\nVan Eck sequence OEIS:A171915; with the first term: 5\n First 10 terms: 5 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 60 459 0 7 13 243 0 4 10 211\n\n\nVan Eck sequence OEIS:A171916; with the first term: 6\n First 10 terms: 6 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 6 19 11 59 292 0 6 6 1 12\n\n\nVan Eck sequence OEIS:A171917; with the first term: 7\n First 10 terms: 7 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 11 7 2 7 2 2 1 34 24 238\n\n\nVan Eck sequence OEIS:A171918; with the first term: 8\n First 10 terms: 8 0 0 1 0 2 0 2 2 1\nTerms 991 through 1000: 16 183 0 6 21 10 249 0 5 48\n```"
}
]
|
[
{
"role": "user",
"content": "A decidely non-challenging task to highlight a potential difference between programming languages.\n\nUsing a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. \nThe purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. \nThere is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. \nShould your first attempt bomb with \"unassigned variable\" exceptions, feel free to code it as (say)\n\n```\n // int prev // crashes with unassigned variable\n int prev = -1 // predictably no output\n\n```\n\nIf your programming language does not support block scope (eg assembly) it should be omitted from this task."
},
{
"role": "assistant",
"content": "By default, Raku variables need a prefix sigil indicating the storage / interface, and a scope declarator to indicate the variables' accessibility. The vast majority of the time, variables are declared with a \"my\" scope declarator that constrains them to the present block and any enclosed sub blocks. When a 'my' variable is declared inside a loop (block), a new independent instance of the variable is instantiated every time through.\n\n```\nmy @s = 1, 2, 2, 3, 4, 4, 5;\nloop (my $i = 0; $i < 7; $i += 1) {\n my $curr = @s[$i];\n my $prev;\n if $i > 1 and $curr == $prev {\n say $i;\n }\n $prev = $curr;\n}\n\n```\n\nYields:\n\n```\nUse of uninitialized value of type Any in numeric context\n in block <unit> at var.p6 line 5\nUse of uninitialized value of type Any in numeric context\n in block <unit> at var.p6 line 5\nUse of uninitialized value of type Any in numeric context\n in block <unit> at var.p6 line 5\nUse of uninitialized value of type Any in numeric context\n in block <unit> at var.p6 line 5\nUse of uninitialized value of type Any in numeric context\n in block <unit> at var.p6 line 5\n```\n\nLots of warnings but nothing else. If we suppress the warnings:\n\n```\nmy @s = 1, 2, 2, 3, 4, 4, 5;\nquietly loop (my $i = 0; $i < 7; $i += 1) {\n my $curr = @s[$i];\n my $prev;\n if $i > 1 and $curr == $prev {\n say $i;\n }\n $prev = $curr;\n}\n\n```\n\nNo output.\n\nWe can however, declare the variable with an \"our\" scope, which effectively makes it a package global. Use of 'our' scoping is discouraged except in a few very specific situations. It \"works\" (for some value of works), but pollutes the namespace. The 'our' variable will trample any other instance of a variable with that name anywhere in the program in any other scope.\n\n```\nmy @s = 1, 2, 2, 3, 4, 4, 5;\nloop (my $i = 0; $i < 7; $i += 1) {\n my $curr = @s[$i];\n our $prev;\n if $i > 1 and $curr == $prev {\n say $i;\n }\n $prev = $curr;\n}\n\n```\n\nYields:\n\n```\n2\n5\n```\n\nA better solution is to declare a state variable. A 'state' variable is essentially scoped similar to a 'my' variable (visible only inside the block), but is persistent across calls.\n\n```\nmy @s = 1, 2, 2, 3, 4, 4, 5;\nloop (my $i = 0; $i < 7; $i += 1) {\n my $curr = @s[$i];\n state $prev;\n if $i > 1 and $curr == $prev {\n say $i;\n }\n $prev = $curr;\n}\n\n```\n\nYields:\n\n```\n2\n5\n```\n\nIf you really want to run fast and loose, and bypass all the protections Raku builds in, you can turn off strict scoping with a pragma. This is ***heavily*** discouraged. Anyone trying to release code with strictures turned off will receive some degree of side-eye... but just because something is a bad idea in general doesn't mean Raku forbids it. The Raku mindset is \"Make it difficult to make casual mistakes but make it possible to bypass those protections if you have the need.\"\n\nNo scope declarators at all. Every variable is a global. Bad idea. Do not do this casually.\n\n```\nno strict;\n@s = 1, 2, 2, 3, 4, 4, 5;\nloop ($i = 0; $i < 7; $i += 1) {\n $curr = @s[$i];\n if $i > 1 and $curr == $prev {\n say $i;\n }\n $prev = $curr;\n}\n\n```\n\nYields:\n\n```\n2\n5\n```"
}
]
|
[
{
"role": "user",
"content": "Demonstrate how to get the size of a variable.\n\nSee also: Host introspection"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nRaku tries to avoid generic terms such as \"size\" and \"length\", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.\n\n```\n# Textual strings are measured in characters (graphemes)\nmy $string = \"abc\";\n\n# Arrays are measured in elements.\nsay $string.chars; # 3\nmy @array = 1..5;\nsay @array.elems; # 5\n\n# Buffers may be viewed either as a byte-string or as an array of elements.\nmy $buffer = '#56997; means \"four dragons\".'.encode('utf8');\nsay $buffer.bytes; # 26\nsay $buffer.elems; # 26\n\n```\n\nRaku's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be \"chunky\" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.\n\nNative types such as int64 or num32 are of fixed size; Raku supports representational polymorphism of such types (and compositions of such types) through a pluggable meta-object protocol providing \"knowhow\" objects for the various representations. Currently the NativeHOW knowhow may be interrogated for the bit sizes of native types, but this is officially outside the purview of the language itself (so far)."
}
]
|
[
{
"role": "user",
"content": "Task\n\nDemonstrate how to specify the minimum size of a variable or a data type."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nIn Raku, normal user-facing types (Int, Rat, Str, Array, Hash) are all auto-sizing, so there is no need to specify a minimum size for them. (Floating point, known as \"Num\", defaults to a machine double.) For storage declarations, native storage types (starting with a lowercase letter) may also be specified, in which case the required bit size is part of the type name: int16, uint8 (aka \"byte\"), num32 (a \"float\"), complex64 (made of two num64's), etc. More generally, such types are created through an API supporting representational polymorphism, in this case, the NativeHOW representation, when provides methods to set the size of a type; the actual allocation calculation happens when such generic types are composed into a class instance representing the semantics of the effective type to the compiler and run-time system. But mostly this is not something users will concern themselves with directly.\n\nBy spec, arrays may be declared with dimensions of fixed size, but as of this writing, such arrays not yet implemented. An array of fixed size that returns elements of a native type will be stored compactly, and uses exactly the memory you'd think it should, (modulo alignment constraints between elements and any slop at the end due to your memory allocator)."
}
]
|
[
{
"role": "user",
"content": "Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and *vice versa*. Any variants are acceptable.\n\nTask\n\nWith above operations,\n\n* convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte);\n* display these sequences of octets;\n* convert these sequences of octets back to numbers, and check that they are equal to original numbers."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nvlq\\_encode() returns a string of encoded octets. vlq\\_decode() takes a string and returns a decimal number.\n\n```\nsub vlq_encode ($number is copy) {\n my @vlq = (127 +& $number).fmt(\"%02X\");\n $number +>= 7;\n while ($number) {\n @vlq.push: (128 +| (127 +& $number)).fmt(\"%02X\");\n $number +>= 7; \n }\n @vlq.reverse.join: ':';\n}\n\nsub vlq_decode ($string) {\n sum $string.split(':').reverse.map: {(:16($_) +& 127) +< (7 ร $++)}\n}\n\n#test encoding and decoding\nfor (\n 0, 0xa, 123, 254, 255, 256,\n 257, 65534, 65535, 65536, 65537, 0x1fffff,\n 0x200000\n ) -> $testcase {\n printf \"%8s %12s %8s\\n\", $testcase,\n my $encoded = vlq_encode($testcase),\n vlq_decode($encoded);\n}\n\n```\n\nOutput:\n\n```\n 0 00 0\n 10 0A 10\n 123 7B 123\n 254 81:7E 254\n 255 81:7F 255\n 256 82:00 256\n 257 82:01 257\n 65534 83:FF:7E 65534\n 65535 83:FF:7F 65535\n 65536 84:80:00 65536\n 65537 84:80:01 65537\n 2097151 FF:FF:7F 2097151\n 2097152 81:80:80:00 2097152\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDemonstrate a language's methods of:\n\n: : : * variable declaration\n * initialization\n * assignment\n * datatypes\n * scope\n * referencing, ย ย and\n * other variable related facilities"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nMuch of what is true for Perl 5 is also true for Raku. Some exceptions:\n\nThere are no typeglobs in Raku.\n\nAssigning an array to a scalar variable now makes that scalar variable a reference to the array:\n\n```\nmy @y = <A B C D>; # Array of strings 'A', 'B', 'C', and 'D'\nsay @y[2]; # the @-sigil requires the container to implement the role Positional\n@y[1,2] = 'x','y'; # that's where subscripts and many other things come from\nsay @y; # OUTPUTยซ[A x y D]โคยป # we start to count at 0 btw.\n\nmy $x = @y; # $x is now a reference for the array @y\n\nsay $x[1]; # prints 'x' followed by a newline character\n\nmy Int $with-type-check; # type checks are enforced by the compiler\n\nmy Int:D $defined-i = 10; # definedness can also be asked for and default values are required in that case\n\nmy Int:D $after-midnight where * > 24 = 25; # SQL is fun and so is Raku\n\nmy \\bad = 'good'; # if you don't like sigils\nsay bad; # you don't have to use them\nsay \"this is quite bad\"; # but then string interpolation\nsay \"this is quite {bad}\" # becomes more wordy\n```\n\nLaziness is a big topic in Raku. Sometimes Raku programmers are so lazy, they can't even be bothered with giving variables names.\n\n```\nsay ++$; # this is an anonymous state variable\nsay ++$; # this is a different anonymous state variable, prefix:<++> forces it into numerical context and defaults it to 0\nsay $+=2 for 1..10; # here we do something useful with another anonymous variable\n\nsub foo { $^a * $^b } # for positional arguments we often can't be bothered to declare them or to give them fancy names\nsay foo 3, 4;\n```\n\nOutput:\n\n```\n1\n1\n2\n4\n6\n12\n```\n\n(Includes code modified from http://design.raku.org/S02.html#Built-In\\_Data\\_Types. See this reference for more details.)"
}
]
|
[
{
"role": "user",
"content": "A fixed-point combinator is a higher order function \n\nfix\n{\\displaystyle {\\displaystyle \\operatorname {fix} }}\n that returns the fixed point of its argument function. If the function \n\nf\n{\\displaystyle {\\displaystyle f}}\n has one or more fixed points, then \n\nfix\nโก\nf\n=\nf\n(\nfix\nโก\nf\n)\n{\\displaystyle {\\displaystyle \\operatorname {fix} f=f(\\operatorname {fix} f)}}\n.\n\nYou can extend a fixed-point combinator to find the fixed point of the i-th function out of n given functions: \n\nfix\n\ni\n,\nn\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\n=\n\nf\n\ni\n(\n\nfix\n\n1\n,\nn\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\n)\nโฆ\n(\n\nfix\n\nn\n,\nn\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\n)\n{\\displaystyle {\\displaystyle \\operatorname {fix} \\_{i,n}f\\_{1}\\dots f\\_{n}=f\\_{i}(\\operatorname {fix} \\_{1,n}f\\_{1}\\dots f\\_{n})\\dots (\\operatorname {fix} \\_{n,n}f\\_{1}\\dots f\\_{n})}}\n\nTask\n\nYour task is to implement a variadic fixed-point combinator \n\nfix\n\nโ\n{\\displaystyle {\\displaystyle \\operatorname {fix} ^{\\*}}}\n that finds and returns the fixed points of all given functions: \n\nfix\n\nโ\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\n=\nโจ\n\nfix\n\n1\n,\nn\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\n,\nโฆ\n,\n\nfix\n\nn\n,\nn\nโก\n\nf\n\n1\nโฆ\n\nf\n\nn\nโฉ\n{\\displaystyle {\\displaystyle \\operatorname {fix} ^{\\*}f\\_{1}\\dots f\\_{n}=\\langle \\operatorname {fix} \\_{1,n}f\\_{1}\\dots f\\_{n},\\dots ,\\operatorname {fix} \\_{n,n}f\\_{1}\\dots f\\_{n}\\rangle }}\n\nThe variadic input and output may be implemented using any feature of the language (e.g. using lists).\n\nIf possible, try not to use explicit recursion and implement the variadic fixed-point combinator using a fixed-point combinator like the Y combinator.\n\nAlso try to come up with examples where \n\nfix\n\nโ\n{\\displaystyle {\\displaystyle \\operatorname {fix} ^{\\*}}}\n could actually be somewhat useful.\n\nRelated tasks\n\n* Y combinator\n* Variadic function\n\nSee also\n\n* Mayer Goldberg: A Variadic Extension of Curryโs Fixed-Point Combinator"
},
{
"role": "assistant",
"content": "**Translation of**: Julia\n\n**Translation of**: Python\n\n```\n# 20240726 Raku programming solution\n\nmy &Y = -> \\a { a.map: -> \\f { -> &x { -> { x(Y(a)) } }(f) } }\n \nmy \\even_odd_fix = -> \\f { -> \\n { n == 0 or f[1]()(n - 1) } },\n -> \\f { -> \\n { nย != 0 and f[0]()(n - 1) } };\n\nmy \\collatz_fix = -> \\f { -> \\n, \\d { n == 1ย ?? dย !! f[(nย % 2)+1]()(n, d+1) } },\n -> \\f { -> \\n, \\d { f[0]()( n div 2, d ) } }, \n -> \\f { -> \\n, \\d { f[0]()( 3*n+1, d ) } };\n\nmy \\even_odd = Y(even_odd_fix).map: -> &f { f() }; # or { $_() }\nmy &collatz = Y(collatz_fix)[0]();\n\nfor 1..10 -> \\i {\n my ( \\e, \\o, \\c ) = even_odd[0](i), even_odd[1](i), collatz(i, 0);\n printf \"%2d: Even: %s Odd: %s Collatz: %s\\n\", i, e, o, c\n}\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a function which takes in a variable number of arguments and prints each one on its own line.\n\nAlso show, if possible in your language, how to call the function on a list of arguments constructed at runtime.\n\nFunctions of this type are also known as Variadic Functions.\n\nRelated task\n\n* Call a function"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #25 \"Minneapolis\"\n\nIf a subroutine has no formal parameters but mentions the variables `@_` or `%_` in its body, it will accept arbitrary positional or keyword arguments, respectively. You can even use both in the same function.\n\n```\nsub foo {\n .say for @_;\n say .key, ': ', .value for %_;\n}\n\nfoo 1, 2, command => 'buckle my shoe',\n 3, 4, order => 'knock at the door';\n```\n\nThis prints:\n\n```\n1\n2\n3\n4\ncommand: buckle my shoe\norder: knock at the door\n```\n\nRaku also supports slurpy arrays and hashes, which are formal parameters that consume extra positional and keyword arguments like `@_` and `%_`. You can make a parameter slurpy with the `*` twigil. This implementation of `&foo` works just like the last:\n\n```\nsub foo (*@positional, *%named) {\n .say for @positional;\n say .key, ': ', .value for %named;\n}\n```\n\nUnlike in Perl 5, arrays and hashes aren't flattened automatically. Use the `|` operator to flatten:\n\n```\nfoo |@ary, |%hsh;\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a *pretty print* function should be implemented.\n\nThe Vector may be initialized in any reasonable way.\n\n* Start and end points, and direction\n* Angular coefficient and value (length)\n\nThe four operations to be implemented are:\n\n* Vector **+** Vector addition\n* Vector **-** Vector subtraction\n* Vector **\\*** scalar multiplication\n* Vector **/** scalar division"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nclass Vector {\n has Real $.x;\n has Real $.y;\n\n multi submethod BUILD (:$!x!,ย :$!y!) {\n *\n }\n multi submethod BUILD (:$length!,ย :$angle!) {\n $!x = $length * cos $angle;\n $!y = $length * sin $angle;\n }\n multi submethod BUILD (:from([$x1, $y1])!,ย :to([$x2, $y2])!) {\n $!x = $x2 - $x1;\n $!y = $y2 - $y1;\n }\n \n method length { sqrt $.x ** 2 + $.y ** 2 }\n method angle { atan2 $.y, $.x }\n \n method add ($v) { Vector.new(x => $.x + $v.x, y => $.y + $v.y) }\n method subtract ($v) { Vector.new(x => $.x - $v.x, y => $.y - $v.y) }\n method multiply ($n) { Vector.new(x => $.x * $n, y => $.y * $n ) }\n method divide ($n) { Vector.new(x => $.x / $n, y => $.y / $n ) }\n \n method gist { \"vec[$.x, $.y]\" }\n}\n\nmulti infix:<+> (Vector $v, Vector $w) is export { $v.add: $w }\nmulti infix:<-> (Vector $v, Vector $w) is export { $v.subtract: $w }\nmulti prefix:<-> (Vector $v) is export { $v.multiply: -1 }\nmulti infix:<*> (Vector $v, $n) is export { $v.multiply: $n }\nmulti infix:</> (Vector $v, $n) is export { $v.divide: $n }\n\n\n#####[ Usage example: ]#####\n\nsay my $u = Vector.new(x => 3, y => 4); #: vec[3, 4]\nsay my $v = Vector.new(from => [1, 0], to => [2, 3]); #: vec[1, 3]\nsay my $w = Vector.new(length => 1, angle => pi/4); #: vec[0.707106781186548, 0.707106781186547]\n\nsay $u.length; #: 5\nsay $u.angle * 180/pi; #: 53.130102354156\n\nsay $u + $v; #: vec[4, 7]\nsay $u - $v; #: vec[2, 1]\nsay -$u; #: vec[-3, -4]\nsay $u * 10; #: vec[30, 40]\nsay $u / 2; #: vec[1.5, 2]\n\n```"
}
]
|
[
{
"role": "user",
"content": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: ย (X, Y, Z).\n\nIf you imagine a graph with the ย **x** ย and ย **y** ย axis being at right angles to each other and having a third, ย **z** ย axis coming out of the page, then a triplet of numbers, ย (X, Y, Z) ย would represent a point in the region, ย and a vector from the origin to the point.\n\nGiven the vectors:\n\n```\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \n\n```\n\nthen the following common vector products are defined:\n\n* **The dot product** ย ย ย (a scalar quantity)\n\n: : : : A โข B = a1b1 ย + ย a2b2 ย + ย a3b3\n\n* **The cross product** ย ย ย (a vector quantity)\n\n: : : : A x B = (a2b3ย - ย a3b2, ย ย a3b1 ย - ย a1b3, ย ย a1b2 ย - ย a2b1)\n\n* **The scalar triple product** ย ย ย (a scalar quantity)\n\n: : : : A โข (B x C)\n\n* **The vector triple product** ย ย ย (a vector quantity)\n\n: : : : A x (B x C)\n\nTask\n\nGiven the three vectors:\n\n```\n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n\n```\n\n1. Create a named function/subroutine/method to compute the dot product of two vectors.\n2. Create a function to compute the cross product of two vectors.\n3. Optionally create a function to compute the scalar triple product of three vectors.\n4. Optionally create a function to compute the vector triple product of three vectors.\n5. Compute and display: `a โข b`\n6. Compute and display: `a x b`\n7. Compute and display: `a โข (b x c)`, the scalar triple product.\n8. Compute and display: `a x (b x c)`, the vector triple product.\n\nReferences\n\n* A starting page on Wolfram MathWorld is ย Vector Multiplication .\n* Wikipedia ย dot product.\n* Wikipedia ย cross product.\n* Wikipedia ย triple product.\n\nRelated tasks\n\n* Dot product\n* Quaternion type"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-24\n\n```\nsub infix:<โ
> { [+] @^aย ยป*ยซย @^b }\n\nsub infix:<โจฏ>([$a1, $a2, $a3], [$b1, $b2, $b3]) {\n [ $a2*$b3 - $a3*$b2,\n $a3*$b1 - $a1*$b3,\n $a1*$b2 - $a2*$b1 ];\n}\n\nsub scalar-triple-product { @^a โ
(@^b โจฏ @^c) }\nsub vector-triple-product { @^a โจฏ (@^b โจฏ @^c) }\n\nmy @a = <3 4 5>;\nmy @b = <4 3 5>;\nmy @c = <-5 -12 -13>;\n\nsay (:@a,ย :@b,ย :@c);\nsay \"a โ
b = { @a โ
@b }\";\nsay \"a โจฏ b = <{ @a โจฏ @b }>\";\nsay \"a โ
(b โจฏ c) = { scalar-triple-product(@a, @b, @c) }\";\nsay \"a โจฏ (b โจฏ c) = <{ vector-triple-product(@a, @b, @c) }>\";\n\n```\n\nOutput:\n\n```\n(\"a\" => [\"3\", \"4\", \"5\"], \"b\" => [\"4\", \"3\", \"5\"], \"c\" => [\"-5\", \"-12\", \"-13\"])\na โ
b = 49\na โจฏ b = <5 5 -7>\na โ
(b โจฏ c) = 6\na โจฏ (b โจฏ c) = <-267 204 -3>\n```"
}
]
|
[
{
"role": "user",
"content": "Description\n\nThe Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at the time thought impossible with such a code.\n\nAs the workings of the algorithm are clearly described in the linked Wikipedia article they will not be repeated here.\n\nTask\n\nWrite routines, methods, procedures etc. in your language to generate a Verhoeff checksum digit for non-negative integers of any length and to validate the result. A combined routine is also acceptable.\n\nThe more mathematically minded may prefer to generate the 3 tables required from the description provided rather than to hard-code them.\n\nWrite your routines in such a way that they can optionally display digit by digit calculations as in the Wikipedia example.\n\nUse your routines to calculate check digits for the integers: **236**, **12345** and **123456789012** and then validate them. Also attempt to validate the same integers if the check digits in all cases were **9** rather than what they actually are.\n\nDisplay digit by digit calculations for the first two integers but not for the third.\n\nRelated task\n\n* Damm algorithm"
},
{
"role": "assistant",
"content": "Generate the tables rather than hard coding, They're not all that complex.\n\n```\nmy @d = [^10] xx 5;\n@d[$_][^5].=rotate($_), @d[$_][5..*].=rotate($_) for 1..4;\npush @d: [@d[$_].reverse] for flat 1..4, 0;\n\nmy @i = 0,4,3,2,1,5,6,7,8,9;\n\nmy %h = flat (0,1,5,8,9,4,2,7,0).rotor(2 =>-1).map({.[0]=>.[1]}), 6=>3, 3=>6;\nmy @p = [^10],;\[email protected]: [@p[*-1].map: {%h{$_}}] for ^7;\n\nsub checksum (Int $int where * โฅ 0,ย :$verbose = True ) {\n my @digits = $int.comb;\n say \"\\nCheckdigit calculation for $int:\";\n say \" i ni p(i, ni) c\" if $verbose;\n my ($i, $p, $c) = 0 xx 3;\n say \" $i 0 $p $c\" if $verbose;\n for @digits.reverse {\n ++$i;\n $p = @p[$iย % 8][$_];\n $c = @d[$c; $p];\n say \"{$i.fmt('%2d')} $_ $p $c\" if $verbose;\n }\n say \"Checkdigit: {@i[$c]}\";\n +($int ~ @i[$c]);\n}\n\nsub validate (Int $int where * โฅ 0,ย :$verbose = True) {\n my @digits = $int.comb;\n say \"\\nValidation calculation for $int:\";\n say \" i ni p(i, ni) c\" if $verbose;\n my ($i, $p, $c) = 0 xx 3;\n for @digits.reverse {\n $p = @p[$iย % 8][$_];\n $c = @d[$c; $p];\n say \"{$i.fmt('%2d')} $_ $p $c\" if $verbose;\n ++$i;\n }\n say \"Checkdigit: {'in' if $c}correct\";\n}\n\n## TESTING\n\nfor 236, 12345, 123456789012 -> $int {\n my $check = checksum $int,ย :verbose( $int.chars < 8 );\n validate $check,ย :verbose( $int.chars < 8 );\n validate +($check.chop ~ 9),ย :verbose( $int.chars < 8 );\n}\n\n```\n\nOutput:\n\n```\nCheckdigit calculation for 236:\n i ni p(i, ni) c\n 0 0 0 0\n 1 6 3 3\n 2 3 3 1\n 3 2 1 2\nCheckdigit: 3\n\nValidation calculation for 2363:\n i ni p(i, ni) c\n 0 3 3 3\n 1 6 3 1\n 2 3 3 4\n 3 2 1 0\nCheckdigit: correct\n\nValidation calculation for 2369:\n i ni p(i, ni) c\n 0 9 9 9\n 1 6 3 6\n 2 3 3 8\n 3 2 1 7\nCheckdigit: incorrect\n\nCheckdigit calculation for 12345:\n i ni p(i, ni) c\n 0 0 0 0\n 1 5 8 8\n 2 4 7 1\n 3 3 6 7\n 4 2 5 2\n 5 1 2 4\nCheckdigit: 1\n\nValidation calculation for 123451:\n i ni p(i, ni) c\n 0 1 1 1\n 1 5 8 9\n 2 4 7 2\n 3 3 6 8\n 4 2 5 3\n 5 1 2 0\nCheckdigit: correct\n\nValidation calculation for 123459:\n i ni p(i, ni) c\n 0 9 9 9\n 1 5 8 1\n 2 4 7 8\n 3 3 6 2\n 4 2 5 7\n 5 1 2 5\nCheckdigit: incorrect\n\nCheckdigit calculation for 123456789012:\nCheckdigit: 0\n\nValidation calculation for 1234567890120:\nCheckdigit: correct\n\nValidation calculation for 1234567890129:\nCheckdigit: incorrect\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a function to determine whether a given set of frequency counts could plausibly have come from a uniform distribution by using the\nฯ\n2\n{\\displaystyle {\\displaystyle \\chi ^{2}}}\ntest with a significance level of 5%.\n\nThe function should return a boolean that is true if and only if the distribution is one that a uniform distribution (with appropriate number of degrees of freedom) may be expected to produce.\n\nNote: normally a two-tailed test would be used for this kind of problem.\n\nReference\n: * an entry at the MathWorld website: ย chi-squared distribution.\n\nRelated task\n: * Statistics/Chi-squared\\_distribution"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nFor the incomplete gamma function we use a series expansion related to Kummer's confluent hypergeometric function\n(see http://en.wikipedia.org/wiki/Incomplete\\_gamma\\_function#Evaluation\\_formulae). The gamma function is calculated\nin closed form, as we only need its value at integers and half integers.\n\n```\nsub incomplete-ฮณ-series($s, $z) {\n my \\numers = $z X** 1..*;\n my \\denoms = [\\*] $s X+ 1..*;\n my $M = 1 + [+] (numers Z/ denoms) ... * < 1e-6;\n $z**$s / $s * exp(-$z) * $M;\n}\n \nsub postfix:<!>(Int $n) { [*] 2..$n }\n \nsub ฮ-of-half(Int $n where * > 0) {\n ($nย %% 2)ย ?? (($_-1)! given $n div 2)\n ย !! ((2*$_)! / (4**$_ * $_!) * sqrt(pi) given ($n-1) div 2);\n}\n \n# degrees of freedom constrained due to numerical limitations\nsub chi-squared-cdf(Int $k where 1..200, $x where * >= 0) {\n my $f = $k < 20ย ?? 20ย !! 10;\n given $x {\n when 0 { 0.0 }\n when * < $k + $f*sqrt($k) { incomplete-ฮณ-series($k/2, $x/2) / ฮ-of-half($k) }\n default { 1.0 }\n }\n}\n \nsub chi-squared-test(@bins,ย :$significance = 0.05) {\n my $n = +@bins;\n my $N = [+] @bins;\n my $expected = $N / $n;\n my $chi-squared = [+] @bins.map: { ($^bin - $expected)**2 / $expected }\n my $p-value = 1 - chi-squared-cdf($n-1, $chi-squared);\n return (:$chi-squared,ย :$p-value, :uniform($p-value > $significance));\n}\n \nfor [< 199809 200665 199607 200270 199649 >],\n [< 522573 244456 139979 71531 21461 >]\n -> $dataset\n{\n my %t = chi-squared-test($dataset);\n say 'data: ', $dataset;\n say \"ฯยฒ = {%t<chi-squared>}, p-value = {%t<p-value>.fmt('%.4f')}, uniform = {%t<uniform>}\";\n}\n\n```\n\nOutput:\n\n```\ndata: 199809 200665 199607 200270 199649\nฯยฒ = 4.14628, p-value = 0.3866, uniform = True\ndata: 522573 244456 139979 71531 21461\nฯยฒ = 790063.27594, p-value = 0.0000, uniform = False\n```"
}
]
|
[
{
"role": "user",
"content": "This task is an adjunct to Seven-sided dice from five-sided dice.\n\nTask\n\nCreate a function to check that the random integers returned from a small-integer generator function have uniform distribution.\n\nThe function should take as arguments:\n\n* The function (or object) producing random integers.\n* The number of times to call the integer generator.\n* A 'delta' value of some sort that indicates how close to a flat distribution is close enough.\n\nThe function should produce:\n\n* Some indication of the distribution achieved.\n* An 'error' if the distribution is not flat enough.\n\nShow the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).\n\nSee also:\n\n* Verify distribution uniformity/Chi-squared test"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nSince the tested function is rolls of a 7 sided die, the test numbers are magnitudes of 10x bumped up to the closest multiple of 7. This reduces spurious error from there not being an integer expected value.\n\n```\nmy $d7 = 1..7;\nsub roll7 { $d7.roll };\n\nmy $threshold = 3;\n\nfor 14, 105, 1001, 10003, 100002, 1000006 -> $n\n { dist( $n, $threshold, &roll7 ) };\n\n\nsub dist ( $n is copy, $threshold, &producer ) {\n my @dist;\n my $expect = $n / 7;\n say \"Expect\\t\",$expect.fmt(\"%.3f\");\n \n loop ($_ = $n; $n; --$n) { @dist[&producer()]++; }\n \n for @dist.kv -> $i, $v is copy {\n next unless $i;\n $v //= 0;\n my $pct = ($v - $expect)/$expect*100;\n printf \"%d\\t%d\\t%+.2f%% %s\\n\", $i, $v, $pct,\n ($pct.abs > $thresholdย ?? '- skewed'ย !! '');\n }\n say '';\n}\n\n```\n\nSample output:\n\n```\nExpect 2.000\n1 2 +0.00%\n2 3 +50.00% - skewed\n3 2 +0.00%\n4 2 +0.00%\n5 3 +50.00% - skewed\n6 0 -100.00% - skewed\n7 2 +0.00%\n\nExpect 15.000\n1 15 +0.00%\n2 17 +13.33% - skewed\n3 13 -13.33% - skewed\n4 16 +6.67% - skewed\n5 14 -6.67% - skewed\n6 16 +6.67% - skewed\n7 14 -6.67% - skewed\n\nExpect 143.000\n1 134 -6.29% - skewed\n2 142 -0.70%\n3 141 -1.40%\n4 137 -4.20% - skewed\n5 142 -0.70%\n6 170 +18.88% - skewed\n7 135 -5.59% - skewed\n\nExpect 1429.000\n1 1396 -2.31%\n2 1468 +2.73%\n3 1405 -1.68%\n4 1442 +0.91%\n5 1453 +1.68%\n6 1417 -0.84%\n7 1422 -0.49%\n\nExpect 14286.000\n1 14222 -0.45%\n2 14320 +0.24%\n3 14326 +0.28%\n4 14425 +0.97%\n5 14140 -1.02%\n6 14275 -0.08%\n7 14294 +0.06%\n\nExpect 142858.000\n1 142510 -0.24%\n2 142436 -0.30%\n3 142438 -0.29%\n4 143152 +0.21%\n5 142905 +0.03%\n6 143232 +0.26%\n7 143333 +0.33%\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\n: : 1. Draw at least 20 rectangles with a common center, to be more precise, the circumcenter of all the rectangles must coincide. None of the rectangles must touch or intersect any other rectangle.\n 2. Animate the colours of the rectangles by *fading in* the colour from the outermost rectangle to the innermost.\n 3. The animation loop can continue for a definite number of iterations or forever.\n\nCreate Vibrating rectangles"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\n### ANSI graphics\n\nOk. The task description is essentially non-existent. In looking at the reference implementation (Ring) it seems like we are supposed to draw a series of concentric rectangles and then alter the colors step-wise. No actual vibration apparent.\n\nCould fire up a GUI but WTH, let's try it at a command line with ANSI.\n\nDraws a series of concentric rectangles then rotates through the color palette. Every three seconds, chooses new random palette colors and reverses rotation direction.\n\n```\n# box drawing characters\nmy %r =ย :tl<โ>, :h<โ>,ย :tr<โ>, :v<โ>,ย :bl<โ>, :br<โ>;\n\nmy @colors = ยซย \\e[1;31m \\e[1;94m \\e[1;33m \\e[1;35m \\e[1;36m \\e[1;32m \\e[1;34mย ยป;\n\n# color palette\nmy @c = flat @colors[0] xx 12, @colors[3] xx 12, @colors[2] xx 12;\n\nprint \"\\e[?25l\"; # hide the cursor\n\nsignal(SIGINT).tap: {\n print \"\\e[0H\\e[0J\\e[?25h\"; # clean up on exit\n exit;\n}\n\nmy $rot = 1;\n\nmy @vibe;\n\nloop {\n rect($_, 31-$_) for ^15;\n display @vibe;\n @c.=rotate($rot);\n if ++$ย %% 30 {\n @c = |@colors.pick(3);\n @c = sort(flat @c xx 12);\n $rot *= -1;\n }\n sleep .1;\n}\n\nsub rect ($b, $e) {\n @vibe[$b;$b..$e] = @c[$bย % @c]~%r<tl>, |((%r<h>) xx ($e - $b - 1)), %r<tr>~\"\\e[0m\";\n @vibe[$e;$b..$e] = @c[$bย % @c]~%r<bl>, |((%r<h>) xx ($e - $b - 1)), %r<br>~\"\\e[0m\";\n ($b ^..^ $e).map: { @vibe[$_;$b] = @vibe[$_;$e] = @c[$bย % @c]~%r<v>~\"\\e[0m\" }\n}\n\nsub display (@rect) {\n print \"\\e[0H\\e[0J\\n\\n\";\n for @rect -> @row {\n print \"\\t\\t\\t\";\n print $_ // ' ' for @row;\n print \"\\n\";\n }\n}\n\n```\n\nSee: Vibrating rectangles (.gif image)\n\n### SDL Animation\n\nFully animated SDL2 graphics lib version. Will adjust rendered rectangles to fill resized windows. Hit the space bar to toggle palette rotation direction.\n\n```\nuse SDL2::Raw;\n\nmy $width = 1200;\nmy $height = 800;\n\nSDL_Init(VIDEO);\n\nmy $window = SDL_CreateWindow(\n 'Vibrating rectangles',\n SDL_WINDOWPOS_CENTERED_MASK,\n SDL_WINDOWPOS_CENTERED_MASK,\n $width, $height,\n RESIZABLE\n);\n\nmy $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);\n\nmy $event = SDL_Event.new;\n\nenum KEY_CODES (\n K_SPACE => 44,\n);\n\nmy $num = 80;\nmy @rgb = palette($num);\nmy ($cx, $cy);\nmy $dir = 1;\n\nmain: loop {\n while SDL_PollEvent($event) {\n my $casted_event = SDL_CastEvent($event);\n given $casted_event {\n when *.type == QUIT { last main }\n when *.type == WINDOWEVENT {\n if .event == 5 {\n $width = .data1;\n $height = .data2;\n }\n }\n when *.type == KEYDOWN {\n if KEY_CODES(.scancode) -> $comm {\n given $comm {\n when 'K_SPACE' { $dir *= -1; }\n }\n }\n #say .scancode; # unknown key pressed\n }\n }\n }\n ($cx, $cy) = $width div 2, $height div 2;\n\n for 1..^$num {\n my ($x, $y) = ($cx - ($width/2/$num*$_), $cy - ($height/2/$num*$_))ยป.round;\n my ($w, $h) = ($width/$num*$_, $height/$num*$_)ยป.round;\n SDL_SetRenderDrawColor($render, |@rgb[$_], 255);\n SDL_RenderDrawRect($render, SDL_Rect.new(:x($x),ย :y($y),ย :w($w),ย :h($h)));\n }\n @rgb.=rotate($dir);\n SDL_RenderPresent($render);\n SDL_SetRenderDrawColor($render, 0, 0, 0, 0);\n SDL_RenderClear($render);\n}\n\nSDL_Quit();\n\nsub palette ($l) { (^$l).map: { hsv2rgb(($_ * 360/$lย % 360)/360, 1, 1).list } };\n\nsub hsv2rgb ( $h, $s, $v ){ # inputs normalized 0-1\n my $c = $v * $s;\n my $x = $c * (1 - abs( (($h*6)ย % 2) - 1 ) );\n my $m = $v - $c;\n my ($r, $g, $b) = do given $h {\n when 0..^(1/6) { $c, $x, 0 }\n when 1/6..^(1/3) { $x, $c, 0 }\n when 1/3..^(1/2) { 0, $c, $x }\n when 1/2..^(2/3) { 0, $x, $c }\n when 2/3..^(5/6) { $x, 0, $c }\n when 5/6..1 { $c, 0, $x }\n }\n ( $r, $g, $b ).map: ((*+$m) * 255).Int\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nRaku runs on several different operating systems over many different architectures so can not easily assume direct control over hardware. Instead, like most modern programming languages, it relies on the current OS and windowing system to provide APIs.\n\nHere is an example which will work for most Debian based Linuxs (and probably others) running some variant of X11 with a single active monitor.\n\n**Works with**: Rakudo version 2018.05\n\n```\nmy @info = QX('xrandr -q').lines;\n\n@info[0] ~~ /<?after 'current '>(\\d+) ' x ' (\\d+)/;\nmy $current = \"$0x$1\";\n\nmy @resolutions;\[email protected]: $0 if $_ ~~ /^\\s+(\\d+'x'\\d+)/ for @info;\n\nQX(\"xrandr -s @resolutions[*-1]\");\nsay \"Current resolution {@resolutions[*-1]}.\";\nfor 9 ... 1 {\n print \"\\rChanging back in $_ seconds...\";\n sleep 1;\n}\nQX(\"xrandr -s $current\");\nsay \"\\rResolution returned to {$current}. \";\n\n```"
}
]
|
[
{
"role": "user",
"content": "Recreate the vidir utility in your favorite programming language.\n\nVidir is a bulk file renaming utility included in the moreutils package available for Linux and Linux-like operating systems.\n\nBasic operation involves:\n\n* Reading the file names from a directory into a text file.\n* Editing the text file with a third party editor to make bulk changes to file names (modify,delete).\n* Using the edited text file to then apply the desired changes to the file system.\n\nIn general, the filenames are typically written to the text file, one to a line with an identifying label (a unique integer in the originals case). The text file is edited as desired; file names changed, files moved, files removed, files added. Then the edited text file is used to apply the changes to the file system.\n\nIt is not required to support multiple operating systems. Make a note of which one(s) are supported.\n\nThere are many possible ways to enhance the utility but that is the basic functionality.\n\nSome possible enhancements:\n\n* Operate on directories other than the current directory.\n* Recursive directory search.\n* File input filtering.\n* File/Directory permissions detection.\n* Allow creation of files / directories.\n* Verbose operation.\n* Text editor selectable from the command line.\n* First party text editing.\n* Support multiple operating systems\n\nAt a minimum support file name modification and file removal in the current directory. Add as many enhancements as desired.\n\nSee also\n\n* Linux.com article covering moreutils / vidir"
},
{
"role": "assistant",
"content": "**Works with**: Rakudo version 2020.05\n\nThis is a fairly faithful recreation of the vidir utility with some extra \"enhancements\". It is set up to work seamlessly with Linux, OSX and most unix-like operating systems. Probably could be adapted for Windows too but won't work there as is.\n\nTakes several positional and/or named command line parameters:\n\n**Positionals:**\n\n* **path**, string, optional, defaults to the present directory (relative './').\n* **filter**, string, optional, defaults to none. A regex assertion you can use to filter the returned file names. E.G. **\\.txt$** (filenames ending with .txt extension)\n\n**Named:**\n\n* **-r** or **--recurse**, flag, optional, default False. Recurse into nested directories and process those files as well.\n* **-v** or **--verbose**, flag, optional, default False. Be chatty about what is going on when making changes.\n* **--e=whatever** or **--editor=whatever**, string, optional, defaults the default text editor. Pass in a command name to specify a specific editor: (E.G. **--editor=vim**)\n\nWill get a list of all file names from the specified director(y|ies), put them in a temporary file and open the text file with the default (or specified) text editor.\n\nEdit the file names or directory names in the text editor: add, remove, modify file names, then save the text file; all of the modifications made to the text file will be applied to the file system.\n\n**To edit a file name:** Just edit the file name, extension, whatever. **Warning!** There is nothing preventing you from using characters in the file name which will make it difficult to open, modify or delete the file. You can screw yourself quite easily if you make an effort. With great power comes great responsibility. The foot cannon is primed and loaded.\n\nIf you add a forward solidus (directory separator: **/**) to a filename, it will treat anything between separators as a directory name and **WILL CREATE** non-existent directories.\n\n**To move a file:** Edit the directory path. The file will be moved to the new path. Non-existing directories will be created.\n\n**To delete a file:** Delete the entire line (file name and identifier) in the text file.\n\n**To add a file:** Add a new line with a unique integer (need not be in any order), one or more tabs, then the new file path/name. May be a relative or absolute path.\n\nNotice that all of the above operations will fail to apply if you lack sufficient permissions for the affected files or directories.\n\n```\nuse Sort::Naturally;\nuse File::Temp;\n\nmy %*SUB-MAIN-OPTS =ย :named-anywhere;\n\nunit sub MAIN (\n Str $path = '.', #= default $path\n Str $filter = '', #= default file filter\n Boolย :r(:$recurse)= False, #= recursion flag\n Boolย :v(:$verbose)= False, #= verbose mode\n Strย :e(:$editor) = $*DISTRO ~~ /'Darwin'/ย ?? \"open\"ย !! \"xdg-open\"; #= default editor\n);\n\nmy $dir = $path;\n\n# fix up path if necessary\n$dir ~= '/' unless $dir.substr(*-1) eq '/';\n\n# check that path is reachable\ndie \"Can not find directory $dir\" unless $dir.IO.d;\n\n\nmy @files;\n\n# get files from that path\ngetdir( $dir, $filter );\n\n@files.= sort( &naturally );\n\n# set up a temp file and file handle\nmy ($filename, $filehandle) = tempfileย :suffix('.vidir');\n\n# write the filenames to the tempfile\[email protected]: { $filehandle.printf(\"%s\\t%s\\n\", $^k, $^v) };\n\n# flush the buffer to make sure all of the filenames have been written\n$filehandle.flush;\n\n# editor command\nmy $command = \"$editor $filename\";\n\n# start text editor; suppress STDERR, some editors complain about open files being deleted\nshell(\"$command 2> /dev/null\");\n\nreact {\n # watch for file changes\n whenever IO::Notification.watch-path($filename) {\n # allow a short interval for the file to finish writing\n sleep .1;\n\n # read in changed file\n my %changes = $filename.IO.lines.map( { my ($k, $v) = .split(/\\t+/); \"{$k.trim}\" => $v} );\n\n # walk the filenames and make the desired changes\n for ^@files -> $k {\n if %changes{\"$k\"}:exists {\n # name has changed, rename the file on disk\n if (%changes{\"$k\"}) ne @files[$k] {\n # check to see that the desired directory exists\n checkdir %changes{\"$k\"};\n # notify and do it\n say \"Renaming: {@files[$k]} to \" ~ %changes{\"$k\"} if $verbose;\n rename @files[$k], %changes{\"$k\"} orelse .die;\n }\n %changes{\"$k\"}:delete;\n }\n else {\n # name is gone, delete the file\n # notify and do it\n say \"Deleting: {@files[$k]}\" if $verbose;\n @files[$k].unlink orelse .die;\n }\n }\n for %changes.kv -> $k, $v {\n # a new name is added, add an empty file with that name\n # check to see that the desired directory exists\n checkdir $v;\n # notify and do it\n say \"Adding: $v\" if $verbose;\n shell(\"touch $v\") orelse .die;\n }\n # clean up when done\n done;\n exit;\n };\n # watch for CTRL-C, cleanup and exit\n whenever signal(SIGINT) {\n print \"\\b\\b\";\n done;\n exit;\n }\n}\n\n# get the files in a specified directory matching the filter parameter\nsub files ( $dir, $filter = '' ) {\n if $filter.chars {\n $dir.IO.dir.grep( *.f ).grep( *.basename.contains(/<$filter>/) );\n } else {\n $dir.IO.dir.grep( *.f );\n }\n}\n\n# get the files in the present directory and recurse if desired\nsub getdir ($dir, $filter) {\n if $recurse {\n @files.append: files($dir, $filter);\n getdir( $_, $filter ) for $dir.IO.dir.grep( *.d );\n } else {\n @files = files($dir, $filter);\n }\n}\n\n# check for existence of a directory and create it if not found\nsub checkdir ($dir) {\n unless $dir.IO.dirname.IO.e {\n # if not, create it\n my @path = $dir.IO.dirname.split('/');\n for 1 .. @path {\n my $thispath = @path[^$_].join('/');\n unless $thispath.IO.e {\n say \"Creating new directory $thispath\" if $verbose;\n mkdir($thispath);\n }\n }\n }\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a ย Vigenรจre cypher, ย both encryption and decryption.\n\nThe program should handle keys and text of unequal length,\nand should capitalize everything and discard non-alphabetic characters. \n(If your program handles non-alphabetic characters in another way,\nmake a note of it.)\n\nRelated tasks\n\n* Caesar cipher\n* Rot-13\n* Substitution Cipher"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-11-14\n\n```\nsub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)ยป.ordย ยป-ยป 65 }\nsub v2s (@v) { (@vย ยป%ยป 26ย ยป+ยป 65)ยป.chr.join }\n\nsub blacken ($red, $key) { v2s(s2v($red)ย ยป+ยป s2v($key)) }\nsub redden ($blk, $key) { v2s(s2v($blk)ย ยป-ยป s2v($key)) }\n\nmy $red = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\nmy $key = \"Vigenere Cipher!!!\";\n\nsay $red;\nsay my $black = blacken($red, $key);\nsay redden($black, $key);\n\n```\n\nOutput:\n\n```\nBeware the Jabberwock, my son! The jaws that bite, the claws that catch!\nWMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nBEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n```\n\nThis is a natural job for hyperoperators, which can vectorize any operator.\nFor infix operators the pointy end indicates which side to \"dwim\", repeating\nelements on that side until the other side runs out. In particular, repeating\nthe key naturally falls out of this cyclic dwimmery, as does repeating the various constants to be applied with any of several operations to every element of the list. Factoring out the canonicalization and decanonicalization lets us see quite clearly that the only difference between encryption and decryptions is the sign of the vector addition/subtraction. Since hyperops are inherently parallelizable, this algorithm might run well in your GPU."
}
]
|
[
{
"role": "user",
"content": "Given some text you suspect has been encrypted with a Vigenรจre cipher, extract the key and plaintext. There are several methods for doing this. See the Wikipedia entry for more information. Use the following encrypted text:\n\n```\nMOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\nVUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\nITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\nFGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\nALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\nILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\nJLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\nLPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\nMTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\nQGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\nRVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\nTTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\nSFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\nZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\nBUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\nBXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\nFWAML ZZRXJ EKAHV FASMU LVVUT TGK\n\n```\n\nLetter frequencies for English can be found here.\n\nSpecifics for this task:\n\n* Take only the ciphertext as input. You can assume it's all capitalized and has no punctuation, but it might have whitespace.\n* Assume the plaintext is written in English.\n* Find and output the key.\n* Use that key to decrypt and output the original plaintext. Maintaining the whitespace from the ciphertext is optional.\n* The algorithm doesn't have to be perfect (which may not be possible) but it should work when given enough ciphertext. The example above is fairly long, and should be plenty for any algorithm."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\n# from Wikipedia\nconstant %English-letter-freq = (\n E => 12.70, L => 4.03, Y => 1.97, P => 1.93, T => 9.06, A => 8.17, O => 7.51, I => 6.97, N => 6.75,\n S => 6.33, H => 6.09, R => 5.99, D => 4.25, C => 2.78, U => 2.76, M => 2.41, W => 2.36, F => 2.23,\n G => 2.02, B => 1.29, V => 0.98, K => 0.77, J => 0.15, X => 0.15, Q => 0.10, Z => 0.07\n);\nconstant @alphabet = %English-letter-freq.keys.sort;\nconstant max_key_lengths = 5; # number of keylengths to try\n\nsub myguess ($text) {\n my ($seqtext, @spacing, @factors, $pos, %freq, %Keys);\n\n # Kasiski examination\n $seqtext = $text;\n while ($seqtext ~~ /$<sequence>=[...].*$<sequence>/) {\n $seqtext = substr($seqtext, 1+index($seqtext, $<sequence>));\n push @spacing, 1 + index($seqtext, $<sequence>);\n }\n for @spacing -> $j {\n %freq{$_}++ for grep { $jย %% $_ }, 2..$j;\n }\n\n # discard very short keys, and test only the most likely remaining key lengths\n (%freq.keys.grep(* > 3).sort({%freq{$_}}).tail(max_key_lengths)).race(:1batch).map: -> $keylen {\n my $key-guess = '';\n loop (my $i = 0; $i < $keylen; $i++) {\n my ($mykey, %chi-square, $best-guess);\n loop (my $j = 0; $j < $text.chars; $j += $keylen) {\n $mykey ~= substr($text, ($j+$i)ย % $text.chars, 1);\n }\n\n for @alphabet -> $subkey {\n my $decrypted = mycrypt($mykey, $subkey);\n my $length = $decrypted.chars;\n for @alphabet -> $char {\n my $expected = %English-letter-freq{$char} * $length / 100;\n my $observed = $decrypted.comb.grep(* eq $char).elems;\n %chi-square{$subkey} += ($observed - $expected)ยฒ / $expected if $observed;\n }\n }\n %Keys{$keylen}{'score'} = %chi-square{@alphabet[0]};\n for %chi-square.keys.sort -> $sk {\n if (%chi-square{$sk} <= %Keys{$keylen}{'score'}) {\n $best-guess = $sk;\n %Keys{$keylen}{'score'} = %chi-square{$sk};\n }\n }\n $key-guess ~= $best-guess;\n }\n %Keys{$keylen}{'key'} = $key-guess;\n }\n %Keys.keys.sort({ %Keys{$_}{'score'} }).map:{ %Keys{$_}{'key'} };\n}\n\nsub mycrypt ($text, $key) {\n constant %values-numbers = @alphabet Z=> ^@alphabet;\n constant %values-letters = %values-numbers.invert;\n\n my ($new-text);\n my $keylen = $key.chars;\n loop (my $i = 0; $i < $text.chars; $i++) {\n my $val = -1 * %values-numbers{substr( $key, $i%$keylen, 1)} # negative shift for decode\n + %values-numbers{substr($text, $i, 1)};\n $new-text ~= %values-letters{ $valย % @alphabet };\n }\n return $new-text;\n}\n\nmy $cipher-text = .uc.trans(@alphabet => '',ย :c) given q:to/EOD/;\n MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\n VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\n ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\n FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\n ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\n ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\n JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\n LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\n MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\n QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\n RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\n TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\n SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\n ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\n BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\n BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\n FWAML ZZRXJ EKAHV FASMU LVVUT TGK\nEOD\n\nfor myguess($cipher-text) -> $key {\n say \"Key $key\\n\" ~\n \"Key length {$key.chars}\\n\" ~\n \"Plaintext {substr(mycrypt($cipher-text, $key), 0, 80)}...\\n\";\n}\n\n```\n\nOutput:\n\n```\nKey THECHESHIRECAT\nKey length 14\nPlaintext THISWASTHEPOEMTHATALICEREADJABBERWOCKYTWASBRILLIGANDTHESLITHYTOVESDIDGYREANDGIMB...\n\nKey THECHESCIRECATTHECHESHIRECAT\nKey length 28\nPlaintext THISWASYHEPOEMTHATALICEREADJABBERWOHKYTWASBRILLIGANDTHESLITHYTOAESDIDGYREANDGIMB...\n\nKey TJGGAHET\nKey length 8\nPlaintext TFGODXGHWMNKEYIVLMBJACIPPTXWTBBNFRADSITFHCOSMGOTFYPOXCASLGRDFQCJTABEDSNFPTOBYIQZ...\n\nKey THECSAS\nKey length 7\nPlaintext THISLESHIRRYENTHATPPIQFEGKDKABBEGAOQLLVGATBRILAMGOOQVRETLITHNXOJFFFSDHYREACHGWNO...\n\nKey THEC\nKey length 4\nPlaintext THISKXGYWOPOLYIMLODNHCIGPVZAABBEFTCHZITWHEQWTGOKFARSECAJLITHMQCATCDIKSNWPVQFFIQQ...\n```"
}
]
|
[
{
"role": "user",
"content": "Description\n\nIn object oriented programming, the Visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying the structures.\n\nIt is one way to follow the open/closed principle which states that: \"software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification\".\n\nThe Visitor pattern is one of the twenty-three Gang of Four design patterns that facilitate the solution of recurring design problems in object-oriented software.\n\nOperation\n\nConsider two objects, each of some class type; one is termed the *element*, and the other is the *visitor*.\n\nThe visitor declares a *visit* method, which takes the element as an argument, for each class of element. Concrete visitors are derived from the visitor class and implement these visit methods, each of which implements part of the algorithm operating on the object structure. The state of the algorithm is maintained locally by the concrete visitor class.\n\nThe element declares an *accept* method to accept a visitor, taking the visitor as an argument. Concrete elements, derived from the element class, implement the accept method. Composite elements, which maintain a list of child objects, typically iterate over these, calling each child's accept method.\n\nHaving created the object structure, a program should first instantiate the concrete visitors. When an operation is to be performed which is implemented using the Visitor pattern, it should then call the accept method of the top-level element(s) passing the visitor(s) as arguments.\n\nExamples\n\nThe Wikipedia article contains examples of the Visitor pattern written in: C#, Smalltalk, Go (partial), Java, Common Lisp and Python.\n\nTask\n\nDemonstrate the workings of the Visitor pattern in your language by translating one (or more) of the Wikipedia examples. If your language is one of those for which an example already exists, try to translate one of the other examples.\n\nIf you don't know any of the example languages or prefer to use your own example, then this is also acceptable.\n\nIf your language does not support the object oriented paradigm at all (or only to a limited extent), then try to emulate the intent of the pattern with the tools it does have by writing a program which produces the same output as one of the Wikipedia examples.\n\nReferences\n\n* Wikipedia: Visitor pattern\n* Code Project - The Visitor Pattern Explained"
},
{
"role": "assistant",
"content": "Raku implements multiple dispatch so the visitor pattern is perhaps not as useful/necessary there. That said, it can be done fairly easily.\n\n(Largely based on an example published by Johnathan Stowe.)\n\n```\nrole CarElementVisitor { ... }\n\nclass CarElement {\n method accept(CarElementVisitor $visitor) {\n $visitor.visit: self\n }\n}\n\nclass Body is CarElement { }\n\nclass Engine is CarElement { }\n\nclass Wheel is CarElement {\n has Str $.name is required;\n}\n\nclass Car is CarElement {\n has CarElement @.elements = ( \n Wheel.new(name => \"front left\"),\n Wheel.new(name => \"front right\"),\n Wheel.new(name => \"rear left\"),\n Wheel.new(name => \"rear right\"),\n Body.new,\n Engine.new\n );\n\n method accept(CarElementVisitor $visitor) {\n for @.elements -> $element { $element.accept: $visitor };\n $visitor.visit: self;\n }\n}\n\nrole CarElementVisitor {\n method visit(CarElement $e) { ... }\n}\n\nclass CarElementDoVisitor does CarElementVisitor {\n multi method visit(Body $e) {\n say \"Moving my body.\";\n }\n multi method visit(Car $e) {\n say \"Starting my car.\";\n }\n multi method visit(Wheel $e) {\n say \"Kicking my { $e.name } wheel.\";\n }\n multi method visit(Engine $e) {\n say \"Starting my engine.\";\n }\n}\n\nclass CarElementPrintVisitor does CarElementVisitor {\n multi method visit(Body $e) {\n say \"Visiting body.\";\n }\n multi method visit(Car $e) {\n say \"Visiting car.\";\n }\n multi method visit(Wheel $e) {\n say \"Visiting { $e.name } wheel.\";\n }\n multi method visit(Engine $e) {\n say \"Visiting engine.\";\n }\n}\n\nmy Car $car = Car.new;\n\n$car.accept: CarElementPrintVisitor.new;\n$car.accept: CarElementDoVisitor.new;\n\n```\n\nOutput:\n\n```\nVisiting front left wheel.\nVisiting front right wheel.\nVisiting rear left wheel.\nVisiting rear right wheel.\nVisiting body.\nVisiting engine.\nVisiting car.\nKicking my front left wheel.\nKicking my front right wheel.\nKicking my rear left wheel.\nKicking my rear right wheel.\nMoving my body.\nStarting my engine.\nStarting my car.\n```"
}
]
|
[
{
"role": "user",
"content": "A tree structure ย (i.e. a rooted, connected acyclic graph) ย is often used in programming.\n\nIt's often helpful to visually examine such a structure.\n\nThere are many ways to represent trees to a reader, such as:\n\n: : : * indented text ย (ร la unix `tree` command)\n * nested HTML tables\n * hierarchical GUI widgets\n * 2D ย or ย 3D ย images\n * etc.\n\nTask\n\nWrite a program to produce a visual representation of some tree.\n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly.\n\nMake do with the vague term \"friendly\" the best you can."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub visualize-tree($tree, &label, &children,\n ย :$indent = '',\n ย :@mid = ('โโ', 'โ '),\n ย :@end = ('โโ', ' '),\n) {\n sub visit($node, *@pre) {\n | gather {\n take @pre[0] ~ label($node);\n my @childrenย := children($node);\n my $end = @children.end;\n for @children.kv -> $_, $child {\n when $end { take visit($child, (@pre[1] X~ @end)) }\n default { take visit($child, (@pre[1] X~ @mid)) }\n }\n }\n }\n visit($tree, $indent xx 2);\n}\n\n# example tree built up of pairs\nmy $tree = root=>[a=>[a1=>[a11=>[]]],b=>[b1=>[b11=>[]],b2=>[],b3=>[]]];\n\n.map({.join(\"\\n\")}).join(\"\\n\").say for visualize-tree($tree, *.key, *.value.list);\n\n```\n\nOutput:\n\n```\nroot\nโโa\nโ โโa1\nโ โโa11\nโโb\n โโb1\n โ โโb11\n โโb2\n โโb3\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at VList. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn computer science, the **VList** is a persistent data structure that combines the fast indexing of arrays with the easy extension of cons-based (or singly-linked) linked lists.\n\nLike arrays, VLists have constant-time lookup on average and are highly compact, requiring only O(log *n*) storage for pointers, allowing them to take advantage of locality of reference.\nLike singly-linked or cons-based lists, they are persistent, and elements can be added to or removed from the front in constant time. Length can also be found in O(log *n*) time.\n\nThe primary operations of a VList are:\n\n* Locate the *k*th element (O(1) average, O(log *n*) worst-case)\n* Add an element to the front of the VList (O(1) average, with an occasional allocation)\n* Obtain a new array beginning at the second element of an old array (O(1))\n* Compute the length of the list (O(log *n*))\n\nTask\n\nThe task is to demonstrate creation of a VList and how to perform the primary operations."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Go\n\n**Translation of**: Kotlin\n\n```\nclass vList {\n\n subset vEle of Any; # or Str\n\n class vSeg {\n has $.next is rw is default(Nil)ย ;\n has vEle @.ele is rwย ;\n }\n\n has vSeg $.base is rw is default(vSeg.new(ele=>()));\n has Int $.offset is rw is default(0)ย ;\n\n method Index(Int $i is copy --> vEle) { # method to locate the kth element\n if $i โฅ 0 {\n loop ( $i += self.offset, $_ = self.base; $_.defined; $_ย := $_.next) {\n ($i < my $len = .ele.elems)ย ?? return .ele[$i]ย !! $i -= $len\n }\n }\n die \"index out of range\"\n }\n\n method cons(vEle \\a --> vList) { # method to add an element to the front\n if not self.base.ele.Bool { # probably faster than .elemsย ?\n self.base.ele.push: aย ;\n return self;\n } elsif self.offset == 0 {\n my \\L2offset = (self.base.ele.elems * 2) - 1ย ;\n my \\s = vSeg.new(next => self.base, ele => flat Nil xx L2offset, a);\n return vList.new(base => s, offset => L2offset )\n }\n self.base.ele[--self.offset] = a;\n return self\n }\n\n # obtain a new array beginning at the second element of an old array\n method cdr(--> vList) {\n die \"cdr on empty vList\" unless self.base.defined;\n return self if ++self.offset < self.base.ele.elems;\n return vList.new(base => self.base.next)\n }\n\n method Length(--> Int) { # method to compute the length of the list\n return 0 unless self.base.defined;\n return self.base.ele.elems*2 - self.offset - 1\n }\n\n method gist { # (mis)used to create output similar to Go/Kotlin\n return '[]' unless self.base.ele.Bool;\n my @sl = self.base.ele[self.offset .. *];\n loop ($_=self.base.next; $_.defined; $_:=$_.next) { @sl.append: .ele }\n return \"[\" ~ @sl.Str ~ \"]\"\n }\n\n method printStructure { # One more method for demonstration purposes\n say \"offset: \", self.offset;\n loop ( $_ = self.base; $_.definedย ; $_ย := $_.next ) { .ele.say }\n }\n}\n\nmy $vย := vList.new;\nsay \"zero value for type. empty vList: \", $v;\n$v.printStructure;\nsay \" \";\n$vย := $v.cons($_.Str) for 6 โฆ 1;\nsay \"demonstrate cons. 6 elements added: \", $v;\n$v.printStructure;\nsay \" \";\n$vย := $v.cdr;\nsay \"demonstrate cdr. 1 element removed: \", $v;\n$v.printStructure;\nsay \" \";\nsay \"demonstrate length. length = \", $v.Length;\nsay \" \";\nsay \"demonstrate element access. v[3] = \", $v.Index(3)ย ;\nsay \" \";\n$vย := $v.cdr.cdr;\nsay \"show cdr releasing segment. 2 elements removed: \", $v;\n$v.printStructure;\n\n```\n\nOutput:\n\n```\nzero value for type. empty vList: []\noffset: 0\n[]\n\ndemonstrate cons. 6 elements added: [1 2 3 4 5 6]\noffset: 1\n[(vEle) 1 2 3]\n[4 5]\n[6]\n\ndemonstrate cdr. 1 element removed: [2 3 4 5 6]\noffset: 2\n[(vEle) 1 2 3]\n[4 5]\n[6]\n\ndemonstrate length. length = 5\n\ndemonstrate element access. v[3] = 5\n\nshow cdr releasing segment. 2 elements removed: [4 5 6]\noffset: 0\n[4 5]\n[6]\n\n```"
}
]
|
[
{
"role": "user",
"content": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them โAโ, โBโ, โCโ, โDโ, and โEโ. They estimate that:\n\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called โWโ, โXโ, โYโ, and โZโ.\n\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\n\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n```\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n```\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n: Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)\n: Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.\n: Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).\n: Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.\n: Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.\n: Step 6: Compute total transportation cost for the feasible allocations.\n\nFor this task assume that the model is balanced.\n\nFor each task and contractor (row and column above) calculating the difference between the smallest two values produces:\n\n```\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n```\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n```\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\n```\n\nFinally calculate the cost of your solution. In the example given it is ยฃ3100:\n\n```\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n```\n\nThe optimal solution determined by GLPK is ยฃ3100:\n\n```\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n```\n\nCf.\n\n* Transportation problem"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03.1\n\n**Translation of**: Sidef\n\n```\nmy %costs =\n ย :W{:16A,ย :16B,ย :13C,ย :22D,ย :17E},\n ย :X{:14A,ย :14B,ย :13C,ย :19D,ย :15E},\n ย :Y{:19A,ย :19B,ย :20C,ย :23D,ย :50E},\n ย :Z{:50A,ย :12B,ย :50C,ย :15D,ย :11E};\n\nmy %demand =ย :30A,ย :20B,ย :70C,ย :30D,ย :60E;\nmy %supply =ย :50W,ย :60X,ย :50Y,ย :50Z;\n\nmy @cols = %demand.keys.sort;\n\nmy %res;\nmy %g = (|%supply.keys.map: -> $x { $x => [%costs{$x}.sort(*.value)ยป.key]}),\n (|%demand.keys.map: -> $x { $x => [%costs.keys.sort({%costs{$_}{$x}})]});\n\nwhile (+%g) {\n my @d = %demand.keys.map: -> $x\n {[$x, my $z = %costs{%g{$x}[0]}{$x},%g{$x}[1]ย ?? %costs{%g{$x}[1]}{$x} - $zย !! $z]}\n\n my @s = %supply.keys.map: -> $x\n {[$x, my $z = %costs{$x}{%g{$x}[0]},%g{$x}[1]ย ?? %costs{$x}{%g{$x}[1]} - $zย !! $z]}\n\n @d = |@d.grep({ (.[2] == max @dยป.[2]) }).&min:ย :by(*.[1]);\n @s = |@s.grep({ (.[2] == max @sยป.[2]) }).&min:ย :by(*.[1]);\n\n my ($t, $f) = @d[2] == @s[2]ย ?? (@s[1],@d[1])ย !! (@d[2],@s[2]);\n my ($d, $s) = $t > $fย ?? (@d[0],%g{@d[0]}[0])ย !! (%g{@s[0]}[0], @s[0]);\n\n my $v = %supply{$s} min %demand{$d};\n\n %res{$s}{$d} += $v;\n %demand{$d} -= $v;\n\n if (%demand{$d} == 0) {\n %supply.grep( *.valueย != 0 )ยป.key.map: -> $v\n { %g{$v}.splice((%g{$v}.first: * eq $d,ย :k),1) };\n %g{$d}:delete;\n %demand{$d}:delete;\n }\n\n %supply{$s} -= $v;\n\n if (%supply{$s} == 0) {\n %demand.grep( *.valueย != 0 )ยป.key.map: -> $v\n { %g{$v}.splice((%g{$v}.first: * eq $s,ย :k),1) };\n %g{$s}:delete;\n %supply{$s}:delete;\n }\n}\n\nsay join \"\\t\", flat '', @cols;\nmy $total;\nfor %costs.keys.sort -> $g {\n print \"$g\\t\";\n for @cols -> $col {\n print %res{$g}{$col} // '-', \"\\t\";\n $total += (%res{$g}{$col} // 0) * %costs{$g}{$col};\n }\n print \"\\n\";\n}\nsay \"\\nTotal cost: $total\";\n\n```\n\nOutput:\n\n```\n\tA\tB\tC\tD\tE\nW\t-\t-\t50\t-\t-\t\nX\t30\t-\t20\t-\t10\t\nY\t-\t20\t-\t30\t-\t\nZ\t-\t-\t-\t-\t50\t\n\nTotal cost: 3100\n```"
}
]
|
[
{
"role": "user",
"content": "A Voronoi diagram is a diagram consisting of a number of sites.\n\nEach Voronoi site *s* also has a Voronoi cell consisting of all points closest to *s*.\n\nTask\n\nDemonstrate how to generate and display a Voroni diagram.\n\nSee algo K-means++ clustering."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.09\n\n**Translation of**: Python\n\nPerhaps \"Inspired by Python\" would be more accurate.\n\nGenerates a Euclidean, a Taxicab and a Minkowski Voronoi diagram using the same set of domain points and colors.\n\n```\nuse Image::PNG::Portable;\n\nmy @bars = 'โโโโ
โโโโโ
โโโ'.comb;\n\nmy %type = ( # Voronoi diagram type distance calculation\n 'Taxicab' => sub ($px, $py, $x, $y) { ($px - $x).abs + ($py - $y).abs },\n 'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)ยฒ + ($py - $y)ยฒ },\n 'Minkowski' => sub ($px, $py, $x, $y) { ($px - $x)ยณ.abs + ($py - $y)ยณ.abs },\n);\n\nmy $width = 400;\nmy $height = 400;\nmy $dots = 30;\n\nmy @domains = map { Hash.new(\n 'x' => (5..$width-5).roll,\n 'y' => (5..$height-5).roll,\n 'rgb' => [(64..255).roll xx 3]\n) }, ^$dots;\n\nfor %type.keys -> $type {\n print \"\\nGenerating $type diagram... \", ' ' x @bars;\n my $img = voronoi(@domains,ย :w($width),ย :h($height),ย :$type);\n @domains.map: *.&dot($img);\n $img.write: \"Voronoi-{$type}-perl6.png\";\n}\n\nsub voronoi (@domains,ย :$w,ย :$h,ย :$type) {\n my $png = Image::PNG::Portable.new:ย :width($w),ย :height($h);\n (^$w).race.map: -> $x {\n print \"\\b\" x 2+@bars, @bars.=rotate(1).join , ' ';\n for ^$h -> $y {\n my ($, $i) = min @domains.map: { %type{$type}(%($_)<x>,ย %($_)<y>, $x, $y), $++ };\n $png.set: $x, $y, |@domains[$i]<rgb>\n }\n }\n $png\n}\n\nsub dot (%h, $png, $radius = 3) {\n for (%h<x> X+ -$radius .. $radius) X (%h<y> X+ -$radius .. $radius) -> ($x, $y) {\n $png.set($x, $y, 0, 0, 0) if ( %h<x> - $x + (%h<y> - $y) * i ).abs <= $radius;\n }\n}\n\n```\n\nSee Euclidean, Taxicab & Minkowski Voronoi diagram example images."
}
]
|
[
{
"role": "user",
"content": "Definition\n\nA *Wagstaff prime* is a prime number of the form *(2^p + 1)/3* where the exponent *p* is an odd prime.\n\nExample\n\n(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.\n\nTask\n\nFind and show here the first *10* Wagstaff primes and their corresponding exponents *p*.\n\nStretch (requires arbitrary precision integers)\n\nFind and show here the exponents *p* corresponding to the next *14* Wagstaff primes (not the primes themselves) and any more that you have the patience for.\n\nWhen testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.\n\nNote\n\nIt can be shown (see talk page) that *(2^p + 1)/3* is always integral if *p* is odd. So there's no need to check for that prior to checking for primality.\n\nReferences\n\n* Wikipedia - Wagstaff prime\n* OEIS:A000979 - Wagstaff primes"
},
{
"role": "assistant",
"content": "```\n# First 20\n\nmy @wagstaff = (^โ).grep: { .is-prime && ((1 + 1 +< $_)/3).is-prime };\n\nsay ++$ ~ \": $_ - {(1 + 1 +< $_)/3}\" for @wagstaff[^20];\n\nsay .fmt(\"\\nTotal elapsed seconds: (%.2f)\\n\") given (my $elapsed = now) - INIT now;\n\n# However many I have patience for\n\nmy atomicint $count = 20;\n\nhyper for @wagstaff[20] .. * {\n next unless .is-prime;\n say ++โ$count ~ \": $_ ({sprintf \"%.2f\", now - $elapsed})\" and $elapsed = now if is-prime (1 + 1 +< $_)/3;\n}\n\n```\n\nOutput:\n\n*Turns out, \"however many I have patience for\" is 9 (29).*\n\n```\n1: 3 - 3\n2: 5 - 11\n3: 7 - 43\n4: 11 - 683\n5: 13 - 2731\n6: 17 - 43691\n7: 19 - 174763\n8: 23 - 2796203\n9: 31 - 715827883\n10: 43 - 2932031007403\n11: 61 - 768614336404564651\n12: 79 - 201487636602438195784363\n13: 101 - 845100400152152934331135470251\n14: 127 - 56713727820156410577229101238628035243\n15: 167 - 62357403192785191176690552862561408838653121833643\n16: 191 - 1046183622564446793972631570534611069350392574077339085483\n17: 199 - 267823007376498379256993682056860433753700498963798805883563\n18: 313 - 5562466239377370006237035693149875298444543026970449921737087520370363869220418099018130434731\n19: 347 - 95562442332919646317117537304253622533190207882011713489066201641121786503686867002917439712921903606443\n20: 701 - 3506757267698915671493993255253419110366893201882115906332187268712488102864720548075777690851725634151321979237452145142012954833455869242085209847101253899970149114085629732127775838589548478180862167823854251\n\nTotal elapsed seconds: (0.09)\n\n21: 1709 (0.87)\n22: 2617 (0.92)\n23: 3539 (2.03)\n24: 5807 (13.18)\n25: 10501 (114.14)\n26: 10691 (114.14)\n27: 11279 (48.13)\n28: 12391 (92.99)\n29: 14479 (179.87)\n^C\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWalk a given directory and print the *names* of files matching a given pattern.\n\n(How is \"pattern\" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)\n\n**Note:** This task is for non-recursive methods. ย These tasks should read a *single directory*, not an entire directory tree.\n\n**Note:** Please be careful when running any code presented here.\n\nRelated task\n\n* Walk Directory Tree ย (read entire directory tree)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nThe `dir` function takes the directory to traverse, and optionally a named parameter `test`, which is smart-matched against the basename of each file (so for example we can use a regex):\n\n```\n.say for dir \".\",ย :test(/foo/);\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWalk a given directory *tree* and print files matching a given pattern.\n\n**Note:** This task is for recursive methods. ย These tasks should read an entire directory tree, not a *single directory*.\n\n**Note:** Please be careful when running any code examples found here.\n\nRelated task\n\n* Walk a directory/Non-recursively ย (read a *single directory*)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nUsing the File::Find module:\n\n```\nuse File::Find;\n\n.say for find dir => '.', name => /'.txt' $/;\n\n```\n\nAlternatively, a custom solution that provides the same interface as the built-in (non-recursive) dir function, and uses gather/take to return a lazy sequence:\n\n```\nsub find-files ($dir, Muย :$test) {\n gather for dir $dir -> $path {\n if $path.basename ~~ $test { take $path }\n if $path.d { .take for find-files $path,ย :$test };\n }\n}\n \n.put for find-files '.', test => /'.txt' $/;\n\n```\n\nOr if you value performance over portability, here's a function that runs the GNU find program and returns a lazy sequence of the files it finds. Parameters are not subjected to shell expansion, and the null-byte (which cannot be present in file paths) is used as the path delimiter, so it should be pretty safe.\n\n```\nsub find-files ($dir,ย :$pattern) {\n run('find', $dir, '-iname', $pattern, '-print0',ย :out,ย :nlยซ\\0ยป).out.lines;\n}\n\n.say for find-files '.', pattern => '*.txt';\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Walsh matrix. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nA **Walsh matrix** is a specific square matrix of dimensions 2*n*, where *n* is some particular natural number. The elements of the matrix are either **+1** or **โ1** and its rows as well as columns are orthogonal, *i.e. dot product is zero*. Each row of a Walsh matrix corresponds to a Walsh function.\n\nWalsh matrices are a special case of Hadamard matrices. The *naturally ordered* Hadamard (Walsh) matrix is defined by the recursive formula below, and the *sequency-ordered* Hadamard (Walsh) matrix is formed by rearranging the rows so that the number of sign changes in a row is in increasing order.\n\nTo generate a naturally ordered Walsh matrix\n\nMatrices of dimension 2*k* for *k*ย โย *N* are given by the recursive formula:\n\n: W\n\n (\n\n 2\n\n 1\n )\n\n\n =\n\n\n [\n\n 1\n\n 1\n\n\n 1\n\n โ\n 1\n ]\n ,\n\n\n W\n\n (\n\n 2\n\n 2\n )\n\n\n =\n\n\n [\n\n 1\n\n 1\n\n 1\n\n 1\n\n\n 1\n\n โ\n 1\n\n 1\n\n โ\n 1\n\n\n 1\n\n 1\n\n โ\n 1\n\n โ\n 1\n\n\n 1\n\n โ\n 1\n\n โ\n 1\n\n 1\n ]\n ,\n {\\displaystyle {\\displaystyle {\\begin{aligned}W\\left(2^{1}\\right)&={\\begin{bmatrix}1&1\\\\1&-1\\end{bmatrix}},\\\\W\\left(2^{2}\\right)&={\\begin{bmatrix}1&1&1&1\\\\1&-1&1&-1\\\\1&1&-1&-1\\\\1&-1&-1&1\\\\\\end{bmatrix}},\\end{aligned}}}}\n\nand in general\n\n: W\n\n (\n\n 2\n\n k\n )\n =\n\n\n [\n\n W\n\n (\n\n 2\n\n k\n โ\n 1\n )\n\n W\n\n (\n\n 2\n\n k\n โ\n 1\n )\n\n\n W\n\n (\n\n 2\n\n k\n โ\n 1\n )\n\n โ\n W\n\n (\n\n 2\n\n k\n โ\n 1\n )\n ]\n =\n W\n (\n 2\n )\n โ\n W\n\n (\n\n 2\n\n k\n โ\n 1\n )\n ,\n {\\displaystyle {\\displaystyle W\\left(2^{k}\\right)={\\begin{bmatrix}W\\left(2^{k-1}\\right)&W\\left(2^{k-1}\\right)\\\\W\\left(2^{k-1}\\right)&-W\\left(2^{k-1}\\right)\\end{bmatrix}}=W(2)\\otimes W\\left(2^{k-1}\\right),}}\n\nfor 2ย โคย *k*ย โย *N*, where โ denotes the Kronecker product.\n\nTask\n\n* Write a routine that, given a natural number **k**, returns a **naturally ordered** Walsh matrix of order 2*k*. * Display a few sample generated matrices.\n: : *Traditionally, Walsh matrices use **1** & **-1** to denote the different cell values in text mode, or **green** and **red** blocks in image mode. You may use whichever display mode is most convenient for your particular language.*\n\nStretch\n\n* Also, optionally generate **sequency ordered** Walsh matrices.\n: : *A sequency ordered Walsh matrix has the rows sorted by number of sign changes.*\n\nSee also\n\n* Wikipedia: Walsh matrix * Related task: Kronecker product"
},
{
"role": "assistant",
"content": "```\nsub walsh (\\m) { (map {$_?? -1ย !! ' 1'}, map { :3(.base: 2)ย % 2 }, [X+&] ^2**m xx 2 ).batch: 2**m }\n\nsub natural (@row) { Same }\n\nsub sign-changes (@row) { sum (1..^@row).map: { 1 if @row[$_]ย !== @row[$_ - 1] } }\n\nuse SVG;\n\nfor &natural, 'natural', &sign-changes, 'sequency' -> &sort, $sort {\n for 2,4,5 -> $order {\n # ASCII text\n .put for \"\\nWalsh matrix - order $order ({exp($order,2)} x {exp($order,2)}), $sort order:\", |walsh($order).sort: &sort;\n\n # SVG image\n my $side = 600;\n my $scale = $side / 2**$order;\n my $row = 0;\n my @blocks;\n my %C = ' 1' => '#0F0', '-1' => '#F00';\n\n for walsh($order).sort: &sort -> @row {\n my \\x = $row++ * $scale;\n for @row.kv {\n my \\y = $^k * $scale;\n @blocks.push: (:rect[:x(x),:y(y),:width($scale),:height($scale),:fill(%C{$^v})]);\n }\n }\n\n \"walsh-matrix--order-{$order}--{$sort}-sort-order--raku.svg\".IO.spurt:\n SVG.serialize(:svg[:width($side),:height($side),:stroke<black>,:stroke-width<1>,|@blocks])\n }\n}\n\n```\n\nOutput:\n\n```\nWalsh matrix - order 2 (4 x 4), natural order:\n 1 1 1 1\n 1 -1 1 -1\n 1 1 -1 -1\n 1 -1 -1 1\n\nWalsh matrix - order 4 (16 x 16), natural order:\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1\n\nWalsh matrix - order 5 (32 x 32), natural order:\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1\n\nWalsh matrix - order 2 (4 x 4), sequency order:\n 1 1 1 1\n 1 1 -1 -1\n 1 -1 -1 1\n 1 -1 1 -1\n\nWalsh matrix - order 4 (16 x 16), sequency order:\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1\n\nWalsh matrix - order 5 (32 x 32), sequency order:\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1\n 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1\n 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 1 1 1 1 -1 -1 -1 -1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1\n 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1\n 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1\n 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1\n 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1\n 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1\n 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1\n 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1\n 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 1 -1 -1 1 -1 1 1 -1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1\n 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1\n 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1\n 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1\n 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 1 -1 1 -1 1 -1 1 -1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1\n 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 -1\n```\n\n| Natural order | Sequency order |\n| --- | --- |\n| File:Walsh-matrix--order-2--natural-sort-order--raku.svg | File:Walsh-matrix--order-2--sign-changes-sort-order--raku.svg |\n| File:Walsh-matrix--order-4--natural-sort-order--raku.svg | File:Walsh-matrix--order-4--sign-changes-sort-order--raku.svg |\n| File:Walsh-matrix--order-5--natural-sort-order--raku.svg | File:Walsh-matrix--order-5--sign-changes-sort-order--raku.svg |"
}
]
|
[
{
"role": "user",
"content": "War Card Game\n\nSimulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.\n\nReferences:\n\n: * Bicycle card company: War game site\n\n: * Wikipedia: War (card game)\n\nRelated tasks:\n\n* Playing cards\n* Card shuffles\n* Deal cards for FreeCell\n* Poker hand\\_analyser\n* Go Fish"
},
{
"role": "assistant",
"content": "The linked Bicycle cards site has slightly different rules for War! than how I used to play when I was but a lad. Implement it both ways.\n\nSome rules are not nailed down very well. Here is how I interpreted it:\n\n* The values of the cards 2-10 are face value; Jack, Queen, King and Ace may effectively be treated as: 11, 12, 13 & 14.\n* Each player plays one card face up. The player whose card is the highest value takes both of the played cards and adds them to the bottom of his deck.\n* When one player runs out of cards and is not able to place enough cards to finish a round, he loses.\n* If both players play a card of the same value, it is then War!\n + **Bicycle rules:** each player then plays another card face down then another face up.\n + **thundergnat rules:** each player then plays *three* cards face down then another face up. (Tends to make for shorter games.)\n + If the final face-up cards are different, the player playing the higher value card takes all of the played cards and adds them to the bottom of his deck\n + If they are the same, continue with rounds of War! until one player plays a higher value war card or a player runs out of cards.\n* When the winning player picks up his cards. the cards are randomized when added to the bottom of his deck. (Cuts a typical game from multi thousands of rounds to multi hundreds of rounds)\n\nPass in which variant you want to play 2 down, (Bicycle), `--war=2`, 4 down (thundergnat), (default), `--war=4` or 3 down (????) , `--war=3`. By default, there is a short delay (.1 seconds) between rounds so you can watch what is going on. Pass in a larger/smaller value to slow down or speed up how long the game takes. `--sleep=0` or whatever.\n\nIn glorious ANSI color! (The output loses much when pasted in as text so show output as screenshot images.)\n\n```\nunit sub MAIN (:$war where 2..4 = 4,ย :$sleep = .1);\n\nmy %c = ( # convenience hash of ANSI colors\n red => \"\\e[38;2;255;10;0m\",\n blue => \"\\e[38;2;05;10;200m\",\n black => \"\\e[38;2;0;0;0m\"\n);\n\nmy @cards = flat (flat\n <๐ข ๐ฃ ๐ค ๐ฅ ๐ฆ ๐ง ๐จ ๐ฉ ๐ช ๐ซ ๐ญ ๐ฎ ๐ก\n ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐>.map({ \"{%c<black>}$_\" }),\n <๐ฒ ๐ณ ๐ด ๐ต ๐ถ ๐ท ๐ธ ๐น ๐บ ๐ป ๐ฝ ๐พ ๐ฑ\n ๐ ๐ ๐ ๐
๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐ ๐>.map({ \"{%c<red>}$_\" })\n).batch(13).map({ .flat Z 2..14 })ยป.map: { .[1] but .[0] };\n\nmy $back = \"{%c<blue>}๐ \";\nmy @won = <๐ ๐>;\n\nsub shuffle (@cards) { @cards.pick: * }\nsub deal (@cards) { [@cards[0,*+2 โฆ *], @cards[1,*+2 โฆ *]] }\n\nmy ($rows, $cols) = qx/stty size/.wordsยป.Int; # get the terminal size\nnote \"Terminal is only $cols characters wide, needs to be at least 80, 120 or more recommended.\"\n and exit if $cols < 80;\n\nsub clean-up {\n reset-scroll-region;\n show-cursor;\n print-at $rows, 1, '';\n print \"\\e[0m\";\n exit(0)\n}\n\nsignal(SIGINT).tap: { clean-up() }\n\nmy @index = ($cols div 2 - 5, $cols div 2 + 4);\nmy @player = (deal shuffle @cards)ยป.Array;\nmy $lose = False;\n\nsub take (@player, Int $cards) {\n if +@player >= $cards {\n return @player.splice(0, $cards);\n }\n else {\n $lose = True;\n return @player.splice(0, +@player);\n }\n}\n\nuse Terminal::ANSI;\n\nclear-screen;\nhide-cursor;\n# Set background color\nprint \"\\e[H\\e[J\\e[48;2;245;245;245m\", ' ' xx $rows * $cols + 1;\n\n# Add header\nprint-at 1, $cols div 2 - 1, \"{%c<red>}WAR!\";\nprint-at 2, 1, 'โ' x $cols;\n\nmy $row = 3;\nmy $height = $rows - $row - 2;\nset-scroll-region($row, $height);\n\n# footer\nprint-at $height + 1, 1, 'โ' x $cols;\n\nmy $round = 0;\nmy @round;\n\nloop {\n @round = [@player[0].&take(1)], [@player[1].&take(1)] unless +@round;\n print-at $row, $cols div 2, \"{%c<red>}โ\";\n print-at $row, @index[0], @round[0;0] // ' ';\n print-at $row, @index[1], @round[1;0] // ' ';\n if $lose {\n if @player[0] < @player[1] {\n print-at $row, $cols div 2 + 1, @won[1] unless +@round[1] == 1;\n print-at $height + 3, $cols div 2 - 10, \"{%c<red>} Player 1 is out of cards \"\n } else {\n print-at $row, $cols div 2 - 2, @won[0] unless +@round[0] == 1;\n print-at $height + 3, $cols div 2 - 10, \"{%c<red>} Player 2 is out of cards \"\n }\n\n }\n if (@round[0].tail // 0) > (@round[1].tail // 0) {\n print-at $row, $cols div 2 - 2, @won[0];\n @player[0].append: flat (|@round[0],|@round[1]).pick: *;\n @round = ();\n }\n elsif (@round[0].tail // 0) < (@round[1].tail // 0) {\n print-at $row, $cols div 2 + 1, @won[1];\n @player[1].append: flat (|@round[0],|@round[1]).pick: *;\n @round = ();\n }\n else {\n @round[0].append: @player[0].&take($war);\n @round[1].append: @player[1].&take($war);\n print-at $row, @index[0] - $_ * 2, ($_ย %% $war)ย ?? @round[0; $_]ย !! $back for ^@round[0];\n print-at $row, @index[1] + $_ * 2, ($_ย %% $war)ย ?? @round[1; $_]ย !! $back for ^@round[1];\n next\n }\n last if $lose;\n print-at $height + 2, $cols div 2 - 4, \"{%c<blue>} Round {++$round} \";\n print-at $height + 2, $cols div 2 - 40, \"{%c<blue>} Player 1: {+@player[0]} cards \";\n print-at $height + 2, $cols div 2 + 21, \"{%c<blue>} Player 2: {+@player[1]} cards \";\n sleep $sleep if +$sleep;\n if $row >= $height { scroll-up } else { ++$row }\n}\n\n# game over\nprint-at $height + 2, $cols div 2 - 40, \"{%c<blue>} Player 1: {+@player[0]ย ?? '52'ย !! \"{%c<red>}0\"}{%c<blue>} cards \";\nprint-at $height + 2, $cols div 2 + 20, \"{%c<blue>} Player 2: {+@player[1]ย ?? '52'ย !! \"{%c<red>}0\"}{%c<blue>} cards \";\nclean-up;\n\n```\n\nSample outout Bicycle:\n\nPass in `:war=2` on the command line.\nSee Bicycle variation (offsite png image)\n\nSample outout using defaults:\n\nSee thundergnat variation (offsite png image)"
}
]
|
[
{
"role": "user",
"content": "Definitions\n\nLet **n** be a positive integer and **l(n)** be the number of its digits in base **b**.\n\nExpress **n** as the product of its prime factors raised to the appropriate powers. Let **D(n)** be the total number of its base **b** digits in all its prime factors and in all their exponents that are greater than 1.\n\nThen **n** is defined to be:\n\n1. a wasteful (or extravagant) number if l(n) **<** D(n); or\n\n2. an equidigital number if l(n) **=** D(n); or\n\n3. a frugal (or economical) number if l(n) **>** D(n)\n\nin base **b**.\n\nBy convention, the number **1** is considered to be an **equidigital** number in **any** base even though it has no prime factors.\n\nFor the avoidance of any doubt, the number **0** is not a positive integer (and arguably not a natural number either) and so is excluded from all 3 categories.\n\nAn **economical** number is sometimes defined as being one for which l(n) **>=** D(n) though this usage won't be followed here.\n\nExamples\n\nIn base 10, the number 30 has a prime factorization of 2 x 3 x 5. The total number of digits is 3 (all exponents being 1) which is more than the 2 digits 30 has. So 30 is wasteful in base 10.\n\nIn base 10, the number 49 has a prime factorization of 7ยฒ. The total number of digits, including those of the exponent, is 2 which is the same as the 2 digits 49 has. So 49 is equidigital in base 10.\n\nIn base 10, the number 125 has a prime factorization of 5ยณ. The total number of digits, including those of the exponent, is 2 which is less than the 3 digits 125 has. So 125 is frugal in base 10.\n\nIn base 2, the number 100000 (32 decimal) has a prime factorization of 10^101 (2^5 decimal). The total number of binary digits, including those of the exponent, is 5 which is less than the 6 binary digits 100000 has. So 32 is frugal in base 2 (but equidigital in base 10).\n\nTask\n\nCompute and show here the first **50** and the **10,000th** number in base **10** for each of the three categories of number defined above.\n\nAlso compute and show how many numbers less than **1,000,000** fall into each of the three categories.\n\nBonus\n\nDo the same for base **11**, but show the results in base **10**.\n\nReferences\n\n* OEIS: A046760 - Wasteful numbers\n* OEIS: A046758 - Equidigital numbers\n* OEIS: A046759 - Economical numbers"
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor;\nuse Lingua::EN::Numbers;\n\nmy %cache;\n\nsub factor-char-sum ($n, $base = 10) { sum $n.&prime-factors.Bag.map: { .key.base($base).chars + (.value > 1ย ?? .value.base($base).charsย !! 0) } }\n\nsub economical ($n, $base = 10) { ($n > 1) && $n.base($base).chars > (%cache{$base}[$n] //= factor-char-sum $n, $base) }\nsub equidigital ($n, $base = 10) { ($n == 1) || $n.base($base).chars == (%cache{$base}[$n] //= factor-char-sum $n, $base) }\nsub extravagant ($n, $base = 10) { $n.base($base).chars < (%cache{$base}[$n] //= factor-char-sum $n, $base) }\n\n\nfor 10, 11 -> $base {\n %cache{$base}[3e6] = Any; # preallocate to avoid concurrency issues\n say \"\\nIn Base $base:\";\n for &extravagant, &equidigital, &economical -> &sub {\n say \"\\nFirst 50 {&sub.name} numbers:\";\n say (^โ).grep( {.&sub($base)} )[^50].batch(10)ยป.&commaยป.fmt(\"%6s\").join: \"\\n\";\n say \"10,000th: \" ~ (^โ).hyper(:2000batch).grep( {.&sub($base)} )[9999].,\n }\n\n my $upto = 1e6.Int;\n my atomicint ($extravagant, $equidigital, $economical);\n say \"\\nOf the positive integers up to {$upto.&cardinal}:\";\n (1..^$upto).race(:5000batch).map: { .&extravagant($base)ย ?? ++โ$extravagantย !! .&equidigital($base)ย ?? ++โ$equidigitalย !! ++โ$economical };\n say \" Extravagant: {comma $extravagant}\\n Equidigital: {comma $equidigital}\\n Economical: {comma $economical}\";\n %cache{$base} = Empty;\n}\n\n```\n\nOutput:\n\n```\nIn Base 10:\n\nFirst 50 extravagant numbers:\n 4 6 8 9 12 18 20 22 24 26\n 28 30 33 34 36 38 39 40 42 44\n 45 46 48 50 51 52 54 55 56 57\n 58 60 62 63 65 66 68 69 70 72\n 74 75 76 77 78 80 82 84 85 86\n10,000th: 14,346\n\nFirst 50 equidigital numbers:\n 1 2 3 5 7 10 11 13 14 15\n 16 17 19 21 23 25 27 29 31 32\n 35 37 41 43 47 49 53 59 61 64\n 67 71 73 79 81 83 89 97 101 103\n 105 106 107 109 111 112 113 115 118 119\n10,000th: 33,769\n\nFirst 50 economical numbers:\n 125 128 243 256 343 512 625 729 1,024 1,029\n 1,215 1,250 1,280 1,331 1,369 1,458 1,536 1,681 1,701 1,715\n 1,792 1,849 1,875 2,048 2,187 2,197 2,209 2,401 2,560 2,809\n 3,125 3,481 3,584 3,645 3,721 4,096 4,374 4,375 4,489 4,802\n 4,913 5,041 5,103 5,329 6,241 6,250 6,561 6,859 6,889 7,203\n10,000th: 1,953,125\n\nOf the positive integers up to one million:\n Extravagant: 831,231\n Equidigital: 165,645\n Economical: 3,123\n\nIn Base 11:\n\nFirst 50 extravagant numbers:\n 4 6 8 9 10 12 18 20 22 24\n 26 28 30 33 34 36 38 39 40 42\n 44 45 46 48 50 51 52 54 55 56\n 57 58 60 62 63 65 66 68 69 70\n 72 74 75 76 77 78 80 82 84 85\n10,000th: 12,890\n\nFirst 50 equidigital numbers:\n 1 2 3 5 7 11 13 14 15 16\n 17 19 21 23 25 27 29 31 32 35\n 37 41 43 47 49 53 59 61 64 67\n 71 73 79 81 83 89 97 101 103 107\n 109 113 121 122 123 127 129 131 133 134\n10,000th: 33,203\n\nFirst 50 economical numbers:\n 125 128 243 256 343 512 625 729 1,024 1,331\n 1,369 1,458 1,536 1,681 1,701 1,715 1,792 1,849 1,875 2,048\n 2,187 2,197 2,209 2,401 2,560 2,809 3,072 3,125 3,481 3,584\n 3,645 3,721 4,096 4,374 4,375 4,489 4,802 4,913 5,041 5,103\n 5,120 5,329 6,241 6,250 6,561 6,859 6,889 7,168 7,203 7,921\n10,000th: 2,659,171\n\nOf the positive integers up to one million:\n Extravagant: 795,861\n Equidigital: 200,710\n Economical: 3,428\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nIn a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,\ncompletely filling all convex enclosures in the chart with water.\n\n```\n9 โโ 9 โโ \n8 โโ 8 โโ \n7 โโ โโ 7 โโโโโโโโโโโโ \n6 โโ โโ โโ 6 โโโโโโโโโโโโ \n5 โโ โโ โโ โโโโ 5 โโโโโโโโโโโโโโโโ \n4 โโ โโ โโโโโโโโ 4 โโโโโโโโโโโโโโโโ \n3 โโโโโโ โโโโโโโโ 3 โโโโโโโโโโโโโโโโ \n2 โโโโโโโโโโโโโโโโ โโ 2 โโโโโโโโโโโโโโโโโโโโ\n1 โโโโโโโโโโโโโโโโโโโโ 1 โโโโโโโโโโโโโโโโโโโโ\n```\n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n```\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n```\n\nSee, also:\n\n* Four Solutions to a Trivial Problem โ a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Haskell\n\n```\nsub max_l ( @a ) { [\\max] @a }\nsub max_r ( @a ) { ([\\max] @a.reverse).reverse }\n\nsub water_collected ( @towers ) {\n return 0 if @towers <= 2;\n\n my @levels = max_l(@towers)ย ยปminยซย max_r(@towers);\n\n return ( @levelsย ยป-ยซย @towers ).grep( * > 0 ).sum;\n}\n\nsay map &water_collected,\n [ 1, 5, 3, 7, 2 ],\n [ 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 ],\n [ 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 ],\n [ 5, 5, 5, 5 ],\n [ 5, 6, 7, 8 ],\n [ 8, 7, 7, 6 ],\n [ 6, 7, 10, 7, 6 ],\n;\n\n```\n\nOutput:\n\n```\n(2 14 35 0 0 0 0)\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nThe **Wave Function Collapse** algorithm is a heuristic for generating tiled images.\n\nThe algorithm begins with a collection of equal sized image blocks and randomly places them, one at a time, within a grid subject to the tiling constraint and an entropy constraint, and it wraps (the top row of blocks in the grid is treated as *adjacent* to the bottom row of blocks, and similarly the left and right columns of blocks are treated as adjacent to each other).\n\nThe blocks are tiled within the grid. *Tiled* means they are placed with a one pixel overlap and the tiling constraint requires that the pixels overlapping border between two adjacent blocks match.\n\n*Entropy*, here, means the number of blocks eligible to be placed in an unassigned grid location. The entropy constraint here is that each block is placed in a grid location with minimum entropy. (Placing a block may constrain the entropy of its four nearest neighbors -- up, down, left, right.)\n\nFor this task, we start with five blocks of 3x3 pixels and place them in an 8x8 grid to form a 17x17 tile. A tile is a block which may be tiled with itself. Here, we show these five blocks adjacent but not *tiled*:\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | | | | | --- | --- | --- | | | | | | | | | | | | | | | | | | | --- | --- | --- | | | | | | | | | | | | | | | | | | | --- | --- | --- | | | | | | | | | | | | | | | | | | | --- | --- | --- | | | | | | | | | | | | | | | | | | | --- | --- | --- | | | | | | | | | | | | | |\n\nNote that this algorithm sometimes does not succeed. If an unassigned grid location has an entropy of 0, the algorithm fails and returns an empty or null result. We'll ignore those failure cases for this task.\n\nReference WFC explained and another WFC explained"
},
{
"role": "assistant",
"content": "**Translation of**: C\n\n```\n# 20220728 Raku programming solution\n\nmy @Blocks = ( [ <0 0 0>, \n <0 0 0>, \n\t\t <0 0 0> ],\n [ <0 0 0>, \n\t <1 1 1>, \n\t\t <0 1 0> ],\n [ <0 1 0>, \n\t <0 1 1>,\n\t \t <0 1 0> ],\n [ <0 1 0>,\n\t <1 1 1>,\n\t \t <0 0 0> ],\n [ <0 1 0>,\n\t <1 1 0>,\n\t \t <0 1 0> ], );\n\nsub XY(\\row, \\col, \\width) { col+row*width }\nsub XYZ(\\page, \\row, \\col, \\height, \\width) {\n XY( XY(page, row, height), col, width)\n}\n\nsub wfc(@blocks, @bdim, @tdim) {\n\n my \\N = [*] my (\\td0,\\td1) = @tdim[0,1]; \n my @adj; # indices in R of the four adjacent blocks\n for ^td0 X ^td1 -> (\\i,\\j) { # in a 3x3 grid\n @adj[XYZ(i,j,0,td1,4)]= XY((i-1)%td0,j%td1,td1); # above (index 1) \n @adj[XYZ(i,j,1,td1,4)]= XY(i%td0,(j-1)%td1,td1); # left (index 3) \n @adj[XYZ(i,j,2,td1,4)]= XY(i%td0,(j+1)%td1,td1); # right (index 5) \n @adj[XYZ(i,j,3,td1,4)]= XY((i+1)%td0,j%td1,td1); # below (index 7) \n }\n\n my (\\bd0,\\bd1,\\bd2) = @bdim[0..2];\n my @horz; # blocks which can sit next to each other horizontally \n for ^bd0 X ^bd0 -> (\\i,\\j) {\n @horz[XY(i,j,bd0)] = 1;\n for ^bd1 -> \\k {\n @horz[XY(i, j, bd0)]= 0 if @blocks[XYZ(i, k, 0, bd1, bd2)]ย !=\n\t @blocks[XYZ(j, k, bd2-1, bd1, bd2)]\n }\n }\n \n my @vert; # blocks which can sit next to each other vertically */\n for ^bd0 X ^bd0 -> (\\i,\\j) {\n @vert[XY(i,j,bd0)] = 1;\n for ^bd2 -> \\k {\n if @blocks[XYZ(i, 0, k, bd1, bd2)]ย != \n\t @blocks[XYZ(j, bd1-1, k, bd1, bd2)] {\n\t @vert[XY(i, j, bd0)]= 0 andthen last;\n\t }\n }\n }\n\n my @allow = 1 xx 4*(bd0+1)*bd0; # all block constraints, based on neighbors\n for ^bd0 X ^bd0 -> (\\i,\\j) {\n @allow[XYZ(0, i, j, bd0+1, bd0)] = @vert[XY(j, i, bd0)]; # above (north)\n @allow[XYZ(1, i, j, bd0+1, bd0)] = @horz[XY(j, i, bd0)]; # left (west) \n @allow[XYZ(2, i, j, bd0+1, bd0)] = @horz[XY(i, j, bd0)]; # right (east) \n @allow[XYZ(3, i, j, bd0+1, bd0)] = @vert[XY(i, j, bd0)]; # below (south) \n }\n\n my (@R, @todo, @wave, @entropy, @indices, $min, @possible) = bd0 xx N;\n loop {\n my $c = 0;\n for ^N { @todo[$c++] = $_ if bd0 == @R[$_] } \n last unless $c;\n $min = bd0;\n for ^$c -> \\i {\n @entropy[i]= 0;\n for ^bd0 -> \\j {\n @entropy[i] += \n @wave[XY(i, j, bd0)] =\n @allow[XYZ(0, @R[@adj[XY(@todo[i],0,4)]], j, bd0+1, bd0)] +& \n @allow[XYZ(1, @R[@adj[XY(@todo[i],1,4)]], j, bd0+1, bd0)] +&\n @allow[XYZ(2, @R[@adj[XY(@todo[i],2,4)]], j, bd0+1, bd0)] +&\n @allow[XYZ(3, @R[@adj[XY(@todo[i],3,4)]], j, bd0+1, bd0)]\n }\n\t $min = @entropy[i] if @entropy[i] < $min\n }\n \n unless $min { @R=[] andthen last } # original behaviour \n #unless $min { @R = bd0 xx N andthen redo } # if failure is not an option\n\n my $d = 0;\n for ^$c { @indices[$d++] = $_ if $min == @entropy[$_] }\n my \\ind = bd0 * my \\ndx = @indices[ ^$d .roll ];\n $d = 0;\n for ^bd0 { @possible[$d++] = $_ if @wave[ind+$_] }\n @R[@todo[ndx]] = @possible[ ^$d .roll ];\n }\n\n exit unless @R.Bool;\n\n my @tile;\n for ^td0 X ^bd1 X ^td1 X ^bd2 -> (\\i0,\\i1,\\j0,\\j1) {\n @tile[XY(XY(j0, j1, bd2-1), XY(i0, i1, bd1-1), 1+td1*(bd2-1))] =\n @blocks[XYZ(@R[XY(i0, j0, td1)], i1, j1, bd1, bd2)]\n }\n\n return @tile\n}\n\nmy (@bdims,@size)ย := (5,3,3), (8,8);\n\nmy @tile = wfc @Blocksยป.List.flat, @bdims, @size ย ;\n\nsay .join.trans( [ '0', '1' ] => [ ' ', '# ' ] ) for @tile.rotor(17)\n\n```\n\nOutput:\n\n```\n # # #\n# # # # # # # # # # # # # # # # #\n # # # # #\n # # # # # # # # # # # # # #\n # # # # # # #\n # # # # # # # # # # # # #\n # # # # # # #\n# # # # # # # # # # # #\n # # # # # #\n# # # # # # # # # # # # #\n # # # # #\n# # # # # # # # # # #\n # # # # #\n# # # # # # # # # # #\n # # # # #\n# # # # # # # # # # # #\n # # #\n\n```"
}
]
|
[
{
"role": "user",
"content": "Analyse a given section of monophonic audio waveform, for average pitch and output one of the sol-fa trigraphs (like these, except each has three letters) corresponding to average pitch level: Doh, Ray, Mee, Fah, Soh, Lah, Tee, doh.\n\nOptionally, follow the trigraph with a plus or minus symbol, to indicate whether the note falls above or below the solfa. Extend the scale to cover 21 notes: DOH, RAY, MEE, FAH, SOH, LAH, TEE, Doh, Ray, Mee, Fah, Soh, Lah, Tee, doh, ray, mee, fah, soh, lah, tee.\n\nA calibration parameter can be provided to suit different voices. This can be provided as a variable defined within the code."
},
{
"role": "assistant",
"content": "The input .wav file (notes.wav) is created by the [Musical Scale#Go] entry.\n\n**Translation of**: Go\n\n```\n# 20200721 Raku programming solution\n\nmy \\freqs = < 261.6 293.6 329.6 349.2 392.0 440.0 493.9 523.3 >;\nmy \\notes = < Doh Ray Mee Fah Soh Lah Tee doh >;\n\nsub getNote (\\freq) {\n my $index = freqs;\n for (0..^$index) { $index = $_ and last if freq โค freqs[$_] }\n given $index {\n when 0 { \"Doh-\" }\n when freqs { \"doh+\" }\n default { freqs[$index] - freq โค freq - freqs[$index-1]\n ย ?? notes[$index] ~ \"-\"ย !! notes[$index-1] ~ \"+\" }\n }\n}\n\nmy $file = slurp \"./notes.wav\",ย :bin or die;\n\n# http://www.topherlee.com/software/pcm-tut-wavformat.html\n# https://stackoverflow.com/a/49081648/3386748\n\nmy $sampleRate = Blob.new(@$file[24..27]).read-uint32(0,LittleEndian);\n# self-ref: [+] @$file[24..27].pairs.map: {$_.value*256**$_.key};\nsay \"Sample Rate ย : \", $sampleRate;\n\nmy $dataLength = Blob.new(@$file[40..43]).read-uint32(0,LittleEndian);\n# self-ref: [+] @$file[40..43].pairs.map: {$_.value*256**$_.key};\nmy $duration = $dataLength / $sampleRate;\nsay \"Duration ย : \", $duration;\n\nmy ( $sum, $sampleRateF ) = ( 0, $sampleRate.Num )ย ;\nmy $nbytes = 20;\n\nsay \"Bytes examinedย : \", $nbytes, \" per sample\";\n\nfor @$file[44..*].rotor($sampleRate) -> $data {\n for (1..$nbytes) -> $k {\n my $bf = @$data[$k] / 32;\n $sum += $bf.asin ร $sampleRateF / ( 2 ร ฯ ร $k );\n }\n}\n\nmy $cav = $sum / ( $duration * $nbytes );\nsay \"Computed average frequency = {$cav.fmt('%.1f')} Hz ({getNote($cav)})\";\n\nmy $aav = ([+] freqs) / freqs;\nsay \"Actual average frequency = {$aav.fmt('%.1f')} Hz ({getNote($aav)})\";\n\n```\n\nOutput:\n\n```\ngo run Musical_scale.go\nfile notes.wav\nnotes.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 8 bit, mono 44100 Hz\n./Doh_ray_me.raku\nSample Rate ย : 44100\nDuration ย : 8\nBytes examinedย : 20 per sample\nComputed average frequency = 387.1 Hz (Soh-)\nActual average frequency = 385.4 Hz (Soh-)\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a program that downloads the time from this URL: ย http://tycho.usno.navy.mil/cgi-bin/timer.pl ย and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page.\n\nIf possible, only use libraries that come at no *extra* monetary cost with the programming language and that are widely available and popular such as CPAN for Perl or Boost for C++."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n# 20210301 Updated Raku programming solution\n\nuse HTTP::Client; # https://github.com/supernovus/perl6-http-client/\n\n#`[ Site inaccessible since 2019ย ?\nmy $site = \"http://tycho.usno.navy.mil/cgi-bin/timer.pl\";\nHTTP::Client.new.get($site).content.match(/'<BR>'( .+? <ws> UTC )/)[0].say\n# ]\n\nmy $site = \"https://www.utctime.net/\";\nmy $matched = HTTP::Client.new.get($site).content.match(\n /'<td>UTC</td><td>'( .*Z )'</td>'/\n)[0];\n\nsay $matched;\n#$matched = '12321321:412312312 123';\nwith DateTime.new($matched.Str) {\n say 'The fetch result seems to be of a valid time format.'\n} else {\n CATCH { put .^name, ': ', .Str }\n}\n\n```\n\nNote that the string between '<' and '>' refers to regex tokens, so to match a literal '<BR>' you need to quote it, while <ws> refers to the built-in token whitespace.\nAlso, whitespace is ignored by default in Raku regexes.\n\nOutput:\n\n```\n๏ฝข2021-03-01T17:02:37Z๏ฝฃ\nThe fetch result seems to be of a valid time format.\n\n```"
}
]
|
[
{
"role": "user",
"content": "In number theory, a weird number is a natural number that is abundant but *not* semiperfect (and therefore not perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is *abundant*), but no subset of those divisors sums to the number itself (the number is not *semiperfect*).\n\nFor example:\n\n* **12** is *not* a weird number.\n + It is abundant; its proper divisors **1, 2, 3, 4, 6** sum to **16** (which *is* > 12),\n + but it *is* semiperfect, e.g.: ย ย **6 + 4 + 2 == 12**.\n* **70** *is* a weird number.\n + It is abundant; its proper divisors **1, 2, 5, 7, 10, 14, 35** sum to **74** (which *is* > 70),\n + and there is no subset of proper divisors that sum to **70**.\n\nTask\n\nFind and display, here on this page, the first **25** weird numbers.\n\nRelated tasks\n: * Abundant, deficient and perfect number classifications\n * Proper divisors\n\nSee also\n: * OEIS: A006037 weird numbers\n * Wikipedia: weird number\n * MathWorld: weird number"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub abundant (\\x) {\n my @l = x.is-primeย ?? 1ย !! flat\n 1, (2 .. x.sqrt.floor).map: -> \\d {\n my \\y = x div d;\n next if y * dย !== x;\n dย !== yย ?? (d, y)ย !! d\n };\n (my $s = @l.sum) > xย ?? ($s, |@l.sort(-*))ย !! ();\n}\n\nmy @weird = (2, 4, {|($_ + 4, $_ + 6)} ... *).map: -> $n {\n my ($sum, @div) = $n.&abundant;\n next unless $sum; # Weird number must be abundant, skip it if it isn't.\n next if $sum / $n > 1.1; # There aren't any weird numbers with a sum:number ratio greater than 1.08 or so.\n if $n >= 10430 and ($nย %% 70) and ($n div 70).is-prime {\n # It's weird. All numbers of the form 70 * (a prime 149 or larger) are weird\n } else {\n my $next;\n my $l = @div.shift;\n ++$next and last if $_.sum == $n - $l for @div.combinations;\n next if $next;\n }\n $n\n}\n\nput \"The first 25 weird numbers:\\n\", @weird[^25];\n\n```\n\nOutput:\n\n```\nThe first 25 weird numbers:\n70 836 4030 5830 7192 7912 9272 10430 10570 10792 10990 11410 11690 12110 12530 12670 13370 13510 13790 13930 14770 15610 15890 16030 16310\n```"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.