messages
listlengths
2
2
[ { "role": "user", "content": "Task\n\nCreate a string variable equal to any text value.\n\nCreate another string variable whose value is the original variable concatenated with another string literal.\n\nTo illustrate the operation, show the content of the variables.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #22 \"Thousand Oaks\"\n\n```\nmy $s = 'hello';\nsay $s ~ ' literal';\nmy $s1 = $s ~ ' literal';\nsay $s1;\n\n# or, using mutating concatenation:\n\n$s ~= ' literal';\nsay $s;\n```\n\nNote also that most concatenation in Raku is done implicitly via interpolation." } ]
[ { "role": "user", "content": "Given a string and defined variables or values, string interpolation is the replacement of defined character sequences in the string by values or variable values.\n\n: For example, given an original string of `\"Mary had a X lamb.\"`, a value of \"big\", and if the language replaces X in its interpolation routine, then the result of its interpolation would be the string `\"Mary had a big lamb\"`.\n\n: (Languages usually include an infrequently used character or sequence of characters to indicate what is to be replaced such as \"%\", or \"#\" rather than \"X\").\n\nTask\n\n1. Use your languages inbuilt string interpolation abilities to interpolate a string missing the text `\"little\"` which is held in a variable, to produce the output string `\"Mary had a little lamb\"`.\n2. If possible, give links to further documentation on your languages string interpolation features.\n\nNote: The task is not to create a string interpolation routine, but to show a language's built-in capability.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $extra = \"little\";\nsay \"Mary had a $extra lamb\"; # variable interpolation\nsay \"Mary had a { $extra } lamb\"; # expression interpolation\nprintf \"Mary had a %s lamb.\\n\", $extra; # standard printf\nsay $extra.fmt(\"Mary had a %s lamb\"); # inside-out printf\nmy @lambs = <Jimmy Bobby Tommy>;\nsay Q :array { $$$ The lambs are called @lambs[]\\\\\\.} # only @-sigiled containers are interpolated\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind the *character* and *byte* length of a string.\n\nThis means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.\n\nBy *character*, we mean an individual Unicode *code point*, not a user-visible *grapheme* containing combining characters.\n\nFor example, the character length of \"møøse\" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16.\n\nNon-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts.\n\nTherefore a string like \"𝔘𝔫𝔦𝔠𝔬𝔡𝔢\" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, **not** 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16.\n\nPlease mark your examples with ===Character Length=== or ===Byte Length===.\n\nIf your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===.\n\nFor example, the string \"J̲o̲s̲é̲\" (\"J\\x{332}o\\x{332}s\\x{332}e\\x{301}\\x{332}\") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8.\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### Byte Length\n\n```\nsay 'møøse'.encode('UTF-8').bytes;\n```\n\n### Character Length\n\n```\nsay 'møøse'.codes;\n```\n\n### Grapheme Length\n\n```\nsay 'møøse'.chars;\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven two strings, demonstrate the following three types of string matching:\n\n: : 1. Determining if the first string starts with second string\n 2. Determining if the first string contains the second string at any location\n 3. Determining if the first string ends with the second string\n\nOptional requirements:\n\n: : 1. Print the location of the match for part 2\n 2. Handle multiple occurrences of a string for part 2.\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\nUsing string methods:\n\n```\n$haystack.starts-with($needle) # True if $haystack starts with $needle\n$haystack.contains($needle) # True if $haystack contains $needle\n$haystack.ends-with($needle) # True if $haystack ends with $needle\n```\n\nUsing regexes:\n\n```\nso $haystack ~~ /^ $needle / # True if $haystack starts with $needle\nso $haystack ~~ / $needle / # True if $haystack contains $needle\nso $haystack ~~ / $needle $/ # True if $haystack ends with $needle\n```\n\nUsing `substr`:\n\n```\nsubstr($haystack, 0, $needle.chars) eq $needle # True if $haystack starts with $needle\nsubstr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle\n```\n\nBonus task:\n\n```\n$haystack.match($needle, :g)».from; # List of all positions where $needle appears in $haystack\n$haystack.indices($needle :overlap); # Also find any overlapping instances of $needle in $haystack\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a string variable equal to any text value.\n\nPrepend the string variable with another string literal.\n\nIf your language supports any idiomatic ways to do this without referring to the variable twice in one expression, include such solutions.\n\nTo illustrate the operation, show the content of the variable." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\n# explicit concatentation\n$_ = 'byte';\n$_ = 'kilo' ~ $_;\n.say;\n\n# interpolation as concatenation\n$_ = 'buck';\n$_ = \"mega$_\";\n.say;\n\n# lvalue substr\n$_ = 'bit';\nsubstr-rw($_,0,0) = 'nano';\n.say;\n\n# regex substitution\n$_ = 'fortnight';\ns[^] = 'micro';\n.say;\n\n# reversed append assignment\n$_ = 'cooper'; \n$_ [R~]= 'mini';\n.say;\n\n```\n\nOutput:\n\n```\nkilobyte\nmegabuck\nnanobit\nmicrofortnight\nminicooper\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a function that strips a set of characters from a string.\n\nThe function should take two arguments:\n\n: : : 1. a string to be stripped\n 2. a string containing the set of characters to be stripped\n\nThe returned string should contain the first string, stripped of any characters in the second argument:\n\n```\n print stripchars(\"She was a soul stripper. She took my heart!\",\"aei\")\nSh ws soul strppr. Sh took my hrt!\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub strip_chars ( $s, $chars ) {\n return $s.trans( $chars.comb X=> '' );\n}\n\nsay strip_chars( 'She was a soul stripper. She took my heart!', 'aei' );\n\n```\n\nOutput:\n\n```\nSh ws soul strppr. Sh took my hrt!\n```" } ]
[ { "role": "user", "content": "A block comment begins with a   *beginning delimiter*   and ends with a   *ending delimiter*,   including the delimiters.   These delimiters are often multi-character sequences.\n\nTask\n\nStrip block comments from program text (of a programming language much like classic C).\n\nYour demos should at least handle simple, non-nested and multi-line block comment delimiters.\n\nThe block comment delimiters are the two-character sequences:\n\n: : : * **/\\***     (beginning delimiter)\n * **\\*/**     (ending delimiter)\n\nSample text for stripping:\n\n```\n /**\n * Some comments\n * longer comments here that we can parse.\n *\n * Rahoo \n */\n function subroutine() {\n a = /* inline comment */ b + c ;\n }\n /*/ <-- tricky comments */\n\n /**\n * Another comment.\n */\n function something() {\n }\n\n```\n\nExtra credit\n\nEnsure that the stripping code is not hard-coded to the particular delimiters described above, but instead allows the caller to specify them.   (If your language supports them,   optional parameters   may be useful for this.)\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```\nsample().split(/ '/*' .+? '*/' /).print;\n\nsub sample {\n' /**\n * Some comments\n * longer comments here that we can parse.\n *\n * Rahoo\n */\n function subroutine() {\n a = /* inline comment */ b + c ;\n }\n /*/ <-- tricky comments */\n\n /**\n * Another comment.\n */\n function something() {\n }\n'}\n\n```\n\nOutput:\n\n```\n \n function subroutine() {\n a = b + c ;\n }\n \n\n \n function something() {\n }\n\n```" } ]
[ { "role": "user", "content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nThe task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.\n\n**Whitespace debacle:**   There is some confusion about whether to remove any whitespace from the input line.\n\nAs of 2 September 2011, at least 8 languages (C, C++, Java, Perl, Python, Ruby, sed, UNIX Shell) were incorrect, out of 36 total languages, because they did not trim whitespace by 29 March 2011 rules. Some other languages might be incorrect for the same reason.\n\n**Please discuss this issue at Talk:Strip comments from a string.**\n\n* From 29 March 2011, this task required that: *\"The comment marker and any whitespace at the beginning or ends of the resultant line should be removed. A line without comments should be trimmed of any leading or trailing whitespace before being produced as a result.\"* The task had 28 languages, which did not all meet this new requirement.\n* From 28 March 2011, this task required that: *\"Whitespace before the comment marker should be removed.\"*\n* From 30 October 2010, this task did not specify whether or not to remove whitespace.\n\nThe following examples will be truncated to either \"apples, pears \" or \"apples, pears\".\n\n(This example has flipped between \"apples, pears \" and \"apples, pears\" in the past.)\n\n```\napples, pears # and bananas\napples, pears ; and bananas\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\n$*IN.slurp.subst(/ \\h* <[ # ; ]> \\N* /, '', :g).print\n\n```" } ]
[ { "role": "user", "content": "Task\n\nStrip control codes and extended characters from a string.\n\nThe solution should demonstrate how to achieve each of the following results:\n\n: * a string with control codes stripped (but extended characters not stripped)\n * a string with control codes and extended characters stripped\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127.\n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nmy $str = (0..400).roll(80)».chr.join;\n\nsay $str;\nsay $str.subst(/<:Cc>/, '', :g); # unicode property: control character\nsay $str.subst(/<-[\\ ..~]>/, '', :g);\n\n```\n\n```\nkşaNĹĭŗ�|Ęw���\"ÄlĄWł8iCƁę��Ż�¬�5ĎĶ'óü¸'ÍŸ;ŢƐ¦�´ŷQċűÒŴ$ÃŅ�Đįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ\nkşaNĹĭŗ|Ęw\"ÄlĄWł8iCƁ꯬5ĎĶ'óü¸'ÍŸ;ŢƐ¦´ŷQċűÒŴ$ÃŅĐįð+=ĥƂ+Ōĭħ¼ŕc¤H~ìïēÕ\nkaN|w\"lW8iC5'';Q$+=+cH~\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate how to strip leading and trailing whitespace from a string.\n\nThe solution should demonstrate how to achieve the following three results:\n\n* String with leading whitespace removed\n* String with trailing whitespace removed\n* String with both leading and trailing whitespace removed\n\nFor the purposes of this task whitespace includes non printable characters such as the space character, the tab character, and other such characters that have no corresponding graphical representation.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\n```\nmy $s = \"\\r\\n \\t\\x2029 Good Stuff \\x202F\\n\";\nsay $s.trim;\nsay $s.trim.raku;\nsay $s.trim-leading.raku;\nsay $s.trim-trailing.raku;\n\n```\n\nOutput:\n\n```\nGood Stuff\n\"Good Stuff\"\n\"Good Stuff  \\n\"\n\"\\r\\n \\t
 Good Stuff\"\n\n```" } ]
[ { "role": "user", "content": "Definitions   (as per number theory)\n: : * The   **prime(*p*)**   is the   ***p*th   prime.**\n\n : : : * **prime(1)**   is   **2**\n * **prime(4)**   is   **7**\n\n * A   **strong   prime**   is when     **prime(*p*)**   is   **>**   **[prime(*p*-1) + prime(*p*+1)] ÷ 2**\n * A   **weak    prime**   is when     **prime(*p*)**   is   **<**   **[prime(*p*-1) + prime(*p*+1)] ÷ 2**\n\nNote that the definition for   **strong primes**   is different when used in the context of   cryptography.\n\nTask\n: : * Find and display (on one line) the first   **36**   strong primes.\n * Find and display the   *count*   of the strong primes below   1,000,000.\n * Find and display the   *count*   of the strong primes below 10,000,000.\n * Find and display (on one line) the first   **37**   weak primes.\n * Find and display the   *count*   of the weak primes below   1,000,000.\n * Find and display the   *count*   of the weak primes below 10,000,000.\n * (Optional)   display the   *counts*   and   \"below numbers\"   with commas.\n\nShow all output here.\n\nRelated Task\n: : * Safe primes and unsafe primes.\n\nAlso see\n: : * The OEIS article A051634: strong primes.\n * The OEIS article A051635: weak primes." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\n```\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nuse Math::Primesieve;\n\nmy $sieve = Math::Primesieve.new;\n\nmy @primes = $sieve.primes(10_000_019);\n\nmy (@weak, @balanced, @strong);\n\nfor 1 ..^ @primes - 1 -> $p {\n given (@primes[$p - 1] + @primes[$p + 1]) / 2 {\n when * > @primes[$p] { @weak.push: @primes[$p] }\n when * < @primes[$p] { @strong.push: @primes[$p] }\n default { @balanced.push: @primes[$p] }\n }\n}\n\nfor @strong, 'strong', 36,\n @weak, 'weak', 37,\n @balanced, 'balanced', 28\n -> @pr, $type, $d {\n say \"\\nFirst $d $type primes:\\n\", @pr[^$d]».&comma;\n say \"Count of $type primes <= {comma 1e6}: \", comma +@pr[^(@pr.first: * > 1e6,:k)];\n say \"Count of $type primes <= {comma 1e7}: \", comma +@pr;\n}\n\n```\n\nOutput:\n\n```\nFirst 36 strong primes:\n(11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439)\nCount of strong primes <= 1,000,000: 37,723\nCount of strong primes <= 10,000,000: 320,991\n\nFirst 37 weak primes:\n(3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401)\nCount of weak primes <= 1,000,000: 37,780\nCount of weak primes <= 10,000,000: 321,750\n\nFirst 28 balanced primes:\n(5 53 157 173 211 257 263 373 563 593 607 653 733 947 977 1,103 1,123 1,187 1,223 1,367 1,511 1,747 1,753 1,907 2,287 2,417 2,677 2,903)\nCount of balanced primes <= 1,000,000: 2,994\nCount of balanced primes <= 10,000,000: 21,837\n```" } ]
[ { "role": "user", "content": "A Sturmian word is a binary sequence, finite or infinite, that makes up the cutting sequence for a positive real number x, as shown in the picture.\n\nExample Sturmian word when x = 0.618..., the golden ratio.\n\nThe Sturmian word can be computed thus as an algorithm:\n\n* If \n\n x\n >\n 1\n {\\displaystyle {\\displaystyle x>1}}\n , then it is the inverse of the Sturmian word for \n\n 1\n\n /\n x\n {\\displaystyle {\\displaystyle 1/x}}\n . So we have reduced to the case of \n\n 0\n <\n x\n ≤\n 1\n {\\displaystyle {\\displaystyle 0<x\\leq 1}}\n .\n* Iterate over \n\n f\n l\n o\n o\n r\n (\n 1\n x\n )\n ,\n f\n l\n o\n o\n r\n (\n 2\n x\n )\n ,\n f\n l\n o\n o\n r\n (\n 3\n x\n )\n ,\n …\n {\\displaystyle {\\displaystyle floor(1x),floor(2x),floor(3x),\\dots }}\n* If \n\n k\n x\n {\\displaystyle {\\displaystyle kx}}\n is an integer, then the program terminates. Else, if \n\n f\n l\n o\n o\n r\n (\n (\n k\n −\n 1\n )\n x\n )\n =\n f\n l\n o\n o\n r\n (\n k\n x\n )\n {\\displaystyle {\\displaystyle floor((k-1)x)=floor(kx)}}\n , then the program outputs 0, else, it outputs 10.\n\nThe problem:\n\n* Given a positive rational number \n\n m\n n\n {\\displaystyle {\\displaystyle {\\frac {m}{n}}}}\n , specified by two positive integers \n\n m\n ,\n n\n {\\displaystyle {\\displaystyle m,n}}\n , output its entire Sturmian word.\n* Given a quadratic real number \n\n b\n\n\n a\n +\n m\n n\n >\n 0\n {\\displaystyle {\\displaystyle {\\frac {b{\\sqrt {a}}+m}{n}}>0}}\n , specified by integers \n\n a\n ,\n b\n ,\n m\n ,\n n\n {\\displaystyle {\\displaystyle a,b,m,n}}\n , where \n\n a\n {\\displaystyle {\\displaystyle a}}\n is not a perfect square, output the first \n\n k\n {\\displaystyle {\\displaystyle k}}\n letters of Sturmian words when given a positive number \n\n k\n {\\displaystyle {\\displaystyle k}}\n .\n\n(If the programming language can represent infinite data structures, then that works too.)\n\nA simple check is to do this for the inverse golden ratio \n\n5\n−\n1\n2\n{\\displaystyle {\\displaystyle {\\frac {{\\sqrt {5}}-1}{2}}}}\n, that is, \n\na\n=\n5\n,\nb\n=\n1\n,\nm\n=\n−\n1\n,\nn\n=\n2\n{\\displaystyle {\\displaystyle a=5,b=1,m=-1,n=2}}\n, which would just output the Fibonacci word.\n\nStretch goal: calculate the Sturmian word for other kinds of definable real numbers, such as cubic roots.\n\nThe key difficulty is accurately calculating \n\nf\nl\no\no\nr\n(\nk\n\n\na\n)\n{\\displaystyle {\\displaystyle floor(k{\\sqrt {a}})}}\n for large \n\nk\n{\\displaystyle {\\displaystyle k}}\n. Floating point arithmetic would lose precision. One can either do this simply by directly searching for some integer \n\na\n′\n{\\displaystyle {\\displaystyle a'}}\n such that \n\na\n\n′\n\n2\n≤\n\nk\n\n2\na\n<\n(\n\na\n′\n+\n1\n\n)\n\n2\n{\\displaystyle {\\displaystyle a'^{2}\\leq k^{2}a<(a'+1)^{2}}}\n, or by more trickly methods, such as the continued fraction approach.\n\nFirst calculate the continued fraction convergents to \n\na\n{\\displaystyle {\\displaystyle {\\sqrt {a}}}}\n. Let \n\nm\nn\n{\\displaystyle {\\displaystyle {\\frac {m}{n}}}}\n be a convergent to \n\na\n{\\displaystyle {\\displaystyle {\\sqrt {a}}}}\n, such that \n\nn\n≥\nk\n{\\displaystyle {\\displaystyle n\\geq k}}\n, then since the convergent sequence is the **best rational approximant** for denominators up to that point, we know for sure that, if we write out \n\n0\nk\n,\n\n\n1\nk\n,\n…\n{\\displaystyle {\\displaystyle {\\frac {0}{k}},{\\frac {1}{k}},\\dots }}\n, the sequence would stride right across the gap \n\n(\nm\n\n/\nn\n,\n2\nx\n−\nm\n\n/\nn\n)\n{\\displaystyle {\\displaystyle (m/n,2x-m/n)}}\n. Thus, we can take the largest \n\nl\n{\\displaystyle {\\displaystyle l}}\n such that \n\nl\n\n/\nk\n≤\nm\n\n/\nn\n{\\displaystyle {\\displaystyle l/k\\leq m/n}}\n, and we would know for sure that \n\nl\n=\nf\nl\no\no\nr\n(\nk\n\n\na\n)\n{\\displaystyle {\\displaystyle l=floor(k{\\sqrt {a}})}}\n.\n\nIn summary, \n\nf\nl\no\no\nr\n(\nk\n\n\na\n)\n=\nf\nl\no\no\nr\n(\nm\nk\n\n/\nn\n)\n{\\displaystyle {\\displaystyle floor(k{\\sqrt {a}})=floor(mk/n)}}\n where \n\nm\n\n/\nn\n{\\displaystyle {\\displaystyle m/n}}\n is the first continued fraction approximant to \n\na\n{\\displaystyle {\\displaystyle {\\sqrt {a}}}}\n with a denominator \n\nn\n≥\nk\n{\\displaystyle {\\displaystyle n\\geq k}}" }, { "role": "assistant", "content": "**Translation of**: Julia\n\n```\n# 20240215 Raku programming solution\n\nsub chenfoxlyndonfactorization(Str $s) {\n sub sturmian-word($m, $n) {\n return sturmian-word($n, $m).trans('0' => '1', '1' => '0') if $m > $n; \n my ($res, $k, $prev) = '', 1, 0;\n while ($k * $m) % $n > 0 {\n my $curr = ($k * $m) div $n;\n $res ~= $prev == $curr ?? '0' !! '10';\n $prev = $curr;\n $k++;\n }\n return $res;\n}\n\nsub fib-word($n) {\n my ($Sn_1, $Sn) = '0', '01';\n for 2..$n { ($Sn, $Sn_1) = ($Sn~$Sn_1, $Sn) }\n return $Sn;\n}\n\nmy $fib = fib-word(7);\nmy $sturmian = sturmian-word(13, 21);\nsay \"{$sturmian} <== 13/21\" if $fib.substr(0, $sturmian.chars) eq $sturmian;\n\nsub cfck($a, $b, $m, $n, $k) {\n my (@p, @q) := [0, 1], [1, 0]; \n my $r = (sqrt($a) * $b + $m) / $n;\n for ^$k {\n my $whole = $r.Int;\n my ($pn, $qn) = $whole * @p[*-1] + @p[*-2], $whole * @q[*-1] + @q[*-2];\n @p.push($pn);\n @q.push($qn);\n $r = 1/($r - $whole);\n }\n return [@p[*-1], @q[*-1]];\n}\n\nmy $cfck-result = cfck(5, 1, -1, 2, 8);\nsay \"{sturmian-word($cfck-result[0], $cfck-result[1])} <== 1/phi (8th convergent golden ratio)\";\n\n```\n\nOutput:\n\nSame as Julia example.\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "A sub-unit square is a square number (product of two identical non-negative integers) that remains a square after having a 1 subtracted from each digit in the square.\n\nE.G.\n\nThe number **1** is a sub-unit square. **1** - **1** is **0**, which is also a square, though it's kind-of a degenerate case.\n\nThe number **3136** is a sub-unit square. **3136** (**56²**) with unit **1** subtracted from each digit is **2025** (**45²**).\n\nA sub-unit square cannot contain a digit zero (**0**) since zero minus one is negative one. Every known sub-unit square, with the exception of **1**, ends with the digits **36**.\n\nTask\n\n* Find and display at least the first five sub-unit squares.\n\nSee also\n\n* OEIS:A061844 - Squares that remain squares if you decrease every digit by 1" }, { "role": "assistant", "content": "First seven take about 5 seconds with this implementation. The eighth would take several hours at least.\n\n```\nmy @upper = 1,|(1 .. *).map((* × 2)²);\nmy @lower = (^∞).map: *²;\nmy \\R = [\\+] 0, 1, 10, 100 … *;\n\nmy $l = 0;\n\n.say for (gather {\n (^∞).map: -> $u {\n next if @upper[$u].contains: 0;\n my $chars = @upper[$u].chars;\n loop {\n $l++ and next if @upper[$u] - @lower[$l] > R[$chars];\n take @upper[$u] if @upper[$u] - @lower[$l] == R[$chars];\n last;\n }\n }\n})[^7]\n\n```\n\nOutput:\n\n```\n1\n36\n3136\n24336\n5973136\n71526293136\n318723477136\n```" } ]
[ { "role": "user", "content": "Subleq is an example of a One-Instruction Set Computer (OISC).\n\nIt is named after its only instruction, which is **SU**btract and **B**ranch if **L**ess than or **EQ**ual to zero.\n\nTask\n\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers.   These integers may be interpreted in three ways:\n\n: : : : * simple numeric values\n * memory addresses\n * characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine.\n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n\n: 1. Let **A** be the value in the memory location identified by the instruction pointer;   let **B** and **C** be the values stored in the next two consecutive addresses in memory.\n 2. Advance the instruction pointer three words, to point at the address *after* the address containing **C**.\n 3. If **A** is **-1** (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by **B**. **C** is unused. (Most implementations adopt the C convention of signaling EOF by storing -1 as the read-in character.)\n 4. If **B** is **-1** (negative unity), then the number contained in the address given by **A** is interpreted as a character and written to the machine's output. **C** is unused.\n 5. Otherwise, both **A** and **B** are treated as addresses. The number contained in address **A** is subtracted from the number in address **B** (and the difference left in address **B**). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the instruction pointer is set to **C**.\n 6. If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address   **0**   (zero).\n\nFor purposes of this task, show the output of your solution when fed the below   \"Hello, world!\"   program.\n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode;   you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n```\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n```\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\n```\nstart:\n 0f 11 ff subleq (zero), (message), -1 ; subtract 0 from next character value to print;\n  ; terminate if it's <=0\n 11 ff ff subleq (message), -1, -1  ; output character\n 10 01 ff subleq (neg1), (start+1), -1 ; modify above two instructions by subtracting -1 \n 10 03 ff subleq (neg1), (start+3), -1 ; (adding 1) to their target addresses \n 0f 0f 00 subleq (zero), (zero), start ; if 0-0 <= 0 (i.e. always) goto start\n\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nmy @hello-world = \n|<15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1>,\n|\"Hello, world!\\n\\0\".comb.map(*.ord);\n\nsub run-subleq(@memory) {\n my $ip = 0;\n while $ip >= 0 && $ip < @memory {\n my ($a, $b, $c) = @memory[$ip..*];\n $ip += 3;\n if $a < 0 {\n @memory[$b] = getc.ord;\n } elsif $b < 0 {\n print @memory[$a].chr;\n } else {\n if (@memory[$b] -= @memory[$a]) <= 0 {\n $ip = $c;\n } \n }\n }\n}\n\nrun-subleq @hello-world;\n\n```\n\nOutput:\n\n```\nHello, world!\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement a function/procedure/method/subroutine that takes a set/array/list/stream/table/collection of words with integer weights, and identifies a non-empty subset of them whose weights sum to zero (cf. the Dropbox Diet candidate screening exercise and the Subset sum problem Wikipedia article).\n\nFor example\n\nThis set of weighted words, one solution would be the set of words:\n\n: : : * {elysee,   efferent,   deploy,   departure,   centipede,   bonnet,   balm,   archbishop}\n\nbecause their respective weights of:\n\n: : : * -326,   54,   44,   952,   -658,   452,   397,   and   -915\n\nsum to zero.\n\n: : : : : : Table of weighted words\n\n | word | weight |\n | --- | --- |\n | alliance | -624 |\n | archbishop | -915 |\n | balm | 397 |\n | bonnet | 452 |\n | brute | 870 |\n | centipede | -658 |\n | cobol | 362 |\n | covariate | 590 |\n | departure | 952 |\n | deploy | 44 |\n | diophantine | 645 |\n | efferent | 54 |\n | elysee | -326 |\n | eradicate | 376 |\n | escritoire | 856 |\n | exorcism | -983 |\n | fiat | 170 |\n | filmy | -874 |\n | flatworm | 503 |\n | gestapo | 915 |\n | infra | -847 |\n | isis | -982 |\n | lindholm | 999 |\n | markham | 475 |\n | mincemeat | -880 |\n | moresby | 756 |\n | mycenae | 183 |\n | plugging | -266 |\n | smokescreen | 423 |\n | speakeasy | -745 |\n | vein | 813 |\n\nAnother solution would be the set of words {flatworm, gestapo, infra, isis, lindholm, plugging, smokescreen, speakeasy}, because their respective weights of 503, 915, -847, -982, 999, -266, 423, and -745 also sum to zero.\n\nYou may assume the weights range from -1000 to 1000.\n\nIf there are multiple solutions, only one needs to be found.\n\nUse any algorithm you want and demonstrate it on a set of at least 30 weighted words with the results shown in a human readable form.\n\nNote that an implementation that depends on enumerating all possible subsets is likely to be infeasible." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @pairs =\n alliance => -624, archbishop => -915, balm => 397, bonnet => 452,\n brute => 870, centipede => -658, cobol => 362, covariate => 590,\n departure => 952, deploy => 44, diophantine => 645, efferent => 54,\n elysee => -326, eradicate => 376, escritoire => 856, exorcism => -983,\n fiat => 170, filmy => -874, flatworm => 503, gestapo => 915,\n infra => -847, isis => -982, lindholm => 999, markham => 475,\n mincemeat => -880, moresby => 756, mycenae => 183, plugging => -266,\n smokescreen => 423, speakeasy => -745, vein => 813;\nmy @weights = @pairs».value;\nmy %name = @pairs.hash.invert;\n\n.say for (1..27).hyper(:3batch).map: -> $n {\n given @weights.combinations($n).first({ 0 == [+] @^comb }) {\n when .so { \"Length $n: ({.map: {%name{$_}}})\" }\n default { \"Length $n: (none)\" }\n }\n}\n\n```\n\nOutput:\n\n```\nLength 1: (none)\nLength 2: (archbishop gestapo)\nLength 3: (centipede markham mycenae)\nLength 4: (alliance balm deploy mycenae)\nLength 5: (alliance brute covariate deploy mincemeat)\nLength 6: (alliance archbishop balm deploy gestapo mycenae)\nLength 7: (alliance archbishop bonnet cobol departure exorcism moresby)\nLength 8: (alliance archbishop balm bonnet fiat flatworm isis lindholm)\nLength 9: (alliance archbishop balm bonnet brute covariate eradicate mincemeat plugging)\nLength 10: (alliance archbishop balm bonnet brute centipede cobol departure deploy mincemeat)\nLength 11: (alliance archbishop balm bonnet brute centipede cobol departure infra moresby speakeasy)\nLength 12: (alliance archbishop balm bonnet brute centipede cobol covariate diophantine efferent elysee infra)\nLength 13: (alliance archbishop balm bonnet brute centipede cobol covariate departure efferent eradicate filmy isis)\nLength 14: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy elysee filmy markham speakeasy)\nLength 15: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy elysee exorcism flatworm infra mycenae)\nLength 16: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine elysee exorcism filmy gestapo infra)\nLength 17: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine exorcism isis mincemeat mycenae plugging vein)\nLength 18: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee exorcism filmy isis mycenae vein)\nLength 19: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate exorcism fiat infra isis smokescreen)\nLength 20: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate exorcism gestapo infra isis smokescreen speakeasy)\nLength 21: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate exorcism flatworm infra lindholm mincemeat plugging speakeasy)\nLength 22: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate escritoire exorcism fiat filmy flatworm mincemeat plugging speakeasy)\nLength 23: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee eradicate escritoire exorcism infra isis mincemeat moresby mycenae smokescreen speakeasy)\nLength 24: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine efferent elysee exorcism filmy gestapo infra markham mincemeat moresby mycenae plugging smokescreen speakeasy)\nLength 25: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine eradicate exorcism fiat filmy flatworm infra isis lindholm markham mincemeat moresby mycenae plugging speakeasy)\nLength 26: (alliance archbishop balm bonnet brute centipede cobol covariate departure deploy diophantine elysee eradicate escritoire exorcism fiat filmy gestapo infra isis markham mincemeat mycenae plugging speakeasy vein)\nLength 27: (alliance archbishop balm bonnet brute centipede covariate departure deploy efferent elysee eradicate escritoire exorcism fiat filmy flatworm infra isis lindholm markham mincemeat moresby mycenae plugging smokescreen speakeasy)\n```" } ]
[ { "role": "user", "content": "Substitution Cipher Implementation - File Encryption/Decryption\n\nTask\n\nEncrypt an input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypted file into original/decrypted file.\n\nThis type of Encryption/Decryption scheme is often called a Substitution Cipher.\n\nRelated tasks\n\n* Caesar cipher\n* Rot-13\n* Vigenère Cipher/Cryptanalysis\n\nSee also\n\n* Wikipedia: Substitution cipher" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015-11-20\n\nFeed it an action (encode, decode) and a file name at the command line and it will spit out the (en|de)coded file to STDOUT. Redirect into a file to save it. If no parameters are passed in, does the demo encode/decode.\n\n```\nmy $chr = (' ' .. '}').join('');\nmy $key = $chr.comb.pick(*).join('');\n\n# Be very boring and use the same key every time to fit task reqs.\n$key = q☃3#}^\",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\\n['6@_{bk)=-5qx(/?$JoU☃;\n\nsub MAIN ($action = 'encode', $file = '') {\n\n die 'Only options are encode or decode.' unless $action ~~ any 'encode'|'decode';\n\n my $text = qq:to/END/;\n Here we have to do is there will be a input/source file in which \n we are going to Encrypt the file by replacing every upper/lower \n case alphabets of the source file with another predetermined \n upper/lower case alphabets or symbols and save it into another \n output/encrypted file and then again convert that output/encrypted \n file into original/decrypted file. This type of Encryption/Decryption\n scheme is often called a Substitution Cipher.\n END\n\n $text = $file.IO.slurp if $file;\n\n say \"Key = $key\\n\";\n\n if $file {\n say &::($action)($text);\n } else {\n my $encoded;\n say \"Encoded text: \\n {$encoded = encode $text}\";\n say \"Decoded text: \\n {decode $encoded}\";\n }\n}\n\nsub encode ($text) { $text.trans($chr => $key) }\n\nsub decode ($text) { $text.trans($key => $chr) }\n\n```\n\nOutput:\n\nwith no passed parameters\n\n```\nKey = 3#}^\",dLs*>tPMcZR!fmC rEKhlw1v4AOgj7Q]YI+|pDB82a&XFV9yzuH<WT%N;iS.0e:`G\\n['6@_{bk)=-5qx(/?$JoU\n\nEncoded text: \n +`=`3(`3n.x`35b3:b3[-35n`=`3([@@30`3.3[{kq5Z-bq=e`3G[@`3[{3(n[en3\n(`3.=`3\\b[{\\35b3]{e=?k535n`3G[@`30?3=`[email protected][{\\3`x`=?3qkk`=Z@b(`=3\ne.-`[email protected]`5-3bG35n`3-bq=e`3G[@`3([5n3.{b5n`=3k=`:`5`=_[{`:3\nqkk`=Z@b(`=3e.-`[email protected]`5-3b=3-?_0b@-3.{:3-.x`3[53[{5b3.{b5n`=3\nbq5kq5Z`{e=?k5`:3G[@`3.{:35n`{3.\\.[{3eb{x`=535n.53bq5kq5Z`{e=?k5`:3\nG[@`3[{5b3b=[\\[{.@Z:`e=?k5`:3G[@`c39n[-35?k`3bG3]{e=?k5[b{ZQ`e=?k5[b{\n-en`_`3[-3bG5`{3e.@@`:3.3Vq0-5[5q5[b{37[kn`=c\n\nDecoded text: \n Here we have to do is there will be a input/source file in which \nwe are going to Encrypt the file by replacing every upper/lower \ncase alphabets of the source file with another predetermined \nupper/lower case alphabets or symbols and save it into another \noutput/encrypted file and then again convert that output/encrypted \nfile into original/decrypted file. This type of Encryption/Decryption\nscheme is often called a Substitution Cipher.\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay a substring:\n\n: * starting from   **n**   characters in and of   **m**   length;\n * starting from   **n**   characters in,   up to the end of the string;\n * whole string minus the last character;\n * starting from a known   character   within the string and of   **m**   length;\n * starting from a known   substring   within the string and of   **m**   length.\n\nIf the program uses UTF-8 or UTF-16,   it must work on any valid Unicode code point,\nwhether in the   Basic Multilingual Plane   or above it.\n\nThe program must reference logical characters (code points),   not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $str = 'abcdefgh';\nmy $n = 2;\nmy $m = 3;\nsay $str.substr($n, $m);\nsay $str.substr($n);\nsay $str.substr(0, *-1);\nsay $str.substr($str.index('d'), $m);\nsay $str.substr($str.index('de'), $m);\n```" } ]
[ { "role": "user", "content": "Task\n\nFind all primes in which all substrings (in base ten) are also primes.\n\nThis *can* be achieved by filtering all primes below 500 (there are 95 of them), but there *are* better ways.\n\nAdvanced\n\nSolve by testing at most 15 numbers for primality. Show a list of all numbers tested that were not prime." }, { "role": "assistant", "content": "```\nmy @p = (^10).grep: *.is-prime;\n\nsay gather while @p {\n .take for @p;\n\n @p = ( @p X~ <3 7> ).grep: { .is-prime and .substr(*-2,2).is-prime }\n}\n\n```\n\nOutput:\n\n```\n(2 3 5 7 23 37 53 73 373)\n```\n\n### Stretch Goal\n\n```\nmy $prime-tests = 0;\nmy @non-primes;\nsub spy-prime ($n) {\n $prime-tests++;\n my $is-p = $n.is-prime;\n\n push @non-primes, $n unless $is-p;\n return $is-p;\n}\n\nmy @p = <2 3 5 7>;\n\nsay gather while @p {\n .take for @p;\n\n @p = ( @p X~ <3 7> ).grep: { !.ends-with(33|77) and .&spy-prime };\n}\n.say for :$prime-tests, :@non-primes;\n\n```\n\nOutput:\n\n```\n(2 3 5 7 23 37 53 73 373)\nprime-tests => 11\nnon-primes => [27 57 237 537 737 3737]\n```" } ]
[ { "role": "user", "content": "The task is to demonstrate how to remove the first and last characters from a string.\n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it.\n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\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\nRaku provides both functional and method forms of substr. Note that, unlike in Perl 5, offsets from the end do not use negative numbers, but instead require a function expressing the negative offset relative to the length parameter, which is supplied by the operator. The form \\*-1 is just a simple way to write such a function.\n\nWe use musical sharps and flats to illustrate that Raku is comfortable with characters from any Unicode plane.\n\n```\nmy $s = '𝄪♯♮♭𝄫';\n\nprint qq:to/END/;\n Original:\n $s\n\n Remove first character:\n { substr($s, 1) }\n { $s.substr(1) }\n\n Remove last character:\n { substr($s, 0, *-1) }\n { $s.substr( 0, *-1) }\n { $s.chop }\n\n Remove first and last characters:\n { substr($s, 1, *-1) }\n { $s.substr(1, *-1) }\n END\n\n```\n\nOutput:\n\n```\nOriginal:\n𝄪♯♮♭𝄫\n\nRemove first character:\n♯♮♭𝄫\n♯♮♭𝄫\n \nRemove last character:\n𝄪♯♮♭\n𝄪♯♮♭\n𝄪♯♮♭\n \nRemove first and last characters:\n♯♮♭\n♯♮♭\n```" } ]
[ { "role": "user", "content": "A *subtractive generator* calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. \nThe formula is\n\n* r\n\n n\n =\n\n r\n\n (\n n\n −\n i\n )\n −\n\n r\n\n (\n n\n −\n j\n )\n\n\n (\n mod\n\n m\n )\n {\\displaystyle {\\displaystyle r\\_{n}=r\\_{(n-i)}-r\\_{(n-j)}{\\pmod {m}}}}\n\nfor some fixed values of \n\ni\n{\\displaystyle {\\displaystyle i}}\n, \n\nj\n{\\displaystyle {\\displaystyle j}}\n and \n\nm\n{\\displaystyle {\\displaystyle m}}\n, all positive integers. Supposing that \n\ni\n>\nj\n{\\displaystyle {\\displaystyle i>j}}\n, then the state of this generator is the list of the previous numbers from \n\nr\n\nn\n−\ni\n{\\displaystyle {\\displaystyle r\\_{n-i}}}\n to \n\nr\n\nn\n−\n1\n{\\displaystyle {\\displaystyle r\\_{n-1}}}\n. Many states generate uniform random integers from \n\n0\n{\\displaystyle {\\displaystyle 0}}\n to \n\nm\n−\n1\n{\\displaystyle {\\displaystyle m-1}}\n, but some states are bad. A state, filled with zeros, generates only zeros. If \n\nm\n{\\displaystyle {\\displaystyle m}}\n is even, then a state, filled with even numbers, generates only even numbers. More generally, if \n\nf\n{\\displaystyle {\\displaystyle f}}\n is a factor of \n\nm\n{\\displaystyle {\\displaystyle m}}\n, then a state, filled with multiples of \n\nf\n{\\displaystyle {\\displaystyle f}}\n, generates only multiples of \n\nf\n{\\displaystyle {\\displaystyle f}}\n.\n\nAll subtractive generators have some weaknesses. The formula correlates \n\nr\n\nn\n{\\displaystyle {\\displaystyle r\\_{n}}}\n, \n\nr\n\n(\nn\n−\ni\n)\n{\\displaystyle {\\displaystyle r\\_{(n-i)}}}\n and \n\nr\n\n(\nn\n−\nj\n)\n{\\displaystyle {\\displaystyle r\\_{(n-j)}}}\n; these three numbers are not independent, as true random numbers would be. Anyone who observes \n\ni\n{\\displaystyle {\\displaystyle i}}\n consecutive numbers can predict the next numbers, so the generator is not cryptographically secure. The authors of *Freeciv* (utility/rand.c) and *xpat2* (src/testit2.c) knew another problem: the low bits are less random than the high bits.\n\nThe subtractive generator has a better reputation than the linear congruential generator, perhaps because it holds more state. A subtractive generator might never multiply numbers: this helps where multiplication is slow. A subtractive generator might also avoid division: the value of \n\nr\n\n(\nn\n−\ni\n)\n−\n\nr\n\n(\nn\n−\nj\n)\n{\\displaystyle {\\displaystyle r\\_{(n-i)}-r\\_{(n-j)}}}\n is always between \n\n−\nm\n{\\displaystyle {\\displaystyle -m}}\n and \n\nm\n{\\displaystyle {\\displaystyle m}}\n, so a program only needs to add \n\nm\n{\\displaystyle {\\displaystyle m}}\n to negative numbers.\n\nThe choice of \n\ni\n{\\displaystyle {\\displaystyle i}}\n and \n\nj\n{\\displaystyle {\\displaystyle j}}\n affects the period of the generator. A popular choice is \n\ni\n=\n55\n{\\displaystyle {\\displaystyle i=55}}\n and \n\nj\n=\n24\n{\\displaystyle {\\displaystyle j=24}}\n, so the formula is\n\n* r\n\n n\n =\n\n r\n\n (\n n\n −\n 55\n )\n −\n\n r\n\n (\n n\n −\n 24\n )\n\n\n (\n mod\n\n m\n )\n {\\displaystyle {\\displaystyle r\\_{n}=r\\_{(n-55)}-r\\_{(n-24)}{\\pmod {m}}}}\n\nThe subtractive generator from *xpat2* uses\n\n* r\n\n n\n =\n\n r\n\n (\n n\n −\n 55\n )\n −\n\n r\n\n (\n n\n −\n 24\n )\n\n\n (\n mod\n\n\n 10\n\n 9\n )\n {\\displaystyle {\\displaystyle r\\_{n}=r\\_{(n-55)}-r\\_{(n-24)}{\\pmod {10^{9}}}}}\n\nThe implementation is by J. Bentley and comes from program\\_tools/universal.c of the DIMACS (netflow) archive at Rutgers University. It credits Knuth, TAOCP, Volume 2, Section 3.2.2 (Algorithm A).\n\nBentley uses this clever algorithm to seed the generator.\n\n1. Start with a single \n\n s\n e\n e\n d\n {\\displaystyle {\\displaystyle seed}}\n in range \n\n 0\n {\\displaystyle {\\displaystyle 0}}\n to \n\n 10\n\n 9\n −\n 1\n {\\displaystyle {\\displaystyle 10^{9}-1}}\n .\n2. Set \n\n s\n\n 0\n =\n s\n e\n e\n d\n {\\displaystyle {\\displaystyle s\\_{0}=seed}}\n and \n\n s\n\n 1\n =\n 1\n {\\displaystyle {\\displaystyle s\\_{1}=1}}\n . The inclusion of \n\n s\n\n 1\n =\n 1\n {\\displaystyle {\\displaystyle s\\_{1}=1}}\n avoids some bad states (like all zeros, or all multiples of 10).\n3. Compute \n\n s\n\n 2\n ,\n\n s\n\n 3\n ,\n .\n .\n .\n ,\n\n s\n\n 54\n {\\displaystyle {\\displaystyle s\\_{2},s\\_{3},...,s\\_{54}}}\n using the subtractive formula \n\n s\n\n n\n =\n\n s\n\n (\n n\n −\n 2\n )\n −\n\n s\n\n (\n n\n −\n 1\n )\n\n\n (\n mod\n\n\n 10\n\n 9\n )\n {\\displaystyle {\\displaystyle s\\_{n}=s\\_{(n-2)}-s\\_{(n-1)}{\\pmod {10^{9}}}}}\n .\n4. Reorder these 55 values so \n\n r\n\n 0\n =\n\n s\n\n 34\n {\\displaystyle {\\displaystyle r\\_{0}=s\\_{34}}}\n , \n\n r\n\n 1\n =\n\n s\n\n 13\n {\\displaystyle {\\displaystyle r\\_{1}=s\\_{13}}}\n , \n\n r\n\n 2\n =\n\n s\n\n 47\n {\\displaystyle {\\displaystyle r\\_{2}=s\\_{47}}}\n , ..., \n\n r\n\n n\n =\n\n s\n\n (\n 34\n ∗\n (\n n\n +\n 1\n )\n\n\n (\n mod\n\n 55\n )\n )\n {\\displaystyle {\\displaystyle r\\_{n}=s\\_{(34\\*(n+1){\\pmod {55}})}}}\n .\n * This is the same order as \n\n s\n\n 0\n =\n\n r\n\n 54\n {\\displaystyle {\\displaystyle s\\_{0}=r\\_{54}}}\n , \n\n s\n\n 1\n =\n\n r\n\n 33\n {\\displaystyle {\\displaystyle s\\_{1}=r\\_{33}}}\n , \n\n s\n\n 2\n =\n\n r\n\n 12\n {\\displaystyle {\\displaystyle s\\_{2}=r\\_{12}}}\n , ..., \n\n s\n\n n\n =\n\n r\n\n (\n (\n 34\n ∗\n n\n )\n −\n 1\n\n\n (\n mod\n\n 55\n )\n )\n {\\displaystyle {\\displaystyle s\\_{n}=r\\_{((34\\*n)-1{\\pmod {55}})}}}\n .\n * This rearrangement exploits how 34 and 55 are relatively prime.\n5. Compute the next 165 values \n\n r\n\n 55\n {\\displaystyle {\\displaystyle r\\_{55}}}\n to \n\n r\n\n 219\n {\\displaystyle {\\displaystyle r\\_{219}}}\n . Store the last 55 values.\n\nThis generator yields the sequence \n\nr\n\n220\n{\\displaystyle {\\displaystyle r\\_{220}}}\n, \n\nr\n\n221\n{\\displaystyle {\\displaystyle r\\_{221}}}\n, \n\nr\n\n222\n{\\displaystyle {\\displaystyle r\\_{222}}}\n and so on. For example, if the seed is 292929, then the sequence begins with \n\nr\n\n220\n=\n467478574\n{\\displaystyle {\\displaystyle r\\_{220}=467478574}}\n, \n\nr\n\n221\n=\n512932792\n{\\displaystyle {\\displaystyle r\\_{221}=512932792}}\n, \n\nr\n\n222\n=\n539453717\n{\\displaystyle {\\displaystyle r\\_{222}=539453717}}\n. By starting at \n\nr\n\n220\n{\\displaystyle {\\displaystyle r\\_{220}}}\n, this generator avoids a bias from the first numbers of the sequence. This generator must store the last 55 numbers of the sequence, so to compute the next \n\nr\n\nn\n{\\displaystyle {\\displaystyle r\\_{n}}}\n. Any array or list would work; a ring buffer is ideal but not necessary.\n\nImplement a subtractive generator that replicates the sequences from *xpat2*." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: Rakudo version 2018.03\n\n```\nsub bentley-clever($seed) {\n constant $mod = 1_000_000_000;\n my @seeds = ($seed % $mod, 1, (* - *) % $mod ... *)[^55];\n my @state = @seeds[ 34, (* + 34 ) % 55 ... 0 ];\n\n sub subrand() {\n push @state, (my $x = (@state.shift - @state[*-24]) % $mod);\n $x;\n }\n\n subrand for 55 .. 219;\n\n &subrand ... *;\n}\n\nmy @sr = bentley-clever(292929);\n.say for @sr[^10];\n\n```\n\nHere we just make the seeder return the random sequence as a lazy list.\n\nOutput:\n\n```\n467478574\n512932792\n539453717\n20349702\n615542081\n378707948\n933204586\n824858649\n506003769\n380969305\n```" } ]
[ { "role": "user", "content": "The series of increasing prime numbers begins: `2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...`\n\nThe task applies a filter to the series returning groups of *successive* primes, (s'primes), that differ from the next by a given value or values.\n\n**Example 1:** Specifying that the difference between s'primes be `2` leads to the groups:\n\n: `(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), ...`\n\n(Known as Twin primes or Prime pairs)\n\n**Example 2:** Specifying more than one difference *between* s'primes leads to groups of size one greater than the number of differences. Differences of `2, 4` leads to the groups:\n\n: `(5, 7, 11), (11, 13, 17), (17, 19, 23), (41, 43, 47), ...`.\n\nIn the first group 7 is two more than 5 and 11 is four more than 7; as well as 5, 7, and 11 being *successive* primes.\nDifferences are checked in the order of the values given, (differences of `4, 2` would give different groups entirely).\n\nTask\n\n* In each case use a list of primes less than 1\\_000\\_000\n* For the following Differences show the first and last group, as well as the number of groups found:\n\n: 1. Differences of `2`.\n 2. Differences of `1`.\n 3. Differences of `2, 2`.\n 4. Differences of `2, 4`.\n 5. Differences of `4, 2`.\n 6. Differences of `6, 4, 2`.\n\n* Show output here.\n\nNote: Generation of a list of primes is a secondary aspect of the task. Use of a built in function, well known library, or importing/use of prime generators from other Rosetta Code tasks is encouraged.\n\nreferences\n: 1. https://pdfs.semanticscholar.org/78a1/7349819304863ae061df88dbcb26b4908f03.pdf\n 2. https://www.primepuzzles.net/puzzles/puzz\\_011.htm\n 3. https://matheplanet.de/matheplanet/nuke/html/viewtopic.php?topic=232720&start=0" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Categorized by Successive\n\n**Works with**: Rakudo version 2019.03\n\nEssentially the code from the Sexy primes task with minor tweaks.\n\n```\nuse Math::Primesieve;\nmy $sieve = Math::Primesieve.new;\n\nmy $max = 1_000_000;\nmy @primes = $sieve.primes($max);\nmy $filter = @primes.Set;\nmy $primes = @primes.categorize: &successive;\n\nsub successive ($i) {\n gather {\n take '2' if $filter{$i + 2};\n take '1' if $filter{$i + 1};\n take '2_2' if all($filter{$i «+« (2,4)});\n take '2_4' if all($filter{$i «+« (2,6)});\n take '4_2' if all($filter{$i «+« (4,6)});\n take '6_4_2' if all($filter{$i «+« (6,10,12)}) and\n none($filter{$i «+« (2,4,8)});\n }\n}\n\nsub comma { $^i.flip.comb(3).join(',').flip }\n\nfor (2,), (1,), (2,2), (2,4), (4,2), (6,4,2) -> $succ {\n say \"## Sets of {1+$succ} successive primes <= { comma $max } with \" ~\n \"successive differences of { $succ.join: ', ' }\";\n my $i = $succ.join: '_';\n for 'First', 0, ' Last', * - 1 -> $where, $ind {\n say \"$where group: \", join ', ', [\\+] flat $primes{$i}[$ind], |$succ\n }\n say ' Count: ', +$primes{$i}, \"\\n\";\n}\n\n```\n\nOutput:\n\n```\n## Sets of 2 successive primes <= 1,000,000 with successive differences of 2\nFirst group: 3, 5\n Last group: 999959, 999961\n Count: 8169\n\n## Sets of 2 successive primes <= 1,000,000 with successive differences of 1\nFirst group: 2, 3\n Last group: 2, 3\n Count: 1\n\n## Sets of 3 successive primes <= 1,000,000 with successive differences of 2, 2\nFirst group: 3, 5, 7\n Last group: 3, 5, 7\n Count: 1\n\n## Sets of 3 successive primes <= 1,000,000 with successive differences of 2, 4\nFirst group: 5, 7, 11\n Last group: 999431, 999433, 999437\n Count: 1393\n\n## Sets of 3 successive primes <= 1,000,000 with successive differences of 4, 2\nFirst group: 7, 11, 13\n Last group: 997807, 997811, 997813\n Count: 1444\n\n## Sets of 4 successive primes <= 1,000,000 with successive differences of 6, 4, 2\nFirst group: 31, 37, 41, 43\n Last group: 997141, 997147, 997151, 997153\n Count: 306\n\n```\n\n### Precomputed Differences\n\n**Works with**: Rakudo version 2019.03\n\n```\nuse Math::Primesieve;\n\nconstant $max = 1_000_000;\nconstant @primes = Math::Primesieve.primes($max);\nconstant @diffs = @primes.skip Z- @primes;\n\nsay \"Given all ordered primes <= $max, sets with successive differences of:\";\nfor (2,), (1,), (2,2), (2,4), (4,2), (6,4,2) -> @succ {\n my $size = @succ.elems;\n\n my @group_start_offsets = @diffs.rotor( $size => 1-$size )\n .grep(:k, { $_ eqv @succ });\n\n my ($first, $last) = @group_start_offsets[0, *-1]\n .map: { @primes.skip($_).head($size + 1) };\n\n say sprintf '%10s has %5d sets: %15s … %s',\n @succ.gist, @group_start_offsets.elems, $first, $last;\n}\n\n```\n\nOutput:\n\n```\nGiven all ordered primes <= 1000000, sets with successive differences of:\n (2) has 8169 sets: 3 5 … 999959 999961\n (1) has 1 sets: 2 3 … 2 3\n (2 2) has 1 sets: 3 5 7 … 3 5 7\n (2 4) has 1393 sets: 5 7 11 … 999431 999433 999437\n (4 2) has 1444 sets: 7 11 13 … 997807 997811 997813\n (6 4 2) has 306 sets: 31 37 41 43 … 997141 997147 997151 997153\n```" } ]
[ { "role": "user", "content": "The **Sudan function** is a classic example of a recursive function, notable especially because it is not a primitive recursive function. This is also true of the better-known Ackermann function. The Sudan function was the first function having this property to be published.\n\nThe Sudan function is usually defined as follows (svg):\n\nF\n\n0\n(\nx\n,\ny\n)\n\n=\nx\n+\ny\n\nF\n\nn\n+\n1\n(\nx\n,\n0\n)\n\n=\nx\n\n\nif \nn\n≥\n0\n\nF\n\nn\n+\n1\n(\nx\n,\ny\n+\n1\n)\n\n=\n\nF\n\nn\n(\n\nF\n\nn\n+\n1\n(\nx\n,\ny\n)\n,\n\nF\n\nn\n+\n1\n(\nx\n,\ny\n)\n+\ny\n+\n1\n)\n\n\nif \nn\n≥\n0\n{\\displaystyle {\\displaystyle {\\begin{array}{lll}F\\_{0}(x,y)&=x+y\\\\F\\_{n+1}(x,0)&=x&{\\text{if }}n\\geq 0\\\\F\\_{n+1}(x,y+1)&=F\\_{n}(F\\_{n+1}(x,y),F\\_{n+1}(x,y)+y+1)&{\\text{if }}n\\geq 0\\\\\\end{array}}}}\n\nTask\n\nWrite a function which returns the value of F(x, y)." }, { "role": "assistant", "content": "Outputting wiki-tables to more closely emulate the wikipedia examples. Not very efficient but good enough.\n\n```\nmulti F (0, $x, $y) { $x + $y }\nmulti F ($n where * > 0, $x, 0) { $x }\nmulti F ($n, $x, $y) { F($n-1, F($n, $x, $y-1), F($n, $x, $y-1) + $y) }\n\n# Testing\nfor 0, 6, 1, 15 -> $f, $g {\n my @range = ^$g;\n say \"\\{|class=\\\"wikitable\\\"\\n\", \"|+ F\\<sub>$f\\</sub> (x,y)\\n\" ~ '!x\\y!!', join '!!', @range;\n -> $r { say \"|-\\n\" ~ '|' ~ join '||', $r, @range.map:{ F($f, $r, $_) } } for @range;\n say( \"|}\" );\n}\n\n```\n\nOutput:\n\nF0 (x,y)\n\n| x\\y | 0 | 1 | 2 | 3 | 4 | 5 |\n| --- | --- | --- | --- | --- | --- | --- |\n| 0 | 0 | 1 | 2 | 3 | 4 | 5 |\n| 1 | 1 | 2 | 3 | 4 | 5 | 6 |\n| 2 | 2 | 3 | 4 | 5 | 6 | 7 |\n| 3 | 3 | 4 | 5 | 6 | 7 | 8 |\n| 4 | 4 | 5 | 6 | 7 | 8 | 9 |\n| 5 | 5 | 6 | 7 | 8 | 9 | 10 |\n\nF1 (x,y)\n\n| x\\y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| 0 | 0 | 1 | 4 | 11 | 26 | 57 | 120 | 247 | 502 | 1013 | 2036 | 4083 | 8178 | 16369 | 32752 |\n| 1 | 1 | 3 | 8 | 19 | 42 | 89 | 184 | 375 | 758 | 1525 | 3060 | 6131 | 12274 | 24561 | 49136 |\n| 2 | 2 | 5 | 12 | 27 | 58 | 121 | 248 | 503 | 1014 | 2037 | 4084 | 8179 | 16370 | 32753 | 65520 |\n| 3 | 3 | 7 | 16 | 35 | 74 | 153 | 312 | 631 | 1270 | 2549 | 5108 | 10227 | 20466 | 40945 | 81904 |\n| 4 | 4 | 9 | 20 | 43 | 90 | 185 | 376 | 759 | 1526 | 3061 | 6132 | 12275 | 24562 | 49137 | 98288 |\n| 5 | 5 | 11 | 24 | 51 | 106 | 217 | 440 | 887 | 1782 | 3573 | 7156 | 14323 | 28658 | 57329 | 114672 |\n| 6 | 6 | 13 | 28 | 59 | 122 | 249 | 504 | 1015 | 2038 | 4085 | 8180 | 16371 | 32754 | 65521 | 131056 |\n| 7 | 7 | 15 | 32 | 67 | 138 | 281 | 568 | 1143 | 2294 | 4597 | 9204 | 18419 | 36850 | 73713 | 147440 |\n| 8 | 8 | 17 | 36 | 75 | 154 | 313 | 632 | 1271 | 2550 | 5109 | 10228 | 20467 | 40946 | 81905 | 163824 |\n| 9 | 9 | 19 | 40 | 83 | 170 | 345 | 696 | 1399 | 2806 | 5621 | 11252 | 22515 | 45042 | 90097 | 180208 |\n| 10 | 10 | 21 | 44 | 91 | 186 | 377 | 760 | 1527 | 3062 | 6133 | 12276 | 24563 | 49138 | 98289 | 196592 |\n| 11 | 11 | 23 | 48 | 99 | 202 | 409 | 824 | 1655 | 3318 | 6645 | 13300 | 26611 | 53234 | 106481 | 212976 |\n| 12 | 12 | 25 | 52 | 107 | 218 | 441 | 888 | 1783 | 3574 | 7157 | 14324 | 28659 | 57330 | 114673 | 229360 |\n| 13 | 13 | 27 | 56 | 115 | 234 | 473 | 952 | 1911 | 3830 | 7669 | 15348 | 30707 | 61426 | 122865 | 245744 |\n| 14 | 14 | 29 | 60 | 123 | 250 | 505 | 1016 | 2039 | 4086 | 8181 | 16372 | 32755 | 65522 | 131057 | 262128 |" } ]
[ { "role": "user", "content": "Task\n\nSolve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format.\n\nreferences\n\n* Algorithmics of Sudoku   may help implement this.\n* Python Sudoku Solver Computerphile video." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Brute Force\n\n**Translation of**: Perl\n\n```\nmy @A = <\n 5 3 0 0 2 4 7 0 0 \n 0 0 2 0 0 0 8 0 0 \n 1 0 0 7 0 3 9 0 2 \n \n 0 0 8 0 7 2 0 4 9 \n 0 2 0 9 8 0 0 7 0 \n 7 9 0 0 0 0 0 8 0 \n \n 0 0 0 0 3 0 5 0 6 \n 9 6 0 0 1 0 3 0 0 \n 0 5 0 6 9 0 0 1 0\n>;\n \nmy &I = * div 9; # line number\nmy &J = * % 9; # column number\nmy &K = { ($_ div 27) * 3 + $_ % 9 div 3 }; # bloc number\n\nsub solve {\n for ^@A -> $i {\n\tnext if @A[$i];\n\tmy @taken-values = @A[\n\t grep {\n\t\tI($_) == I($i) || J($_) == J($i) || K($_) == K($i)\n\t }, ^@A\n\t];\n\tfor grep none(@taken-values), 1..9 {\n\t @A[$i] = $_;\n\t solve;\n\t}\n\treturn @A[$i] = 0;\n }\n my $i = 1;\n for ^@A {\n\tprint \"@A[$_] \";\n\tprint \" \" if $i %% 3;\n\tprint \"\\n\" if $i %% 9;\n\tprint \"\\n\" if $i++ %% 27;\n }\n}\nsolve;\n\n```\n\nOutput:\n\n```\n5 3 9 8 2 4 7 6 1 \n6 7 2 1 5 9 8 3 4 \n1 8 4 7 6 3 9 5 2 \n\n3 1 8 5 7 2 6 4 9 \n4 2 5 9 8 6 1 7 3 \n7 9 6 3 4 1 2 8 5 \n\n8 4 1 2 3 7 5 9 6 \n9 6 7 4 1 5 3 2 8 \n2 5 3 6 9 8 4 1 7\n```\n\n### Finesse It\n\nThis is an alternative solution that uses a more ellaborate set of choices instead of brute-forcing it.\n\n```\n#\n# In this code, a sudoku puzzle is represented as a two-dimentional\n# array. The cells that are not yet solved are represented by yet\n# another array of all the possible values.\n#\n# This implementation is not a simple brute force evaluation of all\n# the options, but rather makes four extra attempts to guide the\n# solution:\n#\n# 1) For every change in the grid, usually made by an attempt at a\n# solution, we will reduce the search space of the possible values\n# in all the other cells before going forward.\n#\n# 2) When a cell that is not yet resolved is the only one that can\n# hold a specific value, resolve it immediately instead of\n# performing the regular search.\n#\n# 3) Instead of trying from cell 1,1 and moving in sequence, this\n# implementation will start trying on the cell that is the closest\n# to being solved already.\n#\n# 4) Instead of trying all possible values in sequence, start with\n# the value that is the most unique. I.e.: If the options for this\n# cell are 1,4,6 and 6 is only a candidate for two of the\n# competing cells, we start with that one.\n#\n\n# keep a list with all the cells, handy for traversal\nmy @cells = do for (flat 0..8 X 0..8) -> $x, $y { [ $x, $y ] };\n\n#\n# Try to solve this puzzle and return the resolved puzzle if it is at\n# all solvable in this configuration.\nsub solve($sudoku, Int $level) {\n # cleanup the impossible values first,\n if (cleanup-impossible-values($sudoku, $level)) {\n # try to find implicit answers\n while (find-implicit-answers($sudoku, $level)) {\n # and every time you find some, re-do the cleanup and try again\n cleanup-impossible-values($sudoku, $level);\n }\n # Now let's actually try to solve a new value. But instead of\n # going in sequence, we select the cell that is the closest to\n # being solved already. This will reduce the overall number of\n # guesses.\n for sort { solution-complexity-factor($sudoku, $_[0], $_[1]) },\n grep { $sudoku[$_[0]][$_[1]] ~~ Array },\n @cells -> $cell\n {\n my Int ($x, $y) = @($cell);\n # Now let's try the possible values in the order of\n # uniqueness.\n for sort { matches-in-competing-cells($sudoku, $x, $y, $_) }, @($sudoku[$x][$y]) -> $val {\n trace $level, \"Trying $val on \"~($x+1)~\",\"~($y+1)~\" \"~$sudoku[$x][$y].raku;\n my $solution = clone-sudoku($sudoku);\n $solution[$x][$y] = $val;\n my $solved = solve($solution, $level+1);\n if $solved {\n trace $level, \"Solved... ($val on \"~($x+1)~\",\"~($y+1)~\")\";\n return $solved;\n }\n }\n # if we fell through, it means that we found no valid\n # value for this cell\n trace $level, \"Backtrack, path unsolvable... (on \"~($x+1)~\" \"~($y+1)~\")\";\n return False;\n }\n # all cells are already solved.\n return $sudoku;\n } else {\n # if the cleanup failed, it means this is an invalid grid.\n return False;\n }\n}\n\n# This function reduces the search space from values that are already\n# assigned to competing cells.\nsub cleanup-impossible-values($sudoku, Int $level = 1) {\n my Bool $resolved;\n repeat {\n $resolved = False;\n for grep { $sudoku[$_[0]][$_[1]] ~~ Array },\n @cells -> $cell {\n my Int ($x, $y) = @($cell);\n # which block is this cell in\n my Int $bx = Int($x / 3);\n my Int $by = Int($y / 3);\n \n # A unfilled cell is not resolved, so it shouldn't match\n my multi match-resolved-cell(Array $other, Int $this) {\n return False;\n }\n my multi match-resolved-cell(Int $other, Int $this) {\n return $other == $this;\n }\n\n # Reduce the possible values to the ones that are still\n # valid\n my @r =\n grep { !match-resolved-cell($sudoku[any(0..2)+3*$bx][any(0..2)+3*$by], $_) }, # same block\n grep { !match-resolved-cell($sudoku[any(0..8)][$y], $_) }, # same line\n grep { !match-resolved-cell($sudoku[$x][any(0..8)], $_) }, # same column\n @($sudoku[$x][$y]);\n if (@r.elems == 1) {\n # if only one element is left, then make it resolved\n $sudoku[$x][$y] = @r[0];\n $resolved = True;\n } elsif (@r.elems == 0) {\n # This is an invalid grid\n return False;\n } else {\n $sudoku[$x][$y] = @r;\n }\n }\n } while $resolved; # repeat if there was any change\n return True;\n}\n\nsub solution-complexity-factor($sudoku, Int $x, Int $y) {\n my Int $bx = Int($x / 3); # this block\n my Int $by = Int($y / 3);\n my multi count-values(Array $val) {\n return $val.elems;\n }\n my multi count-values(Int $val) {\n return 1;\n }\n # the number of possible values should take precedence\n my Int $f = 1000 * count-values($sudoku[$x][$y]);\n for (flat 0..2 X 0..2) -> $lx, $ly {\n $f += count-values($sudoku[$lx+$bx*3][$ly+$by*3])\n }\n for 0..^($by*3), (($by+1)*3)..8 -> $ly {\n $f += count-values($sudoku[$x][$ly])\n }\n for 0..^($bx*3), (($bx+1)*3)..8 -> $lx {\n $f += count-values($sudoku[$lx][$y])\n }\n return $f;\n}\n\nsub matches-in-competing-cells($sudoku, Int $x, Int $y, Int $val) {\n my Int $bx = Int($x / 3); # this block\n my Int $by = Int($y / 3);\n # Function to decide which possible value to try first\n my multi cell-matching(Int $cell) {\n return $val == $cell ?? 1 !! 0;\n }\n my multi cell-matching(Array $cell) {\n return $cell.grep({ $val == $_ }) ?? 1 !! 0;\n }\n my Int $c = 0;\n for (flat 0..2 X 0..2) -> $lx, $ly {\n $c += cell-matching($sudoku[$lx+$bx*3][$ly+$by*3])\n }\n for 0..^($by*3), (($by+1)*3)..8 -> $ly {\n $c += cell-matching($sudoku[$x][$ly])\n }\n for 0..^($bx*3), (($bx+1)*3)..8 -> $lx {\n $c += cell-matching($sudoku[$lx][$y])\n }\n return $c;\n}\n\nsub find-implicit-answers($sudoku, Int $level) {\n my Bool $resolved = False;\n for grep { $sudoku[$_[0]][$_[1]] ~~ Array },\n @cells -> $cell {\n my Int ($x, $y) = @($cell);\n for @($sudoku[$x][$y]) -> $val {\n # If this is the only cell with this val as a possibility,\n # just make it resolved already\n if (matches-in-competing-cells($sudoku, $x, $y, $val) == 1) {\n $sudoku[$x][$y] = $val;\n $resolved = True;\n }\n }\n }\n return $resolved;\n}\n\nmy $puzzle =\n map { [ map { $_ == 0 ?? [1..9] !! $_+0 }, @($_) ] },\n [ 0,0,0,0,3,7,6,0,0 ],\n [ 0,0,0,6,0,0,0,9,0 ],\n [ 0,0,8,0,0,0,0,0,4 ],\n [ 0,9,0,0,0,0,0,0,1 ],\n [ 6,0,0,0,0,0,0,0,9 ],\n [ 3,0,0,0,0,0,0,4,0 ],\n [ 7,0,0,0,0,0,8,0,0 ],\n [ 0,1,0,0,0,9,0,0,0 ],\n [ 0,0,2,5,4,0,0,0,0 ];\n\nmy $solved = solve($puzzle, 0);\nif $solved {\n print-sudoku($solved,0);\n} else {\n say \"unsolvable.\";\n}\n\n# Utility functions, not really part of the solution\n\nsub trace(Int $level, Str $message) {\n # say '.' x $level, $message; # un-comment for verbose logging\n}\n\nsub clone-sudoku($sudoku) {\n my $clone;\n for (flat 0..8 X 0..8) -> $x, $y {\n $clone[$x][$y] = $sudoku[$x][$y];\n }\n return $clone;\n}\n\nsub print-sudoku($sudoku, Int $level = 1) {\n trace $level, '-' x 5*9;\n for @($sudoku) -> $row {\n trace $level, join \" \", do for @($row) -> $cell {\n $cell ~~ Array ?? \"#{$cell.elems}#\" !! \" $cell \" \n }\n }\n}\n\n```\n\nOutput:\n\n```\n 9 5 4 1 3 7 6 8 2 \n 2 7 3 6 8 4 1 9 5 \n 1 6 8 2 9 5 7 3 4 \n 4 9 5 7 2 8 3 6 1 \n 6 8 1 4 5 3 2 7 9 \n 3 2 7 9 6 1 5 4 8 \n 7 4 9 3 1 2 8 5 6 \n 5 1 6 8 7 9 4 2 3 \n 8 3 2 5 4 6 9 1 7 \n\n```" } ]
[ { "role": "user", "content": "A suffix tree is a data structure commonly used in string algorithms.\n\nGiven a string S of length n, its suffix tree is a tree T such that:\n\n* T has exactly n leaves numbered from 1 to n.\n* Except for the root, every internal node has at least two children.\n* Each edge of T is labelled with a non-empty substring of S.\n* No two edges starting out of a node can have string labels beginning with the same character.\n* The string obtained by concatenating all the string labels found on the path from the root to leaf i spells out suffix S[i..n], for i from 1 to n.\n\nSuch a tree does not exist for all strings. To ensure existence, a character that is not found in S must be appended at its end. The character '$' is traditionally used for this purpose.\n\nFor this task, build and display the suffix tree of the string \"banana$\". Displaying the tree can be done using the code from the visualize a tree task, but any other convenient method is accepted.\n\nThere are several ways to implement the tree data structure, for instance how edges should be labelled. Latitude is given in this matter, but notice that a simple way to do it is to label each node with the label of the edge leading to it.\n\nThe computation time for an efficient algorithm should be \n\nO\n(\nn\n)\n{\\displaystyle {\\displaystyle O(n)}}\n, but such an algorithm might be difficult to implement. An easier, \n\nO\n(\n\nn\n\n2\n)\n{\\displaystyle {\\displaystyle O(n^{2})}}\n algorithm is accepted." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04\n\nHere is quite a naive algorithm, probably \n\nO\n(\n\nn\n\n2\n)\n{\\displaystyle {\\displaystyle O(n^{2})}}\n.\n\nThe display code is a variant of the visualize a tree task code.\n\n```\nmulti suffix-tree(Str $str) { suffix-tree flat map &flip, [\\~] $str.flip.comb }\nmulti suffix-tree(@a) {\n hash\n @a == 0 ?? () !!\n @a == 1 ?? ( @a[0] => [] ) !!\n gather for @a.classify(*.substr(0, 1)) {\n my $subtree = suffix-tree(grep *.chars, map *.substr(1), .value[]);\n if $subtree == 1 {\n my $pair = $subtree.pick;\n take .key ~ $pair.key => $pair.value;\n } else {\n take .key => $subtree;\n }\n }\n}\n\nmy $tree = root => suffix-tree 'banana$';\n\n.say for visualize-tree $tree, *.key, *.value.List;\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] ~ $node.&label;\n my @children = sort $node.&children;\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 flat visit($tree, $indent xx 2);\n}\n\n```\n\nOutput:\n\n```\nroot\n├─$\n├─a\n│ ├─$\n│ └─na\n│ ├─$\n│ └─na$\n├─banana$\n└─na\n ├─$\n └─na$\n```" } ]
[ { "role": "user", "content": "**Suffixation**:   a letter or a group of letters added to the end of a word to change its meaning.\n\n: : : : : : : ─────   or, as used herein   ─────\n\n**Suffixation**:   the addition of a metric or \"binary\" metric suffix to a number, with/without rounding.\n\nTask\n\nWrite a function(s) to append (if possible)   a metric   or   a \"binary\" metric   suffix to a\nnumber   (displayed in decimal).\n\nThe number may be rounded   (as per user specification)   (via shortening of the number when the number of\ndigits past the decimal point are to be used).\n\nTask requirements\n: : * write a function (or functions) to add   (if possible)   a suffix to a number\n * the function(s) should be able to express the number (possibly with a suffix) in as many decimal digits as specified\n * the sign should be preserved   (if present)\n * the number may have commas within the number   (the commas need not be preserved)\n * the number may have a decimal point and/or an exponent as in:   -123.7e-01\n * the suffix that might be appended should be in uppercase;   however, the   **i**   should be in lowercase\n * support:\n\n : : * the            metric suffixes:   **K  M  G  T  P  E  Z  Y  X  W  V  U**\n * the binary metric suffixes:   **Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui**\n * the (full name) suffix:   **googol**   (lowercase)   (equal to **1e100**)     (optional)\n * a number of decimal digits past the decimal point   (with rounding).   The default is to display all significant digits\n\n * validation of the (supplied/specified) arguments is optional but recommended\n * display   (with identifying text):\n\n : : * the original number   (with identifying text)\n * the number of digits past the decimal point being used   (or none, if not specified)\n * the type of suffix being used   (metric or \"binary\" metric)\n * the (new) number with the appropriate   (if any)   suffix\n * all output here on this page\n\nMetric suffixes to be supported   (whether or not they're officially sanctioned)\n\n```\n K multiply the number by 10^3 kilo (1,000)\n M multiply the number by 10^6 mega (1,000,000)\n G multiply the number by 10^9 giga (1,000,000,000)\n T multiply the number by 10^12 tera (1,000,000,000,000)\n P multiply the number by 10^15 peta (1,000,000,000,000,000)\n E multiply the number by 10^18 exa (1,000,000,000,000,000,000)\n Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)\n Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)\n X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)\n W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)\n V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)\n U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)\n\n```\n\n\"Binary\" suffixes to be supported   (whether or not they're officially sanctioned)\n\n```\n Ki multiply the number by 2^10 kibi (1,024)\n Mi multiply the number by 2^20 mebi (1,048,576)\n Gi multiply the number by 2^30 gibi (1,073,741,824)\n Ti multiply the number by 2^40 tebi (1,099,571,627,776)\n Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)\n Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)\n Zi multiply the number by 2^70 zebi (1,180,591,620,717,411,303,424)\n Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)\n Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)\n Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)\n Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)\n Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)\n\n```\n\nFor instance, with this pseudo─code\n\n```\n /* 1st arg: the number to be transformed.*/\n /* 2nd arg: # digits past the dec. point.*/\n /* 3rd arg: the type of suffix to use. */\n /* 2 indicates \"binary\" suffix.*/\n /* 10 indicates decimal suffix.*/\n a = '456,789,100,000,000' /* \"A\" has eight trailing zeros. */\n say ' aa=' suffize(a) /* Display a suffized number to terminal.*/\n /* The \"1\" below shows one decimal ···*/\n /* digit past the decimal point. */\n n = suffize(a, 1) /* SUFFIZE is the function name. */\n n = suffize(a, 1, 10) /* (identical to the above statement.) */\n say ' n=' n /* Display value of N to terminal. */\n /* Note the rounding that occurs. */\n f = suffize(a, 1, 2) /* SUFFIZE with one fractional digit */\n say ' f=' f /* Display value of F to terminal. */\n /* Display value in \"binary\" metric. */\n bin = suffize(a, 5, 2) /* SUFFIZE with binary metric suffix. */\n say 'bin=' bin /* Display value of BIN to terminal. */\n win = suffize(a, 0, 2) /* SUFFIZE with binary metric suffix. */\n say 'win=' win /* Display value of WIN to terminal. */\n xvi = ' +16777216 ' /* this used to be a big computer ··· */\n big = suffize(xvi, , 2) /* SUFFIZE with binary metric suffix. */\n say 'big=' big /* Display value of BIG to terminal. */\n\n```\n\nwould display:\n\n```\n aa= 456.7891T\n n= 456.8T\n f= 415.4Ti\n bin= 415.44727Ti\n win= 415Ti\n big= 16Mi\n\n```\n\nUse these test cases\n\n```\n 87,654,321\n -998,877,665,544,332,211,000 3\n +112,233 0\n 16,777,216 1\n 456,789,100,000,000 2\n 456,789,100,000,000 2 10\n 456,789,100,000,000 5 2\n 456,789,100,000.000e+00 0 10\n +16777216 , 2\n 1.2e101\n (your primary disk free space) 1 ◄■■■■■■■ optional\n\n```\n\nUse whatever parameterizing your computer language supports,   and it's permitted to create as many\nseparate functions as are needed   (if needed)   if   function arguments aren't allowed to\nbe omitted or varied.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.09\n\nPass in a number string, optionally a type, and optionally the number of digits to round to.\n\nThe types supported are B, M & G for binary, metric or gigantic. (At this point, the only gigantic unit is googol, so maybe it stands for googol. ¯\\\\_(ツ)\\_/¯ )\n\nIf no type is specified, M (metric) is assumed.\n\nIf you desire the number to be rounded, pass in a number representing the placed past the decimal to round to. If you pass in a negative number for rounding, it will round to a negative number of places past the decimal.\n\n```\nsub sufficate ($val is copy, $type is copy = 'M', $round is copy = Any) {\n if +$type ~~ Int { $round = $type; $type = 'M' }\n my $s = '';\n if $val.substr(0,1) eq '-' { $s = '-'; $val.=substr(1) }\n $val.=subst(',', '', :g);\n if $val ~~ m:i/'e'/ {\n my ($m,$e) = $val.split(/<[eE]>/);\n $val = ($e < 0)\n  ?? $m * FatRat.new(1,10**-$e)\n  !! $m * 10**$e;\n }\n my %s = do given $type {\n when 'M' { <K M G T P E Z Y X W V U> Z=> (1000, * * 1000 … *) }\n when 'B' { <Ki Mi Gi Ti Pi Ei Zi Yi Xi Wi Vi Ui> Z=> (1024, * * 1024 … *) }\n when 'G' { googol => 10**100 }\n default { return 'What we have here is a failure to communicate...' }\n }\n my $k = do given $val {\n when .abs < (my $m = min %s.values) { %s.first( *.value == $m ).key };\n when .abs > (my $x = max %s.values) { %s.first( *.value == $x ).key };\n default { %s.sort(*.value).first({$val.abs/%s{$_.key} < min %s.values}).key}\n }\n $round.defined\n  ?? $s ~ comma(($val.abs/%s{$k}).round(10**-$round)) ~ $k\n  !! $s ~ comma($val.abs/%s{$k}) ~ $k\n}\n\nsub comma ($i is copy) {\n my $s = $i < 0 ?? '-' !! '';\n my ($whole, $frac) = $i.split('.');\n $frac = $frac.defined ?? \".$frac\" !! '';\n $s ~ $whole.abs.flip.comb(3).join(',').flip ~ $frac\n}\n\n## TESTING\n\nmy @tests =\n '87,654,321',\n '-998,877,665,544,332,211,000 3',\n '+112,233 0',\n '16,777,216 1',\n '456,789,100,000,000',\n '456,789,100,000,000 M 2',\n '456,789,100,000,000 B 5',\n '456,789,100,000.000e+00 M 0',\n '+16777216 B',\n '1.2e101 G',\n \"{run('df', '/', :out).out.slurp.words[10] * 1024} B 2\", # Linux df returns Kilobytes by default\n '347,344 M -2', # round to -2 past the decimal\n '1122334455 Q', # bad unit type example\n;\n\nprintf \"%33s : %s\\n\", $_, sufficate(|.words) for @tests;\n\n```\n\nOutput:\n\n```\n 87,654,321 : 87.654321M\n -998,877,665,544,332,211,000 3 : -998.878E\n +112,233 0 : 112K\n 16,777,216 1 : 16.8M\n 456,789,100,000,000 : 456.7891T\n 456,789,100,000,000 M 2 : 456.79T\n 456,789,100,000,000 B 5 : 415.44727Ti\n 456,789,100,000.000e+00 M 0 : 457G\n +16777216 B : 16Mi\n 1.2e101 G : 12googol\n 703674818560 B 2 : 655.35Gi\n 347,344 M -2 : 300K\n 1122334455 Q : What we have here is a failure to communicate...\n```" } ]
[ { "role": "user", "content": "Task\n\nCompute the sum and product of an array of integers." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @ary = 1, 5, 10, 100;\nsay 'Sum: ', [+] @ary;\nsay 'Product: ', [*] @ary;\n```" } ]
[ { "role": "user", "content": "Task\n\nSolve the \"*Impossible Puzzle*\":\n\nX and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X\\*Y. Both S and P know all the information in this paragraph.\n\nThe following conversation occurs:\n\n* S says \"P does not know X and Y.\"\n* P says \"Now I know X and Y.\"\n* S says \"Now I also know X and Y!\"\n\nWhat are X and Y?\n\nGuidance\n\nIt can be hard to wrap one's head around what the three lines of dialog between S (the \"sum guy\") and P (the \"product guy\") convey about the values of X and Y. \nSo for your convenience, here's a break-down:\n\n| | Quote | Implied fact |\n| --- | --- | --- |\n| 1) | S says \"P does not know X and Y.\" | For every possible sum decomposition of the number X+Y, the product has in turn *more than one* product decomposition. |\n| 2) | P says \"Now I know X and Y.\" | The number X\\*Y has *only one* product decomposition for which fact 1 is true. |\n| 3) | S says \"Now I also know X and Y.\" | The number X+Y has *only one* sum decomposition for which fact 2 is true. |\n\nTerminology:\n\n* *\"sum decomposition\" of a number* = Any pair of positive integers (A, B) so that A+B equals the number. Here, with the additional constraint 2 ≤ A < B.\n* *\"product decomposition\" of a number* = Any pair of positive integers (A, B) so that A\\*B equals the number. Here, with the additional constraint 2 ≤ A < B.\n\nYour program can solve the puzzle by considering all possible pairs (X, Y) in the range 2 ≤ X < Y ≤ 98, and then successively eliminating candidates based on the three facts. It turns out only one solution remains! \nSee the Python example for an implementation that uses this approach with a few optimizations.\n\nSee also\n\n* Wikipedia:   Sum and Product Puzzle\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n**Works with**: Rakudo version 2016.07\n\n```\nsub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) }\nsub sums ($n) { ($_, $n - $_ for 2 .. $n div 2) }\nsub product ([$x, $y]) { $x * $y }\nsub sum ([$x, $y]) { $x + $y }\n\nmy @all-pairs = (|($_ X $_+1 .. 98) for 2..97);\n\n# Fact 1:\nmy %p-unique := Set.new: map ~*, grep-unique &product, @all-pairs;\nmy @s-pairs = @all-pairs.grep: { none (%p-unique{~$_} for sums sum $_) };\n\n# Fact 2:\nmy @p-pairs = grep-unique &product, @s-pairs;\n\n# Fact 3:\nmy @final-pairs = grep-unique &sum, @p-pairs;\n\nprintf \"X = %d, Y = %d\\n\", |$_ for @final-pairs;\n\n```\n\nOutput:\n\n```\nX = 4, Y = 13\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a sum data type:\n\nA sum data type is a data structure used to hold a value that could take on several different, but fixed, types.\nOnly one of the types can be in use at any one time.\n\nSum data types are considered an algebraic data type and are also known as tagged union, variant, variant record, choice type, discriminated union, disjoint union or coproduct.\n\nRelated task\n\n* Compound data type\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nRaku doesn't really have Sum Types as a formal data structure but they can be emulated with enums and switches or multi-dispatch. Note that in this case, feeding the dispatcher an incorrect value results in a hard fault; it doesn't just dispatch to the default. Of course those rules can be relaxed or made more restrictive depending on your particular use case.\n\n```\nenum Traffic-Signal < Red Yellow Green Blue >;\n\nsub message (Traffic-Signal $light) {\n with $light {\n when Red { 'Stop!' }\n when Yellow { 'Speed Up!' }\n when Green { 'Go! Go! Go!' }\n when Blue { 'Wait a minute, How did we end up in Japan?!' }\n default { 'Whut?' }\n }\n}\n\nmy \\Pink = 'A Happy Balloon';\n\n\nfor Red, Green, Blue, Pink -> $signal {\n say message $signal;\n}\n\n```\n\nOutput:\n\n```\nStop!\nGo! Go! Go!\nWait a minute, How did we end up in Japan?!\nType check failed in binding to parameter '$light'; expected Traffic-Signal but got Str (\"A Happy Balloon\")\n```" } ]
[ { "role": "user", "content": "Task\n\nTake a   Natural Number   in a given base and return the sum of its digits:\n\n: * **1**10         sums to   **1**\n * **1234**10   sums to   **10**\n * **fe**16       sums to   **29**\n * **f0e**16     sums to   **29**" }, { "role": "assistant", "content": "(formerly Perl 6)\nThis will handle input numbers in any base from 2 to 36.\nThe results are in base 10.\n\n```\nsay Σ $_ for <1 1234 1020304 fe f0e DEADBEEF>;\n\nsub Σ { [+] $^n.comb.map: { :36($_) } }\n```\n\nOutput:\n\n```\n1\n10\n10\n29\n29\n104\n```" } ]
[ { "role": "user", "content": "Task\n\nThe objective is to write a function that finds the sum of all positive multiples of 3 or 5 below *n*.\n\nShow output for *n* = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n**Extra credit:** do this efficiently for *n* = 1e20 or higher." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub sum35($n) { [+] grep * %% (3|5), ^$n; }\n\nsay sum35 1000;\n```\n\nOutput:\n\n```\n233168\n```\n\nHere's an analytical approach that scales much better for large values.\n\n```\nsub sum-mults($first, $limit) {\n (my $last = $limit - 1) -= $last % $first;\n ($last div $first) * ($first + $last) div 2;\n}\n\nsub sum35(\\n) {\n sum-mults(3,n) + sum-mults(5,n) - sum-mults(15,n);\n}\n\nsay sum35($_) for 1,10,100...10**30;\n```\n\nOutput:\n\n```\n0\n23\n2318\n233168\n23331668\n2333316668\n233333166668\n23333331666668\n2333333316666668\n233333333166666668\n23333333331666666668\n2333333333316666666668\n233333333333166666666668\n23333333333331666666666668\n2333333333333316666666666668\n233333333333333166666666666668\n23333333333333331666666666666668\n2333333333333333316666666666666668\n233333333333333333166666666666666668\n23333333333333333331666666666666666668\n2333333333333333333316666666666666666668\n233333333333333333333166666666666666666668\n23333333333333333333331666666666666666666668\n2333333333333333333333316666666666666666666668\n233333333333333333333333166666666666666666666668\n23333333333333333333333331666666666666666666666668\n2333333333333333333333333316666666666666666666666668\n233333333333333333333333333166666666666666666666666668\n23333333333333333333333333331666666666666666666666666668\n2333333333333333333333333333316666666666666666666666666668\n233333333333333333333333333333166666666666666666666666666668\n```" } ]
[ { "role": "user", "content": "Compute the   **n**th   term of a series,   i.e. the sum of the   **n**   first terms of the corresponding sequence.\n\nInformally this value, or its limit when   **n**   tends to infinity, is also called the *sum of the series*, thus the title of this task.\n\nFor this task, use:\n\n: : : : : : S\n\n n\n =\n\n ∑\n\n k\n =\n 1\n\n n\n\n\n 1\n\n k\n\n 2\n {\\displaystyle {\\displaystyle S\\_{n}=\\sum \\_{k=1}^{n}{\\frac {1}{k^{2}}}}}\n\n: : and compute   \n\n S\n\n 1000\n {\\displaystyle {\\displaystyle S\\_{1000}}}\n\nThis approximates the   zeta function   for   S=2,   whose exact value\n\n: : : : : : ζ\n (\n 2\n )\n =\n\n π\n\n 2\n 6\n {\\displaystyle {\\displaystyle \\zeta (2)={\\pi ^{2} \\over 6}}}\n\nis the solution of the Basel problem." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.04\n\nIn general, the `$n`th partial sum of a series whose terms are given by a unary function `&f` is\n\n```\n[+] map &f, 1 .. $n\n```\n\nSo what's needed in this case is\n\n```\nsay [+] map { 1 / $^n**2 }, 1 .. 1000;\n```\n\nOr, using the \"hyper\" metaoperator to vectorize, we can use a more \"point free\" style while keeping traditional precedence:\n\n```\nsay [+] 1 «/« (1..1000) »**» 2;\n```\n\nOr we can use the X \"cross\" metaoperator, which is convenient even if one side or the other is a scalar. In this case, we demonstrate a scalar on either side:\n\n```\nsay [+] 1 X/ (1..1000 X** 2);\n```\n\nNote that cross ops are parsed as list infix precedence rather than using the precedence of the base op as hypers do. Hence the difference in parenthesization.\n\nWith list comprehensions, you can write:\n\n```\nsay [+] (1 / $_**2 for 1..1000);\n```\n\nThat's fine for a single result, but if you're going to be evaluating the sequence multiple times, you don't want to be recalculating the sum each time, so it's more efficient to define the sequence as a constant to let the run-time automatically cache those values already calculated. In a lazy language like Raku, it's generally considered a stronger abstraction to write the correct infinite sequence, and then take the part of it you're interested in.\nHere we define an infinite sequence of partial sums (by adding a backslash into the reduction to make it look \"triangular\"), then take the 1000th term of that:\n\n```\nconstant @x = [\\+] 0, { 1 / ++(state $n) ** 2 } ... *;\nsay @x[1000]; # prints 1.64393456668156\n```\n\nNote that infinite constant sequences can be lazily generated in Raku, or this wouldn't work so well...\n\nA cleaner style is to combine these approaches with a more FP look:\n\n```\nconstant ζish = [\\+] map -> \\𝑖 { 1 / 𝑖**2 }, 1..*;\nsay ζish[1000];\n```\n\nPerhaps the cleanest way is to just define the zeta function and evaluate it for s=2, possibly using memoization:\n\n```\nuse experimental :cached;\nsub ζ($s) is cached { [\\+] 1..* X** -$s }\nsay ζ(2)[1000];\n```\n\nNotice how the thus-defined zeta function returns a lazy list of approximated values, which is arguably the closest we can get from the mathematical definition." } ]
[ { "role": "user", "content": "Given a positive integer, sum its positive divisors.\n\nTask\n\nShow the result for the first 100 positive integers." }, { "role": "assistant", "content": "Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.\n\n```\nuse Prime::Factor:ver<0.3.0+>;\nuse Lingua::EN::Numbers;\n\nsay \"\\nTau function - first 100:\\n\", # ID\n(1..*).map({ +.&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%3d\").join(\"\\n\"); # display formatting\n\nsay \"\\nTau numbers - first 100:\\n\", # ID\n(1..*).grep({ $_ %% +.&divisors })[^100]\\ # the task\n.batch(10)».&comma».fmt(\"%5s\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor sums - first 100:\\n\", # ID\n(1..*).map({ [+] .&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%4d\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor products - first 100:\\n\", # ID\n(1..*).map({ [×] .&divisors })[^100]\\ # the task\n.batch(5)».&comma».fmt(\"%16s\").join(\"\\n\"); # display formatting\n\n```\n\nOutput:\n\n```\nTau function - first 100:\n 1 2 2 3 2 4 2 4 3 4 2 6 2 4 4 5 2 6 2 6\n 4 4 2 8 3 4 4 6 2 8 2 6 4 4 4 9 2 4 4 8\n 2 8 2 6 6 4 2 10 3 6 4 6 2 8 4 8 4 4 2 12\n 2 4 6 7 4 8 2 6 4 8 2 12 2 4 6 6 4 8 2 10\n 5 4 2 12 4 4 4 8 2 12 4 6 4 4 4 12 2 6 6 9\n\nTau numbers - first 100:\n 1 2 8 9 12 18 24 36 40 56\n 60 72 80 84 88 96 104 108 128 132\n 136 152 156 180 184 204 225 228 232 240\n 248 252 276 288 296 328 344 348 360 372\n 376 384 396 424 441 444 448 450 468 472\n 480 488 492 504 516 536 560 564 568 584\n 600 612 625 632 636 640 664 672 684 708\n 712 720 732 776 792 804 808 824 828 852\n 856 864 872 876 880 882 896 904 936 948\n 972 996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096\n\nDivisor sums - first 100:\n 1 3 4 7 6 12 8 15 13 18 12 28 14 24 24 31 18 39 20 42\n 32 36 24 60 31 42 40 56 30 72 32 63 48 54 48 91 38 60 56 90\n 42 96 44 84 78 72 48 124 57 93 72 98 54 120 72 120 80 90 60 168\n 62 96 104 127 84 144 68 126 96 144 72 195 74 114 124 140 96 168 80 186\n 121 126 84 224 108 132 120 180 90 234 112 168 128 144 120 252 98 171 156 217\n\nDivisor products - first 100:\n 1 2 3 8 5\n 36 7 64 27 100\n 11 1,728 13 196 225\n 1,024 17 5,832 19 8,000\n 441 484 23 331,776 125\n 676 729 21,952 29 810,000\n 31 32,768 1,089 1,156 1,225\n 10,077,696 37 1,444 1,521 2,560,000\n 41 3,111,696 43 85,184 91,125\n 2,116 47 254,803,968 343 125,000\n 2,601 140,608 53 8,503,056 3,025\n 9,834,496 3,249 3,364 59 46,656,000,000\n 61 3,844 250,047 2,097,152 4,225\n 18,974,736 67 314,432 4,761 24,010,000\n 71 139,314,069,504 73 5,476 421,875\n 438,976 5,929 37,015,056 79 3,276,800,000\n 59,049 6,724 83 351,298,031,616 7,225\n 7,396 7,569 59,969,536 89 531,441,000,000\n 8,281 778,688 8,649 8,836 9,025\n 782,757,789,696 97 941,192 970,299 1,000,000,000\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and display the sum of elements that are below the main diagonal of a matrix.\n\nThe matrix should be a square matrix.\n\n: : : ───   Matrix to be used:   ───\n\n```\n [[1,3,7,8,10],\n [2,4,16,14,4],\n [3,1,9,18,11],\n [12,14,17,18,20],\n [7,1,3,9,5]] \n\n```" }, { "role": "assistant", "content": "```\nsub lower-triangle-sum (@matrix) { sum flat (1..@matrix).map( { @matrix[^$_]»[^($_-1)] } )»[*-1] }\n\nsay lower-triangle-sum \n[\n [ 1, 3, 7, 8, 10 ],\n [ 2, 4, 16, 14, 4 ],\n [ 3, 1, 9, 18, 11 ],\n [ 12, 14, 17, 18, 20 ],\n [ 7, 1, 3, 9, 5 ]\n];\n\n```\n\nOutput:\n\n```\n69\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show sum of first   **n**   cubes,   where **n < 50** (ie show 50 entries for n=0..49)" }, { "role": "assistant", "content": "```\nmy @sums_of_all_cubes = [\\+] ^Inf X** 3;\n\nsay .fmt('%7d') for @sums_of_all_cubes.head(50).batch(10);\n\n```\n\nOutput:\n\n```\n 0 1 9 36 100 225 441 784 1296 2025\n 3025 4356 6084 8281 11025 14400 18496 23409 29241 36100\n 44100 53361 64009 76176 90000 105625 123201 142884 164836 189225\n216225 246016 278784 314721 354025 396900 443556 494209 549081 608400\n672400 741321 815409 894916 980100 1071225 1168561 1272384 1382976 1500625\n\n```" } ]
[ { "role": "user", "content": "Task\n\nLet **p(i)** be a sequence of prime numbers. such that 2=p(1), 3=p(2), 5=p(3), ...\n \nConsider the **p(1),p(3),p(5), ... ,p(i)**, for each **p(i) < 1,000** and **i** is odd.\n \nLet **sum** be any prefix sum of these primesa.\n \nIf **sum** is prime then print **i**, **p(i)** and **sum**." }, { "role": "assistant", "content": "```\nmy @odd = grep { ++$ !%% 2 }, grep &is-prime, 2 ..^ 1000;\nmy @sums = [\\+] @odd;\n\nsay .fmt('%5d') for grep { .[2].is-prime }, ( (1,3…*) Z @odd Z @sums );\n\n```\n\nOutput:\n\n```\n 1 2 2\n 3 5 7\n 11 31 89\n 27 103 659\n 35 149 1181\n 67 331 5021\n 91 467 9923\n 95 499 10909\n 99 523 11941\n 119 653 17959\n 143 823 26879\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show here all positive integers **n** less than **100** where:\n\n* the sum of the digits of the square of **n** is prime; and\n* the sum of the digits of the cube of **n** is also prime.\n\nExample\n\n**16** satisfies the task descrption because 16 x 16 = 256 has a digit sum of 13 which is prime and\n16 x 16 x 16 = 4096 has a digit sum of 19 which is also prime." }, { "role": "assistant", "content": "```\nsay ^100 .grep: { .².comb.sum.is-prime && .³.comb.sum.is-prime }\n\n```\n\nOutput:\n\n```\n(16 17 25 28 34 37 47 52 64)\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program to find the sum of squares of a numeric vector.\n\nThe program should work on a zero-length vector (with an answer of   **0**).\n\nRelated task\n\n* Mean" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay [+] map * ** 2, (3, 1, 4, 1, 5, 9);\n```\n\nIf this expression seems puzzling, note that `* ** 2` is equivalent to `{$^x ** 2}`— the leftmost asterisk is not the multiplication operator but the `Whatever` star, which specifies currying behavior.\nAnother convenient way to distribute the exponentiation is via the cross metaoperator, which\nas a list infix is looser than comma in precedence but tighter than the reduction list operator:\n\n```\nsay [+] <3 1 4 1 5 9> X** 2\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show numbers   **n**   with property that the sum of the decimal digits of   **n**   is substring of   **n**,   where   **n   <   1,000**\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": "```\nsay \"{+$_} matching numbers\\n{.batch(10)».fmt('%3d').join: \"\\n\"}\" given (^1000).grep: { .contains: .comb.sum }\n\n```\n\nOutput:\n\n```\n48 matching numbers\n 0 1 2 3 4 5 6 7 8 9\n 10 20 30 40 50 60 70 80 90 100\n109 119 129 139 149 159 169 179 189 199\n200 300 400 500 600 700 800 900 910 911\n912 913 914 915 916 917 918 919\n```" } ]
[ { "role": "user", "content": "Task\n\nShow on this page the first 20 prime sums of two consecutive integers.\n\nExtra credit\n\nShow the ten millionth such prime sum." }, { "role": "assistant", "content": "```\nmy @n-n1-triangular = map { $_, $_ + 1, $_ + ($_ + 1) }, ^Inf;\n\nmy @wanted = @n-n1-triangular.grep: *.[2].is-prime;\n\nprintf \"%2d + %2d = %2d\\n\", |.list for @wanted.head(20);\n\n```\n\nOutput:\n\n```\n 1 + 2 = 3\n 2 + 3 = 5\n 3 + 4 = 7\n 5 + 6 = 11\n 6 + 7 = 13\n 8 + 9 = 17\n 9 + 10 = 19\n11 + 12 = 23\n14 + 15 = 29\n15 + 16 = 31\n18 + 19 = 37\n20 + 21 = 41\n21 + 22 = 43\n23 + 24 = 47\n26 + 27 = 53\n29 + 30 = 59\n30 + 31 = 61\n33 + 34 = 67\n35 + 36 = 71\n36 + 37 = 73\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind solutions to the   *sum to one hundred*   puzzle.\n\nAdd (insert) the mathematical\noperators     **+**   or   **-**     (plus\nor minus)   before any of the digits in the\n \ndecimal numeric string   **123456789**   such that the\nresulting mathematical expression adds up to a\n \nparticular sum   (in this iconic case,   **100**).\n\nExample:\n\n```\n 123 + 4 - 5 + 67 - 89 = 100 \n\n```\n\nShow all output here.\n\n: * Show all solutions that sum to   **100**\n * Show the sum that has the maximum   *number*   of solutions   (from zero to infinity‡)\n * Show the lowest positive sum that   *can't*   be expressed   (has no solutions),   using the rules for this task\n * Show the ten highest numbers that can be expressed using the rules for this task   (extra credit)\n\n‡   (where   *infinity*   would be a relatively small   123,456,789)\n\nAn example of a sum that can't be expressed   (within the rules of this task)   is:   **5074**\n \n(which,   of course,   isn't the lowest positive sum that can't be expressed)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.03\n\n```\nmy $sum = 100;\nmy $N = 10;\nmy @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );\nmy @str = [X~] map { .Slip }, ( @ops Z 1..9 );\nmy %sol = @str.classify: *.subst( ' - ', ' -', :g )\\\n .subst( ' + ', ' ', :g ).words.sum;\n\nmy %count.push: %sol.map({ .value.elems => .key });\n\nmy $max-solutions = %count.max( + *.key );\nmy $first-unsolvable = first { %sol{$_} :!exists }, 1..*;\nsub n-largest-sums (Int $n) { %sol.sort(-*.key)[^$n].fmt: \"%8s => %s\\n\" }\n\ngiven %sol{$sum}:p {\n say \"{.value.elems} solutions for sum {.key}:\";\n say \" $_\" for .value.list;\n}\n\n.say for :$max-solutions, :$first-unsolvable, \"$N largest sums:\", n-largest-sums($N);\n\n```\n\nOutput:\n\n```\n12 solutions for sum 100:\n -1 + 2 - 3 + 4 + 5 + 6 + 78 + 9\n 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9\n 1 + 2 + 34 - 5 + 67 - 8 + 9\n 1 + 23 - 4 + 5 + 6 + 78 - 9\n 1 + 23 - 4 + 56 + 7 + 8 + 9\n 12 + 3 + 4 + 5 - 6 - 7 + 89\n 12 + 3 - 4 + 5 + 67 + 8 + 9\n 12 - 3 - 4 + 5 - 6 + 7 + 89\n 123 + 4 - 5 + 67 - 89\n 123 + 45 - 67 + 8 - 9\n 123 - 4 - 5 - 6 - 7 + 8 - 9\n 123 - 45 - 67 + 89\nmax-solutions => 46 => [-9 9]\nfirst-unsolvable => 211\n10 largest sums:\n123456789 => 123456789\n 23456790 => 1 + 23456789\n 23456788 => -1 + 23456789\n 12345687 => 12345678 + 9\n 12345669 => 12345678 - 9\n 3456801 => 12 + 3456789\n 3456792 => 1 + 2 + 3456789\n 3456790 => -1 + 2 + 3456789\n 3456788 => 1 - 2 + 3456789\n 3456786 => -1 - 2 + 3456789\n```" } ]
[ { "role": "user", "content": "There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n\n```\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\n\n```\n\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n\n```\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \n\n```\n\nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\nTask\n\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.\n\n```\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n```\n\nRelated tasks\n\n* Fours is the number of letters in the ...\n* Look-and-say sequence\n* Number names\n* Self-describing numbers\n* Spelling of ordinal numbers\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet\n\nAlso see\n\n* The On-Line Encyclopedia of Integer Sequences." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nmy @list;\nmy $longest = 0;\nmy %seen;\n\nfor 1 .. 1000000 -> $m {\n next unless $m ~~ /0/; # seed must have a zero\n my $j = join '', $m.comb.sort;\n next if %seen{$j}:exists; # already tested a permutation\n %seen{$j} = '';\n my @seq = converging($m);\n my %elems;\n my $count;\n for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };\n if $longest == $count {\n @list.push($m);\n }\n elsif $longest < $count {\n $longest = $count;\n @list = $m;\n print \"\\b\" x 20, \"$count, $m\"; # monitor progress\n }\n};\n\nfor @list -> $m {\n say \"\\nSeed Value(s): \", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } );\n my @seq = converging($m);\n my %elems;\n my $count;\n for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; };\n say \"\\nIterations: \", $count;\n say \"\\nSequence: (Only one shown per permutation group.)\";\n .say for |@seq[^$count], \"\\n\";\n}\n\nsub converging ($seed) { return $seed, -> $l { join '', map { $_.value.elems~$_.key }, $l.comb.classify({$^b}).sort: {-$^c.key} } ... * }\n\nsub permutations ($string, $sofar? = '' ) {\n return $sofar unless $string.chars;\n my @perms;\n for ^$string.chars -> $idx {\n my $this = $string.substr(0,$idx)~$string.substr($idx+1);\n my $char = substr($string, $idx,1);\n @perms.push( |permutations( $this, join '', $sofar, $char ) );\n }\n return @perms;\n}\n\n```\n\nOutput:\n\n```\nSeed Value(s): 9009 9090 9900\n\nIterations: 21\n\nSequence: (Only one shown per permutation group.)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n```" } ]
[ { "role": "user", "content": "Task\n\nConsidering in order of length, n, all sequences of consecutive\nprimes, p, from 2 onwards, where p < 1000 and n>0, select those\nsequences whose sum is prime, and for these display the length of the\nsequence, the last item in the sequence, and the sum." }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\n\nmy @primes = grep *.is-prime, ^Inf;\nmy @primesums = [\\+] @primes;\nsay \"{.elems} cumulative prime sums:\\n\",\n .map( -> $p {\n sprintf \"The sum of the first %3d (up to {@primes[$p]}) is prime: %s\",\n 1 + $p, comma @primesums[$p]\n }\n ).join(\"\\n\")\n given grep { @primesums[$_].is-prime }, ^1000;\n\n```\n\nOutput:\n\n```\n76 cumulative prime sums:\nThe sum of the first 1 (up to 2) is prime: 2\nThe sum of the first 2 (up to 3) is prime: 5\nThe sum of the first 4 (up to 7) is prime: 17\nThe sum of the first 6 (up to 13) is prime: 41\nThe sum of the first 12 (up to 37) is prime: 197\nThe sum of the first 14 (up to 43) is prime: 281\nThe sum of the first 60 (up to 281) is prime: 7,699\nThe sum of the first 64 (up to 311) is prime: 8,893\nThe sum of the first 96 (up to 503) is prime: 22,039\nThe sum of the first 100 (up to 541) is prime: 24,133\nThe sum of the first 102 (up to 557) is prime: 25,237\nThe sum of the first 108 (up to 593) is prime: 28,697\nThe sum of the first 114 (up to 619) is prime: 32,353\nThe sum of the first 122 (up to 673) is prime: 37,561\nThe sum of the first 124 (up to 683) is prime: 38,921\nThe sum of the first 130 (up to 733) is prime: 43,201\nThe sum of the first 132 (up to 743) is prime: 44,683\nThe sum of the first 146 (up to 839) is prime: 55,837\nThe sum of the first 152 (up to 881) is prime: 61,027\nThe sum of the first 158 (up to 929) is prime: 66,463\nThe sum of the first 162 (up to 953) is prime: 70,241\nThe sum of the first 178 (up to 1061) is prime: 86,453\nThe sum of the first 192 (up to 1163) is prime: 102,001\nThe sum of the first 198 (up to 1213) is prime: 109,147\nThe sum of the first 204 (up to 1249) is prime: 116,533\nThe sum of the first 206 (up to 1277) is prime: 119,069\nThe sum of the first 208 (up to 1283) is prime: 121,631\nThe sum of the first 214 (up to 1307) is prime: 129,419\nThe sum of the first 216 (up to 1321) is prime: 132,059\nThe sum of the first 296 (up to 1949) is prime: 263,171\nThe sum of the first 308 (up to 2029) is prime: 287,137\nThe sum of the first 326 (up to 2161) is prime: 325,019\nThe sum of the first 328 (up to 2203) is prime: 329,401\nThe sum of the first 330 (up to 2213) is prime: 333,821\nThe sum of the first 332 (up to 2237) is prime: 338,279\nThe sum of the first 334 (up to 2243) is prime: 342,761\nThe sum of the first 342 (up to 2297) is prime: 360,979\nThe sum of the first 350 (up to 2357) is prime: 379,667\nThe sum of the first 356 (up to 2393) is prime: 393,961\nThe sum of the first 358 (up to 2411) is prime: 398,771\nThe sum of the first 426 (up to 2957) is prime: 581,921\nThe sum of the first 446 (up to 3137) is prime: 642,869\nThe sum of the first 458 (up to 3251) is prime: 681,257\nThe sum of the first 460 (up to 3257) is prime: 687,767\nThe sum of the first 464 (up to 3301) is prime: 700,897\nThe sum of the first 480 (up to 3413) is prime: 754,573\nThe sum of the first 484 (up to 3461) is prime: 768,373\nThe sum of the first 488 (up to 3491) is prime: 782,263\nThe sum of the first 512 (up to 3671) is prime: 868,151\nThe sum of the first 530 (up to 3821) is prime: 935,507\nThe sum of the first 536 (up to 3863) is prime: 958,577\nThe sum of the first 548 (up to 3947) is prime: 1,005,551\nThe sum of the first 568 (up to 4129) is prime: 1,086,557\nThe sum of the first 620 (up to 4583) is prime: 1,313,041\nThe sum of the first 630 (up to 4657) is prime: 1,359,329\nThe sum of the first 676 (up to 5051) is prime: 1,583,293\nThe sum of the first 680 (up to 5087) is prime: 1,603,597\nThe sum of the first 696 (up to 5233) is prime: 1,686,239\nThe sum of the first 708 (up to 5351) is prime: 1,749,833\nThe sum of the first 734 (up to 5563) is prime: 1,891,889\nThe sum of the first 762 (up to 5807) is prime: 2,051,167\nThe sum of the first 768 (up to 5849) is prime: 2,086,159\nThe sum of the first 776 (up to 5897) is prime: 2,133,121\nThe sum of the first 780 (up to 5939) is prime: 2,156,813\nThe sum of the first 784 (up to 6007) is prime: 2,180,741\nThe sum of the first 808 (up to 6211) is prime: 2,327,399\nThe sum of the first 814 (up to 6263) is prime: 2,364,833\nThe sum of the first 820 (up to 6301) is prime: 2,402,537\nThe sum of the first 836 (up to 6427) is prime: 2,504,323\nThe sum of the first 844 (up to 6529) is prime: 2,556,187\nThe sum of the first 848 (up to 6563) is prime: 2,582,401\nThe sum of the first 852 (up to 6581) is prime: 2,608,699\nThe sum of the first 926 (up to 7243) is prime: 3,120,833\nThe sum of the first 942 (up to 7433) is prime: 3,238,237\nThe sum of the first 984 (up to 7757) is prime: 3,557,303\nThe sum of the first 992 (up to 7853) is prime: 3,619,807\n```" } ]
[ { "role": "user", "content": "Task\n\nThe task description is taken from Project Euler (https://projecteuler.net/problem=10)\n \nThe sum of the primes below 10 is 2 + 3 + 5 + 7 = 17\n \nFind the sum of all the primes below **two million**" }, { "role": "assistant", "content": "Slow, but only using compiler built-ins (about 5 seconds)\n\n```\nsay sum (^2e6).grep: {.&is-prime};\n\n```\n\nOutput:\n\n```\n142913828922\n```\n\nMuch faster using external libraries (well under half a second)\n\n```\nuse Math::Primesieve;\nmy $sieve = Math::Primesieve.new;\nsay sum $sieve.primes(2e6.Int);\n\n```\n\nSame output" } ]
[ { "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\nDraw a Sunflower fractal" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\nThis is not really a fractal. It is more accurately an example of a Fibonacci spiral or Phi-packing.\n\nOr, to be completely accurate: It is a variation of a generative Fermat's spiral using the Vogel model to implement phi-packing. See: https://thatsmaths.com/2014/06/05/sunflowers-and-fibonacci-models-of-efficiency\n\n```\nuse SVG;\n\nmy $seeds = 3000;\nmy @center = 300, 300;\nmy $scale = 5;\n\nconstant \\φ = (3 - 5.sqrt) / 2;\n\nmy @c = map {\n my ($x, $y) = ($scale * .sqrt) «*« |cis($_ * φ * τ).reals »+« @center;\n [ $x.round(.01), $y.round(.01), (.sqrt * $scale / 100).round(.1) ]\n}, 1 .. $seeds;\n\nsay SVG.serialize(\n svg => [\n  :600width, :600height, :style<stroke:yellow>,\n  :rect[:width<100%>, :height<100%>, :fill<black>],\n |@c.map( { :circle[:cx(.[0]), :cy(.[1]), :r(.[2])] } ),\n ],\n);\n\n```\n\nSee: Phi packing (SVG image)" } ]
[ { "role": "user", "content": "A super-d number is a positive, decimal (base ten) integer   **n**   such that   **d × nd**   has at least   **d**   consecutive digits   **d**   where\n\n```\n 2 ≤ d ≤ 9\n\n```\n\nFor instance, 753 is a super-3 number because 3 × 7533 = 1280873331.\n\n**Super-d**   numbers are also shown on   **MathWorld**™   as   **super-*d***   or   **super-*d***.\n\nTask\n: * Write a function/procedure/routine to find super-d numbers.\n * For   **d=2**   through   **d=6**,   use the routine to show the first   **10**   super-d numbers.\n\nExtra credit\n: * Show the first   **10**   super-7, super-8, and/or super-9 numbers   (optional).\n\nSee also\n: * Wolfram MathWorld - Super-d Number.\n * OEIS: A014569 - Super-3 Numbers." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n2 - 6 take a few seconds, 7 about 17 seconds, 8 about 90... 9, bleh... around 700 seconds.\n\n```\nsub super (\\d) {\n my \\run = d x d;\n ^∞ .hyper.grep: -> \\n { (d * n ** d).Str.contains: run }\n}\n\n(2..9).race(:1batch).map: {\n my $now = now;\n put \"\\nFirst 10 super-$_ numbers:\\n{.&super[^10]}\\n{(now - $now).round(.1)} sec.\"\n}\n\n```\n\n```\nFirst 10 super-2 numbers:\n19 31 69 81 105 106 107 119 127 131\n0.1 sec.\n\nFirst 10 super-3 numbers:\n261 462 471 481 558 753 1036 1046 1471 1645\n0.1 sec.\n\nFirst 10 super-4 numbers:\n1168 4972 7423 7752 8431 10267 11317 11487 11549 11680\n0.3 sec.\n\nFirst 10 super-5 numbers:\n4602 5517 7539 12955 14555 20137 20379 26629 32767 35689\n0.6 sec.\n\nFirst 10 super-6 numbers:\n27257 272570 302693 323576 364509 502785 513675 537771 676657 678146\n5.2 sec.\n\nFirst 10 super-7 numbers:\n140997 490996 1184321 1259609 1409970 1783166 1886654 1977538 2457756 2714763\n17.1 sec.\n\nFirst 10 super-8 numbers:\n185423 641519 1551728 1854230 6415190 12043464 12147605 15517280 16561735 18542300\n92.1 sec.\n\nFirst 10 super-9 numbers:\n17546133 32613656 93568867 107225764 109255734 113315082 121251742 175461330 180917907 182557181\n704.7 sec.\n```" } ]
[ { "role": "user", "content": "A super-Poulet number is a Poulet number (or Fermat pseudoprime to base 2) whose every divisor ***d*** evenly divides ***2d − 2***.\n\nTask\n\n* Find and display the first **20** super-Poulet numbers.\n\nStretch\n\n* Find and display the index and value of the first super-Poulet number greater than one million.\n\nSee also\n\n* Task: Fermat pseudoprimes * Wikipedia: super-Poulet number * OEIS:A050217 - super-Poulet numbers" }, { "role": "assistant", "content": "```\nuse Prime::Factor;\nuse Lingua::EN::Numbers;\n\nmy @poulet = lazy (2..*).hyper(:2000batch).grep: { !.is-prime && (1 == expmod 2, $_ - 1, $_) }\nmy @super-poulet = @poulet.grep: { all .&divisors.skip(1).map: { 2 == expmod 2, $_, $_ } }\n\nsay \"First 20 super-Poulet numbers:\\n\" ~ @super-poulet[^20].gist;\n\nfor 1e6.Int, 1e7.Int -> $threshold {\n say \"\\nIndex and value of first super-Poulet greater than {$threshold.&cardinal}:\";\n my $index = @super-poulet.first: * > $threshold, :k;\n say \"{(1+$index).&ordinal-digit} super-Poulet number == \" ~ @super-poulet[$index].&comma;\n}\n\n```\n\nOutput:\n\n```\nFirst 20 super-Poulet numbers:\n(341 1387 2047 2701 3277 4033 4369 4681 5461 7957 8321 10261 13747 14491 15709 18721 19951 23377 31417 31609)\n\nIndex and value of first super-Poulet greater than one million:\n109th super-Poulet number == 1,016,801\n\nIndex and value of first super-Poulet greater than ten million:\n317th super-Poulet number == 10,031,653\n\n```" } ]
[ { "role": "user", "content": "A superellipse is a geometric figure defined as the set of all points (x, y) with\n\n: : : |\n\n\n x\n a\n |\n\n n\n\n +\n\n\n |\n\n\n y\n b\n |\n\n n\n\n =\n 1\n ,\n {\\displaystyle {\\displaystyle \\left|{\\frac {x}{a}}\\right|^{n}\\!+\\left|{\\frac {y}{b}}\\right|^{n}\\!=1,}}\n\nwhere *n*, *a*, and *b* are positive numbers.\n\nTask\n\nDraw a superellipse with n = 2.5, and a = b = 200" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy (\\a, \\b, \\n) = 200, 200, 2.5;\n\n# y in terms of x\nsub y ($x) { floor b × (1 - ($x/a).abs ** n ) ** (1/n) }\n\n# find point pairs for one quadrant\nmy @q = flat map -> \\x { x, y(x) }, ^(a+1);\n\nmy $out = open('superellipse.svg', :w);\n$out.print: [~] qq|<svg height=\"{b×2}\" width=\"{a×2}\" xmlns=\"http://www.w3.org/2000/svg\">\\n|,\n pline( @q ),\n pline( @q «×» < 1 -1> ), # flip and mirror\n pline( @q «×» <-1 -1> ), # for the other\n pline( @q «×» <-1 1> ), # three quadrants\n '</svg>';\n\nsub pline (@q) {\n qq|<polyline points=\"{@q}\"\n style=\"fill:none;stroke:black;stroke-width:3\"\n transform=\"translate({a}, {b})\" />\\n|\n}\n\n```\n\nSuperellipse (offsite image)" } ]
[ { "role": "user", "content": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!\\*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N *might* be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet\n\nReference\n\n* The Minimal Superpermutation Problem. by Nathaniel Johnston.\n* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* Superpermutations - Numberphile. A video\n* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.\n* New Superpermutations Discovered! Standupmaths & Numberphile." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nfor 1..8 -> $len {\n my $pre = my $post = my $t = '';\n for ('a'..'z')[^$len].permutations -> @p {\n $t = @p.join('');\n $post ~= $t unless index($post, $t);\n $pre = $t ~ $pre unless index($pre, $t);\n }\n printf \"%1d: %8d %8d\\n\", $len, $pre.chars, $post.chars;\n}\n\n```\n\nOutput:\n\n```\n1: 1 1\n2: 4 4\n3: 12 15\n4: 48 64\n5: 240 325\n6: 1440 1956\n7: 10080 13699\n8: 80640 109600\n```" } ]
[ { "role": "user", "content": "The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).\n\nIt is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed.\n\nTask\n\nTake the closed polygon defined by the points:\n\n: [\n (\n 50\n ,\n 150\n )\n ,\n (\n 200\n ,\n 50\n )\n ,\n (\n 350\n ,\n 150\n )\n ,\n (\n 350\n ,\n 300\n )\n ,\n (\n 250\n ,\n 300\n )\n ,\n (\n 200\n ,\n 250\n )\n ,\n (\n 150\n ,\n 350\n )\n ,\n (\n 100\n ,\n 250\n )\n ,\n (\n 100\n ,\n 200\n )\n ]\n {\\displaystyle {\\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}}\n\nand clip it by the rectangle defined by the points:\n\n: [\n (\n 100\n ,\n 100\n )\n ,\n (\n 300\n ,\n 100\n )\n ,\n (\n 300\n ,\n 300\n )\n ,\n (\n 100\n ,\n 300\n )\n ]\n {\\displaystyle {\\displaystyle [(100,100),(300,100),(300,300),(100,300)]}}\n\nPrint the sequence of points that define the resulting clipped polygon.\n\nExtra credit\n\nDisplay all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.\n\n(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\n**Translation of**: Sidef\n\n```\nsub intersection ($L11, $L12, $L21, $L22) {\n my ($Δ1x, $Δ1y) = $L11 »-« $L12;\n my ($Δ2x, $Δ2y) = $L21 »-« $L22;\n my $n1 = $L11[0] * $L12[1] - $L11[1] * $L12[0];\n my $n2 = $L21[0] * $L22[1] - $L21[1] * $L22[0];\n my $n3 = 1 / ($Δ1x * $Δ2y - $Δ2x * $Δ1y);\n (($n1 * $Δ2x - $n2 * $Δ1x) * $n3, ($n1 * $Δ2y - $n2 * $Δ1y) * $n3)\n}\n\n\nsub is-inside ($p1, $p2, $p3) {\n ($p2[0] - $p1[0]) * ($p3[1] - $p1[1]) > ($p2[1] - $p1[1]) * ($p3[0] - $p1[0])\n}\n\nsub sutherland-hodgman (@polygon, @clip) {\n my @output = @polygon;\n my $clip-point1 = @clip.tail;\n for @clip -> $clip-point2 {\n my @input = @output;\n @output = ();\n my $start = @input.tail;\n for @input -> $end {\n if is-inside($clip-point1, $clip-point2, $end) {\n @output.push: intersection($clip-point1, $clip-point2, $start, $end)\n unless is-inside($clip-point1, $clip-point2, $start);\n @output.push: $end;\n } elsif is-inside($clip-point1, $clip-point2, $start) {\n @output.push: intersection($clip-point1, $clip-point2, $start, $end);\n }\n $start = $end;\n }\n $clip-point1 = $clip-point2;\n }\n @output\n}\n\nmy @polygon = (50, 150), (200, 50), (350, 150), (350, 300), (250, 300),\n (200, 250), (150, 350), (100, 250), (100, 200);\n\nmy @clip = (100, 100), (300, 100), (300, 300), (100, 300);\n\nmy @clipped = sutherland-hodgman(@polygon, @clip);\n\nsay \"Clipped polygon: \", @clipped;\n\n# Output an SVG as well as it is easier to visualize\nuse SVG;\nmy $outfile = 'Sutherland-Hodgman-polygon-clipping-perl6.svg'.IO.open(:w);\n$outfile.say: SVG.serialize(\n svg => [\n  :400width, :400height,\n  :rect[ :400width, :400height, :fill<white> ],\n  :text[ :10x, :20y, \"Polygon (blue)\" ],\n  :text[ :10x, :35y, \"Clip port (green)\" ],\n  :text[ :10x, :50y, \"Clipped polygon (red)\" ],\n  :polyline[ :points(@polygon.join: ','), :style<stroke:blue>,  :fill<blue>,  :opacity<.3> ],\n  :polyline[ :points( @clip.join: ','), :style<stroke:green>, :fill<green>, :opacity<.3> ],\n  :polyline[ :points(@clipped.join: ','), :style<stroke:red>,  :fill<red>,  :opacity<.5> ],\n ],\n);\n\n```\n\nOutput:\n\n```\nClipped polygon: [(100 116.666667) (125 100) (275 100) (300 116.666667) (300 300) (250 300) (200 250) (175 300) (125 300) (100 250)]\n```\n\nAlso see output image: offsite SVG image" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Sylvester's sequence. 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 number theory, **Sylvester's sequence** is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.\n\nIts values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to **1** more rapidly than any other series of unit fractions with the same number of terms.\n\nFurther, the sum of the first **k** terms of the infinite series of reciprocals provides the closest possible underestimate of **1** by any k-term Egyptian fraction.\n\nTask\n\n* Write a routine (function, procedure, generator, whatever) to calculate **Sylvester's sequence**.\n* Use that routine to show the values of the first **10** elements in the sequence.\n* Show the sum of the reciprocals of the first **10** elements on the sequence, ideally as an exact fraction.\n\nRelated tasks\n\n* Egyptian fractions\n* Harmonic series\n\nSee also\n\n* OEIS A000058 - Sylvester's sequence" }, { "role": "assistant", "content": "```\nmy @S = {1 + [*] @S[^($++)]} … *;\n\nput 'First 10 elements of Sylvester\\'s sequence: ', @S[^10];\n\nsay \"\\nSum of the reciprocals of first 10 elements: \", sum @S[^10].map: { FatRat.new: 1, $_ };\n\n```\n\nOutput:\n\n```\nFirst 10 elements of Sylvester's sequence: 2 3 7 43 1807 3263443 10650056950807 113423713055421844361000443 12864938683278671740537145998360961546653259485195807 165506647324519964198468195444439180017513152706377497841851388766535868639572406808911988131737645185443\n\nSum of the reciprocals of first 10 elements: 0.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999635\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven two sets *A* and *B*, compute \n\n(\nA\n∖\nB\n)\n∪\n(\nB\n∖\nA\n)\n.\n{\\displaystyle {\\displaystyle (A\\setminus B)\\cup (B\\setminus A).}}\n\nThat is, enumerate the items that are in *A* or *B* but not both. This set is called the symmetric difference of *A* and *B*.\n\nIn other words: \n\n(\nA\n∪\nB\n)\n∖\n(\nA\n∩\nB\n)\n{\\displaystyle {\\displaystyle (A\\cup B)\\setminus (A\\cap B)}}\n (the set of items that are in at least one of *A* or *B* minus the set of items that are in both *A* and *B*).\n\nOptionally, give the individual differences (\n\nA\n∖\nB\n{\\displaystyle {\\displaystyle A\\setminus B}}\n and \n\nB\n∖\nA\n{\\displaystyle {\\displaystyle B\\setminus A}}\n) as well.\n\nTest cases\n\n```\nA = {John, Bob, Mary, Serena}\nB = {Jim, Mary, John, Bob}\n\n```\n\nNotes\n\n1. If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of `a = [\"John\", \"Serena\", \"Bob\", \"Mary\", \"Serena\"]` and `b = [\"Jim\", \"Mary\", \"John\", \"Jim\", \"Bob\"]` should produce the result of just two strings: `[\"Serena\", \"Jim\"]`, in any order.\n2. In the mathematical notation above `A \\ B` gives the set of items in A that are not in B; `A ∪ B` gives the set of items in both A and B, (their *union*); and `A ∩ B` gives the set of items that are in both A and B (their *intersection*)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy \\A = set <John Serena Bob Mary Serena>;\nmy \\B = set <Jim Mary John Jim Bob>;\n\nsay A ∖ B; # Set subtraction\nsay B ∖ A; # Set subtraction\nsay (A ∪ B) ∖ (A ∩ B); # Symmetric difference, via basic set operations\nsay A ⊖ B; # Symmetric difference, via dedicated operator\n\n```\n\nOutput:\n\n```\nset(Serena)\nset(Jim)\nset(Jim, Serena)\nset(Jim, Serena)\n```" } ]
[ { "role": "user", "content": "Sync subtitles\n\n**Sync subtitles**\n\nSometimes, when you download a movie, the subtitles are out of sync with the audio in this movie. Video players like VLC solve the problem, but it must be done manually.\n\nMake a program that takes the \"movie.srt\" file, and synchronizes the subtitles \"n\" seconds.\n\n* Try to fast-forward the subtitles by 9 seconds.\n* Try rolling back the subtitles by 9 seconds.\n\nTake the excerpt from the following subtitles file as an example:\n\n**movie.srt**\n\n```\n1\n00:01:31,550 --> 00:01:36,347\nFour billion years ago,\nthe first marine life forms.\n\n2\n00:01:36,555 --> 00:01:42,019\nFirst came the fish...then slowly\nother life forms evolved.\n\n3\n00:01:42,144 --> 00:01:43,979\nTherefore, our ancestors...\n\n4\n00:01:43,979 --> 00:01:45,898\n...came from fish.\n\n5\n00:01:46,232 --> 00:01:47,608\nEveryone, come and see this.\n\n6\n00:01:47,733 --> 00:01:50,361\nCretaceous Tyrannosaurus.\n\n7\n00:01:50,736 --> 00:01:52,488\nFerocious!\n\n8\n00:01:58,035 --> 00:01:58,869\nRed,\n\n9\n00:01:59,203 --> 00:02:00,079\nPong!\n\n10\n00:02:02,540 --> 00:02:03,999\nIsn't this a gecko?\n\n11\n00:02:04,416 --> 00:02:07,419\nHow else can I get a 15 ton T-Rex in here?\n\n12\n00:02:07,503 --> 00:02:11,048\nWith our advanced technology, I shrank it down.\n\n```\n\nReferences\n\n: * Wikipedia: SubRip" }, { "role": "assistant", "content": "### Brutal\n\n```\n# 20240621 Raku programming solution\n\nsub MAIN() {\n my @lines = $*IN.lines;\n for 9, -9 -> $seconds {\n say \"Original subtitle adjusted by {$seconds.fmt('%+d')} seconds.\";\n for @lines -> $line {\n if $line ~~ /(\\d ** 2 ':' \\d ** 2 ':' \\d ** 2 ',' \\d ** 3) ' --> ' (\\d ** 2 ':' \\d ** 2 ':' \\d ** 2 ',' \\d ** 3)/ {\n my $start = adjust-time($0.Str, $seconds);\n my $end = adjust-time($1.Str, $seconds);\n my $adjusted = $line;\n $adjusted ~~ s/\\d ** 2 ':' \\d ** 2 ':' \\d ** 2 ',' \\d ** 3 ' --> ' \\d ** 2 ':' \\d ** 2 ':' \\d ** 2 ',' \\d ** 3/$start ~ ' --> ' ~ $end/.Str;\n say $adjusted\n } else {\n say $line;\n }\n }\n say()\n }\n}\n\nsub adjust-time($time, $seconds) {\n my ($time_str, $milliseconds_str) = $time.split(',');\n my (\\hh, \\mm, \\ss) = $time_str.split(':')>>.Int;\n my $milliseconds = $milliseconds_str.Int;\n my $datetime = DateTime.new(:year,  :month,  :day, \n  :hour(hh), :minute(mm), :second(ss));\n given $datetime .= later(:seconds($seconds)) {\n return sprintf('%02d:%02d:%02d,%03d',.hour,.minute,.second,$milliseconds)\n }\n}\n\n```\n\nYou may Attempt This Online!\n\n### Less brutal\n\n```\n# 20240622 Raku programming solution\n\ngrammar SRT { # loc.gov/preservation/digital/formats/fdd/fdd000569.shtml\n token TOP { ^ <subtitle>+ % \\n $ }\n token subtitle { <index> \\n <timecode> \\n <text> \\n? }\n token index { \\d+ }\n token timecode { <timestamp> ' --> ' <timestamp> }\n token timestamp { \\d ** 2 ':' \\d ** 2 ':' \\d ** 2 ',' \\d ** 3 }\n token text { <line>+ % \\n }\n token line { <-[\\n]>+ }\n}\n\nclass SRT::Actions { has @.subtitles;\n\n method TOP($/) {\n @.subtitles = $<subtitle>».made;\n make @.subtitles\n }\n\n method subtitle($/) {\n make {\n index => $<index>.Str,\n start => $<timecode><timestamp>[0].made,\n end => $<timecode><timestamp>[1].made,\n text => $<text>.made,\n }\n }\n\n method timestamp($/) { make $/.Str }\n\n method text($/) { make $<line>.join(\"\\n\") }\n}\n\nclass SubtitleAdjuster {\n\n method adjust-time($time, $seconds) {\n my ($time-str, $milliseconds-str) = $time.split(',');\n my (\\hh, \\mm, \\ss) = $time-str.split(':')>>.Int;\n my \\mls = $milliseconds-str.Int;\n my $datetime = DateTime.new( :year, :month, :day,\n  :hour(hh), :minute(mm), :second(ss));\n given $datetime .= later(:seconds($seconds)) {\n return sprintf('%02d:%02d:%02d,%03d', .hour, .minute, .second, mls)\n }\n }\n\n method adjust-subtitles(@subtitles, Int $seconds) {\n @subtitles.map({\n $_<start> = self.adjust-time($_<start>, $seconds);\n $_<end> = self.adjust-time($_<end>, $seconds);\n $_;\n });\n }\n\n method format-srt(@subtitles) {\n @subtitles.map({\n $_<index> ~ \"\\n\"\n ~ $_<start> ~ \" --> \" ~ $_<end> ~ \"\\n\"\n ~ $_<text> ~ \"\\n\"\n }).join(\"\\n\");\n }\n}\n\nmy $srt-content = $*IN.slurp;\nmy $parsed = SRT.parse($srt-content, :actions(SRT::Actions.new));\nmy @subtitles = $parsed.made;\n\nmy $adjuster = SubtitleAdjuster.new;\n\nfor 9, -9 -> \\N {\n my @adjusted-subtitles = $adjuster.adjust-subtitles(@subtitles.deepmap(*.clone), N);\n say \"Original subtitle adjusted by {N.fmt('%+d')} seconds.\";\n say $adjuster.format-srt(@adjusted-subtitles);\n}\n\n```\n\nYou may Attempt This Online!" } ]
[ { "role": "user", "content": "The goal of this task is to create two concurrent activities (\"Threads\" or \"Tasks\", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.\n\nOne of the concurrent units will read from a file named \"input.txt\" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.\n\nThis task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2013-02-27\n\n```\nsub MAIN ($infile) {\n $infile.IO.lines ==> printer() ==> my $count;\n say \"printed $count lines\";\n}\n\nsub printer(*@lines) {\n my $lines;\n for @lines {\n\t.say;\n\t++$lines;\n }\n $lines;\n}\n\n```\n\nConcurrent units are established by use of the feed operator, which works much like an in-process object pipe. Since the final feed goes to a variable declaration that belongs to the outer thread, it serves as a backchannel from the printer thread. In this case the outer thread signals the desire for a line count by terminating the pipe to the printing thread.\n(Note: soon these will be implemented with real threads in Raku, but this is currently emulated with coroutine semantics, aka lazy lists.)" } ]
[ { "role": "user", "content": "Task\n\nOutput the system **time**   (any units will do as long as they are noted) either by a system command or one built into the language.\n\nThe system time can be used for debugging, network information, random number seeds, or something as simple as program performance.\n\nRelated task\n\n* Date format\n\nSee also\n\n* Retrieving system time (wiki)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay DateTime.now;\ndd DateTime.now.Instant;\n```\n\nOutput:\n\n```\n 2015-11-02T13:34:09+01:00\n Instant $var = Instant.new(<2159577143734/1493>)\n\n```" } ]
[ { "role": "user", "content": "*Szymański's algorithm* is a mutual exclusion algorithm devised by computer scientist Bolesław Szymański.\n\nThe algorithm allows mutiple processes or tasks to access a serial resource without conflict, using only linear waiting times.\nIt has application in multitasking and communications, especially if there is a need for massive parallelism with limited\nwaiting times for access to resources by the parallel program's components.\n\nTask\n\n* Implement Szymanski's algorithm utilizing parallel processes, threads, or similar coroutines.\n* Your example should implement the steps shown in the Wikipedia's pseudocode at the Wikipedia reference below.\n\nSee also\n\n* [Wikipedia entry for Szymański's algorithm] * [ACM digital entry for Szymański's paper]\n\n\"\"\"\nSzymański's algorithm reference:\nBoleslaw K. Szymanski. A simple solution to Lamport's concurrent programming problem with linear wait.\nProceedings of the 2nd International Conference on Supercomputing, 1988, Figure 2, Page 624.\nhttps://dl.acm.org/doi/pdf/10.1145/55364.55425\nhttps://en.wikipedia.org/wiki/Szyma%C5%84ski%27s\\_algorithm\n\"\"\"" }, { "role": "assistant", "content": "```\n# 20230822 Raku programming solution\n\nuse OO::Monitors;\n\nmy \\N = 10;\n\nmonitor Szymański {\n\n has @.tasks;\n my $critical = 0;\n\n method runSzymański($id) {\n @.tasks[$id] = 1; \n ( my @others = @.tasks ).splice: $id,1;\n until @others.all ~~ 0|1|2 { $*THREAD.yield }\n @.tasks[$id] = 3; \n if @others.any ~~ 1 {\n @.tasks[$id] = 2;\n until @others.any ~~ 4 { $*THREAD.yield }\n }\n @.tasks[$id] = 4;\n until @.tasks[^$id].all ~~ 0|1 { $*THREAD.yield }\n $critical = ((my $previous = $critical) + $id * 3) div 2;\n say \"Thread $id changed the critical value from $previous to $critical\";\n until @.tasks[$id^..*-1].all ~~ 0|1|4 { $*THREAD.yield }\n @.tasks[$id] = 0\n }\n}\n\nmy $flag = Szymański.new: tasks => 0 xx N;\nawait Promise.allof( ^N .pick(*).map: { start { $flag.runSzymański: $_ } } );\n\n```\n\nOutput:\n\n```\nThread 6 changed the critical value from 0 to 9\nThread 1 changed the critical value from 9 to 6\nThread 5 changed the critical value from 6 to 10\nThread 4 changed the critical value from 10 to 11\nThread 7 changed the critical value from 11 to 16\nThread 9 changed the critical value from 16 to 21\nThread 8 changed the critical value from 21 to 22\nThread 3 changed the critical value from 22 to 15\nThread 2 changed the critical value from 15 to 10\nThread 0 changed the critical value from 10 to 5\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a database table to exemplify most commonly used data types and options.\n\nRelated task\n\n* Table Creation - Address" }, { "role": "assistant", "content": "(formerly Perl 6)\nIn Raku, there is no 'database' type built in, so it is somewhat ambiguous when specifying 'create a database table'. Raku offers bindings to most common databases through its DBIish module but mostly abstracts away the differences between the underlying databases, which hides many of the finer distinctions of what may be stored where. The actual data types and options available are properties of the database used.\n\nIf on the other hand, we are meant to show built in collective types that may be used to hold tabular data, this may be of some use.\n\nIn general, a container type can hold objects of any data type, even instances of their own type; allowing 'multi-dimensional' (tabular) containers.\n\nRaku offers two broad categories of collective container types; those that do the Positional role and those that do Associative. Positional objects are collective objects that access the individual storage slots using an integer index. Associative objects use some sort of other pointer (typically string) to access their storage slots.\n\nThe various Associative types mostly differ in their value handling. Hash, Map and QuantHash may have any type of object as their value. All the others have some specific, usually numeric, type as their value.\n\n```\nPositional - Object that supports looking up values by integer index\n Array Sequence of itemized objects\n List Immutable sequence of objects\n\nAssociative - Object that supports looking up values by key (typically string)\n Bag Immutable collection of distinct objects with integer weights\n BagHash Mutable collection of distinct objects with integer weights\n Hash Mapping from strings to itemized values\n Map Immutable mapping from strings to values\n Mix Immutable collection of distinct objects with Real weights\n MixHash Mutable collection of distinct objects with Real weights\n QuantHash Collection of objects represented as hash keys\n Set Immutable collection of distinct objects, no value except 'present'\n SetHash Mutable collection of distinct objects, no value except 'present'\n\n```\n\nIf you want a persistent instance of any of these types, you need to declare the name with some scope constraint, but there are no prerequisites to creating instances. Simply assigning values to them will call them into existence." } ]
[ { "role": "user", "content": "Task\n\nCreate a table to store addresses.\n\nYou may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode.   Choose appropriate types for each field.\n\nFor non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nLike Perl DBI, Raku DBIish supports many different databases. An example using SQLite is shown here.\n\n```\nuse DBIish;\n\nmy $dbh = DBIish.connect('SQLite', :database<addresses.sqlite3>);\n\nmy $sth = $dbh.do(q:to/STATEMENT/);\n DROP TABLE IF EXISTS Address;\n CREATE TABLE Address (\n addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n addrStreet TEXT NOT NULL,\n addrCity TEXT NOT NULL,\n addrState TEXT NOT NULL,\n addrZIP TEXT NOT NULL\n )\n STATEMENT\n\n```" } ]
[ { "role": "user", "content": "Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.\nIf NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.\nThen all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.\nIf NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $file = 'notes.txt';\n\nmulti MAIN() {\n print slurp($file);\n}\n\nmulti MAIN(*@note) {\n my $fh = open($file, :a);\n $fh.say: DateTime.now, \"\\n\\t\", @note;\n $fh.close;\n}\n\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Graph. 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\nTarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.\n\nIt runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.\n\nTarjan's Algorithm is named for its discoverer, Robert Tarjan.\n\nReferences\n\n* The article on Wikipedia.\n\nSee also: Kosaraju" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.09\n\n```\nsub tarjan (%k) {\n my %onstack;\n my %index;\n my %lowlink;\n my @stack;\n my @connected;\n\n sub strong-connect ($vertex) {\n state $index = 0;\n %index{$vertex} = $index;\n %lowlink{$vertex} = $index++;\n %onstack{$vertex} = True;\n @stack.push: $vertex;\n for |%k{$vertex} -> $connection {\n if not %index{$connection}.defined {\n strong-connect($connection);\n %lowlink{$vertex} min= %lowlink{$connection};\n }\n elsif %onstack{$connection} {\n %lowlink{$vertex} min= %index{$connection};\n }\n }\n if %lowlink{$vertex} eq %index{$vertex} {\n my @node;\n repeat {\n @node.push: @stack.pop;\n %onstack{@node.tail} = False;\n } while @node.tail ne $vertex;\n @connected.push: @node;\n }\n }\n\n .&strong-connect unless %index{$_} for %k.keys;\n\n @connected\n}\n\n# TESTING\n\n-> $test { say \"\\nStrongly connected components: \", |tarjan($test).sort».sort } for\n\n# hash of vertex, edge list pairs\n(((1),(2),(0),(1,2,4),(3,5),(2,6),(5),(4,6,7)).pairs.hash),\n\n# Same layout test data with named vertices instead of numbered.\n%(:Andy<Bart>,\n  :Bart<Carl>,\n  :Carl<Andy>,\n  :Dave<Bart Carl Earl>,\n  :Earl<Dave Fred>,\n  :Fred<Carl Gary>,\n  :Gary<Fred>,\n  :Hank<Earl Gary Hank>\n)\n\n```\n\nOutput:\n\n```\nStrongly connected components: (0 1 2)(3 4)(5 6)(7)\n\nStrongly connected components: (Andy Bart Carl)(Dave Earl)(Fred Gary)(Hank)\n```" } ]
[ { "role": "user", "content": "Given a positive integer, count the number of its positive divisors.\n\nTask\n\nShow the result for the first   **100**   positive integers.\n\nRelated task\n\n* Tau number" }, { "role": "assistant", "content": "Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.\n\n```\nuse Prime::Factor:ver<0.3.0+>;\nuse Lingua::EN::Numbers;\n\nsay \"\\nTau function - first 100:\\n\", # ID\n(1..*).map({ +.&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%3d\").join(\"\\n\"); # display formatting\n\nsay \"\\nTau numbers - first 100:\\n\", # ID\n(1..*).grep({ $_ %% +.&divisors })[^100]\\ # the task\n.batch(10)».&comma».fmt(\"%5s\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor sums - first 100:\\n\", # ID\n(1..*).map({ [+] .&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%4d\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor products - first 100:\\n\", # ID\n(1..*).map({ [×] .&divisors })[^100]\\ # the task\n.batch(5)».&comma».fmt(\"%16s\").join(\"\\n\"); # display formatting\n\n```\n\nOutput:\n\n```\nTau function - first 100:\n 1 2 2 3 2 4 2 4 3 4 2 6 2 4 4 5 2 6 2 6\n 4 4 2 8 3 4 4 6 2 8 2 6 4 4 4 9 2 4 4 8\n 2 8 2 6 6 4 2 10 3 6 4 6 2 8 4 8 4 4 2 12\n 2 4 6 7 4 8 2 6 4 8 2 12 2 4 6 6 4 8 2 10\n 5 4 2 12 4 4 4 8 2 12 4 6 4 4 4 12 2 6 6 9\n\nTau numbers - first 100:\n 1 2 8 9 12 18 24 36 40 56\n 60 72 80 84 88 96 104 108 128 132\n 136 152 156 180 184 204 225 228 232 240\n 248 252 276 288 296 328 344 348 360 372\n 376 384 396 424 441 444 448 450 468 472\n 480 488 492 504 516 536 560 564 568 584\n 600 612 625 632 636 640 664 672 684 708\n 712 720 732 776 792 804 808 824 828 852\n 856 864 872 876 880 882 896 904 936 948\n 972 996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096\n\nDivisor sums - first 100:\n 1 3 4 7 6 12 8 15 13 18 12 28 14 24 24 31 18 39 20 42\n 32 36 24 60 31 42 40 56 30 72 32 63 48 54 48 91 38 60 56 90\n 42 96 44 84 78 72 48 124 57 93 72 98 54 120 72 120 80 90 60 168\n 62 96 104 127 84 144 68 126 96 144 72 195 74 114 124 140 96 168 80 186\n 121 126 84 224 108 132 120 180 90 234 112 168 128 144 120 252 98 171 156 217\n\nDivisor products - first 100:\n 1 2 3 8 5\n 36 7 64 27 100\n 11 1,728 13 196 225\n 1,024 17 5,832 19 8,000\n 441 484 23 331,776 125\n 676 729 21,952 29 810,000\n 31 32,768 1,089 1,156 1,225\n 10,077,696 37 1,444 1,521 2,560,000\n 41 3,111,696 43 85,184 91,125\n 2,116 47 254,803,968 343 125,000\n 2,601 140,608 53 8,503,056 3,025\n 9,834,496 3,249 3,364 59 46,656,000,000\n 61 3,844 250,047 2,097,152 4,225\n 18,974,736 67 314,432 4,761 24,010,000\n 71 139,314,069,504 73 5,476 421,875\n 438,976 5,929 37,015,056 79 3,276,800,000\n 59,049 6,724 83 351,298,031,616 7,225\n 7,396 7,569 59,969,536 89 531,441,000,000\n 8,281 778,688 8,649 8,836 9,025\n 782,757,789,696 97 941,192 970,299 1,000,000,000\n```" } ]
[ { "role": "user", "content": "A Tau number is a positive integer divisible by the count of its positive divisors.\n\nTask\n\nShow the first   **100**   Tau numbers.\nThe numbers shall be *generated* during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).\n\nRelated task\n\n* Tau function" }, { "role": "assistant", "content": "Yet more tasks that are tiny variations of each other. Tau function, Tau number, Sum of divisors and Product of divisors all use code with minimal changes. What the heck, post 'em all.\n\n```\nuse Prime::Factor:ver<0.3.0+>;\nuse Lingua::EN::Numbers;\n\nsay \"\\nTau function - first 100:\\n\", # ID\n(1..*).map({ +.&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%3d\").join(\"\\n\"); # display formatting\n\nsay \"\\nTau numbers - first 100:\\n\", # ID\n(1..*).grep({ $_ %% +.&divisors })[^100]\\ # the task\n.batch(10)».&comma».fmt(\"%5s\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor sums - first 100:\\n\", # ID\n(1..*).map({ [+] .&divisors })[^100]\\ # the task\n.batch(20)».fmt(\"%4d\").join(\"\\n\"); # display formatting\n\nsay \"\\nDivisor products - first 100:\\n\", # ID\n(1..*).map({ [×] .&divisors })[^100]\\ # the task\n.batch(5)».&comma».fmt(\"%16s\").join(\"\\n\"); # display formatting\n\n```\n\nOutput:\n\n```\nTau function - first 100:\n 1 2 2 3 2 4 2 4 3 4 2 6 2 4 4 5 2 6 2 6\n 4 4 2 8 3 4 4 6 2 8 2 6 4 4 4 9 2 4 4 8\n 2 8 2 6 6 4 2 10 3 6 4 6 2 8 4 8 4 4 2 12\n 2 4 6 7 4 8 2 6 4 8 2 12 2 4 6 6 4 8 2 10\n 5 4 2 12 4 4 4 8 2 12 4 6 4 4 4 12 2 6 6 9\n\nTau numbers - first 100:\n 1 2 8 9 12 18 24 36 40 56\n 60 72 80 84 88 96 104 108 128 132\n 136 152 156 180 184 204 225 228 232 240\n 248 252 276 288 296 328 344 348 360 372\n 376 384 396 424 441 444 448 450 468 472\n 480 488 492 504 516 536 560 564 568 584\n 600 612 625 632 636 640 664 672 684 708\n 712 720 732 776 792 804 808 824 828 852\n 856 864 872 876 880 882 896 904 936 948\n 972 996 1,016 1,040 1,044 1,048 1,056 1,068 1,089 1,096\n\nDivisor sums - first 100:\n 1 3 4 7 6 12 8 15 13 18 12 28 14 24 24 31 18 39 20 42\n 32 36 24 60 31 42 40 56 30 72 32 63 48 54 48 91 38 60 56 90\n 42 96 44 84 78 72 48 124 57 93 72 98 54 120 72 120 80 90 60 168\n 62 96 104 127 84 144 68 126 96 144 72 195 74 114 124 140 96 168 80 186\n 121 126 84 224 108 132 120 180 90 234 112 168 128 144 120 252 98 171 156 217\n\nDivisor products - first 100:\n 1 2 3 8 5\n 36 7 64 27 100\n 11 1,728 13 196 225\n 1,024 17 5,832 19 8,000\n 441 484 23 331,776 125\n 676 729 21,952 29 810,000\n 31 32,768 1,089 1,156 1,225\n 10,077,696 37 1,444 1,521 2,560,000\n 41 3,111,696 43 85,184 91,125\n 2,116 47 254,803,968 343 125,000\n 2,601 140,608 53 8,503,056 3,025\n 9,834,496 3,249 3,364 59 46,656,000,000\n 61 3,844 250,047 2,097,152 4,225\n 18,974,736 67 314,432 4,761 24,010,000\n 71 139,314,069,504 73 5,476 421,875\n 438,976 5,929 37,015,056 79 3,276,800,000\n 59,049 6,724 83 351,298,031,616 7,225\n 7,396 7,569 59,969,536 89 531,441,000,000\n 8,281 778,688 8,649 8,836 9,025\n 782,757,789,696 97 941,192 970,299 1,000,000,000\n```" } ]
[ { "role": "user", "content": "A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way.\n\nThe first taxicab number is   **1729**,   which is:\n\n: : : 13   +   123       and also\n : 93   +   103.\n\nTaxicab numbers are also known as:\n\n: : * taxi numbers\n * taxi-cab numbers\n * taxi cab numbers\n * Hardy-Ramanujan numbers\n\nTask\n\n* Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).\n* For each of the taxicab numbers, show the number as well as it's constituent cubes.\n\nExtra credit\n\n* Show the 2,000th taxicab number, and a half dozen more\n\nSee also\n\n* A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.\n* Hardy-Ramanujan Number on MathWorld.\n* taxicab number on MathWorld.\n* taxicab number on Wikipedia   (includes the story on how taxi-cab numbers came to be called)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis uses a pretty simple search algorithm that doesn't necessarily return the Taxicab numbers in order. Assuming we want all the Taxicab numbers within some range S to N, we'll search until we find N values. When we find the Nth value, we continue to search up to the cube root of the largest Taxicab number found up to that point. That ensures we will find all of them inside the desired range without needing to search arbitrarily or use magic numbers. Defaults to returning the Taxicab numbers from 1 to 25. Pass in a different start and end value if you want some other range.\n\n```\nconstant @cu = (^Inf).map: { .³ }\n\nsub MAIN ($start = 1, $end = 25) {\n my %taxi;\n my int $taxis = 0;\n my $terminate = 0;\n my int $max = 0;\n\n for 1 .. * -> $c1 {\n last if ?$terminate && ($terminate < $c1);\n for 1 .. $c1 -> $c2 {\n my $this = @cu[$c1] + @cu[$c2];\n %taxi{$this}.push: [$c2, $c1];\n if %taxi{$this}.elems == 2 {\n ++$taxis;\n $max max= $this;\n }\n \t $terminate = ceiling $max ** (1/3) if $taxis == $end and !$terminate;\n } \n }\n\n display( %taxi, $start, $end );\n\n}\n\nsub display (%this_stuff, $start, $end) {\n my $i = $start;\n printf \"%4d %10d =>\\t%s\\n\", $i++, $_.key,\n (.value.map({ sprintf \"%4d³ + %-s\\³\", |$_ })).join: \",\\t\"\n for %this_stuff.grep( { $_.value.elems > 1 } ).sort( +*.key )[$start-1..$end-1];\n}\n\n```\n\nOutput:\n\nWith no passed parameters (default)\n\n```\n 1 1729 =>\t 9³ + 10³,\t 1³ + 12³\n 2 4104 =>\t 9³ + 15³,\t 2³ + 16³\n 3 13832 =>\t 18³ + 20³,\t 2³ + 24³\n 4 20683 =>\t 19³ + 24³,\t 10³ + 27³\n 5 32832 =>\t 18³ + 30³,\t 4³ + 32³\n 6 39312 =>\t 15³ + 33³,\t 2³ + 34³\n 7 40033 =>\t 16³ + 33³,\t 9³ + 34³\n 8 46683 =>\t 27³ + 30³,\t 3³ + 36³\n 9 64232 =>\t 26³ + 36³,\t 17³ + 39³\n 10 65728 =>\t 31³ + 33³,\t 12³ + 40³\n 11 110656 =>\t 36³ + 40³,\t 4³ + 48³\n 12 110808 =>\t 27³ + 45³,\t 6³ + 48³\n 13 134379 =>\t 38³ + 43³,\t 12³ + 51³\n 14 149389 =>\t 29³ + 50³,\t 8³ + 53³\n 15 165464 =>\t 38³ + 48³,\t 20³ + 54³\n 16 171288 =>\t 24³ + 54³,\t 17³ + 55³\n 17 195841 =>\t 22³ + 57³,\t 9³ + 58³\n 18 216027 =>\t 22³ + 59³,\t 3³ + 60³\n 19 216125 =>\t 45³ + 50³,\t 5³ + 60³\n 20 262656 =>\t 36³ + 60³,\t 8³ + 64³\n 21 314496 =>\t 30³ + 66³,\t 4³ + 68³\n 22 320264 =>\t 32³ + 66³,\t 18³ + 68³\n 23 327763 =>\t 51³ + 58³,\t 30³ + 67³\n 24 373464 =>\t 54³ + 60³,\t 6³ + 72³\n 25 402597 =>\t 56³ + 61³,\t 42³ + 69³\n```\n\nWith passed parameters 2000 2006:\n\n```\n2000 1671816384 =>\t 940³ + 944³,\t 428³ + 1168³\n2001 1672470592 =>\t 632³ + 1124³,\t 29³ + 1187³\n2002 1673170856 =>\t 828³ + 1034³,\t 458³ + 1164³\n2003 1675045225 =>\t 744³ + 1081³,\t 522³ + 1153³\n2004 1675958167 =>\t 711³ + 1096³,\t 492³ + 1159³\n2005 1676926719 =>\t 714³ + 1095³,\t 63³ + 1188³\n2006 1677646971 =>\t 891³ + 990³,\t 99³ + 1188³\n```" } ]
[ { "role": "user", "content": "On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   **TEA**   appears a number of times separated by bullet characters   (•).\n\nIt occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three-letter word.\n\nSo start at the   **T**   and read   **TEA**.   Start at the   **E**   and read   **EAT**,   or start at the   **A**   and read   **ATE**.\n\nThat got me thinking that maybe there are other words that could be used rather that   **TEA**.   And that's just English.   What about Italian or Greek or ... um ... Telugu.\n\nFor English, we will use the unixdict (now) located at:   unixdict.txt.\n\n(This will maintain continuity with other Rosetta Code tasks that also use it.)\n\nTask\n\nSearch for a set of words that could be printed around the edge of a teacup.   The words in each set are to be of the same length, that length being greater than two (thus precluding   **AH**   and   **HA**,   for example.)\n\nHaving listed a set, for example   [**ate tea eat**],   refrain from displaying permutations of that set, e.g.:   [**eat tea ate**]   etc.\n\nThe words should also be made of more than one letter   (thus precluding   **III**   and   **OOO**   etc.)\n\nThe relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second.   The first letter of the second becomes the last letter of the third.   So   **ATE**   becomes   **TEA**   and   **TEA**   becomes   **EAT**.\n\nAll of the possible permutations, using this particular permutation technique, must be words in the list.\n\nThe set you generate for   **ATE**   will never included the word   **ETA**   as that cannot be reached via the first-to-last movement method.\n\nDisplay one line for each set of teacup rim words.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nThere doesn't seem to be any restriction that the word needs to consist only of lowercase letters, so words of any case are included. Since the example code specifically shows the example words (TEA, EAT, ATE) in uppercase, I elected to uppercase the found words.\n\nAs the specs keep changing, this version will accept ANY text file as its dictionary and accepts parameters to configure the minimum number of characters in a word to consider and whether to allow mono-character words.\n\nDefaults to unixdict.txt, minimum 3 characters and mono-character 'words' disallowed. Feed a file name to use a different word list, an integer to --min-chars and/or a truthy value to --mono to allow mono-chars.\n\n```\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nunit sub MAIN ( $dict = 'unixdict.txt', :$min-chars = 3, :$mono = False );\n\nmy %words;\n$dict.IO.slurp.words.map: { .chars < $min-chars ?? (next) !! %words{.uc.comb.sort.join}.push: .uc };\n\nmy @teacups;\nmy %seen;\n\nfor %words.values -> @these {\n next if !$mono && @these < 2;\n MAYBE: for @these {\n my $maybe = $_;\n next if %seen{$_};\n my @print;\n for ^$maybe.chars {\n if $maybe ∈ @these {\n @print.push: $maybe;\n $maybe = $maybe.comb.list.rotate.join;\n } else {\n @print = ();\n next MAYBE\n }\n }\n if @print.elems {\n @teacups.push: @print;\n %seen{$_}++ for @print;\n }\n }\n}\n\nsay .unique.join(\", \") for sort @teacups;\n\n```\n\nDefaults:\n\nCommand line: raku teacup.p6\n\n```\nAPT, PTA, TAP\nARC, RCA, CAR\nATE, TEA, EAT\n```\n\nAllow mono-chars:\n\nCommand line: raku teacup.p6 --mono=1\n\n```\nAAA\nAPT, PTA, TAP\nARC, RCA, CAR\nATE, TEA, EAT\nIII\n```\n\nUsing a larger dictionary:\n\nwords.txt file from https://github.com/dwyl/english-words\n\nCommand line: raku teacup.p6 words.txt --min-chars=4 --mono=Allow\n\n```\nAAAA\nAAAAAA\nADAD, DADA\nADAR, DARA, ARAD, RADA\nAGAG, GAGA\nALIT, LITA, ITAL, TALI\nAMAN, MANA, ANAM, NAMA\nAMAR, MARA, ARAM, RAMA\nAMEL, MELA, ELAM, LAME\nAMEN, MENA, ENAM, NAME\nAMOR, MORA, ORAM, RAMO\nANAN, NANA\nANIL, NILA, ILAN, LANI\nARAR, RARA\nARAS, RASA, ASAR, SARA\nARIS, RISA, ISAR, SARI\nASEL, SELA, ELAS, LASE\nASER, SERA, ERAS, RASE\nDENI, ENID, NIDE, IDEN\nDOLI, OLID, LIDO, IDOL\nEGOR, GORE, OREG, REGO\nENOL, NOLE, OLEN, LENO\nESOP, SOPE, OPES, PESO\nISIS, SISI\nMMMM\nMORO, OROM, ROMO, OMOR\nOOOO\n```" } ]
[ { "role": "user", "content": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:\nKelvin, Celsius, Fahrenheit, and Rankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n\n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\nTask\n\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.\n\nExample\n\n```\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nmy %scale =\n Celcius => { factor => 1 , offset => -273.15 },\n Rankine => { factor => 1.8, offset => 0 },\n Fahrenheit => { factor => 1.8, offset => -459.67 },\n;\n \nmy $kelvin = +prompt \"Enter a temperature in Kelvin: \";\ndie \"No such temperature!\" if $kelvin < 0;\n \nfor %scale.sort {\n printf \"%12s: %7.2f\\n\", .key, $kelvin * .value<factor> + .value<offset>;\n}\n\n```\n\nOutput:\n\n```\nEnter a temperature in Kelvin: 21\n Celcius: -252.15\n Fahrenheit: -421.87\n Rankine: 37.80\n\n```\n\nAlternative version that accepts the input in any of the four scales:\n\n```\nwhile my $answer = prompt 'Temperature: ' {\n my $k = do given $answer {\n when s/:i C $// { $_ + 273.15 }\n when s/:i F $// { ($_ + 459.67) / 1.8 }\n when s/:i R $// { $_ / 1.8 }\n when s/:i K $// { $_ }\n default { $_ }\n }\n say \" { $k }K\";\n say \" { $k - 273.15 }℃\";\n say \" { $k * 1.8 - 459.67 }℉\";\n say \" { $k * 1.8 }R\";\n}\n\n```\n\nOutput:\n\n```\nTemperature: 0\n 0K\n -273.15℃\n -459.67℉\n 0R\nTemperature: 0c\n 273.15K\n 0℃\n 32℉\n 491.67R\nTemperature: 212f\n 373.15K\n 100℃\n 212℉\n 671.67R\nTemperature: -40c\n 233.15K\n -40℃\n -40℉\n 419.67R\n```" } ]
[ { "role": "user", "content": "Task\n\nClear the terminal window." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub clear { print qx[clear] }\nclear;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay a word in various colours on the terminal.\n\nThe system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.\n\nOptionally demonstrate:\n\n* How the system should determine if the terminal supports colour\n* Setting of the background colour\n* How to cause blinking or flashing (if supported by the terminal)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse Terminal::ANSIColor;\n\nsay colored('RED ON WHITE', 'bold red on_white');\nsay colored('GREEN', 'bold green');\nsay colored('BLUE ON YELLOW', 'bold blue on_yellow');\nsay colored('MAGENTA', 'bold magenta');\nsay colored('CYAN ON RED', 'bold cyan on_red');\nsay colored('YELLOW', 'bold yellow');\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate how to achieve movement of the terminal cursor:\n\n: * how to move the cursor one position to the left\n * how to move the cursor one position to the right\n * how to move the cursor up one line (without affecting its horizontal position)\n * how to move the cursor down one line (without affecting its horizontal position)\n * how to move the cursor to the beginning of the line\n * how to move the cursor to the end of the line\n * how to move the cursor to the top left corner of the screen\n * how to move the cursor to the bottom right corner of the screen\n\nFor the purpose of this task, it is not permitted to overwrite any characters or attributes on any part of the screen (so outputting a space is not a suitable solution to achieve a movement to the right).\n\nHandling of out of bounds locomotion\n\nThis task has no specific requirements to trap or correct cursor movement beyond the terminal boundaries, so the implementer should decide what behavior fits best in terms of the chosen language.   Explanatory notes may be added to clarify how an out of bounds action would behave and the generation of error messages relating to an out of bounds cursor position is permitted." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nshell \"tput cub1\"; # one position to the left\nshell \"tput cuf1\"; # one position to the right\nshell \"tput cuu1\"; # up one line\nshell \"tput cud1\"; # down one line\nshell \"tput cr\"; # beginning of line\nshell \"tput home\"; # top left corner\n\n$_ = qx[stty -a </dev/tty 2>&1];\nmy $rows = +m/'rows ' <(\\d+)>/;\nmy $cols = +m/'columns ' <(\\d+)>/;\n\nshell \"tput hpa $cols\"; # end of line\nshell \"tput cup $rows $cols\"; # bottom right corner\n\n```" } ]
[ { "role": "user", "content": "Task\n\nMove the cursor to column   **3**,   row   **6**,   and display the word   \"Hello\"   (without the quotes),   so that the letter   **H**   is in column   **3**   on row   **6**." }, { "role": "assistant", "content": "(formerly Perl 6)\nAssuming an ANSI terminal:\n\n```\nprint \"\\e[6;3H\";\nprint 'Hello';\n\n```" } ]
[ { "role": "user", "content": "Determine the height and width of the terminal, and store this information into variables for subsequent use." }, { "role": "assistant", "content": "(formerly Perl 6)\nUsing *stty* just for the heck of it.\n\n```\nmy $stty = qx[stty -a];\nmy $lines = $stty.match(/ 'rows ' <( \\d+/);\nmy $cols = $stty.match(/ 'columns ' <( \\d+/);\nsay \"$lines $cols\";\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay an extended (non ASCII) character onto the terminal.\n\nSpecifically, display a   £   (GBP currency sign)." }, { "role": "assistant", "content": "(formerly Perl 6)\nTo demonstrate we're not limited to Latin-1, we'll print the fullwidth variant.\n\n```\nsay '£';\nsay \"\\x[FFE1]\";\nsay \"\\c[FULLWIDTH POUND SIGN]\";\n0xffe1.chr.say;\n\n```" } ]
[ { "role": "user", "content": "The task is to hide the cursor and show it again." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay 'Hiding the cursor for 5 seconds...';\nrun 'tput', 'civis';\nsleep 5;\nrun 'tput', 'cvvis';\n\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay a word in inverse video   (or reverse video)   followed by a word in normal video." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsay \"normal\";\nrun \"tput\", \"rev\";\nsay \"reversed\";\nrun \"tput\", \"sgr0\";\nsay \"normal\";\n\n```" } ]
[ { "role": "user", "content": "Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, rather than query the terminal directly, if those methods are more usual for the system type or language." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Python\n\n```\nuse NCurses;\n\n# Reference:\n# https://github.com/azawawi/perl6-ncurses\n\n# Initialize curses window\nmy $win = initscr() or die \"Failed to initialize ncurses\\n\";\n\n# Print random text in a 10x10 grid\n\nfor ^10 { mvaddstr($_ , 0, (for ^10 {(41 .. 90).roll.chr}).join )};\n\n# Read\n\nmy $icol = 3 - 1;\nmy $irow = 6 - 1;\n\nmy $ch = mvinch($irow,$icol);\n\n# Show result\n\nmvaddstr($irow, $icol+10, 'Character at column 3, row 6 = ' ~ $ch.chr);\n\nmvaddstr( LINES() - 2, 2, \"Press any key to exit...\" );\n\n# Refresh (this is needed)\nnc_refresh;\n\n# Wait for a keypress\ngetch;\n\n# Cleanup\nLEAVE {\n delwin($win) if $win;\n endwin;\n}\n\n```\n\nOutput:\n\n```\n+W18:5I<1N\nN-I.HG45SK\nBFJY8:AK)8\nJ+4U<H1++:\nRP>BX-/19Y\nURDESVX;HX Character at column 3, row 6 = D\nJ7+X3@E<BG\nM;?2U<8+FI\n)@BG,:D)O1\n)>A-=LDY-.\n\n Press any key to exit...\n\n```" } ]
[ { "role": "user", "content": "Task\n\nClear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out.\n\nThere is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved.   If the implementer decides to change the font or kerning during the display of the temporary screen, then these settings need to be restored prior to exit." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nprint \"\\e[?1049h\\e[H\";\nsay \"Alternate buffer!\";\n\nfor 5,4...1 {\n print \"\\rGoing back in: $_\";\n sleep 1;\n}\n\nprint \"\\e[?1049l\";\n\n```" } ]
[ { "role": "user", "content": "Create a routine to obtain data entry using a specific place on the terminal screen. Data entry fields should be restricted to a specific length, and it should not be possible for the cursor to move beyond the input length.\n\nThe routine should accept parameters for row number, column number and input length, and should obtain a string\nvalue entered by the user.\n\nFor the purpose of this task, obtain input from the user, showing data entry at row 3, column 5, with input width restricted to a maximum of 8 characters.\n\nNote: In this task input wrapping is not allowed. (See Terminal control/Restricted width positional input/With wrapping) for input wrapping variant.\n\nFor a similar task using a graphical user interface, see Graphical User Interface/Restricted width positional input/No wrapping." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\nShould work with any termios compatible terminal.\n\nAll printable character keys work, as does backspace and enter. Ctrl-c to exit. All other keys / key-combos are ignored.\n\n```\nuse Term::termios;\n\nconstant $saved = Term::termios.new(fd => 1).getattr;\nconstant $termios = Term::termios.new(fd => 1).getattr;\n# raw mode interferes with carriage returns, so\n# set flags needed to emulate it manually\n$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);\n$termios.unset_lflags(<ECHO ICANON IEXTEN ISIG>);\n$termios.setattr(:DRAIN);\n\n\nEND {\n $saved.setattr(:NOW); # reset terminal to original settings\n print \"\\e[?25h \\e[H\\e[J\"; # clear and reset screen\n}\n\nmy $row = 3;\nmy $column = 5;\nmy $field = '';\nmy $spacer = ' ' x 8;\nmy $pointer = 0;\n\nmy ($rows,$cols) = qx/stty size/.words; # get screen size\n\nmy @screen = \"\\e[41m{' ' x $cols}\\e[0m\" xx $rows;\n\nupdate($spacer);\n\nloop {\n my $key = $*IN.read(4).decode;\n given $key {\n when ' '..'~' {\n if $pointer < 8 {\n $field ~= $_;\n $spacer = ' ' x 8 - $field.chars;\n $pointer +=1;\n update($field~$spacer)\n }\n }\n when \"\\c[127]\" { # backspace\n if $pointer > 0 {\n $field.=substr(0,*-1);\n $spacer = ' ' x 8 - $field.chars;\n $pointer -= 1;\n update($field~$spacer)\n }\n }\n when \"\\c[13]\" {\n update(' ');\n print \"\\e[10;6H\\e[1;33;41mYou entered: $field\\e[0m\\e[$row;{$column}H\";\n $field = '';\n $pointer = 0;\n }\n when \"\\c[0003]\" { exit } # Ctrl-c\n default { }\n }\n}\n\nsub update ($str) {\n ($rows,$cols) = qx/stty size/.words;\n @screen = \"\\e[41m{' ' x $cols}\\e[0m\" xx $rows;\n print \"\\e[H\\e[J{@screen.join: \"\\n\"}\\e[$row;{$column}H$str\\e[$row;{$column + $pointer}H\";\n}\n\n```" } ]
[ { "role": "user", "content": "Create a routine to obtain data entry using a specific place on the terminal screen.\n\nData entry fields should be restricted to a specific length,   and the cursor should not move beyond the input length.\n\nThe routine should accept parameters for row number,   column number,   and input length,   and should obtain a string value entered by the user.\n\nFor the purpose of this task,   obtain input from the user,   showing data entry at   row   **3**,   column   **5**,   with input width restricted to a maximum of   **8**   characters.\n\nNote:   in this task input wrapping is allowed.   If the length of input exceeds the maximum width, the left hand side of the field should disappear, allowing additional input to be obtained.   However, the cursor must not move beyond the designated input length.\n\nIt is permissible to use navigation keys to see input field length.\n\n(See Terminal control/Restricted width positional input/No wrapping for similar input routine with no wrapping).\n\nFor a similar task using a graphical user interface,   see   Graphical User Interface/Restricted width positional input/With wrapping." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\nShould work with any termios compatible terminal.\n\nAll printable character keys (except Tab) work, as does backspace and enter. Ctrl-c to exit. All other keys / key-combos are ignored.\n\n```\nuse Term::termios;\n\nconstant $saved = Term::termios.new(fd => 1).getattr;\nconstant $termios = Term::termios.new(fd => 1).getattr;\n# raw mode interferes with carriage returns, so\n# set flags needed to emulate it manually\n$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);\n$termios.unset_lflags(<ECHO ICANON IEXTEN ISIG>);\n$termios.setattr(:DRAIN);\n\nEND {\n $saved.setattr(:NOW); # reset terminal to original settings\n print \"\\e[?25h \\e[H\\e[J\"; # clear and reset screen\n}\n\nmy $row = 3;\nmy $column = 5;\nmy $field = '';\nmy $spacer = ' ' x 8;\nmy $pointer = 0;\n\nmy ($rows,$cols) = qx/stty size/.words; # get screen size\n\nmy @screen = \"\\e[41m{' ' x $cols}\\e[0m\" xx $rows;\n\nupdate($spacer);\n\nloop {\n my $key = $*IN.read(4).decode;\n given $key {\n when ' '..'~' {\n if $pointer < 8 {\n $field ~= $_;\n $spacer = ' ' x 8 - $field.chars;\n $pointer +=1;\n update($field~$spacer)\n } elsif $pointer >= 8 {\n $field ~= $_;\n $spacer = '';\n update($field.substr(*-8))\n }\n }\n when \"\\c[127]\" { # backspace\n if $pointer > 0 {\n $field.=substr(0,*-1);\n $spacer = ' ' x (8 - $field.chars max 0);\n $pointer -= 1 if $field.chars < 8;\n my $display = $field.chars < 8 ?? $field !! $field.substr(*-8);\n update($display~$spacer)\n }\n }\n when \"\\c[13]\" {\n update(' ');\n print \"\\e[10;6H\\e[1;33;41mYou entered: $field\\e[0m\\e[$row;{$column}H\";\n $field = '';\n $pointer = 0;\n }\n when \"\\c[0003]\" { exit } # Ctrl-c\n default { }\n }\n}\n\nsub update ($str) {\n ($rows,$cols) = qx/stty size/.words;\n @screen = \"\\e[41m{' ' x $cols}\\e[0m\" xx $rows;\n print \"\\e[H\\e[J{@screen.join: \"\\n\"}\\e[$row;{$column}H$str\\e[$row;{$column + $pointer}H\";\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nMake the terminal running the program ring its \"bell\".\n\nOn modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usually used to indicate a problem where a wrong character has been typed.\n\nIn most terminals, if the   Bell character   (ASCII code **7**,   `\\a` in C)   is printed by the program, it will cause the terminal to ring its bell.   This is a function of the terminal, and is independent of the programming language of the program, other than the ability to print a particular character to standard out." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nprint 7.chr;\n\n```" } ]
[ { "role": "user", "content": "The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised.\n\nNote that it is permissible to use system configuration data to determine terminal capabilities if the system provides such a facility." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\ndie \"Terminal can't handle UTF-8\"\n unless first(*.defined, %*ENV<LC_ALL LC_CTYPE LANG>) ~~ /:i 'utf-8'/;\nsay \"△\";\n\n```\n\nOutput:\n\n```\n△\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Ternary logic. 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 logic, a **three-valued logic** (also **trivalent**, **ternary**, or **trinary logic**, sometimes abbreviated **3VL**) is any of several many-valued logic systems in which there are three truth values indicating *true*, *false* and some indeterminate third value.\n\nThis is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for *true* and *false*.\n\nConceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.\n\nThese were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to *n*-valued logics in 1945.\n\n**Example *Ternary Logic Operators* in *Truth Tables*:**\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| *not* a | ¬ | | | --- | --- | | True | False | | Maybe | Maybe | | False | True | | a *and* b | | | | | | --- | --- | --- | --- | | ∧ | True | Maybe | False | | True | True | Maybe | False | | Maybe | Maybe | Maybe | False | | False | False | False | False | | a *or* b | | | | | | --- | --- | --- | --- | | ∨ | True | Maybe | False | | True | True | True | True | | Maybe | True | Maybe | Maybe | | False | True | Maybe | False | |\n| *if* a *then* b | | | | | | --- | --- | --- | --- | | ⊃ | True | Maybe | False | | True | True | Maybe | False | | Maybe | True | Maybe | Maybe | | False | True | True | True | | a *is equivalent to* b | | | | | | --- | --- | --- | --- | | ≡ | True | Maybe | False | | True | True | Maybe | False | | Maybe | Maybe | Maybe | Maybe | | False | False | Maybe | True | |\n\nTask\n\n* Define a new type that emulates *ternary logic* by storing data **trits**.\n* Given all the binary logic operators of the original programming language, reimplement these operators for the new *Ternary logic* type **trit**.\n* Generate a sampling of results using **trit** variables.\n* Kudos for actually thinking up a test case algorithm where *ternary logic* is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.\n\nNote:   **Setun**   (Сетунь) was a   balanced ternary   computer developed in 1958 at   Moscow State University.   The device was built under the lead of   Sergei Sobolev   and   Nikolay Brusentsov.   It was the only modern   ternary computer,   using three-valued ternary logic" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nThe precedence of each operator is specified as equivalent to an existing operator. We've taken the liberty of using a double arrow for implication, to avoid confusing it with ⊃, (U+2283 SUPERSET OF).\n\n```\n# Implementation:\nenum Trit <Foo Moo Too>;\n\nsub prefix:<¬> (Trit $a) { Trit(1-($a-1)) }\n\nsub infix:<∧> (Trit $a, Trit $b) is equiv(&infix:<*>) { $a min $b }\nsub infix:<∨> (Trit $a, Trit $b) is equiv(&infix:<+>) { $a max $b }\n\nsub infix:<⇒> (Trit $a, Trit $b) is equiv(&infix:<..>) { ¬$a max $b }\nsub infix:<≡> (Trit $a, Trit $b) is equiv(&infix:<eq>) { Trit(1 + ($a-1) * ($b-1)) }\n\n# Testing:\nsay '¬';\nsay \"Too {¬Too}\";\nsay \"Moo {¬Moo}\";\nsay \"Foo {¬Foo}\";\n\nsub tbl (&op,$name) {\n say '';\n say \"$name Too Moo Foo\";\n say \" ╔═══════════\";\n say \"Too║{op Too,Too} {op Too,Moo} {op Too,Foo}\";\n say \"Moo║{op Moo,Too} {op Moo,Moo} {op Moo,Foo}\";\n say \"Foo║{op Foo,Too} {op Foo,Moo} {op Foo,Foo}\";\n}\n\ntbl(&infix:<∧>, '∧');\ntbl(&infix:<∨>, '∨');\ntbl(&infix:<⇒>, '⇒');\ntbl(&infix:<≡>, '≡');\n\nsay '';\nsay 'Precedence tests should all print \"Too\":';\nsay ~(\n Foo ∧ Too ∨ Too ≡ Too,\n Foo ∧ (Too ∨ Too) ≡ Foo,\n Too ∨ Too ∧ Foo ≡ Too,\n (Too ∨ Too) ∧ Foo ≡ Foo,\n\n ¬Too ∧ Too ∨ Too ≡ Too,\n ¬Too ∧ (Too ∨ Too) ≡ ¬Too,\n Too ∨ Too ∧ ¬Too ≡ Too,\n (Too ∨ Too) ∧ ¬Too ≡ ¬Too,\n \n Foo ∧ Too ∨ Foo ⇒ Foo ≡ Too,\n Foo ∧ Too ∨ Too ⇒ Foo ≡ Foo,\n);\n\n```\n\nOutput:\n\n```\n¬\nToo Foo\nMoo Moo\nFoo Too\n\n∧ Too Moo Foo\n ╔═══════════\nToo║Too Moo Foo\nMoo║Moo Moo Foo\nFoo║Foo Foo Foo\n\n∨ Too Moo Foo\n ╔═══════════\nToo║Too Too Too\nMoo║Too Moo Moo\nFoo║Too Moo Foo\n\n⇒ Too Moo Foo\n ╔═══════════\nToo║Too Moo Foo\nMoo║Too Moo Moo\nFoo║Too Too Too\n\n≡ Too Moo Foo\n ╔═══════════\nToo║Too Moo Foo\nMoo║Moo Moo Moo\nFoo║Foo Moo Too\n\nPrecedence tests should all print \"Too\":\nToo Too Too Too Too Too Too Too Too Too\n```" } ]
[ { "role": "user", "content": "Task\n\nUsing a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.\n\nIf your language does not have a testing specific library well known to the language's community then state this or omit the language." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse Test;\n\nsub palin( Str $string) { so $string.lc.comb(/\\w/) eq $string.flip.lc.comb(/\\w/) }\n\nfor\n 'A man, a plan, a canal: Panama.' => True,\n 'My dog has fleas' => False,\n \"Madam, I'm Adam.\" => True,\n '1 on 1' => False,\n 'In girum imus nocte et consumimur igni' => True,\n '' => True\n{\n my ($test, $expected-result) = .kv;\n is palin($test), $expected-result,\n \"\\\"$test\\\" is {$expected-result??''!!'not '}a palindrome.\";\n}\n\ndone-testing;\n\n```\n\nOutput:\n\n```\n1..6\nok 1 - \"1 on 1\" is not a palindrome.\nok 2 - \"My dog has fleas\" is not a palindrome.\nok 3 - \"A man, a plan, a canal: Panama.\" is a palindrome.\nok 4 - \"\" is a palindrome.\nok 5 - \"Madam, I'm Adam.\" is a palindrome.\nok 6 - \"In girum imus nocte et consumimur igni\" is a palindrome.\n```" } ]
[ { "role": "user", "content": "Mathematically,\n\n* the integers **Z** are included in the rational numbers **Q**,\n* which are included in the real numbers **R**,\n* which can be generalized to the complex numbers **C**.\n\nThis means that each of those larger sets, and the data types used to represent them, include some integers.\n\nTask[edit]\n\nGiven a rational, real, or complex number of any type, test whether it is mathematically an integer.\n\nYour code should handle all numeric data types commonly used in your programming language.\n\nDiscuss any limitations of your code.\n\nDefinition\n\nFor the purposes of this task, integerness means that a number could theoretically be represented as an integer at no loss of precision *(given an infinitely wide integer type)*. \nIn other words:\n\n| Set | Common representation | C++ type | Considered an integer... |\n| --- | --- | --- | --- |\n| rational numbers **Q** | fraction | `std::ratio` | ...if its denominator is 1 (in reduced form) |\n| real numbers **Z** *(approximated)* | fixed-point | | ...if it has no non-zero digits after the decimal point |\n| floating-point | `float`, `double` | ...if the number of significant decimal places of its mantissa isn't greater than its exponent |\n| complex numbers **C** | pair of real numbers | `std::complex` | ...if its real part is considered an integer and its imaginary part is zero |\n\nExtra credit\n\nOptionally, make your code accept a `tolerance` parameter for fuzzy testing. The tolerance is the maximum amount by which the number may differ from the nearest integer, to still be considered an integer.\n\nThis is useful in practice, because when dealing with approximate numeric types (such as floating point), there may already be round-off errors from previous calculations. For example, a float value of `0.9999999998` might actually be intended to represent the integer `1`.\n\nTest cases\n\n| Input | | Output | | Comment |\n| --- | --- | --- | --- | --- |\n| Type | Value | exact | tolerance = 0.00001 |\n| decimal | `25.000000` | true | | |\n| `24.999999` | false | true | |\n| `25.000100` | false | | |\n| floating-point | `-2.1e120` | true | | This one is tricky, because in most languages it is too large to fit into a native integer type. It is, nonetheless, mathematically an integer, and your code should identify it as such. |\n| `-5e-2` | false | | |\n| `NaN` | false | | |\n| `Inf` | false | | This one is debatable. If your code considers it an integer, that's okay too. |\n| complex | `5.0+0.0i` | true | | |\n| `5-5i` | false | | |\n\n(The types and notations shown in these tables are merely examples – you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n---" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nIn Raku, all numeric types have a method called narrow, which returns an object with the same value but of the most appropriate type. So we can just check if *that* object is an Int. This works even with floats with large exponents, because the Int type supports arbitrarily large integers.\n\nFor the extra credit task, we can add another multi candidate that checks the distance between the number and it's nearest integer, but then we'll have to handle complex numbers specially.\n\n```\nmulti is-int ($n) { $n.narrow ~~ Int }\n\nmulti is-int ($n, :$tolerance!) {\n abs($n.round - $n) <= $tolerance\n}\n\nmulti is-int (Complex $n, :$tolerance!) {\n is-int($n.re, :$tolerance) && abs($n.im) < $tolerance\n}\n\n# Testing:\n\nfor 25.000000, 24.999999, 25.000100, -2.1e120, -5e-2, Inf, NaN, 5.0+0.0i, 5-5i {\n printf \"%-7s  %-9s  %-5s  %-5s\\n\", .^name, $_,\n is-int($_),\n is-int($_, :tolerance<0.00001>);\n}\n\n```\n\nOutput:\n\n```\nRat 25 True True \nRat 24.999999 False True \nRat 25.0001 False False\nNum -2.1e+120 True True \nNum -0.05 False False\nNum Inf False False\nNum NaN False False\nComplex 5+0i True True \nComplex 5-5i False False\n\n```" } ]
[ { "role": "user", "content": "Task\n\nGet the text in a string that occurs between a start and end delimiter.\nPrograms will be given a search string, a start delimiter string, and an end delimiter string. The delimiters will not be unset, and will not be the empty string.\n\nThe value returned should be the text in the search string that occurs between the **first** occurrence of the start delimiter (starting after the text of the start delimiter) and the **first** occurrence of the end delimiter after that.\n\nIf the start delimiter is not present in the search string, a blank string should be returned.\n\nIf the end delimiter is not present after the end of the first occurrence of the start delimiter in the search string, the remainder of the search string after that point should be returned.\n\nThere are two special values for the delimiters. If the value of the start delimiter is \"start\", the beginning of the search string will be matched. If the value of the end delimiter is \"end\", the end of the search string will be matched.\n\nExample 1. Both delimiters set\n\n```\n Text: \"Hello Rosetta Code world\"\n Start delimiter: \"Hello \"\n End delimiter: \" world\"\n Output: \"Rosetta Code\"\n\n```\n\nExample 2. Start delimiter is the start of the string\n\n```\n Text: \"Hello Rosetta Code world\"\n Start delimiter: \"start\"\n End delimiter: \" world\"\n Output: \"Hello Rosetta Code\"\n\n```\n\nExample 3. End delimiter is the end of the string\n\n```\n Text: \"Hello Rosetta Code world\"\n Start delimiter: \"Hello\"\n End delimiter: \"end\"\n Output: \"Rosetta Code world\"\n\n```\n\nExample 4. End delimiter appears before and after start delimiter\n\n```\n Text: \"</div><div style=\\\"chinese\\\">你好嗎</div>\"\n Start delimiter: \"<div style=\\\"chinese\\\">\"\n End delimiter: \"</div>\"\n Output: \"你好嗎\"\n\n```\n\nExample 5. End delimiter not present\n\n```\n Text: \"<text>Hello <span>Rosetta Code</span> world</text><table style=\\\"myTable\\\">\"\n Start delimiter: \"<text>\"\n End delimiter: \"<table>\"\n Output: \"Hello <span>Rosetta Code</span> world</text><table style=\\\"myTable\\\">\"\n\n```\n\nExample 6. Start delimiter not present\n\n```\n Text: \"<table style=\\\"myTable\\\"><tr><td>hello world</td></tr></table>\"\n Start delimiter: \"<table>\"\n End delimiter: \"</table>\"\n Output: \"\"\n\n```\n\nExample 7. Multiple instances of end delimiter after start delimiter (match until the first one)\n\n```\n Text: \"The quick brown fox jumps over the lazy other fox\"\n Start delimiter: \"quick \"\n End delimiter: \" fox\"\n Output: \"brown\"\n\n```\n\nExample 8. Multiple instances of the start delimiter (start matching at the first one)\n\n```\n Text: \"One fish two fish red fish blue fish\"\n Start delimiter: \"fish \"\n End delimiter: \" red\"\n Output: \"two fish\"\n\n```\n\nExample 9. Start delimiter is end delimiter\n\n```\n Text: \"FooBarBazFooBuxQuux\"\n Start delimiter: \"Foo\"\n End delimiter: \"Foo\"\n Output: \"BarBaz\"\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.12\n\nIt seems somewhat pointless to write a special purpose routine to do text matching as built-in primitives can do so more flexibly and concisely, but whatever.\n\nThis version doesn't use strings for meta indexes ('start' and 'end'), rather it accepts regex assertions which are parsed differently from strings. This allows much more robust and fine grained control over what does and doesn't match. (and allows delimiter strings of 'start' and 'end' incidentally.) See the 11th example below which will confound nearly all of the current string-only based implementations.\n\n```\nsub text-between ( $text, $start, $end ) {\n return $/»[0]».Str if $text ~~ m:g/ $start (.*?) $end /;\n []\n}\n\n# Testing\nmy $text = 'Hello Rosetta Code world';\n\n# String start and end delimiter\nput '1> ', $text.&text-between( 'Hello ', ' world' );\n\n# Regex string start delimiter\nput '2> ', $text.&text-between( rx/^/, ' world' );\n\n# Regex string end delimiter\nput '3> ', $text.&text-between( 'Hello ', rx/$/ );\n\n# End delimiter only valid after start delimiter\nput '4> ', '</div><div style=\"chinese\">你好嗎</div>'\\\n .&text-between( '<div style=\"chinese\">', '</div>' );\n\n# End delimiter not found, default to string end\nput '5> ', '<text>Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">'\\\n .&text-between( '<text>', rx/'<table>' | $/ );\n\n# Start delimiter not found, return blank string\nput '6> ', '<table style=\"myTable\"><tr><td>hello world</td></tr></table>'\\\n .&text-between( '<table>', '</table>' );\n\n# Multiple end delimiters, match frugally\nput '7> ', 'The quick brown fox jumps over the lazy other fox'\\\n .&text-between( 'quick ', ' fox' );\n\n# Multiple start delimiters, match frugally\nput '8> ', 'One fish two fish red fish blue fish'\\\n .&text-between( 'fish ', ' red' );\n\n# Start delimiter is end delimiter\nput '9> ', 'FooBarBazFooBuxQuux'\\\n .&text-between( 'Foo', 'Foo' );\n\n# Return all matching strings when multiple matches are possible\nput '10> ', join ',', $text.&text-between( 'e', 'o' );\n\n# Ignore start and end delimiter string embedded in longer words\nput '11> ', 'Soothe a guilty conscience today, string wrangling is not the best tool to use for this job.'\\\n .&text-between( rx/«'the '/, rx/' to'»/ );\n\n```\n\nOutput:\n\n```\n1> Rosetta Code\n2> Hello Rosetta Code\n3> Rosetta Code world\n4> 你好嗎\n5> Hello <span>Rosetta Code</span> world</text><table style=\"myTable\">\n6> \n7> brown\n8> two fish\n9> BarBaz\n10> ll,tta C, w\n11> best tool\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program that takes in a user inputted word and prints out possible words that are valid in the English dictionary.\nPlease state any dictionaries or files/binaries/dependencies used in your program. Do show the similarity of the inputted word and outcome as a percentage. Any algorithm can be used to accomplish this task.\n\nResources\n\nGithub Repo \nRaw Text, Save as .txt file \nHamming Distance \nJaro-Winkler Distance \nSoundEx Algorithm \nSoundEx Algorithm Wiki \nDice's Coefficient \nDice Coefficient Wiki\n\nPossible Output\n\n```\nInput word: \ncomplition\n\ncompaction : 80.00% similar.\ncompletion : 90.00% similar.\ncompletions : 81.82% similar.\ncomplexion : 80.00% similar.\n\n```\n\nExtension\n\n1. How can you make the accuracy of your program higher?" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Hamming distance\n\n**Translation of**: Java\n\n```\nsub MAIN ( Str $user_word = 'complition', Str $filename = 'words.txt' ) {\n my @s1 = $user_word.comb;\n my @listed = gather for $filename.IO.lines -> $line {\n my @s2 = $line.comb;\n\n my $correct = 100 * sum( @s1 Zeq @s2)\n / max(+@s1, +@s2);\n\n my $score = ( $correct >= 100 and @s1[0] eq @s2[0] ) ?? 100\n  !! ( $correct >= 80 and @s1[0] eq @s2[0] ) ?? $correct\n  !! ( $line.contains($user_word) and @s1 * 2 > @s2 ) ?? 80\n  !! 0;\n take [$score, $line] if $score;\n }\n\n @listed = @listed[$_] with @listed.first: :k, { .[0] == 100 };\n\n say \"{.[0].fmt('%.2f')}% {.[1]}\" for @listed;\n}\n\n```\n\nOutput:\n\n```\n80.00% compaction\n90.00% completion\n81.82% completions\n80.00% complexion\n\n```\n\n### Sorenson-Dice\n\nSorenson-Dice tends to return relatively low percentages even for small differences, especially for short words. We need to \"lower the bar\" to get any results at all. Different variations of the algorithm do or don't regularize case. This one does, though it doesn't much matter for the tested words.\n\nUsing unixdict.txt from www.puzzlers.org\n\n```\nsub sorenson ($phrase, %hash) {\n my $match = bigram $phrase;\n %hash.race.map: { [(2 * ($match ∩ .value) / ($match + .value)).round(.001), .key] }\n}\n\nsub bigram (\\these) { Bag.new( flat these.fc.words.map: { .comb.rotor(2 => -1)».join } ) }\n\n# Load the dictionary\nmy %hash = './unixdict.txt'.IO.slurp.words.race.map: { $_ => .&bigram };\n\n# Testing\nfor <complition inconsqual Sørenson> -> $w {\n say \"\\n$w:\";\n .say for sorenson($w, %hash).grep(*.[0] >= .55).sort({-.[0],~.[1]}).head(10);\n}\n\n```\n\nOutput:\n\n```\ncomplition:\n[0.778 completion]\n[0.737 competition]\n[0.737 composition]\n[0.706 coalition]\n[0.7 incompletion]\n[0.667 complexion]\n[0.667 complicity]\n[0.667 decomposition]\n[0.632 compilation]\n[0.632 compunction]\n\ninconsqual:\n[0.609 inconsequential]\n[0.588 continual]\n[0.571 squall]\n[0.556 conceptual]\n[0.556 inconstant]\n\nSørenson:\n[0.714 sorenson]\n[0.667 benson]\n[0.615 swenson]\n[0.571 evensong]\n[0.571 sorensen]\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\nOften data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term \"Data Munging\" is often used in programming circles for this task.\n\nA request on the comp.lang.awk newsgroup led to a typical data munging task:\n\n```\nI have to analyse data files that have the following format:\nEach row corresponds to 1 day and the field logic is: $1 is the date,\nfollowed by 24 value/flag pairs, representing measurements at 01:00,\n02:00 ... 24:00 of the respective day. In short:\n\n<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>\n\nSome test data is available at: \n... (nolonger available at original location)\n\nI have to sum up the values (per day and only valid data, i.e. with\nflag>0) in order to calculate the mean. That's not too difficult.\nHowever, I also need to know what the \"maximum data gap\" is, i.e. the\nlongest period with successive invalid measurements (i.e values with\nflag<=0)\n```\n\nThe data is free to download and use and is of this format:\n\nData is no longer available at that link. Zipped mirror available here (offsite mirror).\n\n```\n1991-03-30\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\n1991-03-31\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t35.000\t1\t50.000\t1\t60.000\t1\t40.000\t1\t30.000\t1\t30.000\t1\t30.000\t1\t25.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t35.000\t1\n1991-03-31\t40.000\t1\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\n1991-04-01\t0.000\t-2\t13.000\t1\t16.000\t1\t21.000\t1\t24.000\t1\t22.000\t1\t20.000\t1\t18.000\t1\t29.000\t1\t44.000\t1\t50.000\t1\t43.000\t1\t38.000\t1\t27.000\t1\t27.000\t1\t24.000\t1\t23.000\t1\t18.000\t1\t12.000\t1\t13.000\t1\t14.000\t1\t15.000\t1\t13.000\t1\t10.000\t1\n1991-04-02\t8.000\t1\t9.000\t1\t11.000\t1\t12.000\t1\t12.000\t1\t12.000\t1\t27.000\t1\t26.000\t1\t27.000\t1\t33.000\t1\t32.000\t1\t31.000\t1\t29.000\t1\t31.000\t1\t25.000\t1\t25.000\t1\t24.000\t1\t21.000\t1\t17.000\t1\t14.000\t1\t15.000\t1\t12.000\t1\t12.000\t1\t10.000\t1\n1991-04-03\t10.000\t1\t9.000\t1\t10.000\t1\t10.000\t1\t9.000\t1\t10.000\t1\t15.000\t1\t24.000\t1\t28.000\t1\t24.000\t1\t18.000\t1\t14.000\t1\t12.000\t1\t13.000\t1\t14.000\t1\t15.000\t1\t14.000\t1\t15.000\t1\t13.000\t1\t13.000\t1\t13.000\t1\t12.000\t1\t10.000\t1\t10.000\t1\n\n```\n\nOnly a sample of the data showing its format is given above. The full example file may be downloaded here.\n\nStructure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @gaps;\nmy $previous = 'valid';\n\nfor $*IN.lines -> $line { \n my ($date, @readings) = split /\\s+/, $line;\n my @valid;\n my $hour = 0;\n for @readings -> $reading, $flag {\n if $flag > 0 { \n @valid.push($reading);\n if $previous eq 'invalid' {\n @gaps[*-1]{'end'} = \"$date $hour:00\";\n $previous = 'valid';\n }\n } \n else\n {\n if $previous eq 'valid' {\n @gaps.push( {start => \"$date $hour:00\"} );\n }\n @gaps[*-1]{'count'}++;\n $previous = 'invalid';\n }\n $hour++;\n }\n say \"$date: { ( +@valid ?? ( ( [+] @valid ) / +@valid ).fmt(\"%.3f\") !! 0 ).fmt(\"%8s\") }\",\n \" mean from { (+@valid).fmt(\"%2s\") } valid.\"; \n};\n\nmy $longest = @gaps.sort({-$^a<count>})[0];\n\nsay \"Longest period of invalid readings was {$longest<count>} hours,\\n\",\n \"from {$longest<start>} till {$longest<end>}.\"\n\n```\n\nOutput:\n\n```\n1990-01-01: 26.818 mean from 22 valid.\n1990-01-02: 17.083 mean from 24 valid.\n1990-01-03: 58.958 mean from 24 valid.\n1990-01-04: 75.000 mean from 24 valid.\n1990-01-05: 47.083 mean from 24 valid.\n...\n(many lines omitted)\n...\n2004-12-27: 2.483 mean from 23 valid.\n2004-12-28: 3.383 mean from 23 valid.\n2004-12-29: 2.448 mean from 23 valid.\n2004-12-30: 2.839 mean from 23 valid.\n2004-12-31: 2.057 mean from 23 valid.\nLongest period of invalid readings was 589 hours,\nfrom 1993-02-09 1:00 till 1993-03-05 14:00.\n\n```" } ]
[ { "role": "user", "content": "The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.\n\nThe fields (from the left) are:\n\n```\n DATESTAMP [ VALUEn FLAGn ] * 24\n\n```\n\ni.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.\n\nA sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:\n\nData is no longer available at that link. Zipped mirror available here\n\n```\n1991-03-30\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\n1991-03-31\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t10.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t35.000\t1\t50.000\t1\t60.000\t1\t40.000\t1\t30.000\t1\t30.000\t1\t30.000\t1\t25.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t20.000\t1\t35.000\t1\n1991-03-31\t40.000\t1\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\t0.000\t-2\n1991-04-01\t0.000\t-2\t13.000\t1\t16.000\t1\t21.000\t1\t24.000\t1\t22.000\t1\t20.000\t1\t18.000\t1\t29.000\t1\t44.000\t1\t50.000\t1\t43.000\t1\t38.000\t1\t27.000\t1\t27.000\t1\t24.000\t1\t23.000\t1\t18.000\t1\t12.000\t1\t13.000\t1\t14.000\t1\t15.000\t1\t13.000\t1\t10.000\t1\n1991-04-02\t8.000\t1\t9.000\t1\t11.000\t1\t12.000\t1\t12.000\t1\t12.000\t1\t27.000\t1\t26.000\t1\t27.000\t1\t33.000\t1\t32.000\t1\t31.000\t1\t29.000\t1\t31.000\t1\t25.000\t1\t25.000\t1\t24.000\t1\t21.000\t1\t17.000\t1\t14.000\t1\t15.000\t1\t12.000\t1\t12.000\t1\t10.000\t1\n1991-04-03\t10.000\t1\t9.000\t1\t10.000\t1\t10.000\t1\t9.000\t1\t10.000\t1\t15.000\t1\t24.000\t1\t28.000\t1\t24.000\t1\t18.000\t1\t14.000\t1\t12.000\t1\t13.000\t1\t14.000\t1\t15.000\t1\t14.000\t1\t15.000\t1\t13.000\t1\t13.000\t1\t13.000\t1\t12.000\t1\t10.000\t1\t10.000\t1\n\n```\n\nTask\n\n1. Confirm the general field format of the file.\n2. Identify any DATESTAMPs that are duplicated.\n3. Report the number of records that have good readings for all instruments." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n**Works with**: Rakudo version 2018.03\n\nThis version does validation with a single Raku regex that is much more readable than the typical regex, and arguably expresses the data structure more straightforwardly.\nHere we use normal quotes for literals, and \\h for horizontal whitespace.\n\nVariables like $good-record that are going to be autoincremented do not need to be initialized.\n\nThe .push method on a hash is magical and loses no information; if a duplicate key is found in the pushed pair, an array of values is automatically created of the old value and the new value pushed. Hence we can easily track all the lines that a particular duplicate occurred at.\n\nThe .all method does \"junctional\" logic: it autothreads through comparators as any English speaker would expect. Junctions can also short-circuit as soon as they find a value that doesn't match, and the evaluation order is up to the computer, so it can be optimized or parallelized.\n\nThe final line simply greps out the pairs from the hash whose value is an array with more than 1 element. (Those values that are not arrays nevertheless have a .elems method that always reports 1.) The .pairs is merely there for clarity; grepping a hash directly has the same effect.\nNote that we sort the pairs after we've grepped them, not before; this works fine in Raku, sorting on the key and value as primary and secondary keys. Finally, pairs and arrays provide a default print format that is sufficient without additional formatting in this case.\n\n```\nmy $good-records;\nmy $line;\nmy %dates;\n\nfor lines() {\n $line++;\n / ^\n (\\d ** 4 '-' \\d\\d '-' \\d\\d)\n [ \\h+ \\d+'.'\\d+ \\h+ ('-'?\\d+) ] ** 24\n $ /\n or note \"Bad format at line $line\" and next;\n %dates.push: $0 => $line;\n $good-records++ if $1.all >= 1;\n}\n\nsay \"$good-records good records out of $line total\";\n\nsay 'Repeated timestamps (with line numbers):';\n.say for sort %dates.pairs.grep: *.value.elems > 1;\n\n```\n\nOutput:\n\n```\n5017 good records out of 5471 total\nRepeated timestamps (with line numbers):\n1990-03-25 => [84 85]\n1991-03-31 => [455 456]\n1992-03-29 => [819 820]\n1993-03-28 => [1183 1184]\n1995-03-26 => [1910 1911]\n```" } ]
[ { "role": "user", "content": "A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.\n\nAssume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.\n\nAn example of checkout and checkin events are:\n\n```\n License OUT @ 2008/10/03_23:51:05 for job 4974\n ...\n License IN @ 2008/10/04_00:18:22 for job 4974\n\n```\n\nTask\n\nSave the 10,000 line log file from   here   into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.\n\nMirror of log file available as a zip here (offsite mirror)." }, { "role": "assistant", "content": "(formerly Perl 6)\nAdd some error trapping as recommended by Dijkstra. Not particularly necessary for this specific example but it doesn't hurt to be proactive.\n\nRedirecting the mlijobs.txt file to STDIN:\n\n```\nmy %licenses;\n\n%licenses<count max> = 0,0;\n\nfor $*IN.lines -> $line {\n my ( $license, $date_time );\n ( *, $license, *, $date_time ) = split /\\s+/, $line;\n if $license eq 'OUT' {\n %licenses<count>++;\n if %licenses<count> > %licenses<max> {\n %licenses<max> = %licenses<count>;\n %licenses<times> = [$date_time];\n }\n elsif %licenses<count> == %licenses<max> {\n %licenses<times>.push($date_time);\n }\n }\n elsif $license eq 'IN' {\n if %licenses<count> == %licenses<max> {\n %licenses<times>[*-1] ~= \" through \" ~ $date_time;\n }\n %licenses<count>--;\n }\n else {\n # Not a licence OUT or IN event, do nothing\n }\n};\n\nmy $plural = %licenses<times>.elems == 1 ?? '' !! 's';\n\nsay \"Maximum concurrent licenses in use: {%licenses<max>}, in the time period{$plural}:\";\nsay join \",\\n\", %licenses<times>.list;\n\n```\n\nExample output:\n\n```\nMaximum concurrent licenses in use: 99, in the time periods:\n2008/10/03_08:39:34 through 2008/10/03_08:39:45,\n2008/10/03_08:40:40 through 2008/10/03_08:40:47\n\n```" } ]
[ { "role": "user", "content": "When developing a Website it is occasionally necessary to handle text that is received without formatting, and present it in a pleasing manner. to achieve this the text needs to be converted to HTML.\n\nWrite a converter from plain text to HTML.\n\nThe plain text has no formatting information.\n\nIt may have centered headlines, numbered sections, paragraphs, lists, and URIs. It could even have tables.\n\nSimple converters restrict themselves at identifying paragraphs, but i believe more can be done if the text is analyzed.\n\nYou are not requested to copy the algorithm from the existing solutions but use whatever faculties available in your language to best solve the problem.\n\nThe only requirement is to ensure that the result is valid xhtml." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\nThe task specs are essentially non-existent. \"Make a best guess at how to render mark-up free text\"? Anything that could be trusted at all would either be extremely trivial or insanely complex. And it shows by the the task example writers staying away in droves. Five examples after seven years!?\n\nRather than waste time on that noise, I'll demonstrate POD6 to HTML conversion. POD6 is a simple, text-only mark-up used for Raku documentation. (It's Plain Old Documentation for Raku) It uses pretty simple textual markup and has multiple tools to convert the POD6 document in to many other formats, HTML among them.\n\nIt is **not** markup free, but it is actually usable in production.\n\n```\nuse Pod::To::HTML;\nuse HTML::Escape;\n\nmy $pod6 = q:to/POD6/;\n=begin pod\n\nA very simple Pod6 document.\n\nThis is a very high-level, hand-wavey overview. There are I<lots> of other\noptions available.\n\n=head1 Section headings\n\n=head1 A top level heading\n\n=head2 A second level heading\n\n=head3 A third level heading\n\n=head4 A fourth level heading\n\n=head1 Text\n\nOrdinary paragraphs do not require an explicit marker or delimiters.\n\nAlternatively, there is also an explicit =para marker that can be used to\nexplicitly mark a paragraph.\n\n=para\nThis is an ordinary paragraph.\nIts text will be squeezed and\nshort lines filled.\n\n=head1 Code\n\nEnclose code in a =code block (or V<C< >> markup for short, inline samples)\n\n=begin code\n my $name = 'Rakudo';\n say $name;\n=end code\n\n=head1 Lists\n\n=head3 Unordered lists\n\n=item Grumpy\n=item Dopey\n=item Doc\n=item Happy\n=item Bashful\n=item Sneezy\n=item Sleepy\n\n=head3 Multi-level lists\n\n=item1 Animal\n=item2 Vertebrate\n=item2 Invertebrate\n\n=item1 Phase\n=item2 Solid\n=item2 Liquid\n=item2 Gas\n\n=head1 Formatting codes\n\nFormatting codes provide a way to add inline mark-up to a piece of text.\n\nAll Pod6 formatting codes consist of a single capital letter followed\nimmediately by a set of single or double angle brackets; Unicode double angle\nbrackets may be used.\n\nFormatting codes may nest other formatting codes.\n\nThere are many formatting codes available, some of the more common ones:\n\n=item1 V<B< >> Bold\n=item1 V<I< >> Italic\n=item1 V<U< >> Underline\n=item1 V<C< >> Code\n=item1 V<L< >> Hyperlink\n=item1 V<V< >> Verbatim (Don't interpret anything inside as POD markup)\n\n=head1 Tables\n\nThere is quite extensive markup to allow rendering tables.\n\nA simple example:\n\n=begin table :caption<Mystery Men>\n The Shoveller Eddie Stevens King Arthur's singing shovel\n Blue Raja Geoffrey Smith Master of cutlery\n Mr Furious Roy Orson Ticking time bomb of fury\n The Bowler Carol Pinnsler Haunted bowling ball\n=end table\n\n=end pod\nPOD6\n\n# for display on Rosettacode\nsay escape-html render($pod6);\n\n# normally\n#say render($pod6);\n\n```\n\nReturns something like:\n\n```\n<!doctype html>\n<html lang=\"en\">\n <head>\n <title></title>\n <meta charset=\"UTF-8\" />\n <style>\n kbd { font-family: \"Droid Sans Mono\", \"Luxi Mono\", \"Inconsolata\", monospace }\n samp { font-family: \"Terminus\", \"Courier\", \"Lucida Console\", monospace }\n u { text-decoration: none }\n .nested {\n margin-left: 3em;\n }\n aside, u { opacity: 0.7 }\n a[id^=\"fn-\"]:target { background: #ff0 }\n </style>\n <link rel=\"stylesheet\" href=\"//design.raku.org/perl.css\">\n\n </head>\n <body class=\"pod\">\n <div id=\"___top\"></div>\n\n <nav class=\"indexgroup\">\n<table id=\"TOC\">\n<caption><h2 id=\"TOC_Title\">Table of Contents</h2></caption>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">1</td><td class=\"toc-text\"><a href=\"#Section_headings\">Section headings</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">2</td><td class=\"toc-text\"><a href=\"#A_top_level_heading\">A top level heading</a></td></tr>\n <tr class=\"toc-level-2\"><td class=\"toc-number\">2.1</td><td class=\"toc-text\"><a href=\"#A_second_level_heading\">A second level heading</a></td></tr>\n <tr class=\"toc-level-3\"><td class=\"toc-number\">2.1.1</td><td class=\"toc-text\"><a href=\"#A_third_level_heading\">A third level heading</a></td></tr>\n <tr class=\"toc-level-4\"><td class=\"toc-number\">2.1.1.1</td><td class=\"toc-text\"><a href=\"#A_fourth_level_heading\">A fourth level heading</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">3</td><td class=\"toc-text\"><a href=\"#Text\">Text</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">4</td><td class=\"toc-text\"><a href=\"#Code\">Code</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">5</td><td class=\"toc-text\"><a href=\"#Lists\">Lists</a></td></tr>\n <tr class=\"toc-level-3\"><td class=\"toc-number\">5.0.1</td><td class=\"toc-text\"><a href=\"#Unordered_lists\">Unordered lists</a></td></tr>\n <tr class=\"toc-level-3\"><td class=\"toc-number\">5.0.2</td><td class=\"toc-text\"><a href=\"#Multi-level_lists\">Multi-level lists</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">6</td><td class=\"toc-text\"><a href=\"#Formatting_codes\">Formatting codes</a></td></tr>\n <tr class=\"toc-level-1\"><td class=\"toc-number\">7</td><td class=\"toc-text\"><a href=\"#Tables\">Tables</a></td></tr>\n \n</table>\n</nav>\n\n <div class=\"pod-body\">\n <p>A very simple Pod6 document.</p>\n<p>This is a very high-level, hand-wavey overview. There are <em>lots</em> of other options available.</p>\n<h1 id=\"Section_headings\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Section headings</a></h1>\n<h1 id=\"A_top_level_heading\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">A top level heading</a></h1>\n<h2 id=\"A_second_level_heading\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">A second level heading</a></h2>\n<h3 id=\"A_third_level_heading\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">A third level heading</a></h3>\n<h4 id=\"A_fourth_level_heading\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">A fourth level heading</a></h4>\n<h1 id=\"Text\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Text</a></h1>\n<p>Ordinary paragraphs do not require an explicit marker or delimiters.</p>\n<p>Alternatively, there is also an explicit =para marker that can be used to explicitly mark a paragraph.</p>\n<p>This is an ordinary paragraph. Its text will be squeezed and short lines filled.</p>\n<h1 id=\"Code\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Code</a></h1>\n<p>Enclose code in a =code block (or C&lt; &gt; markup for short, inline samples)</p>\n<pre class=\"pod-block-code\"> my $name = &#39;Rakudo&#39;;\n say $name;\n</pre>\n<h1 id=\"Lists\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Lists</a></h1>\n<h3 id=\"Unordered_lists\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Unordered lists</a></h3>\n<ul><li><p>Grumpy</p>\n</li>\n<li><p>Dopey</p>\n</li>\n<li><p>Doc</p>\n</li>\n<li><p>Happy</p>\n</li>\n<li><p>Bashful</p>\n</li>\n<li><p>Sneezy</p>\n</li>\n<li><p>Sleepy</p>\n</li>\n</ul>\n<h3 id=\"Multi-level_lists\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Multi-level lists</a></h3>\n<ul><li><p>Animal</p>\n</li>\n<ul><li><p>Vertebrate</p>\n</li>\n<li><p>Invertebrate</p>\n</li>\n</ul>\n<li><p>Phase</p>\n</li>\n<ul><li><p>Solid</p>\n</li>\n<li><p>Liquid</p>\n</li>\n<li><p>Gas</p>\n</li>\n</ul>\n</ul>\n<h1 id=\"Formatting_codes\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Formatting codes</a></h1>\n<p>Formatting codes provide a way to add inline mark-up to a piece of text.</p>\n<p>All Pod6 formatting codes consist of a single capital letter followed immediately by a set of single or double angle brackets; Unicode double angle brackets may be used.</p>\n<p>Formatting codes may nest other formatting codes.</p>\n<p>There are many formatting codes available, some of the more common ones:</p>\n<ul><li><p>B&lt; &gt; Bold</p>\n</li>\n<li><p>I&lt; &gt; Italic</p>\n</li>\n<li><p>U&lt; &gt; Underline</p>\n</li>\n<li><p>C&lt; &gt; Code</p>\n</li>\n<li><p>L&lt; &gt; Hyperlink</p>\n</li>\n<li><p>V&lt; &gt; Verbatim (Don&#39;t interpret anything inside as POD markup)</p>\n</li>\n</ul>\n<h1 id=\"Tables\"><a class=\"u\" href=\"#___top\" title=\"go to top of document\">Tables</a></h1>\n<p>There is quite extensive markup to allow rendering tables.</p>\n<p>A simple example:</p>\n<table class=\"pod-table\">\n<caption>Mystery Men</caption>\n<tbody>\n<tr> <td>The Shoveller</td> <td>Eddie Stevens</td> <td>King Arthur&#39;s singing shovel</td> </tr> <tr> <td>Blue Raja</td> <td>Geoffrey Smith</td> <td>Master of cutlery</td> </tr> <tr> <td>Mr Furious</td> <td>Roy Orson</td> <td>Ticking time bomb of fury</td> </tr> <tr> <td>The Bowler</td> <td>Carol Pinnsler</td> <td>Haunted bowling ball</td> </tr>\n</tbody>\n</table>\n </div>\n\n </body>\n</html>\n```" } ]
[ { "role": "user", "content": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n\n```\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n```\n\nTask\n\nWrite a program that finds textonyms in a list of words such as  \nTextonyms/wordlist   or  \nunixdict.txt.\n\nThe task should produce a report:\n\n```\nThere are #{0} words in #{1} which can be represented by the digit key mapping.\nThey require #{2} digit combinations to represent them.\n#{3} digit combinations represent Textonyms.\n\n```\n\nWhere:\n\n```\n#{0} is the number of words in the list which can be represented by the digit key mapping.\n#{1} is the URL of the wordlist being used.\n#{2} is the number of digit combinations required to represent the words in #{0}.\n#{3} is the number of #{2} which represent more than one word.\n\n```\n\nAt your discretion show a couple of examples of your solution displaying Textonyms.\n\nE.G.:\n\n```\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n```\n\nExtra credit\n\nUse a word list and keypad mapping other than English.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $src = 'unixdict.txt';\n\nmy @words = slurp($src).lines.grep(/ ^ <alpha>+ $ /);\n\nmy @dials = @words.classify: {\n .trans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n => '2223334445556667777888999922233344455566677778889999');\n}\n\nmy @textonyms = @dials.grep(*.value > 1);\n\nsay qq:to 'END';\n There are {+@words} words in $src which can be represented by the digit key mapping.\n They require {+@dials} digit combinations to represent them.\n {+@textonyms} digit combinations represent Textonyms.\n END\n\nsay \"Top 5 in ambiguity:\";\nsay \" \",$_ for @textonyms.sort(-*.value)[^5];\n\nsay \"\\nTop 5 in length:\";\nsay \" \",$_ for @textonyms.sort(-*.key.chars)[^5];\n\n```\n\nOutput:\n\n```\nThere are 24978 words in unixdict.txt which can be represented by the digit key mapping.\nThey require 22903 digit combinations to represent them.\n1473 digit combinations represent Textonyms.\n\nTop 5 in ambiguity:\n 269 => amy any bmw bow box boy cow cox coy\n 729 => paw pax pay paz raw ray saw sax say\n 2273 => acre bard bare base cape card care case\n 726 => pam pan ram ran sam san sao scm\n 426 => gam gao ham han ian ibm ibn\n\nTop 5 in length:\n 25287876746242 => claustrophobia claustrophobic\n 7244967473642 => schizophrenia schizophrenic\n 666628676342 => onomatopoeia onomatopoeic\n 49376746242 => hydrophobia hydrophobic\n 2668368466 => contention convention\n```" } ]
[ { "role": "user", "content": "ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming and scripting languages.\nIt is also simple and succinct, using as it does just two 256-word arrays for its state.\n\nISAAC stands for \"Indirection, Shift, Accumulate, Add, and Count\" which are the principal bitwise operations employed.\nTo date - and that's after more than 20 years of existence - ISAAC has not been broken (unless GCHQ or NSA did it, but they wouldn't be telling).\nISAAC thus deserves a lot more attention than it has hitherto received and it would be salutary to see it more universally implemented.\n\nTask\n\nTranslate ISAAC's reference C or Pascal code into your language of choice.\n\nThe RNG should then be seeded with the string \"this is my secret key\" and\nfinally the message \"a Top Secret secret\" should be encrypted on that key.\nYour program's output cipher-text will be a string of hexadecimal digits.\n\nOptional: Include a decryption check by re-initializing ISAAC and performing\nthe same encryption pass on the cipher-text.\n\nPlease use the C or Pascal as a reference guide to these operations.\n\nTwo encryption schemes are possible:\n(1) XOR (Vernam) or\n(2) Caesar-shift mod 95 (Vigenère).\nXOR is the simplest; C-shifting offers greater security.\n\nYou may choose either scheme, or both, but please specify which you used.\nHere are the alternative sample outputs for checking purposes:\n\n```\nMessage: a Top Secret secret\nKey  : this is my secret key\nXOR  : 1C0636190B1260233B35125F1E1D0E2F4C5422\nMOD  : 734270227D36772A783B4F2A5F206266236978\nXOR dcr: a Top Secret secret\nMOD dcr: a Top Secret secret\n\n```\n\nNo official seeding method for ISAAC has been published, but for this task\nwe may as well just inject the bytes of our key into the randrsl array,\npadding with zeroes before mixing, like so:\n\n```\n// zeroise mm array\nFOR i:= 0 TO 255 DO mm[i]:=0;\n// check seed's highest array element\nm := High(seed);\n// inject the seed\nFOR i:= 0 TO 255 DO BEGIN\n\t// in case seed[] has less than 256 elements.\n\tIF i>m THEN randrsl[i]:=0 \n\t\tELSE randrsl[i]:=seed[i];\nEND;\n// initialize ISAAC with seed\nRandInit(true);\n\n```\n\nISAAC can of course also be initialized with a single 32-bit unsigned integer in the manner of traditional RNGs, and indeed used as such for research and gaming purposes.\nBut building a strong and simple ISAAC-based stream cipher - replacing the irreparably broken RC4 - is our goal here: ISAAC's intended purpose." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy uint32 (@mm, @randrsl, $randcnt, $aa, $bb, $cc);\nmy \\ϕ := 2654435769; constant MOD = 95; constant START = 32;\n\nconstant MAXINT = uint.Range.max;\nenum CipherMode < ENCIPHER DECIPHER NONE >;\n\nsub mix (\\n) {\n sub mix1 (\\i, \\v) { \n n[i] +^= v; \n n[(i+3)%8] += n[i];\n n[(i+1)%8] += n[(i+2)%8];\n } \n mix1 0, n[1]+<11; mix1 1, n[2]+>2; mix1 2, n[3]+<8; mix1 3, n[4]+>16;\n mix1 4, n[5]+<10; mix1 5, n[6]+>4; mix1 6, n[7]+<8; mix1 7, n[0]+>9 ;\n}\n\nsub randinit(\\flag) {\n $aa = $bb = $cc = 0;\n my uint32 @n = [^8].map({ ϕ });\n for ^4 { mix @n }; \n for 0,8 … 255 -> $i { \n { for (0..7) { @n[$^j] += @randrsl[$i + $^j] } } if flag; \n mix @n;\n for (0..7) { @mm[$i + $^j] = @n[$^j] }\n } \n if flag {\n for 0,8 … 255 -> $i {\n for ^8 { @n[$^j] += @mm[$i + $^j] };\n mix @n;\n for ^8 { @mm[$i + $^j] = @n[$^j] };\n }\n }\n isaac; \n $randcnt = 0; \n}\n\nsub isaac() {\n $cc++; \n $bb += $cc; \n for ^256 -> $i {\n my $x = @mm[$i];\n given ($i % 4) {\n when 0 { $aa +^= ($aa +< 13) }\n when 1 { $aa +^= (($aa +& MAXINT) +> 6) }\n when 2 { $aa +^= ($aa +< 2) }\n when 3 { $aa +^= (($aa +& MAXINT) +> 16) }\n }\n $aa += @mm[($i + 128) % 256];\n my $y = @mm[(($x +& MAXINT) +> 2) % 256] + $aa + $bb;\n @mm[$i] = $y;\n $bb = @mm[(($y +& MAXINT) +> 10) % 256] + $x;\n @randrsl[$i] = $bb;\n }\n $randcnt = 0;\n}\n\nsub iRandom {\n my $result = @randrsl[$randcnt++];\n if ($randcnt > 255) {\n isaac;\n $randcnt = 0;\n }\n return $result;\n}\n\nsub iSeed(\\seed, \\flag) {\n @mm = [^256].race.map({0});\n my \\m = seed.chars;\n @randrsl = [^256].hyper.map({ $^i ≥ m ?? 0 !! seed.substr($^i,1).ord });\n randinit(flag);\n}\n\nsub iRandA { return iRandom() % MOD + START };\n\nsub vernam(\\M) { ( map { (iRandA() +^ .ord ).chr }, M.comb ).join };\n \nsub caesar(CipherMode \\m, \\ch, $shift is copy, \\Modulo, \\Start) {\n $shift = -$shift if m == DECIPHER; \n my $n = (ch.ord - Start) + $shift; \n $n %= Modulo;\n $n += Modulo if $n < 0;\n return (Start + $n).chr;\n}\n\nsub caesarStr(CipherMode \\m, \\msg, \\Modulo, \\Start) {\n my $sb = '';\n for msg.comb {\n $sb ~= caesar m, $^c, iRandA(), Modulo, Start;\n }\n return $sb;\n}\n \nmulti MAIN () { \n my \\msg = \"a Top Secret secret\";\n my \\key = \"this is my secret key\";\n \n iSeed key, True ;\n my $vctx = vernam msg;\n my $cctx = caesarStr ENCIPHER, msg, MOD, START;\n\n iSeed key, True ;\n my $vptx = vernam $vctx;\n my $cptx = caesarStr DECIPHER, $cctx, MOD, START;\n\n my $vctx2hex = ( map { .ord.fmt('%02X') }, $vctx.comb ).join(''); \n my $cctx2hex = ( map { .ord.fmt('%02X') }, $cctx.comb ).join('');\n\n say \"Message : \", msg;\n say \"Key  : \", key;\n say \"XOR  : \", $vctx2hex;\n say \"XOR dcr : \", $vptx;\n say \"MOD  : \", $cctx2hex;\n say \"MOD dcr : \", $cptx;\n}\n\n```\n\nOutput:\n\n```\nMessage : a Top Secret secret\nKey  : this is my secret key\nXOR  : 1C0636190B1260233B35125F1E1D0E2F4C5422\nXOR dcr : a Top Secret secret\nMOD  : 734270227D36772A783B4F2A5F206266236978\nMOD dcr : a Top Secret secret\n\n```" } ]
[ { "role": "user", "content": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n```\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\n```\n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n```\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\n```\n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n```\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n```\n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n```\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\n```\n\nFor the name 'Felix', this would be right:\n\n```\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nMeh. The rules leave out some corner cases (see Steve) but what the heck, technically correct is the best kind of correct.\n\n```\nsub mangle ($name, $initial) {\n my $fl = $name.lc.substr(0,1);\n $fl ~~ /<[aeiou]>/\n  ?? $initial~$name.lc\n  !! $fl eq $initial\n  ?? $name.substr(1)\n  !! $initial~$name.substr(1)\n}\n\nsub name-game (Str $name) {\n qq:to/NAME-GAME/;\n $name, $name, bo-{ mangle $name, 'b' }\n Banana-fana fo-{ mangle $name, 'f' }\n Fee-fi-mo-{ mangle $name, 'm' }\n $name!\n NAME-GAME\n}\n\nsay .&name-game for <Gary Earl Billy Felix Mike Steve>\n\n```\n\nOutput:\n\n```\nGary, Gary, bo-bary\nBanana-fana fo-fary\nFee-fi-mo-mary\nGary!\n\nEarl, Earl, bo-bearl\nBanana-fana fo-fearl\nFee-fi-mo-mearl\nEarl!\n\nBilly, Billy, bo-illy\nBanana-fana fo-filly\nFee-fi-mo-milly\nBilly!\n\nFelix, Felix, bo-belix\nBanana-fana fo-elix\nFee-fi-mo-melix\nFelix!\n\nMike, Mike, bo-bike\nBanana-fana fo-fike\nFee-fi-mo-ike\nMike!\n\nSteve, Steve, bo-bteve\nBanana-fana fo-fteve\nFee-fi-mo-mteve\nSteve!\n\n```" } ]
[ { "role": "user", "content": "The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.\n\nStarting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).\n\nStep through the set and if the value is not marked output 2\\*n+1. So from 1 to 4 output 3 5 7.\n\n4 is marked so skip for 5 and 6 output 11 and 13.\n\n7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)\n\nas per to 10 and now mark every seventh starting at 17 (17;24;31....)\n\nas per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.\n\nThe output will be the ordered set of odd primes.\n\nUsing your function find and output the first 100 and the millionth Sundaram prime.\n\nThe faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.\n\nReferences\n\n* The article on Wikipedia.\n\n**Comment on the Sundaram Sieve**\n\nIn case casual readers and programmers read the above blurb and get the impression that something several thousand years newer must needs be better than the \"old\" Sieve of Eratosthenes (SoE), do note the only difference between the Sieve of Sundaram (SoS) and the odds-only SoE is that the SoS marks as composite/\"culls\" according to **all odd \"base\" numbers** as is quite clear in the above description of how to implement it and the above linked Wikipedia article (updated), and the SoE marks as composite/\"culls\" according to only the previously determined unmarked primes (which are all odd except for two, which is not used for the \"odds-only\" algorithm); the time complexity (which relates to the execution time) is therefore O(n log n) for the SoS and O(n log log n) for the SoE, which difference can make a huge difference to the time it takes to sieve as the ranges get larger. It takes about a billion \"culls\" to sieve odds-only to a billion for the SoE, whereas it takes about 2.28 billion \"culls\" to cull to the same range for the SoS, which implies that the SoS must be about this ratio slower for this range with the memory usage identical. Why would one choose the SoS over the SoE to save a single line of code at the cost of this much extra time? The Wren comparison at the bottom of this page makes that clear, as would implementing the same in any language." }, { "role": "assistant", "content": "```\nmy $nth = 1_000_000;\n\nmy $k = Int.new: 2.4 * $nth * log($nth) / 2;\n\nmy int @sieve;\n\n@sieve[$k] = 0;\n\nrace for (1 .. $k).batch(1000) -> @i {\n for @i -> int $i {\n my int $j = $i;\n while (my int $l = $i + $j + 2 * $i * $j++) < $k {\n @sieve[$l] = 1;\n }\n }\n}\n\n@sieve[0] = 1;\n\nsay \"First 100 Sundaram primes:\";\nsay @sieve.kv.map( { next if $^v; $^k * 2 + 1 } )[^100]».fmt(\"%4d\").batch(10).join: \"\\n\";\n\nsay \"\\nOne millionth:\";\nmy ($count, $index);\nfor @sieve {\n $count += !$_;\n say $index * 2 + 1 and last if $count == $nth;\n ++$index;\n}\n\n```\n\nOutput:\n\n```\nFirst 100 Sundaram primes:\n 3 5 7 11 13 17 19 23 29 31\n 37 41 43 47 53 59 61 67 71 73\n 79 83 89 97 101 103 107 109 113 127\n 131 137 139 149 151 157 163 167 173 179\n 181 191 193 197 199 211 223 227 229 233\n 239 241 251 257 263 269 271 277 281 283\n 293 307 311 313 317 331 337 347 349 353\n 359 367 373 379 383 389 397 401 409 419\n 421 431 433 439 443 449 457 461 463 467\n 479 487 491 499 503 509 521 523 541 547\n\nOne millionth:\n15485867\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program that outputs the lyrics of the Christmas carol *The Twelve Days of Christmas*.\nThe lyrics can be found here.\n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy @days = <first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth>;\n\nmy @gifts = lines q:to/END/;\n And a partridge in a pear tree.\n Two turtle doves,\n Three french hens,\n Four calling birds,\n Five golden rings,\n Six geese a-laying,\n Seven swans a-swimming,\n Eight maids a-milking,\n Nine ladies dancing,\n Ten lords a-leaping,\n Eleven pipers piping,\n Twelve drummers drumming,\nEND\n\nsub nth($n) { say \"On the @days[$n] day of Christmas, my true love gave to me:\" }\n\nnth(0);\nsay @gifts[0].subst('And a','A');\n\nfor 1 ... 11 -> $d {\n say '';\n nth($d);\n say @gifts[$_] for $d ... 0;\n}\n\n```\n\nOutput:\n\n```\nOn the first day of Christmas, my true love gave to me:\n A partridge in a pear tree.\n\nOn the second day of Christmas, my true love gave to me:\n Two turtle doves,\n And a partridge in a pear tree.\n\nOn the third day of Christmas, my true love gave to me:\n Three french hens,\n Two turtle doves,\n And a partridge in a pear tree.\n\nOn the fourth day of Christmas, my true love gave to me:\n Four calling birds,\n Three french hens,\n Two turtle doves,\n And a partridge in a pear tree.\n.\n.\n.\nOn the twelfth day of Christmas, my true love gave to me:\n Twelve drummers drumming,\n Eleven pipers piping,\n Ten lords a-leaping,\n Nine ladies dancing,\n Eight maids a-milking,\n Seven swans a-swimming,\n Six geese a-laying,\n Five golden rings,\n Four calling birds,\n Three french hens,\n Two turtle doves,\n And a partridge in a pear tree.\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\n**Thiele's interpolation formula** is an interpolation formula for a function *f*(•) of a single variable.   It is expressed as a continued fraction:\n\n: : f\n (\n x\n )\n =\n f\n (\n\n x\n\n 1\n )\n +\n\n x\n −\n\n x\n\n 1\n\n ρ\n\n 1\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n )\n +\n\n x\n −\n\n x\n\n 2\n\n ρ\n\n 2\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n ,\n\n x\n\n 3\n )\n −\n f\n (\n\n x\n\n 1\n )\n +\n\n x\n −\n\n x\n\n 3\n\n ρ\n\n 3\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n ,\n\n x\n\n 3\n ,\n\n x\n\n 4\n )\n −\n\n ρ\n\n 1\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n )\n +\n ⋯\n {\\displaystyle {\\displaystyle f(x)=f(x\\_{1})+{\\cfrac {x-x\\_{1}}{\\rho \\_{1}(x\\_{1},x\\_{2})+{\\cfrac {x-x\\_{2}}{\\rho \\_{2}(x\\_{1},x\\_{2},x\\_{3})-f(x\\_{1})+{\\cfrac {x-x\\_{3}}{\\rho \\_{3}(x\\_{1},x\\_{2},x\\_{3},x\\_{4})-\\rho \\_{1}(x\\_{1},x\\_{2})+\\cdots }}}}}}}}\n\nρ\n{\\displaystyle {\\displaystyle \\rho }}\n   represents the   reciprocal difference,   demonstrated here for reference:\n\n: : ρ\n\n 1\n (\n\n x\n\n 0\n ,\n\n x\n\n 1\n )\n =\n\n x\n\n 0\n −\n\n x\n\n 1\n\n f\n (\n\n x\n\n 0\n )\n −\n f\n (\n\n x\n\n 1\n )\n {\\displaystyle {\\displaystyle \\rho \\_{1}(x\\_{0},x\\_{1})={\\frac {x\\_{0}-x\\_{1}}{f(x\\_{0})-f(x\\_{1})}}}}\n\n: : ρ\n\n 2\n (\n\n x\n\n 0\n ,\n\n x\n\n 1\n ,\n\n x\n\n 2\n )\n =\n\n x\n\n 0\n −\n\n x\n\n 2\n\n\n ρ\n\n 1\n (\n\n x\n\n 0\n ,\n\n x\n\n 1\n )\n −\n\n ρ\n\n 1\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n )\n +\n f\n (\n\n x\n\n 1\n )\n {\\displaystyle {\\displaystyle \\rho \\_{2}(x\\_{0},x\\_{1},x\\_{2})={\\frac {x\\_{0}-x\\_{2}}{\\rho \\_{1}(x\\_{0},x\\_{1})-\\rho \\_{1}(x\\_{1},x\\_{2})}}+f(x\\_{1})}}\n\n: : ρ\n\n n\n (\n\n x\n\n 0\n ,\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n )\n =\n\n x\n\n 0\n −\n\n x\n\n n\n\n\n ρ\n\n n\n −\n 1\n (\n\n x\n\n 0\n ,\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n −\n 1\n )\n −\n\n ρ\n\n n\n −\n 1\n (\n\n x\n\n 1\n ,\n\n x\n\n 2\n ,\n …\n ,\n\n x\n\n n\n )\n +\n\n ρ\n\n n\n −\n 2\n (\n\n x\n\n 1\n ,\n …\n ,\n\n x\n\n n\n −\n 1\n )\n {\\displaystyle {\\displaystyle \\rho \\_{n}(x\\_{0},x\\_{1},\\ldots ,x\\_{n})={\\frac {x\\_{0}-x\\_{n}}{\\rho \\_{n-1}(x\\_{0},x\\_{1},\\ldots ,x\\_{n-1})-\\rho \\_{n-1}(x\\_{1},x\\_{2},\\ldots ,x\\_{n})}}+\\rho \\_{n-2}(x\\_{1},\\ldots ,x\\_{n-1})}}\n\nDemonstrate Thiele's interpolation function by:\n\n1. Building a   **32**   row *trig table* of values   for   \n\n x\n {\\displaystyle {\\displaystyle x}}\n   from   **0**   by   **0.05**   to   **1.55**   of the trig functions:\n * **sin**\n * **cos**\n * **tan**\n2. Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;\n3. Finally: demonstrate the following well known trigonometric identities:\n * 6 × sin-1 ½ = \n\n π\n {\\displaystyle {\\displaystyle \\pi }}\n * 3 × cos-1 ½ = \n\n π\n {\\displaystyle {\\displaystyle \\pi }}\n * 4 × tan-1 1 = \n\n π\n {\\displaystyle {\\displaystyle \\pi }}" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.09\n\nImplemented to parallel the generalized formula, making for clearer, but slower, code. Offsetting that, the use of `Promise` allows concurrent calculations, so running all three types of interpolation should not take any longer than running just one (presuming available cores).\n\n```\n# reciprocal difference:\nmulti sub ρ(&f, @x where * < 1) { 0 } # Identity\nmulti sub ρ(&f, @x where * == 1) { &f(@x[0]) }\nmulti sub ρ(&f, @x where * > 1) {\n ( @x[0] - @x[* - 1] ) # ( x - x[n] )\n / (ρ(&f, @x[^(@x - 1)]) # / ( ρ[n-1](x[0], ..., x[n-1])\n - ρ(&f, @x[1..^@x]) ) # - ρ[n-1](x[1], ..., x[n]) )\n + ρ(&f, @x[1..^(@x - 1)]); # + ρ[n-2](x[1], ..., x[n-1])\n}\n \n# Thiele:\nmulti sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity\nmulti sub thiele($x, %f, $ord) {\n my &f = {%f{$^a}}; # f(x) as a table lookup\n \n # must sort hash keys to maintain order between invocations\n my $a = ρ(&f, %f.keys.sort[^($ord +1)]);\n my $b = ρ(&f, %f.keys.sort[^($ord -1)]);\n \n my $num = $x - %f.keys.sort[$ord];\n my $cont = thiele($x, %f, $ord +1);\n \n # Thiele always takes this form:\n return $a - $b + ( $num / $cont );\n}\n \n## Demo\nsub mk-inv(&fn, $d, $lim) {\n my %h;\n for 0..$lim { %h{ &fn($_ * $d) } = $_ * $d }\n return %h;\n}\n \nsub MAIN($tblsz = 12) {\n\n my ($sin_pi, $cos_pi, $tan_pi);\n my $p1 = Promise.start( { my %invsin = mk-inv(&sin, 0.05, $tblsz); $sin_pi = 6 * thiele(0.5, %invsin, 0) } );\n my $p2 = Promise.start( { my %invcos = mk-inv(&cos, 0.05, $tblsz); $cos_pi = 3 * thiele(0.5, %invcos, 0) } );\n my $p3 = Promise.start( { my %invtan = mk-inv(&tan, 0.05, $tblsz); $tan_pi = 4 * thiele(1.0, %invtan, 0) } );\n await $p1, $p2, $p3;\n \n say \"pi = {pi}\";\n say \"estimations using a table of $tblsz elements:\";\n say \"sin interpolation: $sin_pi\";\n say \"cos interpolation: $cos_pi\";\n say \"tan interpolation: $tan_pi\";\n}\n\n```\n\nOutput:\n\n```\npi = 3.14159265358979\nestimations using a table of 12 elements:\nsin interpolation: 3.14159265358961\ncos interpolation: 3.1387286696692\ntan interpolation: 3.14159090545243\n```" } ]
[ { "role": "user", "content": "If one were to enter the words: 'softly affiliate activation' at the what3words.com site, the response would be a location in Walt Disney World. The latitude and longitude for that spot is 28.3852 -81.5638. Using that service enables anyone to specify any place on the Earth with three words.\n\nTask: Provide a similar solution - Display a location on the Earth with three words derived from a latitude longitude pair.\n\nFor: latitude = 28.3852 longitude = -81.5638 Display: W18497 W11324 W01322\n\nImplementation:\n\nBuild an array of 28126, 6 character words in the form W00000 thru W28125.\n\nConvert latitude and longitude into positive integers.\n\nBuild a 43 bit integer containing latitude (21 bits) and longitude (22 bits).\n\nIsolate most significant 15 bits for word 1 index.\n\nIsolate next 14 bits for word 2 index.\n\nIsolate next 14 bits for word 3 index.\n\nFetch each word from the word array.\n\nDisplay the words.\n\nReverse the procedure and display the original latitude and longitude.\n\nExtra credit: Find a way to populate the word array with actual words." }, { "role": "assistant", "content": "**Works with**: Rakudo version 2020.07\n\n### The task\n\nIn large part due to the complete lack of specification, reference implementation, or guidance from the task creator, came up with my own bespoke synthetic word list.\n\nWords always consist of a series of consonant/vowel pairs. Uses a cut down alphabet to reduce possible confusion from overlapping pronunciation.\n\nSome letters with overlapping pronunciation are removed: c: confusable with k or s, g: overlaps with j, x: overlaps with z, q: just because, v: similar to w and we have way more than enough characters anyway.\n\nAs it is, with this alphabet we can form 512000 different 6 character \"words\"; 28126 is a drop in the bucket. To spread out the the words a bit, add a bit of randomness. 28126 fits into 512000 18 and a bit times. Add a random multiple of 28126 to the encoder then modulus it back out on decode. Will get different results on different runs.\n\nWe don't bother to pre-calculate and store the words, just generate them on the fly.\n\nOfficial pronunciation guide:\n\n* a - long a (say may day)\n* e - long e (he me see)\n* i - long i (hi sigh die)\n* o - long o (go so low)\n* u - long u (due boo moo)\n\n```\n# SYNTHETICS HANDLING\nmy @synth = flat < b d f h j k l m n p r s t w y z > X~ < a e i o u >;\nmy %htnys = @synth.antipairs;\nmy $exp = @synth.elems;\n\nsub synth (Int $v) { @synth[($v + (^18).pick * 28126).polymod($exp xx *).reverse || 0].join }\n\nsub thnys (Str $v) { (sum %htnys{$v.comb(2).reverse} Z* 1, $exp, $exp**2) % 28126 }\n\n\n# ENCODE / DECODE\nsub w-encode ( Rat(Real) $lat, Rat(Real) $lon, :&f = &synth ) {\n $_ = (($lat + 90) * 10000).round.fmt('%021b') ~ (($lon + 180) * 10000).round.fmt('%022b');\n (:2(.substr(0,15)), :2(.substr(15,14)),:2(.substr(29)))».&f\n}\n\nsub w-decode ( *@words, :&f = &thnys ) {\n my $bin = (@words».&f Z, <0 1 1>).map({.[0].fmt('%015b').substr(.[1])}).join;\n (:2($bin.substr(0,21))/10000) - 90, (:2($bin.substr(21))/10000) - 180\n}\n\n\n# TESTING\nfor 51.4337, -0.2141, # Wimbledon\n 21.2596,-157.8117, # Diamond Head crater\n -55.9652, -67.2256, # Monumento Cabo De Hornos\n 59.3586, 24.7447, # Lake Raku\n 29.2021, 81.5324, # Village Raku\n -7.1662, 53.9470, # The Indian ocean, south west of Seychelles\n 28.3852, -81.5638 # Walt Disney World\n -> $lat, $lon {\n my @words = w-encode $lat, $lon;\n my @index = w-encode $lat, $lon, :f( { $_ } );\n printf \"Coordinates: %s, %s\\n To Index: %s\\n To 3-word: %s\\nFrom 3-word: %s, %s\\n From Index: %s, %s\\n\\n\",\n $lat, $lon, @index.Str, @words.Str, w-decode(@words), w-decode @index, :f( { $_ } );\n}\n\n```\n\nOutput:\n\n```\nCoordinates: 51.4337, -0.2141\n To Index: 22099 365 12003\n To 3-word: zofobe fohujo habute\nFrom 3-word: 51.4337, -0.2141\n From Index: 51.4337, -0.2141\n\nCoordinates: 21.2596, -157.8117\n To Index: 17384 5133 8891\n To 3-word: nijemo zanaza fupawu\nFrom 3-word: 21.2596, -157.8117\n From Index: 21.2596, -157.8117\n\nCoordinates: -55.9652, -67.2256\n To Index: 5317 15428 13632\n To 3-word: zanohu julaso husese\nFrom 3-word: -55.9652, -67.2256\n From Index: -55.9652, -67.2256\n\nCoordinates: 59.3586, 24.7447\n To Index: 23337 4732 15831\n To 3-word: kapupi hokame supoku\nFrom 3-word: 59.3586, 24.7447\n From Index: 59.3586, 24.7447\n\nCoordinates: 29.2021, 81.5324\n To Index: 18625 5535 10268\n To 3-word: dijule nutuza nefini\nFrom 3-word: 29.2021, 81.5324\n From Index: 29.2021, 81.5324\n\nCoordinates: -7.1662, 53.947\n To Index: 12942 12942 12942\n To 3-word: rakudo rakudo rakudo\nFrom 3-word: -7.1662, 53.947\n From Index: -7.1662, 53.947\n\nCoordinates: 28.3852, -81.5638\n To Index: 18497 11324 1322\n To 3-word: tabesa nekaso bupodo\nFrom 3-word: 28.3852, -81.5638\n From Index: 28.3852, -81.5638\n```\n\n(Ok, I admit I manipulated that second to last one, but it **is** a correct and valid 3-word location in this implementation. There is less than 1 chance in 5000 that it will produce that specific word group though.)\n\n### A thought experiment\n\nA little thought experiment... Latitude, longitude to four decimal places is accurate to about 11.1 meters at the equator, smaller the further from the equator you get.\nWhat would it take to support five decimal places? (Accurate to 1.11 meters.)\n\n`360 * 100000 == 36000000;\nceiling 36000000.log(2) == 26;`\n\nSo we need 26 bits to cover 360.00000; half of that for 180.00000, or `26 bits + 25 bits == 51 bits`. `51 / 3 == 17`. `2**17 == 131072` indices. The previous synthetics routine provides much more than enough.\n\nHow many sylabics will we need to minimally cover it?\n\n`∛131072 == 50.7968...`\n\nSo at least 51. The synthetics routine provide sylabics in blocks of 5, so we would need\nat least 11 consonants.\n\nCapriciously and somewhat randomly cutting down the list we arrive at this.\n\n10 times better accuracy in the same three, 6-letter word space.\n\n```\n# SYNTHETICS HANDLING\nmy @synth = flat < b d f j k n p r s t w > X~ < a e i o u >;\nmy %htnys = @synth.antipairs;\nmy $exp = @synth.elems;\nmy $prec = 100_000;\n\n\nsub synth (Int $v) { @synth[$v.polymod($exp xx *).reverse || 0].join }\n\nsub thnys (Str $v) { sum %htnys{$v.comb(2).reverse} Z× 1, $exp, $exp² }\n\n\n# ENCODE / DECODE\nsub w-encode ( Rat(Real) $lat, Rat(Real) $lon, :&f = &synth ) {\n $_ = (($lat + 90) × $prec).round.fmt('%025b') ~ (($lon + 180) × $prec).round.fmt('%026b');\n (:2(.substr(0,17)), :2(.substr(17,17)), :2(.substr(34)))».&f\n}\n\nsub w-decode ( *@words, :&f = &thnys ) {\n my $bin = @words».&f.map({.fmt('%017b')}).join;\n (:2($bin.substr(0,25))/$prec) - 90, (:2($bin.substr(25))/$prec) - 180\n}\n\n\n# TESTING\nfor 51.43372, -0.21412, # Wimbledon center court\n 21.25976,-157.81173, # Diamond Head summit\n -55.96525, -67.22557, # Monumento Cabo De Hornos\n 28.3852, -81.5638, # Walt Disney World\n 89.99999, 179.99999, # test some\n -89.99999,-179.99999 # extremes\n -> $lat, $lon {\n my @words = w-encode $lat, $lon;\n printf \"Coordinates: %s, %s\\n To Index: %s\\n To 3-word: %s\\nFrom 3-word: %s, %s\\n\\n\",\n $lat, $lon, w-encode($lat, $lon, :f({$_})).Str, @words.Str, w-decode(@words);\n}\n\n```\n\nOutput:\n\n```\nCoordinates: 51.43372, -0.21412\n To Index: 55247 71817 21724\n To 3-word: jofuni kosasi diduwu\nFrom 3-word: 51.43372, -0.21412\n\nCoordinates: 21.25976, -157.81173\n To Index: 43460 110608 121675\n To 3-word: fukafa repebo safija\nFrom 3-word: 21.25976, -157.81173\n\nCoordinates: -55.96525, -67.22557\n To Index: 13294 108118 5251\n To 3-word: bukeru rasaso besane\nFrom 3-word: -55.96525, -67.22557\n\nCoordinates: 28.3852, -81.5638\n To Index: 46244 28747 13220\n To 3-word: jajasu duniri bukaka\nFrom 3-word: 28.3852, -81.5638\n\nCoordinates: 89.99999, 179.99999\n To Index: 70312 65298 86271\n To 3-word: kofoki kepifo nonope\nFrom 3-word: 89.99999, 179.99999\n\nCoordinates: -89.99999, -179.99999\n To Index: 0 512 1\n To 3-word: ba duji be\nFrom 3-word: -89.99999, -179.99999\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a Thue-Morse sequence.\n\nSee also\n\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: Fairshare between two and more" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\nFirst 8 of an infinite sequence\n\n```\n.say for (0, { '0' ~ @_.join.trans( \"01\" => \"10\", :g) } ... *)[^8];\n\n```\n\nOutput:\n\n```\n0\n01\n0110\n01101001\n0110100110010110\n01101001100101101001011001101001\n0110100110010110100101100110100110010110011010010110100110010110\n01101001100101101001011001101001100101100110100101101001100101101001011001101001011010011001011001101001100101101001011001101001\n^C\n```" } ]
[ { "role": "user", "content": "Task\n\nPlay a game of tic-tac-toe.\n\nEnsure that legal moves are played and that a winning position is notified.\n\n*Tic-tac-toe*   is also known as:\n\n: : * *noughts and crosses*\n * *tic tac toe*\n * *tick tack toe*\n * *three in a row*\n * *tres en rayo*       and\n * *Xs  and  Os*\n\nSee also\n\n* MathWorld™, Tic-Tac-Toe game.\n* Wikipedia tic-tac-toe." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nThe computer plays a random game.\n\n```\nmy @board = 1..9;\nmy @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8],\n\t[0,4,8], [6,4,2];\n\nsub get-winner() {\n\tfor @winning-positions {\n return (@board[|$_][0], $_) if [eq] @board[|$_];\n\t}\n}\n\nsub free-indexes() {\n\[email protected]: { @board[$_] eq any(1..9) }\n}\n\nsub ai-move() {\n\tgiven free-indexes.pick {\n\t\t@board[$_] = 'o';\n\t\tsay \"I go at: { $_ + 1 }\\n\";\n\t}\n}\n\nsub print-board() {\n print \"\\e[2J\";\n say @board.map({ \"$^a | $^b | $^c\" }).join(\"\\n--+---+--\\n\"), \"\\n\";\n}\n\nsub human-move() {\n\tmy $pos = prompt \"Choose one of { (free-indexes() »+» 1).join(\",\") }: \";\n\tif $pos eq any(free-indexes() »+» 1) {\n\t\t@board[$pos - 1] = 'x';\n\t} else {\n\t\tsay \"Sorry, you want to put your 'x' where?\";\n\t\thuman-move();\n\t}\n}\n\nfor flat (&ai-move, &human-move) xx * {\n\tprint-board;\n last if get-winner() or not free-indexes;\n .();\n}\n\nif get-winner() -> ($player, $across) {\n\tsay \"$player wins across [\", ($across »+» 1).join(\", \"), \"].\";\n} else {\n\tsay \"How boring, a draw!\";\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite a program which uses a timer (with the least granularity available\non your system) to time how long a function takes to execute.\n\nWhenever possible, use methods which measure only the processing time used\nby the current process; instead of the difference in system time\nbetween start and finish, which could include time used by\nother processes on the computer.\n\nThis task is intended as a subtask for Measure relative performance of sorting algorithms implementations." }, { "role": "assistant", "content": "(formerly Perl 6)\nFollows modern trend toward measuring wall-clock time, since CPU time is becoming rather ill-defined in the age of multicore, and doesn't reflect IO overhead in any case.\n\n```\nmy $start = now;\n(^100000).pick(1000);\nsay now - $start;\n\n```\n\nOutput:\n\n```\n0.02301709\n```" } ]
[ { "role": "user", "content": "## Time Conventions and Conversions\n\n### Background\n\nThe accurate timing of events is an important measure in many areas of computing.\n\nComputer benchmarking or network timeouts may use the computer clock only to compute the difference in time between events. For other tasks, such as measuring the time of events in a way that is independent of individual computers or when logging an event as having occurred at a particular time for later evaluation, an external time system is necessary to allow software to \"tag\" an event in time with a **timestamp** that can establish its position within an event history in that time system.\n\nThere are many such **timestamp** standards in use, and sometimes data with one system's timestamp may need to be used with a system that contains other data using a different system's timestamp. To properly correlate such mixed data, conversion of dates and times between timestamps in different systems is required.\n\nThe current task is to create a function or functions to perform timestamp conversions between **time conventions**, systems established as social conventions for tracking events in time.\n\n### Time system epochs\n\nWhen converting between time conventions, the origin (time 0) of each convention needs to be considered, along with the historical times of past adjustment of the system if any. The time 0 (sometimes, time 1) of a system can be referred to as its **epoch**.\n\n#### UTC Time\n\nThe **ISO 8601 standard** created the time convention of **Coordinated Universal Time**, or **UTC**.\n\nThe ISO 8601 standard expresses dates and times in the format \"yyyy-mm-ddTHH:MM:SS.xxx\", where yyyy is 4-digit year, mm is 2-digit month, dd is 2-digit day of month, HH is 2-digit, 24-hour hour, MM is 2-digit minutes past the hour, SS is seconds past the minute, T is the letter T used to separate days from hours, and xxx is an optional decimal fraction of a second. In addition, the timestamp may have a timezone such as GMT appended to the UTC string (note however that time zones will not be covered in this task).\n\nUTC defines Day 1 of the year 1 Common Era (AD) as 0001-1-1T00:00:00. Exceptionally for a mostly continuous variable, there is no 0 year in the conventional AD/BC, CE/BCE calendar. Instead, the previous year is defined to start at 0000:1:1T00:00:00Z, so the years going backwards in the CE/BCE system are are ...3 CE, 2 CE, 1 CE, 1 BCE, 2 BCE... whereas in UTC these are ...3, 2, 1, 0, -1...\n\nThe actual day 0, the UTC epoch start, is then 1 BCE, and the Day 0 epoch is defined as at the last day of year 1 BCE, or December 31, 1 BCE (BC), which is 0000-12-31T00:00:00 in the ISO 8601 standard for UTC time stamps.\n\n#### UNIX Time\n\nThe Unix operating system time() function was the basis for the convention of **Unix system time**.\n\nThe Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of non-leap seconds that have elapsed since January 1, 1970 (midnight Coordinated Universal Time, or UTC, also GMT), not counting leap seconds. The time() function in Unix actually returns the number of (non-leap) milliseconds since the Unix epoch as a floating point number, which would be the Unix timestamp.\n\nThe Unix \"epoch\" is thus expressed in UTC 8601 terms as 1970-01-01T00:00:00.\n\n#### NTP Time\n\nThe Network Time Protocol (or **NTP**) defines the prime epoch as beginning at UTC 1900-01-01T00:00:00. NTP timestamps are defined as the number of non-leap seconds since the NTP epoch.\n\n### Leap seconds\n\nThe moon's tidal drag on Earth makes the Earth's rotation slow very slightly over the years, at a rate that is usually less than a second a year but varies from year to year. Because of a desire to keep the time of day in synchrony with the Earth's rotation, the exact duration of a year varies because of **leap seconds**. On certain years there have been **leap seconds** added at midnight mostly between 31 December and 1 January and occasionally at midnight between June 30 and July 1. These changes have been used to keep the **UTC** time of day in sync with the astronomical day. The **Unix**, **NTP**, and **UTC** time conventions essentially ignore leap seconds in their timekeeping. On the other hand, there other time conventions, including the **TAI** and **GPS** conventions, which advance their second clock even during leap seconds. This has caused **TAI time** and **GPS time** to progressively run ahead of **UTC time** by a slowly increasing number of seconds, even though the second measure itself is constant between conventions.\n\n#### The leap second table\n\nA file is kept current at the **NIST** ftp site, filed as **ftp.boulder.nist.gov/pub/time/leap-seconds.list**, which contains a history of each timestamp (in **NTP** time) in which the leap seconds were added and ignored in the counting of seconds in **NTP**, **Unix**, and **UTC** conventions.\n\nThe leap-seconds.list file currently contains data including the following:\n\n```\nTimestamp of last update of this file in NTP seconds:\n3929093563\n\nPlanned expiration date of the file in NTP timestamp seconds:\n3960057600\n\n2272060800 10 # 1 Jan 1972\n2287785600 11 # 1 Jul 1972\n2303683200 12 # 1 Jan 1973\n2335219200 13 # 1 Jan 1974\n2366755200 14 # 1 Jan 1975\n2398291200 15 # 1 Jan 1976\n2429913600 16 # 1 Jan 1977\n2461449600 17 # 1 Jan 1978\n2492985600 18 # 1 Jan 1979\n2524521600 19 # 1 Jan 1980\n2571782400 20 # 1 Jul 1981\n2603318400 21 # 1 Jul 1982\n2634854400 22 # 1 Jul 1983\n2698012800 23 # 1 Jul 1985\n2776982400 24 # 1 Jan 1988\n2840140800 25 # 1 Jan 1990\n2871676800 26 # 1 Jan 1991\n2918937600 27 # 1 Jul 1992\n2950473600 28 # 1 Jul 1993\n2982009600 29 # 1 Jul 1994\n3029443200 30 # 1 Jan 1996\n3076704000 31 # 1 Jul 1997\n3124137600 32 # 1 Jan 1999\n3345062400 33 # 1 Jan 2006\n3439756800 34 # 1 Jan 2009\n3550089600 35 # 1 Jul 2012\n3644697600 36 # 1 Jul 2015\n3692217600 37 # 1 Jan 2017\n\n```\n\nAccording to the **leap-seconds.list** file, then, an offset of 37 seconds started in 2017 and should be current through 2024. Lesser whole-second adjustments would be correct for dates from 1972 through 2016. So, for example, for the date of \"October 5, 1998\", or UTC \"1998-10-05\", falls after 1997, when the leap seconds last went up to 31, and before 1999, when the total leap seconds then went up to 32. So, the leap seconds value correction for that date is 31 seconds. This is the number of seconds a **UTC** timestamp would lag behind a **TAI** time timestamp (see below).\n\nThe leap-seconds.list file provided by NIST includes a series of NTP timestamps to indicate the date and time of each update to the leap seconds, as given in the table above.\n\n#### TAI Time\n\nThe above mentioned **TAI time**, or international atomic clock time, is defined as the number of seconds since **UTC** 1958-01-01T00:00:00, but with counting the leap seconds not counted by UTC.\n\n#### GPS Time\n\nSimilarly to **TAI** time, the **GPS** time, or **Global Positioning System** convention time, is defined as the number of seconds since **UTC** 1980-01-06T00:00:00. Since the **UTC** time in 1980 had already fallen behind **TAI** time by 19 seconds, **GPS** time's offset is always 19 less than the (positive) **TAI** offset used in conversion to **TAI** from any given **UTC** standard timestamp.\n\n## Task:\n\nIn your chosen programming language, write a function or functions to convert between timestamps in **UTC**, **Unix**, **NTP**, **TAI**, and **GPS** time conventions. Timestamps should be capable of 1 millisecond precision as a minimum, with microsecond or nanosecond precision optional. Negative values for a timestamp before its epoch can be used when necessary. Add or subtract the proper number of leap seconds as appropriate when converting between leap-second-ignoring (UTC, Unix, NTP) and leap-second-counting (TAI, GPS) timestamp standards.\n\nDemonstrate the use of the function or functions to output values to fill in blanks in the following table:\n\n```\n UTC Unix NTP TAI GPS \n__________________________________________________________________________________________\n0000-12-31T00:00:00\n1900-01-01T00:00:00\n1958-01-01T00:00:00\n1970-01-01T00:00:00\n1980-01-06T00:00:00\n1989-12-31T00:00:00\n1990-01-01T00:00:00\n2025-06-01T00:00:00\n2050-01-01T00:00:00\n 1810753809.806\n 154956295.688\n 780673454.121 \n 2871676795\n 2335219189\n 3029443171\n 996796823\n 996796824\n 996796825\n 996796826\n 996796804.250\n 996796805.500\n 996796806.750\n 996796807.9999\n\n \n\n```\n\nReferences\n\n[1] Wikipedia reference\n\n[2] Non-paywalled version of the ISO 8601 standard for UTC\n\n[3] Discussion of the leap-seconds.list file\n\n[4] Comparisons of different time conventions and timestamps\n\n[5] Online time stamp converter" }, { "role": "assistant", "content": "When using the Instant class for leap second operations in Raku, the results may be version-dependent as it is preloaded with leap seconds adjustments at the then current point in time. Users should be aware of this and take it into consideration, as the knowledge of future leap seconds can vary between different Raku compiler versions.\n\n**Translation of**: Wren\n\n```\n# 20241023 Raku programming solution\n\nmy (\\UNIX_EPOCH, \\NTP_EPOCH, \\TAI_EPOCH, \\GPS_EPOCH) = map { DateTime.new: $_ },\n < 1970-01-01 1900-01-01 1958-01-01 1980-01-06 >;\n\nmy %NTP_TO_LS = ( my @CHANGE_TIMES = < \n 2272060800 2287785600 2303683200 2335219200 2366755200 2398291200 2429913600\n 2461449600 2492985600 2524521600 2571782400 2603318400 2634854400 2698012800\n 2776982400 2840140800 2871676800 2918937600 2950473600 2982009600 3029443200\n 3076704000 3124137600 3345062400 3439756800 3550089600 3644697600 3692217600 \n> ) Z=> 10 .. * ;\n\n# The conversions without leap second adjustments\n\nmy &utc2unix = -> $utcStr { \n do given DateTime.new($utcStr).posix { * < 0 ?? $_ !! $_ - UNIX_EPOCH }\n}\n\nmy &utc2ntp = -> $utcStr { utc2unix($utcStr) + UNIX_EPOCH - NTP_EPOCH }\n\nmy &ntp2unix = -> $ntpSecs { $ntpSecs + NTP_EPOCH - UNIX_EPOCH }\n\nmy &unix2ntp = -> $unixSecs { $unixSecs + UNIX_EPOCH - NTP_EPOCH }\n\nmy &unix2utc = -> $unixSecs { Instant.from-posix($unixSecs).DateTime }\n\nmy &ntp2utc = -> $ntpSecs { unix2utc(ntp2unix($ntpSecs)) }\n\nmy &tai2gps = -> $taiSecs { $taiSecs + TAI_EPOCH - GPS_EPOCH - 10 }\n\nmy &gps2tai = -> $gpsSecs { $gpsSecs + GPS_EPOCH - TAI_EPOCH + 10 }\n\n# Conversions requiring leap-second adjustments\n\nmy &ntp2tai = sub ($ntpSecs) {\n my $tai = $ntpSecs + NTP_EPOCH - TAI_EPOCH;\n \n return $tai if $ntpSecs < @CHANGE_TIMES[0];\n\n return $tai+%NTP_TO_LS{@CHANGE_TIMES[*-1]} if $ntpSecs >= @CHANGE_TIMES[*-1];\n\n for 1 .. @CHANGE_TIMES.elems - 1 {\n if $ntpSecs < @CHANGE_TIMES[$_] {\n return $tai + %NTP_TO_LS{@CHANGE_TIMES[$_-1]}\n }\n }\n}\n\nmy &tai2ntp = sub ($taiSecs) {\n my $ntp = $taiSecs + TAI_EPOCH - NTP_EPOCH;\n\n return $ntp if $ntp < @CHANGE_TIMES[0];\n \n my ($idx, $delta) = (0, 0);\n \n if $ntp >= @CHANGE_TIMES[*-1] {\n $delta = %NTP_TO_LS{@CHANGE_TIMES[*-1]}\n } else {\n for 1 .. @CHANGE_TIMES.elems - 1 {\n if $ntp < @CHANGE_TIMES[$_] {\n $delta = %NTP_TO_LS{@CHANGE_TIMES[$_-1]};\n $idx = $_;\n last;\n }\n }\n }\n \n return do given $ntp - $delta {\n when * < @CHANGE_TIMES[0] { @CHANGE_TIMES[0] - 1 + $ntp.fraction }\n when * < @CHANGE_TIMES[$idx-1] { $_ + 1 }\n default { $_ } \n }\n}\n\nmy &ntp2gps = -> $ntpSecs { tai2gps(ntp2tai($ntpSecs)) }\n\nmy &gps2ntp = -> $gpsSecs { tai2ntp(gps2tai($gpsSecs)) }\n\nmy &tai2unix = -> $taiSecs { ntp2unix(tai2ntp($taiSecs)) }\n\nmy &unix2tai = -> $unixSecs { ntp2tai(unix2ntp($unixSecs)) }\n\nmy &tai2utc = -> $taiSecs { ntp2utc(tai2ntp($taiSecs)) }\n\nmy &utc2tai = -> $utcStr { ntp2tai(utc2ntp($utcStr)) }\n\nmy &gps2unix = -> $gpsSecs { tai2unix(gps2tai($gpsSecs)) }\n\nmy &unix2gps = -> $unixSecs { tai2gps(unix2tai($unixSecs)) }\n\nmy &utc2gps = -> $utcStr { tai2gps(utc2tai($utcStr)) }\n\nmy &gps2utc = -> $gpsSecs { tai2utc(gps2tai($gpsSecs)) }\n\n# Output formatting\nsay \" UTC Unix NTP TAI GPS\";\nsay '_' x 100;\n\nmy $fmt = \"%-28s%18.4f%18.4f%18.4f%18.4f\\n\";\n\nfor < 0001-01-01T00:00:00 1900-01-01T00:00:00 1958-01-01T00:00:00\n 1970-01-01T00:00:00 1980-01-06T00:00:00 1989-12-31T00:00:00\n 1990-01-06T00:00:00 2025-06-01T00:00:00 2050-01-01T00:00:00 > {\n printf $fmt, $_, .&utc2unix, .&utc2ntp, .&utc2tai, .&utc2gps\n}\n\nfor < 1810753809.806 154956295.688 780673454.121 > {\n printf $fmt, .&unix2utc, $_, .&unix2ntp, .&unix2tai, .&unix2gps\n}\n\nfor < 2871676795 2335219189 3029443171 3124137599 3124137600 > {\n printf $fmt, .&ntp2utc, .&ntp2unix, $_, .&ntp2tai, .&ntp2gps\n}\n\nfor < 996796823 996796824 996796825 996796826 \n 1293840030 1293840031 1293840032 1293840033 > {\n printf $fmt, .&tai2utc, .&tai2unix, .&tai2ntp, $_, .&tai2gps \n}\n\nfor < 996796804.250 996796805.5 996796806.750 996796807.9999 > {\n printf $fmt, .&gps2utc, .&gps2unix, .&gps2ntp, .&gps2tai, $_\n}\n\n```\n\nYou may Attempt This Online!\n\nOutput:\n\n```\n UTC Unix NTP TAI GPS\n____________________________________________________________________________________________________\n0001-01-01T00:00:00 -62135596800.0000 -59926608000.0000 -61756905600.0000 -62451561619.0000\n1900-01-01T00:00:00 -2208988800.0000 0.0000 -1830297600.0000 -2524953619.0000\n1958-01-01T00:00:00 -378691200.0000 1830297600.0000 0.0000 -694656019.0000\n1970-01-01T00:00:00 0.0000 2208988800.0000 378691200.0000 -315964819.0000\n1980-01-06T00:00:00 315964800.0000 2524953600.0000 694656019.0000 0.0000\n1989-12-31T00:00:00 631065600.0000 2840054400.0000 1009756824.0000 315100805.0000\n1990-01-06T00:00:00 631584000.0000 2840572800.0000 1010275225.0000 315619206.0000\n2025-06-01T00:00:00 1748736000.0000 3957724800.0000 2127427237.0000 1432771218.0000\n2050-01-01T00:00:00 2524608000.0000 4733596800.0000 2903299237.0000 2208643218.0000\n2027-05-19T19:10:09.806000Z 1810753809.8060 4019742609.8060 2189445046.8060 1494789027.8060\n1974-11-29T11:24:55.688000Z 154956295.6880 2363945095.6880 533647508.6880 -161008510.3120\n1994-09-27T13:44:14.121000Z 780673454.1210 2989662254.1210 1159364683.1210 464708664.1210\n1990-12-31T23:59:55Z 662687995.0000 2871676795.0000 1041379220.0000 346723201.0000\n1973-12-31T23:59:49Z 126230389.0000 2335219189.0000 504921601.0000 -189734418.0000\n1995-12-31T23:59:31Z 820454371.0000 3029443171.0000 1199145600.0000 504489581.0000\n1998-12-31T23:59:59Z 915148799.0000 3124137599.0000 1293840030.0000 599184011.0000\n1999-01-01T00:00:00Z 915148800.0000 3124137600.0000 1293840032.0000 599184013.0000\n1989-08-02T23:59:59Z 618105599.0000 2827094399.0000 996796823.0000 302140804.0000\n1989-08-03T00:00:00Z 618105600.0000 2827094400.0000 996796824.0000 302140805.0000\n1989-08-03T00:00:01Z 618105601.0000 2827094401.0000 996796825.0000 302140806.0000\n1989-08-03T00:00:02Z 618105602.0000 2827094402.0000 996796826.0000 302140807.0000\n1998-12-31T23:59:59Z 915148799.0000 3124137599.0000 1293840030.0000 599184011.0000\n1999-01-01T00:00:00Z 915148800.0000 3124137600.0000 1293840031.0000 599184012.0000\n1999-01-01T00:00:00Z 915148800.0000 3124137600.0000 1293840032.0000 599184013.0000\n1999-01-01T00:00:01Z 915148801.0000 3124137601.0000 1293840033.0000 599184014.0000\n2011-08-07T23:59:49.250000Z 1312761589.2500 3521750389.2500 1691452823.2500 996796804.2500\n2011-08-07T23:59:50.500000Z 1312761590.5000 3521750390.5000 1691452824.5000 996796805.5000\n2011-08-07T23:59:51.750000Z 1312761591.7500 3521750391.7500 1691452825.7500 996796806.7500\n2011-08-07T23:59:52.999900Z 1312761592.9999 3521750392.9999 1691452826.9999 996796807.9999\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Time-based one-time password 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\nA Time-based One-time Password Algorithm (TOTP) is an algorithm that computes a one-time password from a shared secret key and the current time. It is the cornerstone of Initiative For Open Authentication (OATH) and is used in a number of two factor authentication systems.\n\nEssentially, both the server and the client compute the time-limited token, then the server checks if the token supplied by the client matches the locally generated token.\n\nTask\n\nImplement this algorithm using **HMAC-SHA1** and an optional step is to generate the random Base-32 string used as the secret key, but this is not a requirement.\n\nA reference implementation, based on JavaScript, can be found at the following location:\n\n: : : http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript\n\nAccording to RFC 6238, the reference implementation is as follows:\n\n* Generate a key, **K**, which is an arbitrary bytestring, and share it securely with the client.\n* Agree upon an epoch, T0, and an interval, TI, which will be used to calculate the value of the counter C (defaults are the Unix epoch as T0 and 30 seconds as TI)\n* Agree upon a cryptographic hash method (default is SHA-1)\n* Agree upon a token length, **N** (default is 6)\n\nAlthough RFC 6238 allows different parameters to be used, the Google implementation of the authenticator app does not support T0, TI values, hash methods and token lengths different from the default.   It also expects the **K** secret key to be entered (or supplied in a QR code) in base-32 encoding according to RFC 3548.\n\n* Google Authenticator App (Apple iOS)\n* Google Authenticator App (Google Android)\n* Microsoft Authenticator App (Windows Phone)" }, { "role": "assistant", "content": "(formerly Perl 6)\nThis is a minimal attempt that covers only the \"Time-based\" part of the requirement.\n\n```\n# Reference:\n# https://github.com/retupmoca/P6-Digest-HMAC\n\nuse v6.d;\nuse Digest::HMAC;\nuse Digest::SHA;\n\nsub totp (Str \\secret, DateTime \\counter, Int \\T0=0, Int \\T1=30 --> Str) {\n my \\key = ( counter - DateTime.new(T0) ).Int div T1; \n return hmac-hex(key.Str, secret, &sha1).substr(0,6) # first 6 chars of sha1\n}\n\nmy $message = \"show me the monKey\";\n\nsay \"Deterministic output at \", DateTime.new(2177452800), \" with fixed checks,\";\nloop (my $t = 2177452800 ; $t < 2177452900 ; $t+= 17 ) { # Y2038 safe\n say totp $message, DateTime.new($t);\n}\n\nsay \"Current time output at \", DateTime.new(now), \" with random checks,\";\nloop (my $n = 0 ; $n < 6 ; $n++, sleep (13..23).roll ) {\n say totp $message, DateTime.new(now);\n}\n\n```\n\nOutput:\n\n```\nDeterministic output at 2039-01-01T00:00:00Z with fixed checks,\n34ca2a\nacfa3f\n950fc3\n950fc3\na2d4ea\na2d4ea\nCurrent time output at 2019-03-31T15:00:01.765312Z with random checks,\n4e36de\nd4e9f8\nd4e9f8\n077e2c\n63bbb5\n63bbb5\n```" } ]
[ { "role": "user", "content": "Separate the string \"Hello,How,Are,You,Today\" by commas into an array (or list) so that each element of it stores a different word.\n\nDisplay the words to the 'user', in the simplest manner possible, separated by a period.\n\nTo simplify, you may display a trailing period.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #22 \"Thousand Oaks\"\n\n```\n'Hello,How,Are,You,Today'.split(',').join('.').say;\n```\n\nOr with function calls:\n\n```\nsay join '.', split ',', 'Hello,How,Are,You,Today';\n```" } ]