messages
listlengths
2
2
[ { "role": "user", "content": "Given two lists of data, calculate the p-value used for Welch's t-test. This is meant to translate R's `t.test(vector1, vector2, alternative=\"two.sided\", var.equal=FALSE)` for calculation of the p-value.\n\n**Task Description**\n\nGiven two sets of data, calculate the p-value:\n\n```\n x = {3.0,4.0,1.0,2.1}\n y = {490.2,340.0,433.9}\n\n```\n\nYour task is to discern whether or not the difference in means between the two sets is statistically significant and worth further investigation. P-values are significance tests to gauge the probability that the difference in means between two data sets is significant, or due to chance. A threshold level, alpha, is usually chosen, 0.01 or 0.05, where p-values below alpha are worth further investigation and p-values above alpha are considered not significant. The p-value is not considered a final test of significance, only whether the given variable should be given further consideration.\n\nThere is more than one way of calculating the t-statistic, and you must choose which method is appropriate for you. Here we use Welch's t-test, which assumes that the variances between the two sets `x` and `y` are not equal. Welch's t-test statistic can be computed:\n\nt\n\n=\n\nX\n¯\n\n1\n−\n\nX\n¯\n\n2\n\ns\n\n1\n\n2\n\nN\n\n1\n\n+\n\ns\n\n2\n\n2\n\nN\n\n2\n\n{\\displaystyle {\\displaystyle t\\quad =\\quad {\\;{\\overline {X}}\\_{1}-{\\overline {X}}\\_{2}\\; \\over {\\sqrt {\\;{s\\_{1}^{2} \\over N\\_{1}}\\;+\\;{s\\_{2}^{2} \\over N\\_{2}}\\quad }}}}}\n\nwhere\n\nX\n¯\n\nn\n{\\displaystyle {\\displaystyle {\\overline {X}}\\_{n}}}\n is the mean of set \n\nn\n{\\displaystyle {\\displaystyle n}}\n,\n\nand\n\nN\n\nn\n{\\displaystyle {\\displaystyle N\\_{n}}}\n is the number of observations in set \n\nn\n{\\displaystyle {\\displaystyle n}}\n,\n\nand\n\ns\n\nn\n{\\displaystyle {\\displaystyle s\\_{n}}}\n is the square root of the unbiased sample variance of set \n\nn\n{\\displaystyle {\\displaystyle n}}\n, i.e.\n\ns\n\nn\n=\n\n1\n\n\nN\n\nn\n−\n1\n\n∑\n\ni\n=\n1\n\n\nN\n\nn\n\n\n(\n\n\nX\n\ni\n−\n\nX\n¯\n\nn\n)\n\n2\n{\\displaystyle {\\displaystyle s\\_{n}={\\sqrt {{\\frac {1}{N\\_{n}-1}}\\sum \\_{i=1}^{N\\_{n}}\\left(X\\_{i}-{\\overline {X}}\\_{n}\\right)^{2}}}}}\n\nand the degrees of freedom, \n\nν\n{\\displaystyle {\\displaystyle \\nu }}\n can be approximated:\n\nν\n\n≈\n\n(\n\ns\n\n1\n\n2\n\nN\n\n1\n\n+\n\ns\n\n2\n\n2\n\nN\n\n2\n\n)\n\n2\n\ns\n\n1\n\n4\n\n\nN\n\n1\n\n2\n(\n\nN\n\n1\n−\n1\n)\n\n+\n\ns\n\n2\n\n4\n\n\nN\n\n2\n\n2\n(\n\nN\n\n2\n−\n1\n)\n\n{\\displaystyle {\\displaystyle \\nu \\quad \\approx \\quad {{\\left(\\;{s\\_{1}^{2} \\over N\\_{1}}\\;+\\;{s\\_{2}^{2} \\over N\\_{2}}\\;\\right)^{2}} \\over {\\quad {s\\_{1}^{4} \\over N\\_{1}^{2}(N\\_{1}-1)}\\;+\\;{s\\_{2}^{4} \\over N\\_{2}^{2}(N\\_{2}-1)}\\quad }}}}\n\nThe two-tailed p-value, \n\np\n{\\displaystyle {\\displaystyle p}}\n, can be computed as a cumulative distribution function\n\np\n\n2\n−\nt\na\ni\nl\n=\n\nI\n\n\nν\n\n\nt\n\n2\n+\nν\n\n(\n\nν\n2\n,\n\n\n1\n2\n)\n{\\displaystyle {\\displaystyle p\\_{2-tail}=I\\_{\\frac {\\nu }{t^{2}+\\nu }}\\left({\\frac {\\nu }{2}},{\\frac {1}{2}}\\right)}}\n\nwhere I is the regularized incomplete beta function. This is the same as:\n\np\n\n2\n−\nt\na\ni\nl\n=\n\nB\n(\n\n\nν\n\n\nt\n\n2\n+\nν\n;\n\n\nν\n2\n,\n\n\n1\n2\n)\n\n\nB\n(\n\n\nν\n2\n,\n\n\n1\n2\n)\n{\\displaystyle {\\displaystyle p\\_{2-tail}={\\frac {\\mathrm {B} ({\\frac {\\nu }{t^{2}+\\nu }};{\\frac {\\nu }{2}},{\\frac {1}{2}})}{\\mathrm {B} ({\\frac {\\nu }{2}},{\\frac {1}{2}})}}}}\n\nKeeping in mind that\n\nB\n(\nx\n;\na\n,\nb\n)\n=\n\n∫\n\n0\n\nx\n\nr\n\na\n−\n1\n\n(\n1\n−\nr\n\n)\n\nb\n−\n1\n\n\nd\nr\n.\n\n{\\displaystyle {\\displaystyle \\mathrm {B} (x;a,b)=\\int \\_{0}^{x}r^{a-1}\\,(1-r)^{b-1}\\,\\mathrm {d} r.\\!}}\n\nand\n\nB\n(\nx\n,\ny\n)\n=\n\nΓ\n(\nx\n)\n\nΓ\n(\ny\n)\n\nΓ\n(\nx\n+\ny\n)\n=\nexp\n⁡\n(\nln\n⁡\n\nΓ\n(\nx\n)\n\nΓ\n(\ny\n)\n\nΓ\n(\nx\n+\ny\n)\n)\n=\nexp\n⁡\n(\n(\nln\n⁡\n(\nΓ\n(\nx\n)\n)\n+\nln\n⁡\n(\nΓ\n(\ny\n)\n)\n−\nln\n⁡\n(\nΓ\n(\nx\n+\ny\n)\n)\n)\n\n{\\displaystyle {\\displaystyle \\mathrm {B} (x,y)={\\dfrac {\\Gamma (x)\\,\\Gamma (y)}{\\Gamma (x+y)}}=\\exp(\\ln {\\dfrac {\\Gamma (x)\\,\\Gamma (y)}{\\Gamma (x+y)}})=\\exp((\\ln(\\Gamma (x))+\\ln(\\Gamma (y))-\\ln(\\Gamma (x+y)))\\!}}\n\np\n\n2\n−\nt\na\ni\nl\n{\\displaystyle {\\displaystyle p\\_{2-tail}}}\n can be calculated in terms of gamma functions and integrals more simply:\n\np\n\n2\n−\nt\na\ni\nl\n=\n\n∫\n\n0\n\n\nν\n\n\nt\n\n2\n+\nν\n\nr\n\nν\n2\n−\n1\n\n(\n1\n−\nr\n\n)\n\n−\n0.5\n\n\nd\nr\n\nexp\n⁡\n(\n(\nln\n⁡\n(\nΓ\n(\n\n\nν\n2\n)\n)\n+\nln\n⁡\n(\nΓ\n(\n0.5\n)\n)\n−\nln\n⁡\n(\nΓ\n(\n\n\nν\n2\n+\n0.5\n)\n)\n)\n{\\displaystyle {\\displaystyle p\\_{2-tail}={\\frac {\\int \\_{0}^{\\frac {\\nu }{t^{2}+\\nu }}r^{{\\frac {\\nu }{2}}-1}\\,(1-r)^{-0.5}\\,\\mathrm {d} r}{\\exp((\\ln(\\Gamma ({\\frac {\\nu }{2}}))+\\ln(\\Gamma (0.5))-\\ln(\\Gamma ({\\frac {\\nu }{2}}+0.5)))}}}}\n\nwhich simplifies to\n\np\n\n2\n−\nt\na\ni\nl\n=\n\n∫\n\n0\n\n\nν\n\n\nt\n\n2\n+\nν\n\nr\n\nν\n2\n−\n1\n\n1\n−\nr\n\n\nd\nr\n\nexp\n⁡\n(\n(\nln\n⁡\n(\nΓ\n(\n\n\nν\n2\n)\n)\n+\nln\n⁡\n(\nΓ\n(\n0.5\n)\n)\n−\nln\n⁡\n(\nΓ\n(\n\n\nν\n2\n+\n0.5\n)\n)\n)\n{\\displaystyle {\\displaystyle p\\_{2-tail}={\\frac {\\int \\_{0}^{\\frac {\\nu }{t^{2}+\\nu }}{\\frac {r^{{\\frac {\\nu }{2}}-1}}{\\sqrt {1-r}}}\\,\\mathrm {d} r}{\\exp((\\ln(\\Gamma ({\\frac {\\nu }{2}}))+\\ln(\\Gamma (0.5))-\\ln(\\Gamma ({\\frac {\\nu }{2}}+0.5)))}}}}\n\nThe definite integral can be approximated with Simpson's Rule but other methods are also acceptable.\n\nThe \n\nln\n⁡\n(\nΓ\n(\nx\n)\n)\n{\\displaystyle {\\displaystyle \\ln(\\Gamma (x))}}\n, or `lgammal(x)` function is necessary for the program to work with large `a` values, as Gamma functions can often return values larger than can be handled by `double` or `long double` data types. The `lgammal(x)` function is standard in `math.h` with C99 and C11 standards." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Integration using Simpson's Rule\n\n**Works with**: Rakudo version 2019.11\n\n**Translation of**: C\n\nPerhaps \"inspired by C example\" may be more accurate. Gamma subroutine from Gamma function task.\n\n```\nsub Γ(\\z) {\n constant g = 9;\n z < .5 ?? π / sin(π × z) / Γ(1 - z) !!\n τ.sqrt × (z + g - 1/2)**(z - 1/2) ×\n exp(-(z + g - 1/2)) ×\n [+] <\n 1.000000000000000174663\n 5716.400188274341379136\n -14815.30426768413909044\n 14291.49277657478554025\n -6348.160217641458813289\n 1301.608286058321874105\n -108.1767053514369634679\n 2.605696505611755827729\n -0.7423452510201416151527e-2\n 0.5384136432509564062961e-7\n -0.4023533141268236372067e-8\n > Z× 1, |map 1/(z + *), 0..*\n}\n\nsub p-value (@A, @B) {\n return 1 if @A <= 1 or @B <= 1;\n\n my $a-mean = @A.sum / @A;\n my $b-mean = @B.sum / @B;\n my $a-variance = @A.map( { ($a-mean - $_)² } ).sum / (@A - 1);\n my $b-variance = @B.map( { ($b-mean - $_)² } ).sum / (@B - 1);\n return 1 unless $a-variance && $b-variance;\n\n my \\Welchs-𝒕-statistic = ($a-mean - $b-mean)/($a-variance/@A + $b-variance/@B).sqrt;\n\n my $DoF = ($a-variance / @A + $b-variance / @B)² /\n (($a-variance² / (@A³ - @A²)) + ($b-variance² / (@B³ - @B²)));\n\n my $sa = $DoF / 2 - 1;\n my $x = $DoF / (Welchs-𝒕-statistic² + $DoF);\n my $N = 65355;\n my $h = $x / $N;\n my ( $sum1, $sum2 );\n\n for ^$N »×» $h -> $i {\n $sum1 += (($i + $h / 2) ** $sa) / (1 - ($i + $h / 2)).sqrt;\n $sum2 += $i ** $sa / (1 - $i).sqrt;\n }\n\n (($h / 6) × ( $x ** $sa / (1 - $x).sqrt + 4 × $sum1 + 2 × $sum2)) /\n ( Γ($sa + 1) × π.sqrt / Γ($sa + 1.5) );\n}\n\n# Testing\nfor (\n [<27.5 21.0 19.0 23.6 17.0 17.9 16.9 20.1 21.9 22.6 23.1 19.6 19.0 21.7 21.4>],\n [<27.1 22.0 20.8 23.4 23.4 23.5 25.8 22.0 24.8 20.2 21.9 22.1 22.9 20.5 24.4>],\n\n [<17.2 20.9 22.6 18.1 21.7 21.4 23.5 24.2 14.7 21.8>],\n [<21.5 22.8 21.0 23.0 21.6 23.6 22.5 20.7 23.4 21.8 20.7 21.7 21.5 22.5 23.6 21.5 22.5 23.5 21.5 21.8>],\n\n [<19.8 20.4 19.6 17.8 18.5 18.9 18.3 18.9 19.5 22.0>],\n [<28.2 26.6 20.1 23.3 25.2 22.1 17.7 27.6 20.6 13.7 23.2 17.5 20.6 18.0 23.9 21.6 24.3 20.4 24.0 13.2>],\n\n [<30.02 29.99 30.11 29.97 30.01 29.99>],\n [<29.89 29.93 29.72 29.98 30.02 29.98>],\n\n [<3.0 4.0 1.0 2.1>],\n [<490.2 340.0 433.9>]\n) -> @left, @right { say p-value @left, @right }\n\n```\n\nOutput:\n\n```\n0.0213780014628669\n0.148841696605328\n0.0359722710297969\n0.0907733242856673\n0.010751534033393\n\n```\n\n### Using Burkhardt's 'incomplete beta'\n\n**Works with**: Rakudo version 2019.11\n\n**Translation of**: Perl\n\nThis uses the Soper reduction formula to evaluate the integral, which converges much more quickly than Simpson's formula.\n\n```\nsub lgamma ( Num(Real) \\n --> Num ){\n use NativeCall;\n sub lgamma (num64 --> num64) is native {}\n lgamma( n )\n}\n\nsub p-value (@a, @b) {\n return 1 if @a.elems | @b.elems ≤ 1;\n my $mean1 = @a.sum / @a.elems;\n my $mean2 = @b.sum / @b.elems;\n return 1 if $mean1 == $mean2;\n\n my $variance1 = sum (@a «-» $mean1) X**2;\n my $variance2 = sum (@b «-» $mean2) X**2;\n return 1 if $variance1 | $variance2 == 0;\n\n $variance1 /= @a.elems - 1;\n $variance2 /= @b.elems - 1;\n my $Welchs-𝒕-statistic = ($mean1-$mean2)/sqrt($variance1/@a.elems+$variance2/@b.elems);\n my $DoF = ($variance1/@a.elems + $variance2/@b.elems)² /\n (($variance1 × $variance1)/(@a.elems × @a.elems × (@a.elems-1)) +\n ($variance2 × $variance2)/(@b.elems × @b.elems × (@b.elems-1))\n );\n my $A = $DoF / 2;\n my $value = $DoF / ($Welchs-𝒕-statistic² + $DoF);\n return $value if $A | $value ≤ 0 or $value ≥ 1;\n\n # from here, translation of John Burkhardt's C\n my $beta = lgamma($A) + 0.57236494292470009 - lgamma($A+0.5); # constant is logΓ(.5), more precise than 'lgamma' routine\n my $eps = 10**-15;\n my $psq = $A + 0.5;\n my $cx = 1 - $value;\n my ($xx,$pp,$qq,$indx);\n if $A < $psq × $value { ($xx, $cx, $pp, $qq, $indx) = $cx, $value, 0.5, $A, 1 }\n else { ($xx, $pp, $qq, $indx) = $value, $A, 0.5, 0 }\n my $term = my $ai = $value = 1;\n my $ns = floor $qq + $cx × $psq;\n\n # Soper reduction formula\n my $qq-ai = $qq - $ai;\n my $rx = $ns == 0 ?? $xx !! $xx / $cx;\n loop {\n $term ×= $qq-ai × $rx / ($pp + $ai);\n $value += $term;\n $qq-ai = $term.abs;\n if $qq-ai ≤ $eps & $eps×$value {\n $value = $value × ($pp × $xx.log + ($qq - 1) × $cx.log - $beta).exp / $pp;\n $value = 1 - $value if $indx;\n last\n }\n $ai++;\n $ns--;\n if $ns ≥ 0 {\n $qq-ai = $qq - $ai;\n $rx = $xx if $ns == 0;\n } else {\n $qq-ai = $psq;\n $psq += 1;\n }\n }\n $value\n}\n\nmy $error = 0;\nmy @answers = (\n0.021378001462867,\n0.148841696605327,\n0.0359722710297968,\n0.090773324285671,\n0.0107515611497845,\n0.00339907162713746,\n0.52726574965384,\n0.545266866977794,\n);\n\nfor (\n [<27.5 21.0 19.0 23.6 17.0 17.9 16.9 20.1 21.9 22.6 23.1 19.6 19.0 21.7 21.4>],\n [<27.1 22.0 20.8 23.4 23.4 23.5 25.8 22.0 24.8 20.2 21.9 22.1 22.9 20.5 24.4>],\n\n [<17.2 20.9 22.6 18.1 21.7 21.4 23.5 24.2 14.7 21.8>],\n [<21.5 22.8 21.0 23.0 21.6 23.6 22.5 20.7 23.4 21.8 20.7 21.7 21.5 22.5 23.6 21.5 22.5 23.5 21.5 21.8>],\n\n [<19.8 20.4 19.6 17.8 18.5 18.9 18.3 18.9 19.5 22.0>],\n [<28.2 26.6 20.1 23.3 25.2 22.1 17.7 27.6 20.6 13.7 23.2 17.5 20.6 18.0 23.9 21.6 24.3 20.4 24.0 13.2>],\n\n [<30.02 29.99 30.11 29.97 30.01 29.99>],\n [<29.89 29.93 29.72 29.98 30.02 29.98>],\n\n [<3.0 4.0 1.0 2.1>],\n [<490.2 340.0 433.9>],\n\n [<0.010268 0.000167 0.000167>],\n [<0.159258 0.136278 0.122389>],\n\n [<1.0/15 10.0/62.0>],\n [<1.0/10 2/50.0>],\n\n [<9/23.0 21/45.0 0/38.0>],\n [<0/44.0 42/94.0 0/22.0>],\n) -> @left, @right {\n my $p-value = p-value @left, @right;\n printf(\"p-value = %.14g\\n\",$p-value);\n $error += abs($p-value - shift @answers);\n}\nprintf(\"cumulative error is %g\\n\", $error);\n\n```\n\nOutput:\n\n```\np-value = 0.021378001462867\np-value = 0.14884169660533\np-value = 0.035972271029797\np-value = 0.090773324285667\np-value = 0.010751561149784\np-value = 0.0033990716271375\np-value = 0.52726574965384\np-value = 0.54526686697779\ncumulative error is 5.30131e-15\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nIn number theory, a **Wieferich prime** is a prime number ***p*** such that ***p2*** evenly divides ***2(p − 1) − 1*** .\n\nIt is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified.\n\nTask\n\n* Write a routine (function procedure, whatever) to find Wieferich primes.\n\n* Use that routine to identify and display all of the Wieferich primes less than 5000.\n\nSee also\n\n* OEIS A001220 - Wieferich primes" }, { "role": "assistant", "content": "```\nput \"Wieferich primes less than 5000: \", join ', ', ^5000 .grep: { .is-prime and not ( exp($_-1, 2) - 1 ) % .² };\n\n```\n\nOutput:\n\n```\nWieferich primes less than 5000: 1093, 3511\n```" } ]
[ { "role": "user", "content": "Task\n\nMake a file that can be useful with spell checkers like Ispell and Aspell.\n\nUse the wiktionary dump (input) to create a file equivalent to \"/usr/share/dict/spanish\" (output). The input file is an XML dump of the Wiktionary that is a bz2'ed file of about 800MB. The output file should be a file similar to \"/usr/share/dict/spanish\", a simple text file each line of which is one word in the given language. An example of such a file is available in Ubuntu with the package **wspanish**." }, { "role": "assistant", "content": "I misunderstood the data format and now just copy verbatim from Julia entry the processing logics ..\n\n```\n# 20211209 Raku programming solution \n\nuse LWP::Simple;\nuse Compress::Bzip2;\nuse IO::Socket::SSL;\n\nmy $LanguageMark = \"==French==\";\nmy $Target = 5; # words\nmy $URL = 'https://dumps.wikimedia.org/enwiktionary/latest/enwiktionary-latest-pages-articles.xml.bz2';\n\nclass CustomLWP is LWP::Simple { has $.URL ;\n\n method CustomRequest {\n\n my Blob $resp = Buf.new;\n my $bzip = Compress::Bzip2::Stream.new;\n my ( $tail, %needles ) = '';\n\n my ($host, $port, $path) = self.parse_url($.URL)[1..3]; \n my $sock = IO::Socket::SSL.new: :$host, :$port;\n\n $sock.print( \"GET {$path} HTTP/1.1\\r\\n\" ~ self.stringify_headers( { \n 'Connection' => 'close', \n 'User-Agent' => \"LWP::Simple/{LWP::Simple::<$VERSION>} \" ~\n \"Raku/{$*RAKU.compiler.gist}\",\n 'Host' => $host\n } ) ~ \"\\r\\n\" ) or die ; # request string\n\n while !self.got-header($resp) { $resp ~= $sock.read(2048) }\n\n my $bzip-stream = supply {\n emit self.parse_response($resp)[2]; # $resp_content @ parent class \n loop { \n done if %needles.elems >= $Target ;\n ( my $chunk = $sock.read(4096) ) ?? emit $chunk !! done \n }\n } \n\n react {\n whenever $bzip-stream -> $crypt {\n my $plain = ( [~] $bzip.decompress: $crypt ).decode('utf8-c8');\n my @haystacks = $plain.split: \"\\n\";\n @haystacks[0] = $tail ~ @haystacks[0]; \n $tail = @haystacks[*-1];\n\n my ($title,$got_text_last) = '', False ; \n\n for @haystacks[0..*-2] { \n if / '<title>' (\\w+?) '</title>' / {\n ($title,$got_text_last) = $0, False;\n } elsif / '<text' / { \n $got_text_last = True\n } elsif / $LanguageMark / {\n %needles{$title}++ if ( $got_text_last and $title.Bool ); \n last if ( %needles.elems >= $Target ) ; \n $got_text_last = False;\n } elsif / '</text>' / { $got_text_last = False } \n }\n }\n }\n return %needles.keys[^$Target]\n }\n}\n\nmy $ua = CustomLWP.new: URL => $URL ;\n\n$ua.CustomRequest>>.say\n\n```\n\nOutput:\n\n```\nchien\ngratuit\ngratis\npond\nlivre\n\n```" } ]
[ { "role": "user", "content": "Definition\n\nA Wilson prime of order n is a prime number   **p**   such that   **p2**   exactly divides:\n\n```\n (n − 1)! × (p − n)! − (− 1)n \n\n```\n\nIf   **n**   is   **1**,   the latter formula reduces to the more familiar:   **(p - n)! + 1**   where the only known examples for   **p**   are   **5**,   **13**,   and   **563**.\n\nTask\n\nCalculate and show on this page the Wilson primes, if any, for orders **n = 1 to 11 inclusive** and for primes **p < 18**   or,\n \nif your language supports *big integers*, for **p < 11,000**.\n\nRelated task\n: * Primality by Wilson's theorem" }, { "role": "assistant", "content": "```\n# Factorial\nsub postfix:<!> (Int $n) { (constant f = 1, |[\\×] 1..*)[$n] }\n\n# Invisible times\nsub infix:<⁢> is tighter(&infix:<**>) { $^a * $^b };\n\n# Prime the iterator for thread safety\nsink 11000!;\n\nmy @primes = ^1.1e4 .grep: *.is-prime;\n\nsay\n' n: Wilson primes\n────────────────────';\n\n.say for (1..40).hyper(:1batch).map: -> \\𝒏 { \n sprintf \"%3d: %s\", 𝒏, @primes.grep( -> \\𝒑 { (𝒑 ≥ 𝒏) && ((𝒏 - 1)!⁢(𝒑 - 𝒏)! - (-1) ** 𝒏) %% 𝒑² } ).Str\n}\n\n```\n\nOutput:\n\n```\n n: Wilson primes\n────────────────────\n 1: 5 13 563\n 2: 2 3 11 107 4931\n 3: 7\n 4: 10429\n 5: 5 7 47\n 6: 11\n 7: 17\n 8: \n 9: 541\n 10: 11 1109\n 11: 17 2713\n 12: \n 13: 13\n 14: \n 15: 349\n 16: 31\n 17: 61 251 479\n 18: \n 19: 71\n 20: 59 499\n 21: \n 22: \n 23: \n 24: 47 3163\n 25: \n 26: \n 27: 53\n 28: 347\n 29: \n 30: 137 1109 5179\n 31: \n 32: 71\n 33: 823 1181 2927\n 34: 149\n 35: 71\n 36: \n 37: 71 1889\n 38: \n 39: 491\n 40: 59 71 1171\n```" } ]
[ { "role": "user", "content": "Display a GUI window. The window need not have any contents, but should respond to requests to be closed." }, { "role": "assistant", "content": "(formerly Perl 6)\n**Library** GTK\n\nExit either by clicking the button or the close window control in the upper corner.\n\n```\nuse GTK::Simple;\nuse GTK::Simple::App;\n\nmy GTK::Simple::App $app .= new(title => 'Simple GTK Window');\n\n$app.size-request(250, 100);\n\n$app.set-content(\n GTK::Simple::VBox.new(\n my $button = GTK::Simple::Button.new(label => 'Exit'),\n )\n);\n\n$app.border-width = 40;\n\n$button.clicked.tap: { $app.exit }\n\n$app.run;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nCreate a simple **X11** application,   using an **X11** protocol library such as Xlib or XCB,   that draws a box and   \"Hello World\"   in a window.\n\nImplementations of this task should   *avoid using a toolkit*   as much as possible." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: C\n\nThere is not yet a X11 library in Raku but we can write the minimal C mappings for this task.\n\n```\nuse NativeCall;\n\nclass Display is repr('CStruct') {\n has int32 $!screen;\n has int32 $!window;\n }\nclass GC is repr('CStruct') {\n has int32 $!context;\n}\nclass XEvent is repr('CStruct') {\n has int32 $.type;\n method init { $!type = 0 }\n}\n\nsub XOpenDisplay(Str $name = ':0') returns Display is native('X11') { * }\nsub XDefaultScreen(Display $) returns int32 is native('X11') { * }\nsub XRootWindow(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XBlackPixel(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XWhitePixel(Display $, int32 $screen_number) returns int32 is native('X11') { * }\nsub XCreateSimpleWindow(\n Display $, int32 $parent_window, int32 $x, int32 $y,\n int32 $width, int32 $height, int32 $border_width,\n int32 $border, int32 $background\n) returns int32 is native('X11') { * }\nsub XMapWindow(Display $, int32 $window) is native('X11') { * }\nsub XSelectInput(Display $, int32 $window, int32 $mask) is native('X11') { * }\nsub XFillRectangle(\n Display $, int32 $window, GC $, int32 $x, int32 $y, int32 $width, int32 $height\n) is native('X11') { * }\nsub XDrawString(\n Display $, int32 $window, GC $, int32 $x, int32 $y, Str $, int32 $str_length\n) is native('X11') { * }\nsub XDefaultGC(Display $, int32 $screen) returns GC is native('X11') { * }\nsub XNextEvent(Display $, XEvent $e) is native('X11') { * }\nsub XCloseDisplay(Display $) is native('X11') { * }\n\nmy Display $display = XOpenDisplay()\n or die \"Can not open display\";\n\nmy int $screen = XDefaultScreen($display);\nmy int $window = XCreateSimpleWindow(\n $display,\n XRootWindow($display, $screen),\n 10, 10, 100, 100, 1,\n XBlackPixel($display, $screen), XWhitePixel($display, $screen)\n);\nXSelectInput($display, $window, 1 +< 15 +| 1);\nXMapWindow($display, $window);\n\nmy Str $msg = 'Hello, World!';\nmy XEvent $e .= new; $e.init;\nloop {\n XNextEvent($display, $e);\n if $e.type == 12 {\n\t XFillRectangle($display, $window, XDefaultGC($display, $screen), 20, 20, 10, 10);\n\t XDrawString($display, $window, XDefaultGC($display, $screen), 10, 50, $msg, my int $ = $msg.chars);\n }\n elsif $e.type == 2 {\n\t last;\n }\n}\nXCloseDisplay($display);\n\n```" } ]
[ { "role": "user", "content": "Treat windows or at least window identities as first class objects.\n\n* Store window identities in variables, compare them for equality.\n* Provide examples of performing some of the following:\n + hide,\n + show,\n + close,\n + minimize,\n + maximize,\n + move,     and\n + resize a window.\n\nThe window of interest may or may not have been created by your program." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nThis are generic window handling routines. They work for any window managed by the X11 display server, not just windows created by the program.\n\n```\nuse X11::libxdo;\n\nmy $xdo = Xdo.new;\n\nsay 'Visible windows:';\nprintf \"Class: %-21s ID#: %10d pid: %5d Name: %s\\n\", $_<class ID pid name>\n for $xdo.get-windows.sort(+*.key)».value;\nsleep 2;\n\nmy $id = $xdo.get-active-window;\n\nmy ($w, $h ) = $xdo.get-window-size( $id );\nmy ($wx, $wy) = $xdo.get-window-location( $id );\nmy ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );\n\n$xdo.move-window( $id, 150, 150 );\n\n$xdo.set-window-size( $id, 350, 350, 0 );\n\nsleep .25;\n\nfor flat 1 .. $dw - 350, $dw - 350, {$_ - 1} … 1 -> $mx { #\n my $my = (($mx / $dw * τ).sin * 500).abs.Int;\n $xdo.move-window( $id, $mx, $my );\n $xdo.activate-window($id);\n}\n\nsleep .25;\n\n$xdo.move-window( $id, 150, 150 );\n\nmy $dx = $dw - 300;\nmy $dy = $dh - 300;\n\n$xdo.set-window-size( $id, $dx, $dy, 0 );\n\nsleep .25;\n\nmy $s = -1;\n\nloop {\n $dx += $s * ($dw / 200).ceiling;\n $dy += $s * ($dh / 200).ceiling;\n $xdo.set-window-size( $id, $dx, $dy, 0 );\n $xdo.activate-window($id);\n sleep .005;\n $s *= -1 if $dy < 200;\n last if $dx >= $dw;\n}\n\nsleep .25;\n\n$xdo.set-window-size( $id, $w, $h, 0 );\n$xdo.move-window( $id, $wx, $wy );\n$xdo.activate-window($id);\n\nsleep .25;\n\n$xdo.minimize($id);\n$xdo.activate-window($id);\nsleep 1;\n$xdo.raise-window($id);\nsleep .25;\n\n```" } ]
[ { "role": "user", "content": "Wireworld is a cellular automaton with some similarities to Conway's Game of Life.\n\nIt is capable of doing sophisticated computations with appropriate programs\n(it is actually Turing complete),\nand is much simpler to program for.\n\nA Wireworld arena consists of a Cartesian grid of cells,\neach of which can be in one of four states.\nAll cell transitions happen simultaneously.\n\nThe cell transition rules are this:\n\n: : | Input State | Output State | Condition |\n | --- | --- | --- |\n | empty | empty | |\n | electron head | electron tail | |\n | electron tail | conductor | |\n | conductor | electron head | if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” |\n | conductor | conductor | otherwise |\n\nTask\n\nCreate a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using \"H\" for an electron head, \"t\" for a tail, \".\" for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate:\n\n```\ntH.........\n. .\n ...\n. .\nHt.. ......\n\n```\n\nWhile text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nclass Wireworld {\n has @.line;\n method height returns Int { @!line.elems }\n method width returns Int { max @!line».chars }\n\n multi method new(@line) { samewith :@line }\n multi method new($str ) { samewith $str.lines }\n\n method gist { join \"\\n\", @.line }\n\n method !neighbors($i where ^$.height, $j where ^$.width)\n {\n my @i = grep ^$.height, $i «+« (-1, 0, 1);\n my @j = grep ^$.width, $j «+« (-1, 0, 1);\n gather for @i X @j -> (\\i, \\j) {\n next if [ i, j ] ~~ [ $i, $j ];\n take @!line[i].comb[j];\n }\n }\n method succ {\n my @succ;\n for ^$.height X ^$.width -> ($i, $j) {\n @succ[$i] ~=\n do given @.line[$i].comb[$j] {\n when 'H' { 't' }\n when 't' { '.' }\n when '.' {\n grep('H', self!neighbors($i, $j)) == 1|2 ?? 'H' !! '.'\n }\n default { ' ' }\n }\n }\n return self.new: @succ;\n }\n}\n\nmy %*SUB-MAIN-OPTS;\n%*SUB-MAIN-OPTS<named-anywhere> = True;\n\nmulti sub MAIN (\n IO() $filename,\n Numeric:D :$interval = 1/4,\n Bool  :$stop-on-repeat,\n) {\n run-loop :$interval, :$stop-on-repeat, Wireworld.new: $filename.slurp;\n}\n\n#| run a built-in example\nmulti sub MAIN (\n Numeric:D :$interval = 1/4,\n Bool  :$stop-on-repeat,\n) {\n run-loop\n  :$interval,\n  :$stop-on-repeat,\n Wireworld.new:\n\tQ:to/§/\n\ttH.........\n\t. .\n\t ...\n\t. .\n\tHt.. ......\n\t§\n}\n\nsub run-loop (\n Wireworld:D $initial,\n Real:D(Numeric) :$interval = 1/4,\n Bool  :$stop-on-repeat\n){\n my %seen is SetHash;\n\n print \"\\e7\"; # save cursor position\n for $initial ...^ * eqv * { # generate a sequence (uses .succ)\n print \"\\e8\"; # restore cursor position\n .say;\n last if $stop-on-repeat and %seen{ .gist }++;\n sleep $interval;\n }\n}\n\n```\n\nWhen run with `--stop-on-repeat`\n\nOutput:\n\n```\nH.tH.tH.tH.\nt . \n ttt \nt . \n.H.t ......\n```" } ]
[ { "role": "user", "content": "A Wolstenholme number is a number that is the fully reduced numerator of a second order harmonic number:\n\nH\n\nn\n,\n2\n=\n\n∑\n\nk\n=\n1\n\nn\n\n\n1\n\nk\n\n2\n.\n{\\displaystyle H\\_{n,2}=\\sum \\_{k=1}^{n}{\\frac {1}{k^{2}}}.}\n\nPrime Wolstenholme numbers are Wolstenholme numbers that are prime.\n\n(Oddly enough, there is also a class of numbers called Wolstenholme primes that are **not** Wolstenholme numbers that are prime. This is not them.)\n\nTask\n\n* Find and display the first 20 Wolstenholme numbers. (Or as many as reasonably supported by your language if it is fewer.)\n* Find and display the first 4 prime Wolstenholme numbers. (Or as many as reasonably supported by your language if it is fewer.)\n\nStretch\n\n* Find and display the digit count of the 500th, 1000th, 2500th, 5000th, 10000th Wolstenholme numbers.\n* Find and display the digit count of the first 15 prime Wolstenholme numbers.\n\nSee also\n\n* Wikipedia: Wolstenholme number * OEIS:A007406 - Wolstenholme numbers * OEIS:A123751 - Prime Wolstenholme numbers" }, { "role": "assistant", "content": "```\nuse Lingua::EN::Numbers;\n\nsub abbr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '..' ~ .substr(*-20) ~ \" (digits: {.chars})\" }\n\nmy @wolstenholme = lazy ([\\+] (1..∞).hyper.map: {FatRat.new: 1, .²}).map: *.numerator;\n\nsay 'Wolstenholme numbers:';\nprintf \"%8s: %s\\n\", .&ordinal-digit(:c), abbr @wolstenholme[$_-1] for flat 1..20, 5e2, 1e3, 2.5e3, 5e3, 1e4;\n\nsay \"\\nPrime Wolstenholme numbers:\";\nprintf \"%8s: %s\\n\", .&ordinal-digit(:c), @wolstenholme.grep(&is-prime)[$_-1]».&abbr for 1..15;\n\n```\n\nOutput:\n\n```\nWolstenholme numbers:\n 1st: 1\n 2nd: 5\n 3rd: 49\n 4th: 205\n 5th: 5269\n 6th: 5369\n 7th: 266681\n 8th: 1077749\n 9th: 9778141\n 10th: 1968329\n 11th: 239437889\n 12th: 240505109\n 13th: 40799043101\n 14th: 40931552621\n 15th: 205234915681\n 16th: 822968714749\n 17th: 238357395880861\n 18th: 238820721143261\n 19th: 86364397717734821\n 20th: 17299975731542641\n 500th: 40989667509417020364..48084984597965892703 (digits: 434)\n 1,000th: 83545938483149689478..99094240207812766449 (digits: 866)\n 2,500th: 64537911900230612090..12785535902976933153 (digits: 2164)\n 5,000th: 34472086597488537716..22525144829082590451 (digits: 4340)\n10,000th: 54714423173933343999..49175649667700005717 (digits: 8693)\n\nPrime Wolstenholme numbers:\n 1st: 5\n 2nd: 266681\n 3rd: 40799043101\n 4th: 86364397717734821\n 5th: 36190908596780862323..79995976006474252029 (digits: 104)\n 6th: 33427988094524601237..48446489305085140033 (digits: 156)\n 7th: 22812704758392002353..84405125167217413149 (digits: 218)\n 8th: 28347687473208792918..45794572911130248059 (digits: 318)\n 9th: 78440559440644426017..30422337523878698419 (digits: 520)\n 10th: 22706893975121925531..02173859396183964989 (digits: 649)\n 11th: 27310394808585898968..86311385662644388271 (digits: 935)\n 12th: 13001072736642048751..08635832246554146071 (digits: 984)\n 13th: 15086863305391456002..05367804007944918693 (digits: 1202)\n 14th: 23541935187269979100..02324742766220468879 (digits: 1518)\n 15th: 40306783143871607599..58901192511859288941 (digits: 1539)\n```" } ]
[ { "role": "user", "content": "Task\n: Given an input string and a dictionary of words, segment the input string into a space-separated sequence of dictionary words if possible.\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.04\n\nThis implementation does not necessarily find *every* combination, it returns the one with the longest matching tokens.\n\n```\nmy @words = <a bc abc cd b>;\nmy $regex = @words.join('|');\n\nput \"$_: \", word-break($_) for <abcd abbc abcbcd acdbc abcdd>;\n\nsub word-break (Str $word) { ($word ~~ / ^ (<$regex>)+ $ /)[0] // \"Not possible\" }\n\n```\n\nOutput:\n\n```\nabcd: a b cd\nabbc: a b bc\nabcbcd: abc b cd\nacdbc: a cd bc\nabcdd: Not possible\n```" } ]
[ { "role": "user", "content": "Task\n\nGiven a text file and an integer   **n**,   print/display the   **n**   most\ncommon words in the file   (and the number of their occurrences)   in decreasing frequency.\n\nFor the purposes of this task:\n\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a   *letter*   is.\n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like   **well-dressed**   as either one word or two.\n* The word   **it's**   could also be one or two words as you see fit.\n* You may also choose not to support non US-ASCII characters.\n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences.\n* Treat   **color**   and   **colour**   as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\nShow example output using Les Misérables from Project Gutenberg as the text file input and display the top   **10**   most used words.\n\nHistory\n\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\nReferences\n\n* McIlroy's program\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 2022.07\n\nNote: much of the following exposition is no longer critical to the task as the requirements have been updated, but is left here for historical and informational reasons.\n\nThis is slightly trickier than it appears initially. The task specifically states: \"A word is a sequence of one or more contiguous letters\", so contractions and hyphenated words are broken up. Initially we might reach for a regex matcher like /\\w+/ , but \\w includes underscore, which is not a letter but a punctuation connector; and this text is **full** of underscores since that is how Project Gutenberg texts denote italicized text. The underscores are not actually parts of the words though, they are markup.\n\nWe might try /A-Za-z/ as a matcher but this text is bursting with French words containing various diacritics. Those **are** letters, so words will be incorrectly split up; (Misérables will be counted as 'mis' and 'rables', probably not what we want.)\n\nActually, in this case /A-Za-z/ returns **very nearly** the correct answer. Unfortunately, the name \"Alèthe\" appears once (only once!) in the text, gets incorrectly split into Al & the, and incorrectly reports 41089 occurrences of \"the\".\nThe text has several words like \"Panathenæa\", \"ça\", \"aérostiers\" and \"Keksekça\" so the counts for 'a' are off too. The other 8 of the top 10 are \"correct\" using /A-Za-z/, but it is mostly by accident.\n\nA more accurate regex matcher would be some kind of Unicode aware /\\w/ minus underscore. It may also be useful, depending on your requirements, to recognize contractions with embedded apostrophes, hyphenated words, and hyphenated words broken across lines.\n\nHere is a sample that shows the result when using various different matchers.\n\n```\nsub MAIN ($filename, UInt $top = 10) {\n my $file = $filename.IO.slurp.lc.subst(/ (<[\\w]-[_]>'-')\\n(<[\\w]-[_]>) /, {$0 ~ $1}, :g );\n my @matcher = \n rx/ <[a..z]>+ /, # simple 7-bit ASCII\n rx/ \\w+ /, # word characters with underscore\n rx/ <[\\w]-[_]>+ /, # word characters without underscore\n rx/ [<[\\w]-[_]>+]+ % < ' - '- > / # word characters without underscore but with hyphens and contractions\n  ;\n for @matcher -> $reg {\n say \"\\nTop $top using regex: \", $reg.raku;\n\t my @words = $file.comb($reg).Bag.sort(-*.value)[^$top];\n\t my $length = max @words».key».chars;\n printf \"%-{$length}s %d\\n\", .key, .value for @words;\n }\n}\n\n```\n\nOutput:\n\nPassing in the file name and 10:\n\n```\nTop 10 using regex: rx/ <[a..z]>+ /\nthe\t41089\nof\t19949\nand\t14942\na\t14608\nto\t13951\nin\t11214\nhe\t9648\nwas\t8621\nthat\t7924\nit\t6661\n\nTop 10 using regex: rx/ \\w+ /\nthe\t41035\nof\t19946\nand\t14940\na\t14577\nto\t13939\nin\t11204\nhe\t9645\nwas\t8619\nthat\t7922\nit\t6659\n\nTop 10 using regex: rx/ <[\\w]-[_]>+ /\nthe\t41088\nof\t19949\nand\t14942\na\t14596\nto\t13951\nin\t11214\nhe\t9648\nwas\t8621\nthat\t7924\nit\t6661\n\nTop 10 using regex: rx/ <[\\w]-[_]>+[[\"'\"|'-'|\"'-\"]<[\\w]-[_]>+]* /\nthe\t41081\nof\t19930\nand\t14934\na\t14587\nto\t13735\nin\t11204\nhe\t9607\nwas\t8620\nthat\t7825\nit\t6535\n```\n\nIt can be difficult to figure out what words the different regexes do or don't match. Here are the three more complex regexes along with a list of \"words\" that are treated as being different using this regex as opposed to /a..z/. IE: It is lumped in as one of the top 10 word counts using /a..z/ but not with this regex.\n\n```\nTop 10 using regex: rx/ \\w+ /\nthe\t41035\talèthe _the _the_\nof\t19946\tof_ _of_\nand\t14940\t_and_ paternoster_and\na\t14577\t_ça aïe ça keksekça aérostiers _a poréa panathenæa\nto\t13939\tto_ _to\nin\t11204\t_in\nhe\t9645\t_he\nwas\t8619\t_was\nthat\t7922\t_that\nit\t6659\t_it\n\nTop 10 using regex: rx/ <[\\w]-[_]>+ /\nthe\t41088\talèthe\nof\t19949\t\nand\t14942\t\na\t14596\tporéa ça aérostiers panathenæa aïe keksekça\nto\t13951\t\nin\t11214\t\nhe\t9648\t\nwas\t8621\t\nthat\t7924\t\nit\t6661\t\n\nTop 10 using regex: rx/ <[\\w]-[_]>+[[\"'\"|'-'|\"'-\"]<[\\w]-[_]>+]* /\nthe\t41081\twill-o'-the-wisps alèthe skip-the-gutter police-agent-ja-vert-was-found-drowned-un-der-a-boat-of-the-pont-au-change jean-the-screw will-o'-the-wisp\nof\t19930\tchromate-of-lead-colored die-of-hunger die-of-cold-if-you-have-bread police-agent-ja-vert-was-found-drowned-un-der-a-boat-of-the-pont-au-change unheard-of die-of-hunger-if-you-have-a-fire\nand\t14934\tcome-and-see so-and-so cock-and-bull hide-and-seek sambre-and-meuse\na\t14587\tkeksekça l'a ça now-a-days vis-a-vis a-dreaming police-agent-ja-vert-was-found-drowned-un-der-a-boat-of-the-pont-au-change poréa panathenæa aérostiers a-hunting aïe die-of-hunger-if-you-have-a-fire\nto\t13735\tto-morrow to-day hand-to-hand to-night well-to-do face-to-face\nin\t11204\tin-pace son-in-law father-in-law whippers-in general-in-chief sons-in-law\nhe\t9607\the's he'll\nwas\t8620\tpolice-agent-ja-vert-was-found-drowned-un-der-a-boat-of-the-pont-au-change\nthat\t7825\tthat's pick-me-down-that\nit\t6535\tit's it'll\n```\n\nOne nice thing is this isn't special cased. It will work out of the box for any text / language.\n\nRussian? No problem.\n\n```\n$ raku wf 14741-0.txt 5\n```\n\n```\nTop 5 using regex: rx/ <[a..z]>+ /\nthe\t176\nof\t119\ngutenberg\t93\nproject\t87\nto\t80\n\nTop 5 using regex: rx/ \\w+ /\nи\t860\nв\t579\nне\t290\nна\t222\nты\t195\n\nTop 5 using regex: rx/ <[\\w]-[_]>+ /\nи\t860\nв\t579\nне\t290\nна\t222\nты\t195\n\nTop 5 using regex: rx/ <[\\w]-[_]>+[[\"'\"|'-'|\"'-\"]<[\\w]-[_]>+]* /\nи\t860\nв\t579\nне\t290\nна\t222\nты\t195\n```\n\nGreek? Sure, why not.\n\n```\n$ raku wf 39963-0.txt 5\n```\n\n```\nTop 5 using regex: rx/ <[a..z]>+ /\nthe\t187\nof\t123\ngutenberg\t93\nproject\t87\nto\t82\n\nTop 5 using regex: rx/ \\w+ /\nκαι\t1628\nεις\t986\nδε\t982\nτου\t895\nτων\t859\n\nTop 5 using regex: rx/ <[\\w]-[_]>+ /\nκαι\t1628\nεις\t986\nδε\t982\nτου\t895\nτων\t859\n\nTop 5 using regex: rx/ <[\\w]-[_]>+[[\"'\"|'-'|\"'-\"]<[\\w]-[_]>+]* /\nκαι\t1628\nεις\t986\nδε\t982\nτου\t895\nτων\t859\n```\n\nOf course, for the first matcher, we are asking specifically to match Latin ASCII, so we end up with... well... Latin ASCII; but the other 3 match any Unicode characters." } ]
[ { "role": "user", "content": "Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.\n\nOnly one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.\n\nDemonstrate the following:\n\nA boy can be made into a man: boy -> bay -> ban -> man\n\nWith a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady\n\nA john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane\n\nA child can not be turned into an adult.\n\nOptional transpositions of your choice.\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": "```\nconstant %dict = 'unixdict.txt'.IO.lines\n .classify(*.chars)\n .map({ .key => .value.Set });\n\nsub word_ladder ( Str $from, Str $to ) {\n die if $from.chars != $to.chars;\n\n my $sized_dict = %dict{$from.chars};\n \n my @workqueue = (($from,),);\n my $used = ($from => True).SetHash;\n while @workqueue {\n my @new_q;\n for @workqueue -> @words {\n my $last_word = @words.tail;\n my @new_tails = gather for 'a' .. 'z' -> $replacement_letter {\n for ^$last_word.chars -> $i {\n my $new_word = $last_word;\n $new_word.substr-rw($i, 1) = $replacement_letter;\n\n next unless $new_word ∈ $sized_dict\n and not $new_word ∈ $used;\n take $new_word;\n $used{$new_word} = True;\n \n return |@words, $new_word if $new_word eq $to;\n }\n }\n push @new_q, ( |@words, $_ ) for @new_tails;\n }\n @workqueue = @new_q;\n }\n}\nfor <boy man>, <girl lady>, <john jane>, <child adult> -> ($from, $to) {\n say word_ladder($from, $to)\n // \"$from into $to cannot be done\";\n}\n\n```\n\nOutput:\n\n```\n(boy bay may man)\n(girl gill gall gale gaze laze lazy lady)\n(john cohn conn cone cane jane)\nchild into adult cannot be done\n```" } ]
[ { "role": "user", "content": "A word search puzzle typically consists of a grid of letters in which words are hidden.\n\nThere are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.\n\nThe words may overlap but are not allowed to zigzag, or wrap around.\n\nTask\n\nCreate a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.\n\nThe cells not used by the hidden words should contain the message: *Rosetta Code*, read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.\n\nPack a minimum of 25 words into the grid.\n\nPrint the resulting grid and the solutions.\n\nExample\n\n```\n 0 1 2 3 4 5 6 7 8 9\n\n0 n a y r y R e l m f \n1 y O r e t s g n a g \n2 t n e d i S k y h E \n3 n o t n c p c w t T \n4 a l s u u n T m a x \n5 r o k p a r i s h h \n6 a A c f p a e a c C \n7 u b u t t t O l u n \n8 g y h w a D h p m u \n9 m i r p E h o g a n \n\nparish (3,5)(8,5) gangster (9,1)(2,1)\npaucity (4,6)(4,0) guaranty (0,8)(0,1)\nprim (3,9)(0,9) huckster (2,8)(2,1)\nplasm (7,8)(7,4) fancy (3,6)(7,2)\nhogan (5,9)(9,9) nolo (1,2)(1,5)\nunder (3,4)(3,0) chatham (8,6)(8,0)\nate (4,8)(6,6) nun (9,7)(9,9)\nbutt (1,7)(4,7) hawk (9,5)(6,2)\nwhy (3,8)(1,8) ryan (3,0)(0,0)\nfay (9,0)(7,2) much (8,8)(8,5)\ntar (5,7)(5,5) elm (6,0)(8,0)\nmax (7,4)(9,4) pup (5,3)(3,5)\nmph (8,8)(6,8)\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 2020.01\n\n```\nmy $rows = 10;\nmy $cols = 10;\n\nmy $message = q:to/END/;\n .....R....\n ......O...\n .......S..\n ........E.\n T........T\n .A........\n ..C.......\n ...O......\n ....D.....\n .....E....\n END\n\nmy %dir =\n '→' => (1,0),\n '↘' => (1,1),\n '↓' => (0,1),\n '↙' => (-1,1),\n '←' => (-1,0),\n '↖' => (-1,-1),\n '↑' => (0,-1),\n '↗' => (1,-1)\n;\n\nmy @ws = $message.comb(/<print>/);\n\nmy $path = './unixdict.txt'; # or wherever\n\nmy @words = $path.IO.slurp.words.grep( { $_ !~~ /<-[a..z]>/ and 2 < .chars < 11 } ).pick(*);\nmy %index;\nmy %used;\n\nwhile @ws.first( * eq '.') {\n\n # find an unfilled cell\n my $i = @ws.grep( * eq '.', :k ).pick;\n\n # translate the index to x / y coordinates\n my ($x, $y) = $i % $cols, floor($i / $rows);\n\n # find a word that fits\n my $word = find($x, $y);\n\n # Meh, reached an impasse, easier to just throw it all\n # away and start over rather than trying to backtrack.\n restart, next unless $word;\n\n %used{\"$word\"}++;\n\n # Keeps trying to place an already used word, choices\n # must be limited, start over\n restart, next if %used{$word} > 15;\n\n # Already used this word, try again\n next if %index{$word.key};\n\n # Add word to used word index\n %index ,= $word;\n\n # place the word into the grid\n place($x, $y, $word);\n\n}\n\ndisplay();\n\nsub display {\n put flat \" \", 'ABCDEFGHIJ'.comb;\n .put for (^10).map: { ($_).fmt(\" %2d\"), @ws[$_ * $cols .. ($_ + 1) * $cols - 1] }\n put \"\\n Words used:\";\n my $max = 1 + %index.keys.max( *.chars ).chars;\n for %index.sort {\n printf \"%{$max}s %4s %s \", .key, .value.key, .value.value;\n print \"\\n\" if $++ % 2;\n }\n say \"\\n\"\n}\n\nsub restart {\n @ws = $message.comb(/<print>/);\n %index = ();\n %used = ();\n}\n\nsub place ($x is copy, $y is copy, $w) {\n my @word = $w.key.comb;\n my $dir = %dir{$w.value.value};\n @ws[$y * $rows + $x] = @word.shift;\n while @word {\n ($x, $y) »+=« $dir;\n @ws[$y * $rows + $x] = @word.shift;\n }\n }\n\nsub find ($x, $y) {\n my @trials = %dir.keys.map: -> $dir {\n my $space = '.';\n my ($c, $r) = $x, $y;\n loop {\n ($c, $r) »+=« %dir{$dir};\n last if 9 < $r|$c;\n last if 0 > $r|$c;\n my $l = @ws[$r * $rows + $c];\n last if $l ~~ /<:Lu>/;\n $space ~= $l;\n }\n next if $space.chars < 3;\n [$space.trans( '.' => ' ' ),\n (\"{'ABCDEFGHIJ'.comb[$x]} {$y}\" => $dir)]\n };\n\n for @words.pick(*) -> $word {\n for @trials -> $space {\n next if $word.chars > $space[0].chars;\n return ($word => $space[1]) if compare($space[0].comb, $word.comb)\n }\n }\n}\n\nsub compare (@s, @w) {\n for ^@w {\n next if @s[$_] eq ' ';\n return False if @s[$_] ne @w[$_]\n }\n True\n}\n\n```\n\nSample output:\n\n```\n A B C D E F G H I J\n 0 b y e e a R s w u k\n 1 r g e n p f O s e s\n 2 d i n l e i i S t i\n 3 r e b i l a c e E f\n 4 T g t a d a g n l T\n 5 d A a t d o w a i d\n 6 g i C n a n a l r c\n 7 a o g O p a l p r f\n 8 p g n p D d a i o a\n 9 c r u s h E s p t d\n\n Words used:\n aaa G 8 ↖ afield E 0 ↘ \n alley F 4 ↖ bye A 0 → \n caliber G 3 ← crush A 9 → \n dan F 8 ↑ dig A 5 ↘ \n epic D 0 ↘ fad J 7 ↓ \n fisk J 3 ↑ gap A 6 ↓ \n geigy B 4 ↑ get G 4 ↗ \n gnp B 8 → goa C 7 ← \n lane H 6 ↑ law G 7 ↑ \n nag D 6 ↖ nne D 1 ↙ \n odin F 5 ↖ orr I 8 ↑ \n paddle E 7 ↑ picnic E 1 ↘ \n pip H 9 ↑ rib A 1 ↘ \n sir G 9 ↗ sst G 0 ↘ \n tail D 5 ↑ ted C 4 ↖ \n tor I 9 ↑ usia I 0 ↙ \n wei H 0 ↘ \n```" } ]
[ { "role": "user", "content": "A \"word wheel\" is a type of word game commonly found on the \"puzzle\" page of\nnewspapers. You are presented with nine letters arranged in a circle or 3×3\ngrid. The objective is to find as many words as you can using only the letters\ncontained in the wheel or grid. Each word must contain the letter in the centre\nof the wheel or grid. Usually there will be a minimum word length of 3 or 4\ncharacters. Each letter may only be used as many times as it appears in the wheel\nor grid.\n\nAn example\n\n**: : : : : : : | | | |\n | --- | --- | --- |\n | N | D | E |\n | O | K | G |\n | E | L | W |**\n\nTask\n\nWrite a program to solve the above \"word wheel\" puzzle.\n\nSpecifically:\n\n: * Find all words of 3 or more letters using only the letters in the string   **ndeokgelw**.\n * All words must contain the central letter   **K**.\n * Each letter may be used only as many times as it appears in the string.\n * For this task we'll use lowercase English letters exclusively.\n\nA \"word\" is defined to be any string contained in the file located at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt.\n \nIf you prefer to use a different dictionary,   please state which one you have used.\n\nOptional extra\n\nWord wheel puzzles usually state that there is at least one nine-letter word to be found.\nUsing the above dictionary, find the 3x3 grids with at least one nine-letter\nsolution that generate the largest number of words of three or more letters.\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": "**Works with**: Rakudo version 2020.05\n\nEverything is adjustable through command line parameters.\n\nDefaults to task specified wheel, unixdict.txt, minimum 3 letters.\n\nUsing Terminal::Boxer from the Raku ecosystem.\n\n```\nuse Terminal::Boxer;\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nunit sub MAIN ($wheel = 'ndeokgelw', :$dict = './unixdict.txt', :$min = 3);\n\nmy $must-have = $wheel.comb[4].lc;\n\nmy $has = $wheel.comb».lc.Bag;\n\nmy %words;\n$dict.IO.slurp.words».lc.map: {\n next if not .contains($must-have) or .chars < $min;\n %words{.chars}.push: $_ if .comb.Bag ⊆ $has;\n};\n\nsay \"Using $dict, minimum $min letters.\";\n\nprint rs-box :3col, :3cw, :indent(\"\\t\"), $wheel.comb».uc;\n\nsay \"{sum %words.values».elems} words found\";\n\nprintf \"%d letters: %s\\n\", .key, .value.sort.join(', ') for %words.sort;\n\n```\n\nOutput:\n\nUsing defaults\n\n```\nraku word-wheel.raku\n\n```\n\n```\nUsing ./unixdict.txt, minimum 3 letters.\n\t╭───┬───┬───╮\n\t│ N │ D │ E │\n\t├───┼───┼───┤\n\t│ O │ K │ G │\n\t├───┼───┼───┤\n\t│ E │ L │ W │\n\t╰───┴───┴───╯\n17 words found\n3 letters: eke, elk, keg, ken, wok\n4 letters: keel, keen, keno, knee, knew, know, kong, leek, week, woke\n5 letters: kneel\n9 letters: knowledge\n```\n\nLarger dictionary\n\nUsing the much larger dictionary **words.txt** file from **https://github.com/dwyl/english-words**\n\n```\nraku word-wheel.raku --dict=./words.txt\n\n```\n\n```\nUsing ./words.txt, minimum 3 letters.\n\t╭───┬───┬───╮\n\t│ N │ D │ E │\n\t├───┼───┼───┤\n\t│ O │ K │ G │\n\t├───┼───┼───┤\n\t│ E │ L │ W │\n\t╰───┴───┴───╯\n86 words found\n3 letters: dkg, dkl, eek, egk, eke, ekg, elk, gok, ked, kee, keg, kel, ken, keo, kew, kln, koe, kol, kon, lek, lgk, nek, ngk, oke, owk, wok\n4 letters: deek, deke, doek, doke, donk, eked, elke, elko, geek, genk, gonk, gowk, keel, keen, keld, kele, kend, keno, keon, klee, knee, knew, know, koel, koln, kone, kong, kwon, leek, leke, loke, lonk, okee, oken, week, welk, woke, wolk, wonk\n5 letters: dekle, dekow, gleek, kedge, kendo, kleon, klong, kneed, kneel, knowe, konde, oklee, olnek, woken\n6 letters: gowked, keldon, kelwen, knowle, koleen\n8 letters: weeklong\n9 letters: knowledge\n```\n\nTop 5 maximum word wheels with at least one 9 letter word\n\nUsing unixdict.txt:\n\n```\nWheel\t\twords\neimnaprst:\t215\ncelmanort:\t215\nceimanrst:\t210\nelmnaoprt:\t208\nahlneorst:\t201\n```\n\nUsing words.txt:\n\n```\nWheel\t\twords\nmeilanrst:\t1329\ndeilanrst:\t1313\nceilanrst:\t1301\npeilanrst:\t1285\ngeilanrst:\t1284\n```" } ]
[ { "role": "user", "content": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.\n\nBasic task\n\nThe basic task is to wrap a paragraph of text in a simple way in your language.\n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\nExtra credit\n\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.\nIf your language provides this, you get easy extra credit,\nbut you *must reference documentation* indicating that the algorithm\nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where\nthe two algorithms give different results.\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 $s = \"In olden times when wishing still helped one, there lived a king\nwhose daughters were all beautiful, but the youngest was so beautiful\nthat the sun itself, which has seen so much, was astonished whenever\nit shone in her face. Close-by-the-king's-castle-lay-a-great-dark\nforest, and under an old lime-tree in the forest was a well, and when\nthe day was very warm, the king's child went out into the forest and\nsat down by the side of the cool fountain, and when she was bored she\ntook a golden ball, and threw it up on high and caught it, and this\nball was her favorite plaything.\";\n\n$s ~~ s:g/»\\s+/ /;\n$s ~~ s/\\s*$/\\n\\n/;\n\nsay $s.subst(/ \\s* (. ** 1..66) \\s /, -> $/ { \"$0\\n\" }, :g);\nsay $s.subst(/ \\s* (. ** 1..25) \\s /, -> $/ { \"$0\\n\" }, :g);\n\n```" } ]
[ { "role": "user", "content": "Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from\nthe last by a change in one letter.\n\nThe change can be either:\n\n1. a deletion of one letter;\n2. addition of one letter;\n3. or change in one letter.\n\nNote:\n\n* All words must be in the dictionary.\n* No word in a game can be repeated.\n* The first word must be three or four letters long.\n\nTask\n\nCreate a program to aid in the playing of the game by:\n\n* Asking for contestants names.\n* Choosing an initial random three or four letter word from the dictionary.\n* Asking each contestant in their turn for a wordiff word.\n* Checking the wordiff word is:\n\n: * in the dictionary,\n * not a repetition of past words,\n * and differs from the last appropriately.\n\nOptional stretch goals\n\n* Add timing.\n* Allow players to set a maximum playing time for the game.\n* An internal timer accumulates how long each user takes to respond in their turns.\n* Play is halted if the maximum playing time is exceeded on a players input.\n\n: * That last player must have entered a wordiff or loses.\n * If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "```\nmy @words = 'unixdict.txt'.IO.slurp.lc.words.grep(*.chars > 2);\n\nmy @small = @words.grep(*.chars < 6);\n\nuse Text::Levenshtein;\n\nmy ($rounds, $word, $guess, @used, @possibles) = 0;\n\nloop {\n my $lev;\n $word = @small.pick;\n hyper for @words -> $this {\n next if ($word.chars - $this.chars).abs > 1;\n last if ($lev = distance($word, $this)[0]) == 1;\n }\n last if $lev;\n}\n\nmy $name = ',';\n\n#[[### Entirely unnecessary and unuseful \"chatty repartee\" but is required by the task\n\nrun 'clear';\n$name = prompt \"Hello player one, what is your name? \";\nsay \"Cool. I'm going to call you Gomer.\";\n$name = ' Gomer,';\nsleep 1;\nsay \"\\nPlayer two, what is your name?\\nOh wait, this isn't a \\\"specified number of players\\\" game...\";\nsleep 1;\nsay \"Nevermind.\\n\";\n\n################################################################################]]\n\nloop {\n say \"Word in play: $word\";\n push @used, $word;\n @possibles = @words.hyper.map: -> $this {\n next if ($word.chars - $this.chars).abs > 1;\n $this if distance($word, $this)[0] == 1 and $this ∉ @used;\n }\n $guess = prompt \"your word? \";\n last unless $guess ∈ @possibles;\n ++$rounds;\n say qww<Ok! Woot! 'Way to go!' Nice! 👍 😀>.pick ~ \"\\n\";\n $word = $guess;\n}\n\nmy $already = ($guess ∈ @used) ?? \" $guess was already played but\" !! '';\n\nif @possibles {\n say \"\\nOops. Sorry{$name}{$already} one of [{@possibles}] would have continued the game.\"\n} else {\n say \"\\nGood job{$name}{$already} there were no possible words to play.\"\n}\nsay \"You made it through $rounds rounds.\";\n\n```\n\nSample output:\n\n```\nHello player one, what is your name? Burtram Redneck\nCool. I'm going to call you Gomer.\n\nPlayer two, what is your name?\nOh wait, this isn't a \"specified number of players\" game...\nNevermind.\n\nWord in play: howe\nyour word? how\nWoot!\n\nWord in play: how\nyour word? show\n👍\n\nWord in play: show\nyour word? shot\nNice!\n\nWord in play: shot\nyour word? hot\n😀\n\nWord in play: hot\nyour word? hit\nWay to go!\n\nWord in play: hit\nyour word? mit\nNice!\n\nWord in play: mit\nyour word? kit\n😀\n\nWord in play: kit\nyour word? nit\nWoot!\n\nWord in play: nit\nyour word? nip\n😀\n\nWord in play: nip\nyour word? snip\nOk!\n\nWord in play: snip\nyour word? slip\nOk!\n\nWord in play: slip\nyour word? slap\nWay to go!\n\nWord in play: slap\nyour word? lap\nWoot!\n\nWord in play: lap\nyour word? nap\nWoot!\n\nWord in play: nap\nyour word? nan\nNice!\n\nWord in play: nan\nyour word? man\nNice!\n\nWord in play: man\nyour word? men\nWoot!\n\nWord in play: men\nyour word? ben\nNice!\n\nWord in play: ben\nyour word? ban\n👍\n\nWord in play: ban\nyour word? man\n\nOops. Sorry Gomer, man was already played but one of [bad bag bah bam band bane bang bank bar barn bat bay bean bin bon bran bun can dan fan han ian jan pan ran san tan van wan zan] would have continued the game.\nYou made it through 19 rounds.\n```" } ]
[ { "role": "user", "content": "Rationale\n\nWhile similar to both Bulls and cows and Mastermind, Wordle is a notable variation, having experienced a viral surge in popularity, and reverse engineering the game or creating variants has become a popular programming exercise. However, a sampling of the \"code a Wordle clone\" videos on YouTube shows that seven of the eight reviewed had a serious flaw in the way that they assigned colours to the letters of a guessed word. This aspect of the game is described here: en.wikipedia.org/wiki/Wordle#Gameplay\n\n> After every guess, each letter is marked as either green, yellow or gray: green indicates that letter is correct and in the correct position, yellow means it is in the answer but not in the right position, while gray indicates it is not in the answer at all. Multiple instances of the same letter in a guess, such as the \"o\"s in \"robot\", will be colored green or yellow only if the letter also appears multiple times in the answer; otherwise, excess repeating letters will be colored gray.\n\nTask\n\nCreate a function or procedure that takes two strings; the answer string, and the guess string, and returns a string, list, dynamic array or other ordered sequence indicating how each letter should be marked as per the description above. (e.g. \"green\", \"yellow\", or \"grey\", or, equivalently, the integers 2, 1, or 0 or suchlike.)\n\nYou can assume that both the answer string and the guess string are the same length, and contain only printable characters/code points in the ASCII/UniCode Range ! to ~ (hex 20 to 7F) and that case is significant. (The original game only uses strings of 5 characters, all alphabetic letters, all in the same case, but this allows for most existing variants of the game.)\n\nProvide test data and show the output here.\n\nThe test data should include the answer string `ALLOW` and the guess string `LOLLY`, and the result should be `(yellow, yellow, green, grey, grey)` or equivalent." }, { "role": "assistant", "content": "Updated to add a proof of concept matching for similarity where commonly found on spoofing domain names. Of course this is just the tip of the iceberg (only comparing results after decomposition) and there are way too many Unicode homoglyphs that can only be matched using a lookup table/database.\n\n```\n# 20220216 Raku programming solution\n\nsub wordle (\\answer,\\guess where [==] (answer,guess)».chars ) {\n\n my ($aSet, $gSet, @return) = (answer,guess)».&{ (set .comb.pairs).SetHash }\n\n (my \\intersection = $aSet ∩ $gSet).keys».&{ @return[.key] = 'green' }\n ($aSet,$gSet)».&{ $_ ∖= intersection } # purge common subset\n\n for $gSet.keys.sort -> \\trial { # pair \n @return[trial.key] = 'grey';\n for $aSet.keys -> \\actual { # pair\n if [eq] (trial,actual)».value {\n @return[trial.key] = 'yellow'; \n $aSet{actual}:delete;\n last\n } \n my @NFD = (trial,actual).map: { .value.NFD }\n if [ne] @NFD and [==] @NFD».first {\n @return[trial.key] = 'azure';\n $aSet{actual}:delete;\n last\n }\n }\n }\n @return\n}\n\nsay .[0]~' vs '~.[1]~\"\\t\"~ wordle .[0],.[1] for (\n<ALLOW LOLLY>, <ROBIN ALERT>, <ROBIN SONIC>, <ROBIN ROBIN>, <BULLY LOLLY>,\n<ADAPT SÅLÅD>, <Ukraine Ukraíne>, <BBAABBB BBBBBAA>, <BBAABBB AABBBAA> );\n\n```\n\nOutput:\n\n```\nALLOW vs LOLLY yellow yellow green grey grey\nROBIN vs ALERT grey grey grey yellow grey\nROBIN vs SONIC grey green yellow green grey\nROBIN vs ROBIN green green green green green\nBULLY vs LOLLY grey grey green green green\nADAPT vs SÅLÅD\tgrey azure grey azure yellow\nUkraine vs Ukraíne\tgreen green green green azure green green\nBBAABBB vs BBBBBAA green green yellow yellow green yellow yellow\nBBAABBB vs AABBBAA yellow yellow yellow yellow green grey grey\n\n```" } ]
[ { "role": "user", "content": "Task\n\nUsing the dictionary   unixdict.txt,   search words containing \"the\" substring,\n \nthen display the found words (on this page).\n\nThe length of any word shown should have a length   **>  11****.**\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": "A trivial modification of the ABC words task.\n\n```\nput 'unixdict.txt'.IO.words».fc.grep({ (.chars > 11) && (.contains: 'the') })\\\n .&{\"{+$_} words:\\n \" ~ .batch(8)».fmt('%-17s').join: \"\\n \"};\n\n```\n\nOutput:\n\n```\n32 words:\n authenticate chemotherapy chrysanthemum clothesbrush clotheshorse eratosthenes featherbedding featherbrain \n featherweight gaithersburg hydrothermal lighthearted mathematician neurasthenic nevertheless northeastern \n northernmost otherworldly parasympathetic physiotherapist physiotherapy psychotherapeutic psychotherapist psychotherapy \n radiotherapy southeastern southernmost theoretician weatherbeaten weatherproof weatherstrip weatherstripping \n```" } ]
[ { "role": "user", "content": "Task\n\nUse the dictionary   unixdict.txt\n\nIgnore any word in the dictionary whose length is less than 9.\n\nLet's take the words from next characters:\n \n1 <= n < (dictionary length) - 9.\n \nchar1 = 1st character of         nth   word.\n \nchar2 = 2nd character of  (n+1)th  word.\n \nchar3 = 3rd character of  (n+2)th  word.\n \n     ⋮ \n \nchar9 = 9th character of  (n+8)th  word.\n\nConcatenate (append) the nine characters by:\n\n```\n newword = char1 + char2 + char3 + ... + char9 \n\n```\n\nIf   *newword*   is in the dictionary, then show on this page.\n\nLength of  *newword* = 9\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "```\nmy @words_ge_9 = 'unixdict.txt'.IO.lines.grep( *.chars >= 9 );\nmy %words_eq_9 = @words_ge_9 .grep( *.chars == 9 ).Set;\n\nmy @new_words = gather for @words_ge_9.rotor( 9 => -8 ) -> @nine_words {\n my $new_word = [~] map { @nine_words[$_].substr($_, 1) }, ^9;\n\n take $new_word if %words_eq_9{$new_word};\n}\n\n.say for unique @new_words;\n\n```\n\nOutput:\n\n```\napplicate\narchitect\nastronomy\nchristine\nchristoph\ncommittee\ncomposite\nconstrict\nconstruct\ndifferent\nextensive\ngreenwood\nimplement\nimprovise\nintercept\ninterpret\ninterrupt\nphilosoph\nprescript\nreceptive\ntelephone\ntranscend\ntransport\ntranspose\n\n```" } ]
[ { "role": "user", "content": "It's World Cup season (or at least it was when this page was created)!\n\nThe World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams.\n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage.\n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.\n\n: : : * A win is worth three points.\n * A draw/tie is worth one point.\n * A loss is worth zero points.\n\nTask\n: * Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.\n * Calculate the standings points for each team with each combination of outcomes.\n * Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\nDon't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n*Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.*" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.12\n\n**Translation of**: Python\n\n```\nconstant scoring = 0, 1, 3;\nmy @histo = [0 xx 10] xx 4;\n\nfor [X] ^3 xx 6 -> @results {\n my @s;\n\n for @results Z (^4).combinations(2) -> ($r, @g) {\n @s[@g[0]] += scoring[$r];\n @s[@g[1]] += scoring[2 - $r];\n }\n\n for @histo Z @s.sort -> (@h, $v) {\n ++@h[$v];\n }\n}\n\nsay .fmt('%3d',' ') for @histo.reverse;\n\n```\n\nOutput:\n\n```\n 0 0 0 1 14 148 152 306 0 108\n 0 0 4 33 338 172 164 18 0 0\n 0 18 136 273 290 4 8 0 0 0\n108 306 184 125 6 0 0 0 0 0\n```" } ]
[ { "role": "user", "content": "Recreate https://xkcd.com/1205/ which shows a (humorous) table of how long you can work on making a\nroutine task more efficient before spending more time than saved, for various s(h)avings against how\noften the task is run (over the course of five years).\n\nThere are of course several possible interpretations of \"day\" and \"week\" in this context. The Phix\nimplementation assumes 8 hour days and 5 day weeks might be more realistic, whereas it seems the\noriginal author worked with 24 hour days and 7 day weeks, and, tbh, my interest is piqued to see\nwhat built-in facilities other languages might have for handling such non-standard terms, if any.\nExtra kudos awarded for getting into the mind of the original author and reproducing their results\nexactly (see talk page), or drumming up non-trivial (but still elegant) and potentially actually useful routines.\nThis task can be made as trivial or as convoluted as you please, and should aim more for a little\nplayfulness than rigid scientific accuracy." }, { "role": "assistant", "content": "**Translation of**: Wren\n\n```\n# 20220207 Raku programming solution \n\nmy \\shaved = [1, 5, 30, 60, 300, 1800, 3600, 21600, 86400]; # time shaved off in seconds\nmy \\columns = [ \"1 SECOND\", \"5 SECONDS\", \"30 SECONDS\", \"1 MINUTE\", \"5 MINUTES\",\n \"30 MINUTES\", \"1 HOUR\", \"6 HOURS\", \"1 DAY\" ];\nmy \\diy = 365.25;\nmy \\minute = 60;\nmy \\hour = minute * 60;\nmy \\day = hour * 24;\nmy \\week = day * 7;\nmy \\month = day * diy / 12;\nmy \\year = day * diy;\nmy \\freq = [50 * diy, 5 * diy, diy, diy/7, 12, 1]; # frequency per year\nmy \\mult = 5; # multiplier for table\n\nsub fmtTime (\\t, \\interval) { printf \"%-12s \", t.floor~\" \"~interval~(t == 1 ?? \"\" !! \"S\") }\n\nsay ' ' x 34~\"HOW OFTEN YOU DO THE TASK\";\nprintf(\"%-12s | %-12s %-12s %-12s %-12s %-12s %-12s\\n\", \n [\"SHAVED OFF\", \"50/DAY\", \"5/DAY\", \"DAILY\", \"WEEKLY\", \"MONTHLY\", \"YEARLY\"]);\nsay '-' x 93;\n\nfor ^9 -> \\y {\n printf \"%-12s | \", columns[y];\n for ^6 -> \\x {\n given my \\t = freq[x] * shaved[y] * mult {\n when t < minute { fmtTime t, \"SECOND\" } \n when t < hour { fmtTime t/minute, \"MINUTE\" } \n when t < day { fmtTime t/hour, \"HOUR\" } \n when t < 14*day { fmtTime t/day, \"DAY\" } \n when t < 9*week { fmtTime t/week, \"WEEK\" }\n when t < year { fmtTime t/month, \"MONTH\" }\n default { print ' N/A ' }\n }\n }\n print \"\\n\"\n}\n\n```\n\nOutput:\n\n```\n HOW OFTEN YOU DO THE TASK\nSHAVED OFF | 50/DAY 5/DAY DAILY WEEKLY MONTHLY YEARLY\n---------------------------------------------------------------------------------------------\n1 SECOND | 1 DAYS 2 HOURS 30 MINUTES 4 MINUTES 1 MINUTE 5 SECONDS\n5 SECONDS | 5 DAYS 12 HOURS 2 HOURS 21 MINUTES 5 MINUTES 25 SECONDS\n30 SECONDS | 4 WEEKS 3 DAYS 15 HOURS 2 HOURS 30 MINUTES 2 MINUTES\n1 MINUTE | 2 MONTHS 6 DAYS 1 DAYS 4 HOURS 1 HOUR 5 MINUTES\n5 MINUTES | 10 MONTHS 4 WEEKS 6 DAYS 21 HOURS 5 HOURS 25 MINUTES\n30 MINUTES | N/A 6 MONTHS 5 WEEKS 5 DAYS 1 DAYS 2 HOURS\n1 HOUR | N/A N/A 2 MONTHS 10 DAYS 2 DAYS 5 HOURS\n6 HOURS | N/A N/A N/A 2 MONTHS 2 WEEKS 1 DAYS\n1 DAY | N/A N/A N/A 8 MONTHS 8 WEEKS 5 DAYS\n\n```" } ]
[ { "role": "user", "content": "Task\n\n(Over)write a file so that it contains a string.\n\nThe reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nspurt 'path/to/file', $file-data;\n\n```\n\nor\n\n```\n'path/to/file'.IO.spurt: $file-data;\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite two equal-sized numerical arrays 'x' and 'y' to\na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a\ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n\n```\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\n```\n\nThe file should look like:\n\n```\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\n```\n\nThis task is intended as a subtask for Measure relative performance of sorting algorithms implementations." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Perl 5-ish\n\nWritten in the style of the 2nd Perl 5 example.\n\n```\nsub writefloat ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) {\n my $fh = open $filename, :w;\n for flat @x Z @y -> $x, $y {\n $fh.printf: \"%.*g\\t%.*g\\n\", $x_precision, $x, $y_precision, $y;\n }\n $fh.close;\n}\n \nmy @x = 1, 2, 3, 1e11;\nmy @y = @x.map({.sqrt});\n\nwritefloat( 'sqrt.dat', @x, @y );\n\n```\n\nOutput:\n\n```\n1\t1\n2\t1.4142\n3\t1.7321\n1e+11\t3.1623e+05\n```\n\n### Idiomatic\n\nWritten in a more idiomatic style.\n\n```\nsub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 3) {\n open($filename, :w).print:\n join '', flat (@x».fmt(\"%.{$x-precision}g\") X \"\\t\") Z (@y».fmt(\"%.{$y-precision}g\") X \"\\n\");\n}\nmy @x = 1, 2, 3, 1e11;\nwritefloat('sqrt.dat', @x, @x».sqrt, :y-precision(5));\n\n```\n\nOutput:\n\n```\n1\t1\n2\t1.4142\n3\t1.7321\n1e+11\t3.1623e+05\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite/display a language's name in **3D** ASCII.\n\n(We can leave the definition of \"3D ASCII\" fuzzy,\nso long as the result is interesting or amusing,\nnot a cheap hack to satisfy the task.)\n\nRelated tasks\n\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar" }, { "role": "assistant", "content": "(formerly Perl 6)\nProduces a good old-fashioned stereogram, meant to be looked at by focusing beyond the screen, not by crossing your eyes. If you can't get it to converge, try shrinking the font size till the images are closer together than your eyes. Also helps to be old enough to have progressive lenses, so you can look through the reading part of your glasses. Or borrow glasses from someone who's farsighted. :-)\n\n```\n# must be evenly padded with white-space$\nmy $text = q:to/END/;\n \n @@@@@ @@ \n @ @ @ @@@ \n @ @ @ @@ \n @ @ @@@ @ @@ @ @@ \n @@@@@ @ @ @@ @ @ @@@@@ \n @ @@@@@ @ @ @@ @@ \n @ @ @ @ @@ @@ \n @ @@@ @ @@ @@@@ \n \nEND\n\nsay '' for ^5;\nfor $text.lines -> $_ is copy {\n my @chars = |「-+ ., ;: '\"」.comb.pick(*) xx *;\n s:g [' '] = @chars.shift;\n print \" $_ \";\n s:g [('@'+)(.)] = @chars.shift ~ $0;\n .say;\n}\nsay '' for ^5;\n\n```\n\nOutput:\n\n```\n\n \";,' :-+ . ,. ; -:+\"',';-. : \" + \";,' :-+ . ,. ; -:+\"',';-. : \" + \n  :@@@@@ ,'+\".-; ;-+,@@\"'  :.  ;. \"  :'@@@@@ ,'+\".-; ;-+,,@@'  :.  ;. \"\n \"@-. @ ';,+:- +: ,;@'\". +@@@, \"- \" @. .@';,+:- +: ,;:@\". +;@@@ \"-\n '@,- ;@ \"+: .+ -',:\" @; . @@; -\" , ':@- ;'@\"+: .+ -',:\" .@ . +@@ -\" ,\n  ;@ +, @\"-@@@' :@.@@ @-,:.@@+ ;'\":  ; @+, .@-'@@@ : @;@@ @,:.+@@ ;'\":\n @@@@@+-@':.@, @@\" @;@ +\":@@@@@',  ;@@@@@--@:. @ .@@ :@ @+\": @@@@@, \n @;-+, .@@@@@ :@\"'+' @\"-,:@@; @@. +@-+, .,@@@@@::@'+' @-,: @@ \"@@ \n  :@ . \"- @,;+'; @\" .-'@ +:,@@ ;@@'+  :-@. \"- ,@;+'; \"@ .-' @+:, @@;:@@+\n +@'\"., ; @@@ -:@;' \"@@-+.:@@@@, +:@\"., ; \"@@@-:;@' \".@@+.: @@@@ \n  ;.:+\"-,' +:'; -,\" .+:\"  ;-.,' .  ;.:+\"-,' +:'; -,\" .+:\"  ;-.,' .\n\n```" } ]
[ { "role": "user", "content": "Task\n\nWrite script status to the Windows Event Log" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.01\n\nThere is not yet (that I am aware of) a native interface to the Windows logging functions, but Raku can shell out and run a console command just as easily as most of these other languages. It *does* have a native interface to the syslog functions under POSIX environments though.\n\n(Same caveats as the others, needs to be run as administrator or with elevated privileges under Windows.)\n\n```\ngiven $*DISTRO {\n when .is-win {\n my $cmd = \"eventcreate /T INFORMATION /ID 123 /D \\\"Bla de bla bla bla\\\"\";\n run($cmd);\n }\n default { # most POSIX environments\n use Log::Syslog::Native;\n my $logger = Log::Syslog::Native.new(facility => Log::Syslog::Native::User);\n $logger.info(\"[$*PROGRAM-NAME pid=$*PID user=$*USER] Just thought you might like to know.\");\n }\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement the   Xiaolin Wu's line algorithm   described in Wikipedia.\n\nThis algorithm draws anti-aliased lines.\n\nRelated task\n\n* See   Bresenham's line algorithm   for *aliased* lines." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub plot(\\x, \\y, \\c) { say \"plot {x} {y} {c}\" }\n \nsub fpart(\\x) { x - floor(x) }\n \nsub draw-line(@a is copy, @b is copy) {\n my Bool \\steep = abs(@b[1] - @a[1]) > abs(@b[0] - @a[0]);\n my $plot = &OUTER::plot;\n \n if steep {\n\t$plot = -> $y, $x, $c { plot($x, $y, $c) }\n\t@a.=reverse;\n\t@b.=reverse;\n }\n if @a[0] > @b[0] { my @t = @a; @a = @b; @b = @t }\n\n my (\\x0,\\y0) = @a;\n my (\\x1,\\y1) = @b;\n \n my \\dx = x1 - x0;\n my \\dy = y1 - y0;\n my \\gradient = dy / dx;\n \n # handle first endpoint\n my \\x-end1 = round(x0);\n my \\y-end1 = y0 + gradient * (x-end1 - x0);\n my \\x-gap1 = 1 - round(x0 + 0.5);\n\n my \\x-pxl1 = x-end1; # this will be used in the main loop\n my \\y-pxl1 = floor(y-end1);\n my \\c1 = fpart(y-end1) * x-gap1;\n\n $plot(x-pxl1, y-pxl1 , 1 - c1) unless c1 == 1;\n $plot(x-pxl1, y-pxl1 + 1, c1 ) unless c1 == 0;\n \n # handle second endpoint\n my \\x-end2 = round(x1);\n my \\y-end2 = y1 + gradient * (x-end2 - x1);\n my \\x-gap2 = fpart(x1 + 0.5);\n\n my \\x-pxl2 = x-end2; # this will be used in the main loop\n my \\y-pxl2 = floor(y-end2);\n my \\c2 = fpart(y-end2) * x-gap2;\n \n my \\intery = y-end1 + gradient;\n\n # main loop\n for (x-pxl1 + 1 .. x-pxl2 - 1)\n\tZ\n\t(intery, intery + gradient ... *)\n -> (\\x,\\y) {\n\tmy \\c = fpart(y);\n\t$plot(x, floor(y) , 1 - c) unless c == 1;\n\t$plot(x, floor(y) + 1, c ) unless c == 0;\n }\n\n $plot(x-pxl2, y-pxl2 , 1 - c2) unless c2 == 1;\n $plot(x-pxl2, y-pxl2 + 1, c2 ) unless c2 == 0;\n}\n\ndraw-line [0,1], [10,2];\n\n```\n\nOutput:\n\n```\nplot 0 1 1\nplot 1 1 0.9\nplot 1 2 0.1\nplot 2 1 0.8\nplot 2 2 0.2\nplot 3 1 0.7\nplot 3 2 0.3\nplot 4 1 0.6\nplot 4 2 0.4\nplot 5 1 0.5\nplot 5 2 0.5\nplot 6 1 0.4\nplot 6 2 0.6\nplot 7 1 0.3\nplot 7 2 0.7\nplot 8 1 0.2\nplot 8 2 0.8\nplot 9 1 0.1\nplot 9 2 0.9\nplot 10 2 1\n```" } ]
[ { "role": "user", "content": "Given an XML document and an XSD schema definition validate that the document follows the schema described.\n\nSample XML and XSD for tests can be found on this W3 Schools page." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\n# Reference: https://github.com/libxml-raku/LibXML-raku\n\nuse v6.d;\nuse LibXML;\nuse LibXML::Schema;\n\nmy $good_xml = '<a>5</a>';\nmy $bad_xml = '<a>5<b>foobar</b></a>';\n\nmy $xsdschema = q:to<EOF>;\n <xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <xsd:element name=\"a\" type=\"xsd:integer\"/>\n </xsd:schema>\nEOF\n\nmy LibXML $p .= new();\n\nfor ( $good_xml, $bad_xml ) {\n my $x = $p.parse: :string($_);\n try { LibXML::Schema.new( string => $xsdschema ).validate( $x ) }\n  !$! ?? say \"Valid.\" !! say $!.message() ;\n}\n\n```\n\nOutput:\n\n```\nValid.\nSchemas validity error : Element 'a': Element content is not allowed, because the type definition is simple.\n\n```" } ]
[ { "role": "user", "content": "Create a simple DOM and having it serialize to:\n\n```\n <?xml version=\"1.0\" ?>\n <root>\n <element>\n Some text here\n </element>\n </root>\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\n```\nuse XML;\nuse XML::Writer;\n\nsay my $document = XML::Document.new(\n XML::Writer.serialize( :root[ :element['Some text here', ], ] )\n);\n\n```\n\nOutput:\n\n```\n<?xml version=\"1.0\"?><root><element>Some text here</element></root>\n\n```" } ]
[ { "role": "user", "content": "Given the following XML fragment, extract the list of *student names* using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.\n\n```\n<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>\n\n```\n\nExpected Output\n\n```\nApril\nBob\nChad\nDave\nÉmily\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.02\n\n**Library:** XML\n\n```\nuse XML;\n\nmy $xml = from-xml '<Students>\n <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n <Pet Type=\"dog\" Name=\"Rover\" />\n </Student>\n <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n</Students>';\n\nsay .<Name> for $xml.nodes.grep(/Student/)\n\n```" } ]
[ { "role": "user", "content": "Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of `<Character>` elements each with a name attributes and each enclosing its remarks.\nAll `<Character>` elements are to be enclosed in turn, in an outer `<CharacterRemarks>` element.\n\nAs an example, calling the function with the three names of:\n\n```\nApril\nTam O'Shanter\nEmily\n```\n\nAnd three remarks of:\n\n```\nBubbly: I'm > Tam and <= Emily\nBurns: \"When chapman billies leave the street ...\"\nShort & shrift\n```\n\nShould produce the XML (but not necessarily with the indentation):\n\n```\n<CharacterRemarks>\n <Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n <Character name=\"Tam O'Shanter\">Burns: \"When chapman billies leave the street ...\"</Character>\n <Character name=\"Emily\">Short &amp; shrift</Character>\n</CharacterRemarks>\n\n```\n\nThe document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation *must* include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification.\n\nNote: the example is chosen to show correct escaping of XML strings.\nNote too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable.\n\n**Note to editors:** Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this).\nAlternately, output can be placed in <syntaxhighlight lang=\"xml\"></syntaxhighlight> tags without any special treatment." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\n```\nuse XML::Writer;\n\nmy @students =\n [ Q[April], Q[Bubbly: I'm > Tam and <= Emily] ],\n [ Q[Tam O'Shanter], Q[Burns: \"When chapman billies leave the street ...\"] ],\n [ Q[Emily], Q[Short & shrift] ]\n;\n\nmy @lines = map { :Character[:name(.[0]), .[1]] }, @students;\n\nsay XML::Writer.serialize( CharacterRemarks => @lines );\n\n```\n\nOutput:\n\n```\n<CharacterRemarks><Character name=\"April\">Bubbly: I'm &gt; Tam and &lt;= Emily</Character>\n<Character name=\"Tam O'Shanter\">Burns: &quot;When chapman billies leave the street ...&quot;</Character>\n<Character name=\"Emily\">Short &amp; shrift</Character></CharacterRemarks>\n\n```" } ]
[ { "role": "user", "content": "Perform the following three XPath queries on the XML Document below:\n\n* **//item[1]**: Retrieve the first \"item\" element\n* **//price/text()**: Perform an action on each \"price\" element (print it out)\n* **//name**: Get an array of all the \"name\" elements\n\nXML Document:\n\n```\n<inventory title=\"OmniCorp Store #45x10^3\">\n\n<item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n\n<item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n\n</inventory>\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nuse XML::XPath;\n\nmy $XML = XML::XPath.new(xml => q:to/END/);\n<inventory title=\"OmniCorp Store #45x10^3\">\n <section name=\"health\">\n <item upc=\"123456789\" stock=\"12\">\n <name>Invisibility Cream</name>\n <price>14.50</price>\n <description>Makes you invisible</description>\n </item>\n <item upc=\"445322344\" stock=\"18\">\n <name>Levitation Salve</name>\n <price>23.99</price>\n <description>Levitate yourself for up to 3 hours per application</description>\n </item>\n </section>\n <section name=\"food\">\n <item upc=\"485672034\" stock=\"653\">\n <name>Blork and Freen Instameal</name>\n <price>4.95</price>\n <description>A tasty meal in a tablet; just add water</description>\n </item>\n <item upc=\"132957764\" stock=\"44\">\n <name>Grob winglets</name>\n <price>3.56</price>\n <description>Tender winglets of Grob. Just add water</description>\n </item>\n </section>\n</inventory>\nEND\n\nput \"First item:\\n\", $XML.find('//item[1]')[0];\n\nput \"\\nPrice elements:\";\n.contents.put for $XML.find('//price').List;\n\nput \"\\nName elements:\\n\", $XML.find('//name')».contents.join: ', ';\n\n```\n\nOutput:\n\n```\nFirst item:\n<item upc=\"123456789\" stock=\"12\"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item>\n\nPrice elements:\n14.50\n23.99\n4.95\n3.56\n\nName elements:\nInvisibility Cream, Levitation Salve, Blork and Freen Instameal, Grob winglets\n```" } ]
[ { "role": "user", "content": "You've been given a contract from a three letter abbreviation government agency. They want a program to automatically redact sensitive information from documents to be released to the public. They want fine control over what gets redacted though.\n\nGiven a piece of free-form, possibly Unicode text, (assume text only, no markup or formatting codes) they want to be able to redact: whole words, (case sensitive or insensitive) or partial words, (case sensitive or insensitive). Further, they want the option to \"overkill\" redact a partial word. Overkill redact means if the word *contains* the redact target, even if is only part of the word, redact the **entire** word.\n\nFor our purposes, a \"word\" here, means: a character group, separated by white-space and possibly punctuation; not necessarily strictly alphabetic characters. To \"redact\" a word or partial word, replace each character in the redaction target with a capital letter 'X'. There should be the same number of graphemes in the final redacted word as there were in the non-redacted word.\n\nTask\n\nWrite a procedure to \"redact\" a given piece of text. Your procedure should take the text (or a link to it), the redaction target (or a link to it) and the redaction options. It need not be a single routine, as long as there is some way to programmatically select which operation will be performed. It may be invoked from a command line or as an internal routine, but it should be separately invokable, not just a hard coded block.\n\n*The given strings are enclosed in square brackets to denote them. The brackets should not be counted as part of the strings.*\n\nUsing the test string: [**Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.**]\n\nShow the redacted sentence for each of the redaction target strings [**Tom**] & [**tom**] using the following options:\n\n: * Whole word\n * Whole word, Case insensitive\n * Partial word\n * Partial word, Case insensitive\n * Partial word, Overkill\n * Partial word, Case insensitive, Overkill\n\nNote that some combinations don't, or at least, shouldn't really differ from less specific combination. E.G. \"Whole word, Overkill\" should be theoretically be exactly the same as \"Whole word\".\n\nExtra kudos for not including adjoining punctuation during \"Overkill\" redaction.\n\nExtra kudos if the redaction target can contain non-letter characters.\n\n*The demo strings use the abbreviations **w/p** for whole/partial word, **i/s** for case insensitive/sensitive, **n/o** for normal/overkill. You are not required to use those, or any abbreviation. They are just for display, though may be useful to show what operation you are **intending** to perform.*\n\nIdeal expected output (adjoining punctuation untouched):\n\n```\n Redact 'Tom':\n [w|s|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.\n [w|i|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n [p|s|n] XXX? XXXs bottom tomato is in his stomach while playing the \"XXX-tom\" brand tom-toms. That's so tom.\n [p|i|n] XXX? XXXs botXXX XXXato is in his sXXXach while playing the \"XXX-XXX\" brand XXX-XXXs. That's so XXX.\n [p|s|o] XXX? XXXX bottom tomato is in his stomach while playing the \"XXXXXXX\" brand tom-toms. That's so tom.\n [p|i|o] XXX? XXXX XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n\n```\n\n```\n Redact 'tom':\n [w|s|n] Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n [w|i|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n [p|s|n] Tom? Toms botXXX XXXato is in his sXXXach while playing the \"Tom-XXX\" brand XXX-XXXs. That's so XXX.\n [p|i|n] XXX? XXXs botXXX XXXato is in his sXXXach while playing the \"XXX-XXX\" brand XXX-XXXs. That's so XXX.\n [p|s|o] Tom? Toms XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n [p|i|o] XXX? XXXX XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n\n```\n\nStretch\n\nComplex Unicode: Using the test string: [🧑 👨 🧔 👨‍👩‍👦] and the redaction strings: [👨] and [👨‍👩‍👦]\n\nShow the redacted strings when using the option \"Whole word\" (Case sensitivity shouldn't matter.) A single grapheme should be replaced by a single 'X'.\n\n```\n 🧑 👨 🧔 👨‍👩‍👦\n Redact '👨' [w] 🧑 X 🧔 👨‍👩‍👦\n Redact '👨‍👩‍👦' [w] 🧑 👨 🧔 X\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": "**Works with**: Rakudo version 2020.02\n\n```\nsub redact ( Str $str, Str $redact, :i(:$insensitive) = False, :p(:$partial) = False, :o(:$overkill) = False ) {\n my $rx =\n $insensitive ??\n $partial ??\n $overkill ?? rx/:i <?after ^ | <:Po> | \\s > (<[\\w<:!Po>-]>*? [\\w*\\']? $redact [\\w*\\'\\w+]? \\S*?) <?before $ | <:Po> | \\s > / #'\n  !! rx/:i ($redact) /\n  !! rx/:i <?after ^ | [\\s<:Po>] | \\s > ($redact) <?before $ | <:Po> | \\s > /\n  !!\n $partial ??\n $overkill ?? rx/ <?after ^ | <:Po> | \\s > (<[\\w<:!Po>-]>*? [\\w*\\']? $redact [\\w*\\'\\w+]? \\S*?) <?before $ | <:Po> | \\s > / #'\n  !! rx/ ($redact) /\n  !! rx/ <?after ^ | [\\s<:Po>] | \\s > ($redact) <?before $ | <:Po> | \\s > /\n  ;\n $str.subst( $rx, {'X' x $0.chars}, :g )\n}\n\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\n# Operate on a given file with the given parameters\nmulti MAIN (\n Str $file, #= File name with path\n Str $target, #= Redact target text string\n  :$i = False, #= Case insensitive flag\n  :$p = False, #= Partial words flag\n  :$o = False #= Overkill flag\n ) { put $file.IO.slurp.&redact( $target, :i($i), :p($p), :o($o) ) }\n\n# Operate on the internal strings / parameters\nmulti MAIN () {\n\n# TESTING\n\n my $test = q:to/END/;\n Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.\n 'Tis very tomish, don't you think?\n END\n #'\n\n for 'Tom', 'tom', 't' -> $redact {\n say \"\\nRedact '$redact':\";\n for '[w|s|n]', $redact, {},\n '[w|i|n]', $redact, {:i},\n '[p|s|n]', $redact, {:p},\n '[p|i|n]', $redact, {:p, :i},\n '[p|s|o]', $redact, {:p, :o},\n '[p|i|o]', $redact, {:p, :i, :o}\n -> $option, $str, %opts { printf \"%s %s\\n\", $option, $test.&redact($str, |%opts) }\n }\n\n my $emoji = '🧑 👨 🧔 👨‍👩‍👦';\n printf \"%20s %s\\n\", '', $emoji;\n printf \"%20s %s\\n\", \"Redact '👨' [w]\", $emoji.&redact('👨');\n printf \"%20s %s\\n\", \"Redact '👨‍👩‍👦' [w]\", $emoji.&redact('👨‍👩‍👦');\n\n # Even more complicated Unicode\n\n $emoji = 'Argentina🧑🇦🇹 France👨🇫🇷 Germany🧔🇩🇪 Netherlands👨‍👩‍👦🇳🇱';\n printf \"\\n%20s %s\\n\", '', $emoji;\n printf \"%20s %s\\n\", \"Redact '👨' [p]\", $emoji.&redact('👨', :p);\n printf \"%20s %s\\n\", \"Redact '👨‍👩‍👦' [p]\", $emoji.&redact('👨‍👩‍👦', :p);\n printf \"%20s %s\\n\", \"Redact '👨' [p|o]\", $emoji.&redact('👨', :p, :o);\n printf \"%20s %s\\n\", \"Redact '👨‍👩‍👦' [p|o]\", $emoji.&redact('👨‍👩‍👦', :p, :o);\n}\n\n```\n\nOutput:\n\n```\nRedact 'Tom':\n[w|s|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.\n'Tis very tomish, don't you think?\n\n[w|i|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n'Tis very tomish, don't you think?\n\n[p|s|n] XXX? XXXs bottom tomato is in his stomach while playing the \"XXX-tom\" brand tom-toms. That's so tom.\n'Tis very tomish, don't you think?\n\n[p|i|n] XXX? XXXs botXXX XXXato is in his sXXXach while playing the \"XXX-XXX\" brand XXX-XXXs. That's so XXX.\n'Tis very XXXish, don't you think?\n\n[p|s|o] XXX? XXXX bottom tomato is in his stomach while playing the \"XXXXXXX\" brand tom-toms. That's so tom.\n'Tis very tomish, don't you think?\n\n[p|i|o] XXX? XXXX XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n'Tis very XXXXXX, don't you think?\n\n\nRedact 'tom':\n[w|s|n] Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n'Tis very tomish, don't you think?\n\n[w|i|n] XXX? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so XXX.\n'Tis very tomish, don't you think?\n\n[p|s|n] Tom? Toms botXXX XXXato is in his sXXXach while playing the \"Tom-XXX\" brand XXX-XXXs. That's so XXX.\n'Tis very XXXish, don't you think?\n\n[p|i|n] XXX? XXXs botXXX XXXato is in his sXXXach while playing the \"XXX-XXX\" brand XXX-XXXs. That's so XXX.\n'Tis very XXXish, don't you think?\n\n[p|s|o] Tom? Toms XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n'Tis very XXXXXX, don't you think?\n\n[p|i|o] XXX? XXXX XXXXXX XXXXXX is in his XXXXXXX while playing the \"XXXXXXX\" brand XXXXXXXX. That's so XXX.\n'Tis very XXXXXX, don't you think?\n\n\nRedact 't':\n[w|s|n] Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.\n'Tis very tomish, don't you think?\n\n[w|i|n] Tom? Toms bottom tomato is in his stomach while playing the \"Tom-tom\" brand tom-toms. That's so tom.\n'Tis very tomish, don't you think?\n\n[p|s|n] Tom? Toms boXXom XomaXo is in his sXomach while playing Xhe \"Tom-Xom\" brand Xom-Xoms. ThaX's so Xom.\n'Tis very Xomish, don'X you Xhink?\n\n[p|i|n] Xom? Xoms boXXom XomaXo is in his sXomach while playing Xhe \"Xom-Xom\" brand Xom-Xoms. XhaX's so Xom.\n'Xis very Xomish, don'X you Xhink?\n\n[p|s|o] Tom? Toms XXXXXX XXXXXX is in his XXXXXXX while playing XXX \"XXXXXXX\" brand XXXXXXXX. XXXXXX so XXX.\n'Tis very XXXXXX, XXXXX you XXXXX?\n\n[p|i|o] XXX? XXXX XXXXXX XXXXXX is in his XXXXXXX while playing XXX \"XXXXXXX\" brand XXXXXXXX. XXXXXX so XXX.\nXXXX very XXXXXX, XXXXX you XXXXX?\n\n 🧑 👨 🧔 👨‍👩‍👦\n Redact '👨' [w] 🧑 X 🧔 👨‍👩‍👦\n Redact '👨‍👩‍👦' [w] 🧑 👨 🧔 X\n\n Argentina🧑🇦🇹 France👨🇫🇷 Germany🧔🇩🇪 Netherlands👨‍👩‍👦🇳🇱\n Redact '👨' [p] Argentina🧑🇦🇹 FranceX🇫🇷 Germany🧔🇩🇪 Netherlands👨‍👩‍👦🇳🇱\n Redact '👨‍👩‍👦' [p] Argentina🧑🇦🇹 France👨🇫🇷 Germany🧔🇩🇪 NetherlandsX🇳🇱\n Redact '👨' [p|o] Argentina🧑🇦🇹 XXXXXXXX Germany🧔🇩🇪 Netherlands👨‍👩‍👦🇳🇱\n Redact '👨‍👩‍👦' [p|o] Argentina🧑🇦🇹 France👨🇫🇷 Germany🧔🇩🇪 XXXXXXXXXXXXX\n\n```" } ]
[ { "role": "user", "content": "In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions.\n\nThis rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function.\n\nThe   Y combinator   is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function.\n\nThe Y combinator is the simplest of the class of such functions, called fixed-point combinators.\n\nTask\n\nDefine the stateless   *Y combinator*   and use it to compute factorials and Fibonacci numbers from other stateless functions or lambda expressions.\n\nCf\n\n* Jim Weirich: Adventures in Functional Programming" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nsub Y (&f) { sub (&x) { x(&x) }( sub (&y) { f(sub ($x) { y(&y)($x) }) } ) }\nsub fac (&f) { sub ($n) { $n < 2 ?? 1 !! $n * f($n - 1) } }\nsub fib (&f) { sub ($n) { $n < 2 ?? $n !! f($n - 1) + f($n - 2) } }\nsay map Y($_), ^10 for &fac, &fib;\n```\n\nOutput:\n\n```\n(1 1 2 6 24 120 720 5040 40320 362880)\n(0 1 1 2 3 5 8 13 21 34)\n```\n\nNote that Raku doesn't actually need a Y combinator because you can name anonymous functions from the inside:\n\n```\nsay .(10) given sub (Int $x) { $x < 2 ?? 1 !! $x * &?ROUTINE($x - 1); }\n```" } ]
[ { "role": "user", "content": "Create a class for searching Yahoo! results.\n\nIt must implement a **Next Page** method, and read URL, Title and Content from results." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Library:** Gumbo\n\n**Library:** LWP-Simple\n\n**Library:** exemel\n\nYahooSearch.rakumod:\n\n```\nuse Gumbo;\nuse LWP::Simple;\nuse XML::Text;\n\nclass YahooSearch {\n has $!dom;\n\n submethod BUILD (:$!dom) { }\n\n method new($term) {\n self.bless(\n dom => parse-html(\n LWP::Simple.get(\"http://search.yahoo.com/search?p={ $term }\")\n )\n );\n }\n\n method next {\n $!dom = parse-html(\n LWP::Simple.get(\n $!dom.lookfor( TAG => 'a', class => 'next' ).head.attribs<href> \n )\n );\n self;\n }\n\n method text ($node) {\n return '' unless $node;\n return $node.text if $node ~~ XML::Text;\n\n $node.nodes.map({ self.text($_).trim }).join(' ');\n }\n\n method results {\n state $n = 0;\n for $!dom.lookfor( TAG => 'h3', class => 'title') {\n given .lookfor( TAG => 'a' )[0] {\n next unless $_; # No Link\n next if .attribs<href> ~~ / ^ 'https://r.search.yahoo.com' /; # Ad\n say \"=== #{ ++$n } ===\";\n say \"Title: { .contents[0] ?? self.text( .contents[0] ) !! '' }\";\n say \" URL: { .attribs<href> }\";\n\n my $pt = .parent.parent.parent.elements( TAG => 'div' ).tail;\n say \" Text: { self.text($pt) }\";\n }\n }\n self;\n }\n\n}\n\nsub MAIN (Str $search-term) is export {\n YahooSearch.new($search-term).results.next.results;\n}\n\n```\n\nAnd the invocation script is simply:\n\nyahoo-search.raku\n\n```\n use YahooSearch; \n\n```\n\nSo:\n\n```\n raku yahoo-search.raku test \n\n```\n\nShould give out something like the following:\n\n```\n=== #1 ===\nTitle: \n URL: https://www.speedtest.net/\n Text: At Ookla, we are committed to ensuring that individuals with disabilities can access all of the content at www.speedtest.net. We also strive to make all content in Speedtest apps accessible. If you are having trouble accessing www.speedtest.net or Speedtest apps, please email [email protected] for assistance. Please put \"ADA Inquiry\" in the ...\n=== #2 ===\nTitle: Test | Definition of Test by Merriam-Webster\n URL: https://www.merriam-webster.com/dictionary/test\n Text: Test definition is - a means of testing: such as. How to use test in a sentence.\n=== #3 ===\nTitle: - Video Results\n URL: https://video.search.yahoo.com/search/video?p=test\n Text: More Test videos\n\n```\n\n...and should go up to result #21!" } ]
[ { "role": "user", "content": "The **Yellowstone sequence**, also called the **Yellowstone permutation**, is defined as:\n\nFor n <= 3,\n\n```\n a(n) = n\n\n```\n\nFor n >= 4,\n\n```\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n```\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\nExample\n\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\nTask\n: Find and show as output the first  **30**  Yellowstone numbers.\n\nExtra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\nRelated tasks\n: * Greatest common divisor.\n * Plot coordinate pairs.\n * EKG sequence convergence\n\nSee also\n: * The OEIS entry:   A098550 The Yellowstone permutation.\n * Applegate et al, 2015: The Yellowstone Permutation [1]." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.01\n\nNot really clear whether a line graph or bar graph was desired, so generate both. Also, 100 points don't really give a good feel for the overall shape so do 500.\n\n```\nmy @yellowstone = 1, 2, 3, -> $q, $p {\n state @used = True xx 4;\n state $min = 3;\n my \\index = ($min .. *).first: { not @used[$_] and $_ gcd $q != 1 and $_ gcd $p == 1 };\n @used[index] = True;\n $min = @used.first(!*, :k) // +@used - 1;\n index\n} … *;\n\nput \"The first 30 terms in the Yellowstone sequence:\\n\", @yellowstone[^30];\n\nuse SVG;\nuse SVG::Plot;\n\nmy @x = ^500;\n\nmy $chart = SVG::Plot.new(\n background => 'white',\n width => 1000,\n height => 600,\n plot-width => 950,\n plot-height => 550,\n x => @x,\n x-tick-step => { 10 },\n y-tick-step => { 50 },\n min-y-axis => 0,\n values => [@yellowstone[@x],],\n title => \"Yellowstone Sequence - First {+@x} values (zero indexed)\",\n);\n\nmy $line = './Yellowstone-sequence-line-perl6.svg'.IO;\nmy $bars = './Yellowstone-sequence-bars-perl6.svg'.IO;\n\n$line.spurt: SVG.serialize: $chart.plot: :lines;\n$bars.spurt: SVG.serialize: $chart.plot: :bars;\n\n```\n\nOutput:\n\n```\nThe first 30 terms in the Yellowstone sequence:\n1 2 3 4 9 8 15 14 5 6 25 12 35 16 7 10 21 20 27 22 39 11 13 33 26 45 28 51 32 17\n```\n\nSee (offsite SVG images) Line graph or Bar graph" } ]
[ { "role": "user", "content": "One well-known symbol of the philosophy of duality known as yin and yang is the taijitu.\n\nTask\n: * Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.\n * Generate and display the symbol for two different (small) sizes." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nTranslation / Modification of C and Perl examples.\n\n```\nsub circle ($rad, $cx, $cy, $fill = 'white', $stroke = 'black' ){\n say \"<circle cx='$cx' cy='$cy' r='$rad' fill='$fill' stroke='$stroke' stroke-width='1'/>\";\n}\n\nsub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90) {\n my ($c, $w) = (1, 0);\n say \"<g transform='rotate($angle, $cx, $cy)'>\" if $angle;\n circle($rad, $cx, $cy, $fill, $stroke);\n say \"<path d='M $cx {$cy + $rad}A {$rad/2} {$rad/2} 0 0 $c $cx $cy \",\n \"{$rad/2} {$rad/2} 0 0 $w $cx {$cy - $rad} $rad $rad 0 0 $c $cx \",\n \"{$cy + $rad} z' fill='$stroke' stroke='none' />\";\n circle($rad/5, $cx, $cy + $rad/2, $fill, $stroke);\n circle($rad/5, $cx, $cy - $rad/2, $stroke, $fill);\n say \"</g>\" if $angle;\n}\n\nsay '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n<svg height=\"400\" width=\"400\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\">';\n\nyin_yang(100, 130, 130);\nyin_yang(50, 300, 300);\n\nsay '</svg>';\n\n```\n\nSeems like something of a cheat since it relies on a web browser /\nsvg image interpreter to actually view the output image.\nIf that's the case, we may as well cheat harder. ;-)\n\n```\nsub cheat_harder ($scale) { \"<span style=\\\"font-size:$scale%;\\\">&#x262f;</span>\"; }\n\nsay '<div>', cheat_harder(700), cheat_harder(350), '</div>';\n\n```\n\n☯☯" } ]
[ { "role": "user", "content": "The Zebra puzzle, a.k.a. Einstein's Riddle,\nis a logic puzzle which is to be solved programmatically.\n\nIt has several variants, one of them this:\n\n: 1. There are five houses.\n 2. The English man lives in the red house.\n 3. The Swede has a dog.\n 4. The Dane drinks tea.\n 5. The green house is immediately to the left of the white house.\n 6. They drink coffee in the green house.\n 7. The man who smokes Pall Mall has a bird.\n 8. In the yellow house they smoke Dunhill.\n 9. In the middle house they drink milk.\n 10. The Norwegian lives in the first house.\n 11. The Blend-smoker lives in the house next to the house with a cat.\n 12. In a house next to the house with a horse, they smoke Dunhill.\n 13. The man who smokes Blue Master drinks beer.\n 14. The German smokes Prince.\n 15. The Norwegian lives next to the blue house.\n 16. They drink water in a house next to the house where they smoke Blend.\n\nThe question is, who owns the zebra? For clarity, each of the five houses is painted a different color, and their inhabitants are of different nationalities, own different pets, drink different beverages and smoke different brands of cigarettes.\n\nAdditionally, list the solution for all the houses.\n \nOptionally, show the solution is unique.\n\nRelated tasks\n\n* Dinesman's multiple-dwelling problem\n* Twelve statements" }, { "role": "assistant", "content": "(formerly Perl 6)\nA rule driven approach:\n\n```\nmy Hash @houses = (1 .. 5).map: { %(:num($_)) }; # 1 there are five houses\n\nmy @facts = (\n { :nat<English>, :color<red> }, # 2 The English man lives in the red house.\n { :nat<Swede>, :pet<dog> }, # 3 The Swede has a dog.\n { :nat<Dane>, :drink<tea> }, # 4 The Dane drinks tea.\n { :color<green>, :Left-Of(:color<white>) }, # 5 the green house is immediately to the left of the white house\n { :drink<coffee>, :color<green> }, # 6 They drink coffee in the green house.\n { :smoke<Pall-Mall>, :pet<birds> }, # 7 The man who smokes Pall Mall has birds.\n { :color<yellow>, :smoke<Dunhill> }, # 8 In the yellow house they smoke Dunhill.\n { :num(3), :drink<milk> }, # 9 In the middle house they drink milk.\n { :num(1), :nat<Norwegian> }, # 10 The Norwegian lives in the first house.\n { :smoke<Blend>, :Next-To(:pet<cats>) }, # 11 The man who smokes Blend lives in the house next to the house with cats.\n { :pet<horse>, :Next-To(:smoke<Dunhill>) }, # 12 In a house next to the house where they have a horse, they smoke Dunhill.\n { :smoke<Blue-Master>, :drink<beer> }, # 13 The man who smokes Blue Master drinks beer.\n { :nat<German>, :smoke<Prince> }, # 14 The German smokes Prince.\n { :nat<Norwegian>, :Next-To(:color<blue>) }, # 15 The Norwegian lives next to the blue house.\n { :drink<water>, :Next-To(:smoke<Blend>) }, # 16 They drink water in a house next to the house where they smoke Blend.\n { :pet<zebra> }, # who owns this?\n);\n\nsub MAIN {\n for gather solve(@houses, @facts) {\n #-- output\n say .head.sort.map(*.key.uc.fmt(\"%-9s\")).join(' | ');\n say .sort.map(*.value.fmt(\"%-9s\")).join(' | ')\n for .list;\n last; # stop after first solution\n }\n}\n\n#| a solution has been found that fits all the facts\nmulti sub solve(@solution, @facts [ ]) {\n take @solution;\n}\n\n#| extend this scenario to fit the next fact\nmulti sub solve(@scenario, [ $fact, *@facts ]) {\n for gather match(@scenario, |$fact) -> @houses {\n solve(@houses, @facts)\n }\n}\n\n#| find all possible solutions for pairs of houses with\n#| properties %b, left of a house with properties %a\nmulti sub match(@houses, :Left-Of(%a)!, *%b) {\n for 1 ..^ @houses {\n my %left-house  := @houses[$_-1];\n my %right-house := @houses[$_];\n \n if plausible(%left-house, %a) && plausible(%right-house, %b) {\n temp %left-house ,= %a;\n temp %right-house ,= %b;\n take @houses;\n }\n }\n}\n\n#| match these houses are next to each other (left or right)\nmulti sub match(@houses, :Next-To(%b)!, *%a ) {\n match(@houses, |%a, :Left-Of(%b) );\n match(@houses, |%b, :Left-Of(%a) );\n}\n\n#| find all possible houses that match the given properties\nmulti sub match(@houses, *%props) {\n for @houses.grep({plausible($_, %props)}) -> %house {\n temp %house ,= %props;\n take @houses;\n }\n}\n\n#| plausible if doesn't conflict with anything\nsub plausible(%house, %props) {\n  ! %props.first: {%house{.key} && %house{.key} ne .value };\n}\n\n```\n\nOutput:\n\n```\nCOLOR | DRINK | NAT | NUM | PET | SMOKE \nyellow | water | Norwegian | 1 | cats | Dunhill \nblue | tea | Dane | 2 | horse | Blend \nred | milk | English | 3 | birds | Pall-Mall\ngreen | coffee | German | 4 | zebra | Prince \nwhite | beer | Swede | 5 | dog | Blue-Master\n\n```\n\nNote: Facts can be shuffled by changing line 3 to `my @facts = pick *, (`. It seems to reliably find solutions, although execution times will vary (from under 1 sec up to about 10sec)." } ]
[ { "role": "user", "content": "This task is a *total immersion* zeckendorf task; using decimal numbers will attract serious disapprobation.\n\nThe task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.\n\nAddition\n\nLike binary 1 + 1 = 10, note carry 1 left. There the similarity ends. 10 + 10 = 101, note carry 1 left and 1 right. 100 + 100 = 1001, note carry 1 left and 2 right, this is the general case.\n\nOccurrences of 11 must be changed to 100. Occurrences of 111 may be changed from the right by replacing 11 with 100, or from the left converting 111 to 100 + 100;\n\nSubtraction\n\n10 - 1 = 1. The general rule is borrow 1 right carry 1 left. eg:\n\n```\n abcde\n 10100 -\n 1000\n _____\n 100 borrow 1 from a leaves 100\n + 100 add the carry\n _____\n 1001\n\n```\n\nA larger example:\n\n```\n abcdef\n 100100 -\n 1000\n ______\n 1*0100 borrow 1 from b\n + 100 add the carry\n ______\n 1*1001\n\nSadly we borrowed 1 from b which didn't have it to lend. So now b borrows from a:\n\n 1001\n + 1000 add the carry\n ____\n 10100\n\n```\n\nMultiplication\n\nHere you teach your computer its zeckendorf tables. eg. 101 \\* 1001:\n\n```\n a = 1 * 101 = 101\n b = 10 * 101 = a + a = 10000\n c = 100 * 101 = b + a = 10101\n d = 1000 * 101 = c + b = 101010\n\n 1001 = d + a therefore 101 * 1001 =\n \n 101010\n + 101\n ______\n 1000100\n\n```\n\nDivision\n\nLets try 1000101 divided by 101, so we can use the same table used for multiplication.\n\n```\n 1000101 -\n 101010 subtract d (1000 * 101)\n _______\n 1000 -\n 101 b and c are too large to subtract, so subtract a\n ____\n 1 so 1000101 divided by 101 is d + a (1001) remainder 1\n\n```\n\nEfficient algorithms for Zeckendorf arithmetic is interesting. The sections on addition and subtraction are particularly relevant for this task." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nThis is a somewhat limited implementation of Zeckendorf arithmetic operators. They only handle positive integer values. There are no actual calculations, everything is done with string manipulations, so it doesn't matter what glyphs you use for 1 and 0.\n\nImplemented arithmetic operators:\n\n```\n +z addition \n -z subtraction\n ×z multiplication\n /z division (more of a divmod really)\n ++z post increment\n --z post decrement\n\n```\n\nComparison operators:\n\n```\n eqz equal \n nez not equal \n gtz greater than \n ltz less than \n\n```\n\n```\nmy $z1 = '1'; # glyph to use for a '1'\nmy $z0 = '0'; # glyph to use for a '0'\n\nsub zorder($a) { ($z0 lt $z1) ?? $a !! $a.trans([$z0, $z1] => [$z1, $z0]) }\n\n######## Zeckendorf comparison operators #########\n\n# less than\nsub infix:<ltz>($a, $b) { $a.&zorder lt $b.&zorder }\n\n# greater than\nsub infix:<gtz>($a, $b) { $a.&zorder gt $b.&zorder }\n\n# equal\nsub infix:<eqz>($a, $b) { $a eq $b }\n\n# not equal\nsub infix:<nez>($a, $b) { $a ne $b }\n\n######## Operators for Zeckendorf arithmetic ########\n\n# post increment\nsub postfix:<++z>($a is rw) {\n $a = (\"$z0$z0\"~$a).subst(/(\"$z0$z0\")($z1+ %% $z0)?$/,\n -> $/ { \"$z0$z1\" ~ ($1 ?? $z0 x $1.chars !! '') });\n $a ~~ s/^$z0+//;\n $a\n}\n\n# post decrement\nsub postfix:<--z>($a is rw) {\n $a.=subst(/$z1($z0*)$/,\n -> $/ {$z0 ~ \"$z1$z0\" x $0.chars div 2 ~ $z1 x $0.chars mod 2});\n $a ~~ s/^$z0+(.+)$/$0/;\n $a\n}\n\n# addition\nsub infix:<+z>($a is copy, $b is copy) { $a++z; $a++z while $b--z nez $z0; $a }\n\n# subtraction\nsub infix:<-z>($a is copy, $b is copy) { $a--z; $a--z while $b--z nez $z0; $a }\n\n# multiplication\nsub infix:<×z>($a, $b) { \n return $z0 if $a eqz $z0 or $b eqz $z0;\n return $a if $b eqz $z1;\n return $b if $a eqz $z1;\n my $c = $a;\n my $d = $z1;\n repeat { \n my $e = $z0;\n repeat { $c++z; $e++z } until $e eqz $a;\n $d++z;\n } until $d eqz $b;\n $c\n}\n\n# division (really more of a div mod)\nsub infix:</z>($a is copy, $b is copy) {\n fail \"Divide by zero\" if $b eqz $z0;\n return $a if $a eqz $z0 or $b eqz $z1;\n my $c = $z0;\n repeat { \n my $d = $b +z ($z1 ~ $z0);\n $c++z;\n $a++z;\n $a--z while $d--z nez $z0\n } until $a ltz $b;\n $c ~= \" remainder $a\" if $a nez $z0;\n $c\n}\n\n###################### Testing ######################\n\n# helper sub to translate constants into the particular glyphs you used\nsub z($a) { $a.trans([<1 0>] => [$z1, $z0]) }\n\nsay \"Using the glyph '$z1' for 1 and '$z0' for 0\\n\";\n\nmy $fmt = \"%-22s = %15s %s\\n\";\n\nmy $zeck = $z1;\n\nprintf( $fmt, \"$zeck++z\", $zeck++z, '# increment' ) for 1 .. 10;\n\nprintf $fmt, \"$zeck +z {z('1010')}\", $zeck +z= z('1010'), '# addition';\n\nprintf $fmt, \"$zeck -z {z('100')}\", $zeck -z= z('100'), '# subtraction';\n\nprintf $fmt, \"$zeck ×z {z('100101')}\", $zeck ×z= z('100101'), '# multiplication';\n\nprintf $fmt, \"$zeck /z {z('100')}\", $zeck /z= z('100'), '# division';\n\nprintf( $fmt, \"$zeck--z\", $zeck--z, '# decrement' ) for 1 .. 5;\n\nprintf $fmt, \"$zeck ×z {z('101001')}\", $zeck ×z= z('101001'), '# multiplication';\n\nprintf $fmt, \"$zeck /z {z('100')}\", $zeck /z= z('100'), '# division';\n\n```\n\n**Testing Output**\n\n```\nUsing the glyph '1' for 1 and '0' for 0\n\n1++z = 10 # increment\n10++z = 100 # increment\n100++z = 101 # increment\n101++z = 1000 # increment\n1000++z = 1001 # increment\n1001++z = 1010 # increment\n1010++z = 10000 # increment\n10000++z = 10001 # increment\n10001++z = 10010 # increment\n10010++z = 10100 # increment\n10100 +z 1010 = 101000 # addition\n101000 -z 100 = 100010 # subtraction\n100010 ×z 100101 = 100001000001 # multiplication\n100001000001 /z 100 = 101010001 # division\n101010001--z = 101010000 # decrement\n101010000--z = 101001010 # decrement\n101001010--z = 101001001 # decrement\n101001001--z = 101001000 # decrement\n101001000--z = 101000101 # decrement\n101000101 ×z 101001 = 101010000010101 # multiplication\n101010000010101 /z 100 = 1001010001001 remainder 10 # division\n```\n\nUsing alternate glyphs:\n\n```\nUsing the glyph 'X' for 1 and 'O' for 0\n\nX++z = XO # increment\nXO++z = XOO # increment\nXOO++z = XOX # increment\nXOX++z = XOOO # increment\nXOOO++z = XOOX # increment\nXOOX++z = XOXO # increment\nXOXO++z = XOOOO # increment\nXOOOO++z = XOOOX # increment\nXOOOX++z = XOOXO # increment\nXOOXO++z = XOXOO # increment\nXOXOO +z XOXO = XOXOOO # addition\nXOXOOO -z XOO = XOOOXO # subtraction\nXOOOXO ×z XOOXOX = XOOOOXOOOOOX # multiplication\nXOOOOXOOOOOX /z XOO = XOXOXOOOX # division\nXOXOXOOOX--z = XOXOXOOOO # decrement\nXOXOXOOOO--z = XOXOOXOXO # decrement\nXOXOOXOXO--z = XOXOOXOOX # decrement\nXOXOOXOOX--z = XOXOOXOOO # decrement\nXOXOOXOOO--z = XOXOOOXOX # decrement\nXOXOOOXOX ×z XOXOOX = XOXOXOOOOOXOXOX # multiplication\nXOXOXOOOOOXOXOX /z XOO = XOOXOXOOOXOOX remainder XO # division\n```" } ]
[ { "role": "user", "content": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.\n\nThe decimal number eleven can be written as 0\\*13 + 1\\*8 + 0\\*5 + 1\\*3 + 0\\*2 + 0\\*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0\\*13 + 1\\*8 + 0\\*5 + 0\\*3 + 1\\*2 + 1\\*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that *no two consecutive Fibonacci numbers can be used* which leads to the former unique solution.\n\nTask\n\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.\n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.\n\nAlso see\n\n* OEIS A014417   for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\nRelated task\n\n* Fibonacci sequence" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.12\n\n```\nprintf \"%2d: %8s\\n\", $_, zeckendorf($_) for 0 .. 20;\n\nmulti zeckendorf(0) { '0' }\nmulti zeckendorf($n is copy) {\n constant FIBS = (1,2, *+* ... *).cache;\n [~] map {\n $n -= $_ if my $digit = $n >= $_;\n +$digit;\n }, reverse FIBS ...^ * > $n;\n}\n\n```\n\nOutput:\n\n```\n 0: 0\n 1: 1\n 2: 10\n 3: 100\n 4: 101\n 5: 1000\n 6: 1001\n 7: 1010\n 8: 10000\n 9: 10001\n10: 10010\n11: 10100\n12: 10101\n13: 100000\n14: 100001\n15: 100010\n16: 100100\n17: 100101\n18: 101000\n19: 101001\n20: 101010\n```" } ]
[ { "role": "user", "content": "Some computer programming languages are not exactly consistent   (with other computer programming languages)  \n \nwhen   *raising zero to the zeroth power*:     **00**\n\nTask\n\nShow the results of raising   zero   to the   zeroth   power.\n\nIf your computer language objects to     **0\\*\\*0**     or     **0^0**     at compile time,   you may also try something like:\n\n```\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n```\n\n**Show the result here.** \nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation.\n\nSee also\n\n* The Wiki entry: Zero to the power of zero.\n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld™ entry: exponent laws.\n + Also, in the above MathWorld™ entry, see formula (**9**): \n\n x\n\n 0\n =\n 1\n {\\displaystyle {\\displaystyle x^{0}=1}}\n .\n* The OEIS entry: The special case of zero to the zeroth power" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nsay ' type n n**n exp(n,n)';\nsay '-------- -------- -------- --------';\n\nfor 0, 0.0, FatRat.new(0), 0e0, 0+0i {\n printf \"%8s %8s %8s %8s\\n\", .^name, $_, $_**$_, exp($_,$_);\n}\n\n```\n\nOutput:\n\n```\n type n n**n exp(n,n)\n-------- -------- -------- --------\n Int 0 1 1\n Rat 0 1 1\n FatRat 0 1 1\n Num 0 1 1\n Complex 0+0i 1+0i 1+0i\n\n```" } ]
[ { "role": "user", "content": "This is an algorithm used to thin a black and white i.e. one bit per pixel images.\n\nFor example, with an input image of:\n\n```\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \n```\n\nIt produces the thinned output:\n\n```\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n```\n\nAlgorithm\n\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours.\n\nThe neighbours are, in order, arranged as:\n\n| | | |\n| --- | --- | --- |\n| P9 | P2 | P3 |\n| P8 | **P1** | P4 |\n| P7 | P6 | P5 |\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define \n\n A\n (\n P\n 1\n )\n {\\displaystyle {\\displaystyle A(P1)}}\n = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define \n\n B\n (\n P\n 1\n )\n {\\displaystyle {\\displaystyle B(P1)}}\n = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\nStep 1\n\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n\n* (0) The pixel is black and has eight neighbours\n* (1) \n\n 2\n <=\n B\n (\n P\n 1\n )\n <=\n 6\n {\\displaystyle {\\displaystyle 2<=B(P1)<=6}}\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\nStep 2\n\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n\n* (0) The pixel is black and has eight neighbours\n* (1) \n\n 2\n <=\n B\n (\n P\n 1\n )\n <=\n 6\n {\\displaystyle {\\displaystyle 2<=B(P1)<=6}}\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and **P8** is white\n* (4) At least one of **P2** and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\nIteration\n\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\nTask\n\n1. Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n2. Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.\n\n```\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n```\n\nReference\n\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen" }, { "role": "assistant", "content": "(formerly Perl 6)\nSource image may be based on any characters whose low bits are 0 or 1 (which conveniently includes . and #).\n\n```\nmy $source = qq:to/EOD/;\n................................\n.#########.......########.......\n.###...####.....####..####......\n.###....###.....###....###......\n.###...####.....###.............\n.#########......###.............\n.###.####.......###....###......\n.###..####..###.####..####.###..\n.###...####.###..########..###..\n................................\nEOD\n\nmy @lines = ([.ords X+& 1] for $source.split(\"\\n\")); # The low bits Just Work.\nmy \\v = +@lines;\nmy \\h = +@lines[0];\nmy @black = flat @lines.map: *.values; # Flatten to 1-dimensional.\n\nmy \\p8 = [-h-1, -h+0, -h+1, # Flatland distances to 8 neighbors.\n 0-1, 0+1,\n h-1, h+0, h+1].[1,2,4,7,6,5,3,0]; # (in cycle order)\n\n# Candidates have 8 neighbors and are known black\nmy @cand = grep { @black[$_] }, do\n for 1..v-2 X 1..h-2 -> (\\y,\\x) { y*h + x }\n\nrepeat while my @goners1 or my @goners2 {\n sub seewhite (\\w1,\\w2) {\n sub cycles (@neighbors) { [+] @neighbors Z< @neighbors[].rotate }\n sub blacks (@neighbors) { [+] @neighbors }\n\n my @prior = @cand; @cand = ();\n\n gather for @prior -> \\p {\n my \\n = @black[p8 X+ p];\n if cycles(n) == 1 and 2 <= blacks(n) <= 6 and n[w1].any == 0 and n[w2].any == 0\n { take p }\n else { @cand.push: p }\n }\n }\n\n @goners1 = seewhite (0,2,4), (2,4,6);\n @black[@goners1] = 0 xx *;\n say \"Ping: {[+] @black} remaining after removing \", @goners1;\n\n @goners2 = seewhite (0,2,6), (0,4,6);\n @black[@goners2] = 0 xx *;\n say \"Pong: {[+] @black} remaining after removing \", @goners2;\n}\n\nsay @black.splice(0,h).join.trans('01' => '.#') while @black;\n\n```\n\nOutput:\n\n```\nPing: 66 remaining after removing 33 41 49 56 67 71 74 80 83 86 89 99 106 114 119 120 121 131 135 138 146 169 178 195 197 210 215 217 227 230 233 236 238 240 243 246 249 251 253 257 258 259 263 264 266 268 269 270 273 274 279 280 283 284 285\nPong: 47 remaining after removing 65 73 88 97 104 112 129 137 144 161 167 176 193 198 208 216 225 226 231\nPing: 45 remaining after removing 87 194\nPong: 45 remaining after removing \nPing: 45 remaining after removing \nPong: 45 remaining after removing \n................................\n..#######.........######........\n..#.....#........##.............\n..#......#.......#..............\n..#.....#........#..............\n..#####.#........#..............\n.......##........#..............\n........#....#...##....##...#...\n.........#.........####.........\n................................\n```" } ]
[ { "role": "user", "content": "Task\n\nProduce a zig-zag array.\n\nA   *zig-zag*   array is a square arrangement of the first   N2   natural numbers,   where the\n \nnumbers increase sequentially as you zig-zag along the array's   anti-diagonals.\n\nFor a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images).\n\nFor example, given   **5**,   produce this array:\n\n```\n 0 1 5 6 14\n 2 4 7 13 15\n 3 8 12 16 21\n 9 11 17 20 22\n10 18 19 23 24\n\n```\n\nRelated tasks\n\n* Spiral matrix\n* Identity matrix\n* Ulam spiral (for primes)\n\nSee also\n\n* Wiktionary entry:   anti-diagonals" }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUsing the same Turtle class as in the Spiral matrix task:\n\n```\nclass Turtle {\n my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1];\n my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.\n \n has @.loc = 0,0;\n has $.dir = 0;\n has %.world;\n has $.maxegg;\n has $.range-x;\n has $.range-y;\n \n method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; }\n method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; }\n \n method lay-egg($egg) {\n  %!world{~@!loc} = $egg;\n $!maxegg max= $egg;\n $!range-x minmax= @!loc[0];\n $!range-y minmax= @!loc[1];\n }\n \n method look($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n  %!world{~$there};\n }\n \n method forward($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n @!loc = @($there);\n }\n \n method showmap() {\n my $form = \"%{$!maxegg.chars}s\";\n my $endx = $!range-x.max;\n for $!range-y.list X $!range-x.list -> ($y, $x) {\n print (%!world{\"$x $y\"} // '').fmt($form);\n print $x == $endx ?? \"\\n\" !! ' ';\n }\n }\n}\n\nsub MAIN(Int $size = 5) {\n my $t = Turtle.new(dir => 1);\n my $counter = 0;\n for 1 ..^ $size -> $run {\n\tfor ^$run {\n\t $t.lay-egg($counter++);\n\t $t.forward;\n\t}\n\tmy $yaw = $run %% 2 ?? -1 !! 1;\n\t$t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45);\n }\n for $size ... 1 -> $run {\n\tfor ^$run -> $ {\n\t $t.lay-egg($counter++);\n\t $t.forward;\n\t}\n\t$t.turn-left(180); $t.forward;\n\tmy $yaw = $run %% 2 ?? 1 !! -1;\n\t$t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45);\n }\n $t.showmap;\n}\n```" } ]
[ { "role": "user", "content": "**Zsigmondy numbers** **n** to **a**, **b**, are the greatest divisor of **an - bn** that is coprime to **am - bm** for all positive integers **m < n**.\n\nE.G.\n\nSuppose we set **a** = **2** and **b** = **1**. *(**Zs(n,2,1)**)*\n\nFor each **n**, find the divisors of **an - bn** and return the largest that is coprime to all of **am - bm**, where **m** is each of the positive integers **1** to **n - 1**.\n\nWhen **n** = **4**, **24 - 14 = 15**. The divisors of **15** are **1, 3, 5,** and **15**.\n\nFor **m = 1, 2, 3** we get **2-1, 22-12, 23-13**, or **1, 3, 7**.\n\nThe divisors of **15** that are coprime to each are **5** and **1**, (***1** is always included*).\n\nThe largest coprime divisor is **5**, so **Zs(4,2,1) = 5**.\n\nWhen **n** = **6**, **26 - 16 = 63**; its divisors are **1, 3, 7, 9, 21, 63**. The largest divisor coprime to all of **1, 3, 7, 15, 31** is **1**, (***1** is always included*), so **Zs(6,2,1) = 1**.\n\nIf a particular **an - bn** is prime, then **Zs(n,a,b)** will be equal to that prime. **25 - 15 = 31** so **Zs(5,2,1) = 31**.\n\nTask\n\n* Write a general routine (function, procedure, whatever) to find the Zsigmondy number sequence given a set of radices.\n* Use that routine to generate the first several elements, (at least 10), for the following radix sets.\n\n: * (2,1)\n * (3,1)\n * (4,1)\n * (5,1)\n * (6,1)\n * (7,1)\n * (3,2)\n * (5,3)\n * (7,3)\n * (7,5)\n\nSee also\n\n* OEIS:A064078 - Zsigmondy numbers for a = 2, b = 1 * OEIS:A064077 - Zsigmondy numbers for a = 3, b = 1 * OEIS:A064080 - Zsigmondy numbers for a = 4, b = 1 * OEIS:A064081 - Zsigmondy numbers for a = 5, b = 1 * OEIS:A064082 - Zsigmondy numbers for a = 6, b = 1 * OEIS:A064083 - Zsigmondy numbers for a = 7, b = 1 * OEIS:A109325 - Zsigmondy numbers for a = 3, b = 2 * OEIS:A109347 - Zsigmondy numbers for a = 5, b = 3 * OEIS:A109348 - Zsigmondy numbers for a = 7, b = 3 * OEIS:A109349 - Zsigmondy numbers for a = 7, b = 5" }, { "role": "assistant", "content": "First twenty elements of each.\n\n```\nuse Prime::Factor;\n\nsub Zsigmondy ($a, $b) {\n my @aexp = 1, * × $a … *;\n my @bexp = 1, * × $b … *;\n (1..∞).map: -> $n {\n (@aexp[$n] - @bexp[$n]).&divisors.sort(-*).first: -> $d {\n all (1..^$n).map: { (@aexp[$_] - @bexp[$_]) gcd $d == 1 }\n }\n }\n}\n\nfor '064078', (2,1), '064079', (3,1), '064080', (4,1), '064081', (5,1), '064082', (6,1),\n '064083', (7,1), '109325', (3,2), '109347', (5,3), '109348', (7,3), '109349', (7,5)\n -> $oeis, $seq {\n say \"\\nA$oeis: Zsigmondy(n,$seq[0],$seq[1]):\\n\" ~ Zsigmondy(|$seq)[^20]\n}\n\n```\n\nOutput:\n\n```\nA064078: Zsigmondy(n,2,1):\n1 3 7 5 31 1 127 17 73 11 2047 13 8191 43 151 257 131071 19 524287 41\n\nA064079: Zsigmondy(n,3,1):\n2 1 13 5 121 7 1093 41 757 61 88573 73 797161 547 4561 3281 64570081 703 581130733 1181\n\nA064080: Zsigmondy(n,4,1):\n3 5 7 17 341 13 5461 257 1387 41 1398101 241 22369621 3277 49981 65537 5726623061 4033 91625968981 61681\n\nA064081: Zsigmondy(n,5,1):\n4 3 31 13 781 7 19531 313 15751 521 12207031 601 305175781 13021 315121 195313 190734863281 5167 4768371582031 375601\n\nA064082: Zsigmondy(n,6,1):\n5 7 43 37 311 31 55987 1297 46873 1111 72559411 1261 2612138803 5713 1406371 1679617 3385331888947 46441 121871948002099 1634221\n\nA064083: Zsigmondy(n,7,1):\n6 1 19 25 2801 43 137257 1201 39331 2101 329554457 2353 16148168401 102943 4956001 2882401 38771752331201 117307 1899815864228857 1129901\n\nA109325: Zsigmondy(n,3,2):\n1 5 19 13 211 7 2059 97 1009 11 175099 61 1586131 463 3571 6817 129009091 577 1161737179 4621\n\nA109347: Zsigmondy(n,5,3):\n2 1 49 17 1441 19 37969 353 19729 421 24325489 481 609554401 10039 216001 198593 381405156481 12979 9536162033329 288961\n\nA109348: Zsigmondy(n,7,3):\n4 5 79 29 4141 37 205339 1241 127639 341 494287399 2041 24221854021 82573 3628081 2885681 58157596211761 109117 2849723505777919 4871281\n\nA109349: Zsigmondy(n,7,5):\n2 3 109 37 6841 13 372709 1513 176149 1661 964249309 1801 47834153641 75139 3162961 3077713 115933787267041 30133 5689910849522509 3949201\n```" } ]
[ { "role": "user", "content": "Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on *how* the divisors are partitioned, only that the two partition sums are equal.\n\nE.G.\n\n: **6** is a Zumkeller number; The divisors **{1 2 3 6}** can be partitioned into two groups **{1 2 3}** and **{6}** that both sum to 6.\n\n: **10** is not a Zumkeller number; The divisors **{1 2 5 10}** can not be partitioned into two groups in any way that will both sum to the same value.\n\n: **12** is a Zumkeller number; The divisors **{1 2 3 4 6 12}** can be partitioned into two groups **{1 3 4 6}** and **{2 12}** that both sum to 14.\n\nEven Zumkeller numbers are common; odd Zumkeller numbers are much less so. For values below 10^6, there is *at least* one Zumkeller number in every 12 consecutive integers, and the vast majority of them are even. The odd Zumkeller numbers are very similar to the list from the task Abundant odd numbers; they are nearly the same except for the further restriction that the abundance (**A(n) = sigma(n) - 2n**), must be even: **A(n) mod 2 == 0**\n\nTask\n: * Write a routine (function, procedure, whatever) to find Zumkeller numbers.\n * Use the routine to find and display here, on this page, the first **220 Zumkeller numbers**.\n * Use the routine to find and display here, on this page, the first **40 odd Zumkeller numbers**.\n * Optional, stretch goal: Use the routine to find and display here, on this page, the first **40 odd Zumkeller numbers that don't end with 5**.\n\nSee Also\n\n: * **OEIS:A083207 - Zumkeller numbers** to get an impression of different partitions **OEIS:A083206 Zumkeller partitions**\n * **OEIS:A174865 - Odd Zumkeller numbers**\n\nRelated Tasks\n\n: * **Abundant odd numbers**\n * **Abundant, deficient and perfect number classifications**\n * **Proper divisors** , **Factors of an integer**" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Library:** ntheory\n\n```\nuse ntheory:from<Perl5> <factor is_prime>;\n\nsub zumkeller ($range) {\n $range.grep: -> $maybe {\n next if $maybe < 3 or $maybe.&is_prime;\n my @divisors = $maybe.&factor.combinations».reduce( &[×] ).unique.reverse;\n next unless [and] @divisors > 2, @divisors %% 2, (my $sum = @divisors.sum) %% 2, ($sum /= 2) ≥ $maybe;\n my $zumkeller = False;\n if $maybe % 2 {\n $zumkeller = True\n } else {\n TEST: for 1 ..^ @divisors/2 -> $c {\n @divisors.combinations($c).map: -> $d {\n next if $d.sum != $sum;\n $zumkeller = True and last TEST\n }\n }\n }\n $zumkeller\n }\n}\n\nsay \"First 220 Zumkeller numbers:\\n\" ~\n zumkeller(^Inf)[^220].rotor(20)».fmt('%3d').join: \"\\n\";\n\nput \"\\nFirst 40 odd Zumkeller numbers:\\n\" ~\n zumkeller((^Inf).map: * × 2 + 1)[^40].rotor(10)».fmt('%7d').join: \"\\n\";\n\n# Stretch. Slow to calculate. (minutes) \nput \"\\nFirst 40 odd Zumkeller numbers not divisible by 5:\\n\" ~\n zumkeller(flat (^Inf).map: {my \\p = 10 * $_; p+1, p+3, p+7, p+9} )[^40].rotor(10)».fmt('%7d').join: \"\\n\";\n\n```\n\nOutput:\n\n```\nFirst 220 Zumkeller numbers:\n 6 12 20 24 28 30 40 42 48 54 56 60 66 70 78 80 84 88 90 96\n102 104 108 112 114 120 126 132 138 140 150 156 160 168 174 176 180 186 192 198\n204 208 210 216 220 222 224 228 234 240 246 252 258 260 264 270 272 276 280 282\n294 300 304 306 308 312 318 320 330 336 340 342 348 350 352 354 360 364 366 368\n372 378 380 384 390 396 402 408 414 416 420 426 432 438 440 444 448 456 460 462\n464 468 474 476 480 486 490 492 496 498 500 504 510 516 520 522 528 532 534 540\n544 546 550 552 558 560 564 570 572 580 582 588 594 600 606 608 612 616 618 620\n624 630 636 640 642 644 650 654 660 666 672 678 680 684 690 696 700 702 704 708\n714 720 726 728 732 736 740 744 750 756 760 762 768 770 780 786 792 798 804 810\n812 816 820 822 828 832 834 836 840 852 858 860 864 868 870 876 880 888 894 896\n906 910 912 918 920 924 928 930 936 940 942 945 948 952 960 966 972 978 980 984\n\nFirst 40 odd Zumkeller numbers:\n 945 1575 2205 2835 3465 4095 4725 5355 5775 5985\n 6435 6615 6825 7245 7425 7875 8085 8415 8505 8925\n 9135 9555 9765 10395 11655 12285 12705 12915 13545 14175\n 14805 15015 15435 16065 16695 17325 17955 18585 19215 19305\n\nFirst 40 odd Zumkeller numbers not divisible by 5:\n 81081 153153 171171 189189 207207 223839 243243 261261 279279 297297\n 351351 459459 513513 567567 621621 671517 729729 742203 783783 793611\n 812889 837837 891891 908523 960687 999999 1024947 1054053 1072071 1073709\n1095633 1108107 1145529 1162161 1198197 1224531 1270269 1307691 1324323 1378377\n```" } ]