Dataset Viewer
Auto-converted to Parquet
messages
listlengths
2
2
[ { "role": "user", "content": "There are 100 doors in a row that are all initially closed.\n\nYou make 100 passes by the doors.\n\nThe first time through, visit every door and *toggle* the door (if the door is closed, open it; if it is open, close it).\n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.\n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\nTask\n\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n**Alternate:**\nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed;\nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\nWhy doesn't syntax highlighting work on this page ?\n\nCurrently, there is a limit on how many <syntaxhighlight> tags can appear on a page, so only the first few languages get highlighting, the rest are shown in monochrome. \nYou could try \"manual highlighting\", possibly using one of the highlighters on Syntax highlighting using Mediawiki formatting or something similar." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### unoptimized\n\n**Works with**: Rakudo version 2015.09\"\n\n```\nmy @doors = False xx 101;\n \n(.=not for @doors[0, $_ ... 100]) for 1..100;\n \nsay \"Door $_ is \", <closed open>[ @doors[$_] ] for 1..100;\n```\n\n### optimized\n\n```\nsay \"Door $_ is open\" for map {$^n ** 2}, 1..10;\n```\n\n### probably the most compact idiom\n\n```\nsay 'Door $_ is open' for (1..10)»²;\n```\n\n### Here's a version using the cross meta-operator instead of a map:\n\n```\n say \"Door $_ is open\" for 1..10 X** 2;\n```\n\nThis one prints both opened and closed doors:\n\n```\nsay \"Door $_ is \", <closed open>[.sqrt == .sqrt.floor] for 1..100;\n```\n\n### verbose version, but uses ordinary components\n\n**Works with**: Rakudo version 2016.07 Tom Legrady\n\n```\nsub output( @arr, $max ) {\n my $output = 1;\n for 1..^$max -> $index {\n\tif @arr[$index] {\n\t printf \"%4d\", $index;\n\t say '' if $output++ %% 10;\n\t}\n }\n say '';\n}\n\nsub MAIN ( Int :$doors = 100 ) {\n my $doorcount = $doors + 1;\n my @door[$doorcount] = 0 xx ($doorcount);\n \n INDEX:\n for 1...^$doorcount -> $index {\n # flip door $index & its multiples, up to last door.\n #\n\tfor ($index, * + $index ... *)[^$doors] -> $multiple {\n\t next INDEX if $multiple > $doors;\n\t @door[$multiple] = @door[$multiple] ?? 0 !! 1;\n\t}\n }\n output @door, $doors+1;\n}\n```\n\nOutput:\n\n```\n$ ./100_doors.pl6 -doors=100\n 1 4 9 16 25 36 49 64 81\n\n```" } ]
[ { "role": "user", "content": "The Problem\n\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n\n: * They can decide some strategy before any enter the room.\n * Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n * A prisoner can open no more than 50 drawers.\n * A prisoner tries to find his own number.\n * A prisoner finding his own number is then held apart from the others.\n\n* If **all** 100 prisoners find their own numbers then they will all be pardoned. If *any* don't then *all* sentences stand.\n\nThe task\n\n1. Simulate several thousand instances of the game where the prisoners randomly open drawers\n2. Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n\n: * First opening the drawer whose outside number is his prisoner number.\n * If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\nReferences\n\n1. The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n2. wp:100 prisoners problem\n3. 100 Prisoners Escape Puzzle DataGenetics.\n4. Random permutation statistics#One hundred prisoners on Wikipedia." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nAccepts command line parameters to modify the number of prisoners and the number of simulations to run.\n\nAlso test with 10 prisoners to verify that the logic is correct for random selection. Random selection should succeed with 10 prisoners at a probability of (1/2)\\*\\*10, so in 100\\_000 simulations, should get pardons about .0977 percent of the time.\n\n```\nunit sub MAIN (:$prisoners = 100, :$simulations = 10000);\nmy @prisoners = ^$prisoners;\nmy $half = floor +@prisoners / 2;\n\nsub random ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n for @drawers.pick($half) -> $card {\n $found = 1 and last if $card == $prisoner\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsub optimal ($n) {\n ^$n .race.map( {\n my @drawers = @prisoners.pick: *;\n @prisoners.map( -> $prisoner {\n my $found = 0;\n my $card = @drawers[$prisoner];\n if $card == $prisoner {\n $found = 1\n } else {\n for ^($half - 1) {\n $card = @drawers[$card];\n $found = 1 and last if $card == $prisoner\n }\n }\n last unless $found;\n $found\n }\n ).sum == @prisoners\n }\n ).grep( *.so ).elems / $n * 100\n}\n\nsay \"Testing $simulations simulations with $prisoners prisoners.\";\nprintf \" Random play wins: %.3f%% of simulations\\n\", random $simulations;\nprintf \"Optimal play wins: %.3f%% of simulations\\n\", optimal $simulations;\n\n```\n\nOutput:\n\n**With defaults**\n\n```\nTesting 10000 simulations with 100 prisoners.\n Random play wins: 0.000% of simulations\nOptimal play wins: 30.510% of simulations\n```\n\n**With passed parameters: --prisoners=10, --simulations=100000**\n\n```\nTesting 100000 simulations with 10 prisoners.\n Random play wins: 0.099% of simulations\nOptimal play wins: 35.461% of simulations\n\n```" } ]
[ { "role": "user", "content": "Task\n\nFind and show on this page the 10001st prime number." }, { "role": "assistant", "content": "```\nsay (^∞).grep( &is-prime )[10000]\n\n```\n\nOutput:\n\n```\n104743\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement the Fifteen Puzzle Game.\n\nThe   **15-puzzle**   is also known as:\n\n: : : * **Fifteen Puzzle**\n * **Gem Puzzle**\n * **Boss Puzzle**\n * **Game of Fifteen**\n * **Mystic Square**\n * **14-15 Puzzle**\n * and some others.\n\nRelated Tasks\n: * 15 Puzzle Solver\n * 16 Puzzle Game" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\nMost of this is interface code. Reused substantial portions from the 2048 task. Use the arrow keys to slide tiles, press 'q' to quit or 'n' for a new puzzle. Requires a POSIX termios aware terminal. Ensures that the puzzle is solvable by shuffling the board with an even number of swaps, then checking for even taxicab parity for the empty space.\n\n```\nuse Term::termios;\n\nconstant $saved = Term::termios.new(fd => 1).getattr;\nconstant $termios = Term::termios.new(fd => 1).getattr;\n# raw mode interferes with carriage returns, so\n# set flags needed to emulate it manually\n$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);\n$termios.unset_lflags(< ECHO ICANON IEXTEN ISIG>);\n$termios.setattr(:DRAIN);\n\n# reset terminal to original setting on exit\nEND { $saved.setattr(:NOW) }\n\nconstant n = 4; # board size\nconstant cell = 6; # cell width\n\nconstant $top = join '─' x cell, '┌', '┬' xx n-1, '┐';\nconstant $mid = join '─' x cell, '├', '┼' xx n-1, '┤';\nconstant $bot = join '─' x cell, '└', '┴' xx n-1, '┘';\n\nmy %dir = (\n \"\\e[A\" => 'up',\n \"\\e[B\" => 'down',\n \"\\e[C\" => 'right',\n \"\\e[D\" => 'left',\n);\n\nmy @solved = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' '];\nmy @board;\nnew();\n\nsub new () {\n loop {\n @board = shuffle();\n last if parity-ok(@board);\n }\n}\n\nsub parity-ok (@b) {\n my $row = @b.first(/' '/,:k);\n my $col = @b[$row].first(/' '/,:k);\n so ([3,3] <<->> [$row,$col]).sum %% 2;\n}\n\nsub shuffle () {\n my @c = [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' '];\n for (^16).pick(*) -> $y, $x {\n my ($yd, $ym, $xd, $xm) = ($y div n, $y mod n, $x div n, $x mod n);\n @(@c[$ym;$yd],@c[$xm;$xd]) = @(@c[$xm;$xd],@c[$ym;$yd]);\n }\n @c;\n}\n\nsub row (@row) { '│' ~ (join '│', @row».&center) ~ '│' }\n\nsub center ($s){\n my $c = cell - $s.chars;\n my $pad = ' ' x ceiling($c/2);\n sprintf \"%{cell}s\", \"$s$pad\";\n}\n\nsub draw-board {\n run('clear');\n print qq:to/END/;\n\n\n\tPress direction arrows to move.\n\n\tPress q to quit. Press n for a new puzzle.\n\n\t$top\n\t{ join \"\\n\\t$mid\\n\\t\", map { .&row }, @board }\n\t$bot\n\n\t{ (so @board ~~ @solved) ?? 'Solved!!' !! '' }\nEND\n}\n\nsub slide (@c is copy) {\n my $t = (grep { /' '/ }, :k, @c)[0];\n return @c unless $t and $t > 0;\n @c[$t,$t-1] = @c[$t-1,$t];\n @c;\n}\n\nproto sub move (|) {*};\n\nmulti move('up') {\n map { @board[*;$_] = reverse slide reverse @board[*;$_] }, ^n;\n}\n\nmulti move('down') {\n map { @board[*;$_] = slide @board[*;$_] }, ^n;\n}\n\nmulti move('left') {\n map { @board[$_] = reverse slide reverse @board[$_] }, ^n;\n}\n\nmulti move('right') {\n map { @board[$_] = slide @board[$_] }, ^n;\n}\n\nloop {\n draw-board;\n\n # Read up to 4 bytes from keyboard buffer.\n # Page navigation keys are 3-4 bytes each.\n # Specifically, arrow keys are 3.\n my $key = $*IN.read(4).decode;\n\n move %dir{$key} if so %dir{$key};\n last if $key eq 'q'; # (q)uit\n new() if $key eq 'n';\n}\n\n```\n\nSample screen shot:\n\n```\n\tPress direction arrows to move.\n\n\tPress q to quit. Press n for a new puzzle.\n\n\t┌──────┬──────┬──────┬──────┐\n\t│ 2 │ 1 │ 10 │ 14 │\n\t├──────┼──────┼──────┼──────┤\n\t│ 15 │ 11 │ 12 │ │\n\t├──────┼──────┼──────┼──────┤\n\t│ 13 │ 3 │ 6 │ 7 │\n\t├──────┼──────┼──────┼──────┤\n\t│ 9 │ 4 │ 5 │ 8 │\n\t└──────┴──────┴──────┴──────┘\n\n```" } ]
[ { "role": "user", "content": "Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. \nFor this task you will be using the following puzzle:\n\n```\n15 14 1 6\n 9 11 4 12\n 0 10 7 3\n13 8 5 2\n```\n\nSolution:\n\n```\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n13 14 15 0\n\n```\n\nThe output must show the moves' directions, like so: left, left, left, down, right... and so on. \nThere are two solutions, of fifty-two moves: \nrrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd \nrrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd \nsee: Pretty Print of Optimal Solution\n\nFinding either one, or both is an acceptable result.\n\nExtra credit.\n\nSolve the following problem:\n\n```\n 0 12 9 13\n 15 11 10 14\n 3 7 2 5\n 4 8 6 1\n\n```\n\nRelated Task\n\n* 15 puzzle game\n* A\\* search algorithm" }, { "role": "assistant", "content": "**Translation of**: C++\n\n```\n# 20210623 Raku programming solution vCSMt9hkak0\n\nconstant \\Nr = <3 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3>;\nconstant \\Nc = <3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2>;\n\nmy ($n,$m) = 0,0 ;\nmy @N0 is default(0);\nmy @N3 is default(0);\nmy @N4 is default(0);\nmy @N2 is default(0);\n\nsub fY() {\n if @N2[$n] == 0x123456789abcdef0 {\n say \"Solution found in \", $n, \" moves: \", [~] @N3[1..$n] and exit();\n }\n return @N4[$n] ≤ $m ?? fN() !! False ;\n}\n\nsub fN() {\n sub common { ++$n; return True if fY(); --$n }\n if (@N3[$n] ne 'u' && @N0[$n] div 4 < 3) { fI() and common }\n if (@N3[$n] ne 'd' && @N0[$n] div 4 > 0) { fG() and common }\n if (@N3[$n] ne 'l' && @N0[$n]  % 4 < 3) { fE() and common }\n if (@N3[$n] ne 'r' && @N0[$n]  % 4 > 0) { fL() and common }\n return False;\n}\n\nsub fI() {\n my \\g = (11-@N0[$n])*4;\n my \\a = @N2[$n] +& (15 +< g);\n @N0[$n+1]=@N0[$n]+4;\n @N2[$n+1]=@N2[$n]-a+(a+<16);\n @N3[$n+1]='d';\n @N4[$n+1]=@N4[$n]+(Nr[a+>g] ≤ @N0[$n] div 4 ?? 0 !! 1);\n}\n\nsub fG() {\n my \\g = (19-@N0[$n])*4;\n my \\a = @N2[$n] +& (15 +< g);\n @N0[$n+1]=@N0[$n]-4;\n @N2[$n+1]=@N2[$n]-a+(a+>16);\n @N3[$n+1]='u';\n @N4[$n+1]=@N4[$n]+(Nr[a+>g] ≥ @N0[$n] div 4 ?? 0 !! 1);\n}\n\nsub fE() {\n my \\g = (14-@N0[$n])*4;\n my \\a = @N2[$n] +& (15 +< g);\n @N0[$n+1]=@N0[$n]+1;\n @N2[$n+1]=@N2[$n]-a+(a+<4);\n @N3[$n+1]='r';\n @N4[$n+1]=@N4[$n]+(Nc[a+>g] ≤ @N0[$n]%4 ?? 0 !! 1);\n}\n\nsub fL(){\n my \\g = (16-@N0[$n])*4;\n my \\a = @N2[$n] +& (15 +< g);\n @N0[$n+1]=@N0[$n]-1;\n @N2[$n+1]=@N2[$n]-a+(a+>4);\n @N3[$n+1]='l';\n @N4[$n+1]=@N4[$n]+(Nc[a+>g] ≥ @N0[$n]%4 ?? 0 !! 1);\n}\n\nsub fifteenSolver(\\n, \\g){@N0[0]=n; @N2[0]=g}\n\n\nfifteenSolver(8,0xfe169b4c0a73d852);\nloop { fY() or ++$m }\n\n```\n\nOutput:\n\n```\nSolution found in 52 moves: rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd\n\n```" } ]
[ { "role": "user", "content": "16 numbered pieces of the puzzle are placed out of order on a 4 X 4 grid. The correct order to win is to order the pieces\nas 1 through 16, read left to right, top to bottom:\n\n```\n 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\n\n```\n\nHow to Play: The aim is to get the pieces back in order by clicking on the yellow arrows (choosing a location to rotate a row or column) to slide the pieces left or right, up or down.\n\n```\n 1 14 3 4 1 2 3 4\n 5 2 7 8 --> 5 6 7 8\n 9 6 11 12 9 10 11 12\n 13 10 15 16 13 14 15 16\n ^\n\n\n```\n\nThe Easy puzzle target is 3 moves, for the Hard puzzle it is 12 moves (or less!). Can it be that simple?\n\nTask\n\nCreate 16 Puzzle Game.\n\nSee details: [1]\n\nVideo: 16 Puzzle Game\n\nRelated task\n: * 15 Puzzle Game" }, { "role": "assistant", "content": "For brevity, changed to zero-based and skipped some error handling.\n\n**Translation of**: Go\n\n```\n# 20210914 Raku programming solution \n\nmy (\\easy,\\hard) = 1,4 ; my @n = ^16; my \\level = $ = easy ; my \\moves = $ = 0;\n\nsub hasWon { @n eq ^16 }\n\nsub setDiff($level) {\n say \"\\nTarget is \", ( moves = $level == hard ?? 12 !! 3 ).Str, \" moves.\"; \n for ^moves {\n my \\s = (^4).roll;\n @n[ ( [ s, s+4 ... s+12 ] , [ s*4 .. s*4+3 ] ).roll ] .= rotate ;\n redo if hasWon\n }\n}\n\nsub drawGrid {\n say \"\\n U1 U2 U3 U4\";\n say \" ╔════╦════╦════╦════╗\";\n printf \"L1 ║ %2d ║ %2d ║ %2d ║ %2d ║ R1\\n\", @n[0..3];\n say \" ╠════╬════╬════╬════╣\";\n printf \"L2 ║ %2d ║ %2d ║ %2d ║ %2d ║ R2\\n\", @n[4..7];\n say \" ╠════╬════╬════╬════╣\";\n printf \"L3 ║ %2d ║ %2d ║ %2d ║ %2d ║ R3\\n\", @n[8..11];\n say \" ╠════╬════╬════╬════╣\";\n printf \"L4 ║ %2d ║ %2d ║ %2d ║ %2d ║ R4\\n\", @n[12..15];\n say \" ╚════╩════╩════╩════╝\";\n say \" D1 D2 D3 D4\\n\"\n}\n\nsub init {\n loop {\n print \"Enter difficulty level easy or hard E/H : \";\n given $*IN.get.uc {\n when 'E'|'H' { level = $_ eq 'H' ?? hard !! easy ; last } \n default { say \"Invalid response, try again.\" }\n }\n }\n setDiff(level);\n moves = 0;\n}\n\ninit;\n\nloop {\n drawGrid;\n if hasWon() {\n say \"Congratulations, you have won the game in {moves} moves.\\n\" and exit\n } \n say \"When entering moves, you can also enter Q to quit or S to start again.\";\n say \"\\nMoves so far = {moves}\\n\";\n print \"Enter move : \" ;\n given $*IN.get.uc {\n my \\c = .substr(*-1).ord - 49 ; moves++ ; \n when 'D1'|'D2'|'D3'|'D4' { @n[ (12,8,4,0) >>+>> c ] .= rotate }\n when 'L1'|'L2'|'L3'|'L4' { @n[ (0,1,2,3) >>+>> 4*c ] .= rotate }\n when 'U1'|'U2'|'U3'|'U4' { @n[ (0,4,8,12) >>+>> c ] .= rotate }\n when 'R1'|'R2'|'R3'|'R4' { @n[ (3,2,1,0) >>+>> 4*c ] .= rotate }\n when 'Q' { exit } \n when 'S' { init } \n default { say \"\\nInvalid move, try again.\" and moves-- }\n }\n}\n\n```" } ]
[ { "role": "user", "content": "Task\n\nImplement a 2D sliding block puzzle game where blocks with numbers are combined to add their values.\n\nRules of the game\n: * The rules are that on each turn the player must choose a direction   (up, down, left or right).\n * All tiles move as far as possible in that direction, some move more than others.\n * Two adjacent tiles (in that direction only) with matching numbers combine into one bearing the sum of those numbers.\n * A move is valid when at least one tile can be moved, including by combination.\n * A new tile is spawned at the end of each turn at a randomly chosen empty square   (if there is one).\n * Most of the time, a new **2** is to be added, but occasionally (**10%** of the time), a **4**.\n * To win, the player must create a tile with the number **2048**.\n * The player loses if no valid moves are possible.\n\nThe name comes from the popular open-source implementation of this game mechanic, 2048.\n\nRequirements\n\n* \"Non-greedy\" movement. \n   The tiles that were created by combining other tiles should not be combined again during the same turn (move). \n   That is to say, that moving the tile row of:\n\n```\n [2][2][2][2] \n\n```\n\n: : to the right should result in:\n\n```\n ......[4][4] \n\n```\n\n: : and not:\n\n```\n .........[8] \n\n```\n\n* \"Move direction priority\". \n   If more than one variant of combining is possible, move direction shall indicate which combination will take effect. \n   For example, moving the tile row of:\n\n```\n ...[2][2][2] \n\n```\n\n: : to the right should result in:\n\n```\n ......[2][4] \n\n```\n\n: : and not:\n\n```\n ......[4][2] \n\n```\n\n* Check for valid moves. The player shouldn't be able to gain new tile by trying a move that doesn't change the board.\n* Check for a win condition.\n* Check for a lose condition." }, { "role": "assistant", "content": "(formerly Perl 6)\nUses termios to set the terminal options, so only compatible with POSIX terminals. This version does not include a specific \"win\" or \"lose\" condition. (though it would be trivial to add them.) You can continue to play this even after getting a 2048 tile; and if there is no valid move you can make, you can't do anything but quit.\n\n**Works with**: Rakudo version 2018.05\n\n```\nuse Term::termios;\n\nconstant $saved = Term::termios.new(fd => 1).getattr;\nconstant $termios = Term::termios.new(fd => 1).getattr;\n# raw mode interferes with carriage returns, so\n# set flags needed to emulate it manually\n$termios.unset_iflags(<BRKINT ICRNL ISTRIP IXON>);\n$termios.unset_lflags(< ECHO ICANON IEXTEN ISIG>);\n$termios.setattr(:DRAIN);\n\n# reset terminal to original setting on exit\nEND { $saved.setattr(:NOW) }\n\nconstant n = 4; # board size\nconstant cell = 6; # cell width\nconstant ansi = True; # color!\n\nmy @board = ( ['' xx n] xx n );\nmy $save = '';\nmy $score = 0;\n\nconstant $top = join '─' x cell, '┌', '┬' xx n-1, '┐';\nconstant $mid = join '─' x cell, '├', '┼' xx n-1, '┤';\nconstant $bot = join '─' x cell, '└', '┴' xx n-1, '┘';\n\nmy %dir = (\n \"\\e[A\" => 'up',\n \"\\e[B\" => 'down',\n \"\\e[C\" => 'right',\n \"\\e[D\" => 'left',\n);\n\nmy @ANSI = <0 1;97 1;93 1;92 1;96 1;91 1;95 1;94 1;30;47 1;43\n 1;42 1;46 1;41 1;45 1;44 1;33;43 1;33;42 1;33;41 1;33;44>;\n\nsub row (@row) { '│' ~ (join '│', @row».&center) ~ '│' }\n\nsub center ($s){\n my $c = cell - $s.chars;\n my $pad = ' ' x ceiling($c/2);\n my $tile = sprintf \"%{cell}s\", \"$s$pad\";\n my $idx = $s ?? $s.log(2) !! 0;\n ansi ?? \"\\e[{@ANSI[$idx]}m$tile\\e[0m\" !! $tile;\n}\n\nsub draw-board {\n run('clear');\n print qq:to/END/;\n\n\n\tPress direction arrows to move.\n\n\tPress q to quit.\n\n\t$top\n\t{ join \"\\n\\t$mid\\n\\t\", map { .&row }, @board }\n\t$bot\n\n\tScore: $score\n\nEND\n}\n\nsub squash (@c) {\n my @t = grep { .chars }, @c;\n map { combine(@t[$_], @t[$_+1]) if @t[$_] && @t[$_+1] == @t[$_] }, ^@t-1;\n @t = grep { .chars }, @t;\n @t.push: '' while @t < n;\n @t;\n}\n\nsub combine ($v is rw, $w is rw) { $v += $w; $w = ''; $score += $v; }\n\nproto sub move (|) {*};\n\nmulti move('up') {\n map { @board[*;$_] = squash @board[*;$_] }, ^n;\n}\n\nmulti move('down') {\n map { @board[*;$_] = reverse squash reverse @board[*;$_] }, ^n;\n}\n\nmulti move('left') {\n map { @board[$_] = squash @board[$_] }, ^n;\n}\n\nmulti move('right') {\n map { @board[$_;*] = reverse squash reverse @board[$_] }, ^n;\n}\n\nsub another {\n my @empties;\n for @board.kv -> $r, @row {\n @empties.push(($r, $_)) for @row.grep(:k, '');\n }\n my ( $x, $y ) = @empties.roll;\n @board[$x; $y] = (flat 2 xx 9, 4).roll;\n}\n\nsub save () { join '|', flat @board».list }\n\nloop {\n another if $save ne save();\n draw-board;\n $save = save();\n\n # Read up to 4 bytes from keyboard buffer.\n # Page navigation keys are 3-4 bytes each.\n # Specifically, arrow keys are 3.\n my $key = $*IN.read(4).decode;\n\n move %dir{$key} if so %dir{$key};\n last if $key eq 'q'; # (q)uit\n}\n\n```\n\nSample output:\n\n```\n\n\n\tPress direction arrows to move.\n\n\tPress q to quit. \n\n\t┌──────┬──────┬──────┬──────┐\n\t│ 4 │ 2 │ │ │\n\t├──────┼──────┼──────┼──────┤\n\t│ 16 │ 8 │ │ │\n\t├──────┼──────┼──────┼──────┤\n\t│ 64 │ 32 │ 16 │ │\n\t├──────┼──────┼──────┼──────┤\n\t│ 128 │ 512 │ 128 │ 64 │\n\t└──────┴──────┴──────┴──────┘\n\n\tScore: 6392\n\n```" } ]
[ { "role": "user", "content": "**21** is a two player game, the game is played by choosing\na number (**1**, **2**, or **3**) to be added to the *running total*.\n\nThe game is won by the player whose chosen number causes the *running total*\nto reach *exactly* **21**.\n\nThe *running total* starts at zero.\nOne player will be the computer.\n\nPlayers alternate supplying a number to be added to the *running total*.\n\nTask\n\nWrite a computer program that will:\n\n: : * do the prompting (or provide a button menu),\n * check for errors and display appropriate error messages,\n * do the additions (add a chosen number to the *running total*),\n * display the *running total*,\n * provide a mechanism for the player to quit/exit/halt/stop/close the program,\n * issue a notification when there is a winner, and\n * determine who goes first (maybe a random or user choice, or can be specified when the game begins)." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.09\n\nSince there is no requirement that the computer play sensibly, it always plays a random guess so the player has some chance to win.\n\n```\nsay qq :to 'HERE';\n The 21 game. Each player chooses to add 1, 2, or 3 to a running total.\n The player whose turn it is when the total reaches 21 wins. Enter q to quit.\n HERE\n\nmy $total = 0;\nloop {\n say \"Running total is: $total\";\n my ($me,$comp);\n loop {\n $me = prompt 'What number do you play> ';\n last if $me ~~ /^<[123]>$/;\n insult $me;\n }\n $total += $me;\n win('Human') if $total >= 21;\n say \"Computer plays: { $comp = (1,2,3).roll }\\n\";\n $total += $comp;\n win('Computer') if $total >= 21;\n}\n\nsub win ($player) {\n say \"$player wins.\";\n exit;\n}\n\nsub insult ($g) {\n exit if $g eq 'q';\n print ('Yo mama,', 'Jeez,', 'Ummmm,', 'Grow up,', 'Did you even READ the instructions?').roll;\n say \" $g is not an integer between 1 & 3...\"\n}\n\n```\n\nSample game:\n\n```\nThe 21 game. Each player chooses to add 1, 2, or 3 to a running total.\nThe player whose turn it is when the total reaches 21 wins. Enter q to quit.\n\nRunning total is: 0\nWhat number do you play> 5\nDid you even READ the instructions? 5 is not an integer between 1 & 3...\nWhat number do you play> g\nYo mama, g is not an integer between 1 & 3...\nWhat number do you play> 12\nJeez, 12 is not an integer between 1 & 3...\nWhat number do you play> 3\nComputer plays: 2\n\nRunning total is: 5\nWhat number do you play> 3\nComputer plays: 3\n\nRunning total is: 11\nWhat number do you play> 1\nComputer plays: 1\n\nRunning total is: 13\nWhat number do you play> 3\nComputer plays: 2\n\nRunning total is: 18\nWhat number do you play> 3\nHuman wins.\n```" } ]
[ { "role": "user", "content": "The 24 Game tests one's mental arithmetic.\n\nTask\n\nWrite a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using *just* those, and *all* of those four digits, used exactly *once* each. The program should *check* then evaluate the expression.\n\nThe goal is for the player to enter an expression that (numerically) evaluates to **24**.\n\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is *disallowed*. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\nNotes\n\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\nRelated tasks\n\n* 24 game/Solve\n\nReference\n\n* The 24 Game on h2g2." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nsay \"Here are your digits: \", \nconstant @digits = (1..9).roll(4)».Str;\n \ngrammar Exp24 {\n token TOP { ^ <exp> $ { fail unless EVAL($/) == 24 } }\n rule exp { <term>+ % <op> }\n rule term { '(' <exp> ')' | <@digits> }\n token op { < + - * / > }\n}\n \nwhile my $exp = prompt \"\\n24? \" {\n if try Exp24.parse: $exp {\n say \"You win :)\";\n last;\n } else {\n say (\n 'Sorry. Try again.' xx 20,\n 'Try harder.' xx 5,\n 'Nope. Not even close.' xx 2,\n 'Are you five or something?',\n 'Come on, you can do better than that.'\n ).flat.pick\n }\n}\n\n```\n\nThe `MONKEY-SEE-NO-EVAL` pragma enables the dangerous `EVAL` function, which will compile and execute even user input. In this example, the grammar used to parse the input should ensure that only safe expressions are evaluated." } ]
[ { "role": "user", "content": "task\n\nWrite a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game.\n\nShow examples of solutions generated by the program.\n\nRelated task\n\n* Arithmetic Evaluator" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### With EVAL\n\nA loose translation of the Perl entry. Does not return every possible permutation of the possible solutions. Filters out duplicates (from repeated digits) and only reports the solution for a particular order of digits and operators with the fewest parenthesis (avoids reporting duplicate solutions only differing by unnecessary parenthesis). Does not guarantee the order in which results are returned.\n\nSince Raku uses Rational numbers for division (whenever possible) there is no loss of precision as is common with floating point division. So a comparison like (1 + 7) / (1 / 3) == 24 \"Just Works\"™\n\n```\nuse MONKEY-SEE-NO-EVAL;\n\nmy @digits;\nmy $amount = 4;\n\n# Get $amount digits from the user,\n# ask for more if they don't supply enough\nwhile @digits.elems < $amount {\n @digits.append: (prompt \"Enter {$amount - @digits} digits from 1 to 9, \"\n ~ '(repeats allowed): ').comb(/<[1..9]>/);\n}\n# Throw away any extras\n@digits = @digits[^$amount];\n\n# Generate combinations of operators\nmy @ops = [X,] <+ - * /> xx 3;\n\n# Enough sprintf formats to cover most precedence orderings\nmy @formats = (\n '%d %s %d %s %d %s %d',\n '(%d %s %d) %s %d %s %d',\n '(%d %s %d %s %d) %s %d',\n '((%d %s %d) %s %d) %s %d',\n '(%d %s %d) %s (%d %s %d)',\n '%d %s (%d %s %d %s %d)',\n '%d %s (%d %s (%d %s %d))',\n);\n\n# Brute force test the different permutations\[email protected]».join.unique».comb.race.map: -> @p {\n for @ops -> @o {\n for @formats -> $format {\n my $result = .EVAL given my $string = sprintf $format, roundrobin(@p, @o, :slip);\n say \"$string = 24\" and last if $result and $result == 24;\n }\n }\n}\n\n```\n\nOutput:\n\n```\nEnter 4 digits from 1 to 9, (repeats allowed): 3711\n(1 + 7) * 3 * 1 = 24\n(1 + 7) * 3 / 1 = 24\n(1 * 3) * (1 + 7) = 24\n3 * (1 + 1 * 7) = 24\n(3 * 1) * (1 + 7) = 24\n3 * (1 / 1 + 7) = 24\n(3 / 1) * (1 + 7) = 24\n3 / (1 / (1 + 7)) = 24\n(1 + 7) * 1 * 3 = 24\n(1 + 7) / 1 * 3 = 24\n(1 + 7) / (1 / 3) = 24\n(1 * 7 + 1) * 3 = 24\n(7 + 1) * 3 * 1 = 24\n(7 + 1) * 3 / 1 = 24\n(7 - 1) * (3 + 1) = 24\n(1 + 1 * 7) * 3 = 24\n(1 * 1 + 7) * 3 = 24\n(1 / 1 + 7) * 3 = 24\n(3 + 1) * (7 - 1) = 24\n3 * (1 + 7 * 1) = 24\n3 * (1 + 7 / 1) = 24\n(3 * 1) * (7 + 1) = 24\n(3 / 1) * (7 + 1) = 24\n3 / (1 / (7 + 1)) = 24\n(1 + 3) * (7 - 1) = 24\n(1 * 3) * (7 + 1) = 24\n(7 + 1) * 1 * 3 = 24\n(7 + 1) / 1 * 3 = 24\n(7 + 1) / (1 / 3) = 24\n(7 - 1) * (1 + 3) = 24\n(7 * 1 + 1) * 3 = 24\n(7 / 1 + 1) * 3 = 24\n3 * (7 + 1 * 1) = 24\n3 * (7 + 1 / 1) = 24\n3 * (7 * 1 + 1) = 24\n3 * (7 / 1 + 1) = 24\n\nEnter 4 digits from 1 to 9, (repeats allowed): 5 5 5 5\n5 * 5 - 5 / 5 = 24\n\nEnter 4 digits from 1 to 9, (repeats allowed): 8833\n8 / (3 - 8 / 3) = 24\n\n```\n\n### No EVAL\n\nAlternately, a version that doesn't use EVAL. More general case. Able to handle 3 or 4 integers, able to select the goal value.\n\n```\nmy %*SUB-MAIN-OPTS = :named-anywhere;\n\nsub MAIN (*@parameters, Int :$goal = 24) {\n my @numbers;\n if +@parameters == 1 {\n @numbers = @parameters[0].comb(/\\d/);\n USAGE() and exit unless 2 < @numbers < 5;\n } elsif +@parameters > 4 {\n USAGE() and exit;\n } elsif +@parameters == 3|4 {\n @numbers = @parameters;\n USAGE() and exit if @numbers.any ~~ /<-[-\\d]>/;\n } else {\n USAGE();\n exit if +@parameters == 2;\n @numbers = 3,3,8,8;\n say 'Running demonstration with: ', |@numbers, \"\\n\";\n }\n solve @numbers, $goal\n}\n\nsub solve (@numbers, $goal = 24) {\n my @operators = < + - * / >;\n my @ops = [X] @operators xx (@numbers - 1);\n my @perms = @numbers.permutations.unique( :with(&[eqv]) );\n my @order = (^(@numbers - 1)).permutations;\n my @sol;\n @sol[250]; # preallocate some stack space\n\n my $batch = ceiling +@perms/4;\n\n my atomicint $i;\n @perms.race(:batch($batch)).map: -> @p {\n for @ops -> @o {\n for @order -> @r {\n my $result = evaluate(@p, @o, @r);\n @sol[$i⚛++] = $result[1] if $result[0] and $result[0] == $goal;\n }\n }\n }\n @sol.=unique;\n say @sol.join: \"\\n\";\n my $pl = +@sol == 1 ?? '' !! 's';\n my $sg = $pl ?? '' !! 's';\n say +@sol, \" equation{$pl} evaluate{$sg} to $goal using: {@numbers}\";\n}\n\nsub evaluate ( @digit, @ops, @orders ) {\n my @result = @digit.map: { [ $_, $_ ] };\n my @offset = 0 xx +@orders;\n\n for ^@orders {\n my $this = @orders[$_];\n my $order = $this - @offset[$this];\n my $op = @ops[$this];\n my $result = op( $op, @result[$order;0], @result[$order+1;0] );\n return [ NaN, Str ] unless defined $result;\n my $string = \"({@result[$order;1]} $op {@result[$order+1;1]})\";\n @result.splice: $order, 2, [ $[ $result, $string ] ];\n @offset[$_]++ if $order < $_ for ^@offset;\n }\n @result[0];\n}\n\nmulti op ( '+', $m, $n ) { $m + $n }\nmulti op ( '-', $m, $n ) { $m - $n }\nmulti op ( '/', $m, $n ) { $n == 0 ?? fail() !! $m / $n }\nmulti op ( '*', $m, $n ) { $m * $n }\n\nmy $txt = \"\\e[0;96m\";\nmy $cmd = \"\\e[0;92m> {$*EXECUTABLE-NAME} {$*PROGRAM-NAME}\";\nsub USAGE {\n say qq:to\n '========================================================================'\n {$txt}Supply 3 or 4 integers on the command line, and optionally a value\n to equate to.\n\n Integers may be all one group: {$cmd} 2233{$txt}\n Or, separated by spaces: {$cmd} 2 4 6 7{$txt}\n\n If you wish to supply multi-digit or negative numbers, you must\n separate them with spaces: {$cmd} -2 6 12{$txt}\n\n If you wish to use a different equate value,\n supply a new --goal parameter: {$cmd} --goal=17 2 -3 1 9{$txt}\n\n If you don't supply any parameters, will use 24 as the goal, will run a\n demo and will show this message.\\e[0m\n ========================================================================\n}\n\n```\n\nOutput:\n\nWhen supplied 1399 on the command line:\n\n```\n(((9 - 1) / 3) * 9)\n((9 - 1) / (3 / 9))\n((9 / 3) * (9 - 1))\n(9 / (3 / (9 - 1)))\n((9 * (9 - 1)) / 3)\n(9 * ((9 - 1) / 3))\n(((9 - 1) * 9) / 3)\n((9 - 1) * (9 / 3))\n8 equations evaluate to 24 using: 1 3 9 9\n```" } ]
[ { "role": "user", "content": "Task\n\nReplace       **a, b, c, d, e, f,**   and\n  **g**       with the decimal\ndigits   LOW   ───►   HIGH\n \nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n```\n ╔══════════════╗ ╔══════════════╗\n ║ ║ ║ ║\n ║ a ║ ║ e ║\n ║ ║ ║ ║\n ║ ┌───╫──────╫───┐ ┌───╫─────────┐\n ║ │ ║ ║ │ │ ║ │\n ║ │ b ║ ║ d │ │ f ║ │\n ║ │ ║ ║ │ │ ║ │\n ║ │ ║ ║ │ │ ║ │\n ╚══════════╪═══╝ ╚═══╪══════╪═══╝ │\n │ c │ │ g │\n │ │ │ │\n │ │ │ │\n └──────────────┘ └─────────────┘\n\n```\n\nShow all output here.\n\n: * Show all solutions for each letter being unique with\n\n```\n LOW=1 HIGH=7\n\n```\n\n: * Show all solutions for each letter being unique with\n\n```\n LOW=3 HIGH=9\n\n```\n\n: * Show only the   *number*   of solutions when each letter can be non-unique\n\n```\n LOW=0 HIGH=9\n\n```\n\nRelated task\n\n* Solve the no connection puzzle" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.12\n\n```\nsub four-squares ( @list, :$unique=1, :$show=1 ) {\n\n my @solutions;\n\n for $unique.&combos -> @c {\n @solutions.push: @c if [==]\n @c[0] + @c[1],\n @c[1] + @c[2] + @c[3],\n @c[3] + @c[4] + @c[5],\n @c[5] + @c[6];\n }\n\n say +@solutions, ($unique ?? ' ' !! ' non-'), \"unique solutions found using {join(', ', @list)}.\\n\";\n\n my $f = \"%{@list.max.chars}s\";\n\n say join \"\\n\", (('a'..'g').fmt: $f), @solutions».fmt($f), \"\\n\" if $show;\n\n multi combos ( $ where so * ) { @list.combinations(7).map: |*.permutations }\n\n multi combos ( $ where not * ) { [X] @list xx 7 }\n}\n\n# TASK\nfour-squares( [1..7] );\nfour-squares( [3..9] );\nfour-squares( [8, 9, 11, 12, 17, 18, 20, 21] );\nfour-squares( [0..9], :unique(0), :show(0) );\n\n```\n\nOutput:\n\n```\n8 unique solutions found using 1, 2, 3, 4, 5, 6, 7.\n\na b c d e f g\n3 7 2 1 5 4 6\n4 5 3 1 6 2 7\n4 7 1 3 2 6 5\n5 6 2 3 1 7 4\n6 4 1 5 2 3 7\n6 4 5 1 2 7 3\n7 2 6 1 3 5 4\n7 3 2 5 1 4 6\n\n\n4 unique solutions found using 3, 4, 5, 6, 7, 8, 9.\n\na b c d e f g\n7 8 3 4 5 6 9\n8 7 3 5 4 6 9\n9 6 4 5 3 7 8\n9 6 5 4 3 8 7\n\n\n8 unique solutions found using 8, 9, 11, 12, 17, 18, 20, 21.\n\n a b c d e f g\n17 21 8 9 11 18 20\n20 18 11 9 8 21 17\n17 21 9 8 12 18 20\n20 18 8 12 9 17 21\n20 18 12 8 9 21 17\n21 17 9 12 8 18 20\n20 18 11 9 12 17 21\n21 17 12 9 11 18 20\n\n\n2860 non-unique solutions found using 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.\n\n```" } ]
[ { "role": "user", "content": "This task is a variation of the short story by Arthur C. Clarke.\n\n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a   “name”:\n\n: The integer 1 has 1 name     “1”.\n: The integer 2 has 2 names   “1+1”,   and   “2”.\n: The integer 3 has 3 names   “1+1+1”,   “2+1”,   and   “3”.\n: The integer 4 has 5 names   “1+1+1+1”,   “2+1+1”,   “2+2”,   “3+1”,   “4”.\n: The integer 5 has 7 names   “1+1+1+1+1”,   “2+1+1+1”,   “2+2+1”,   “3+1+1”,   “3+2”,   “4+1”,   “5”.\n\nTask\n\nDisplay the first 25 rows of a number triangle which begins:\n\n```\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n```\n\nWhere row   \n\nn\n{\\displaystyle {\\displaystyle n}}\n   corresponds to integer   \n\nn\n{\\displaystyle {\\displaystyle n}}\n,   and each column   \n\nC\n{\\displaystyle {\\displaystyle C}}\n   in row   \n\nm\n{\\displaystyle {\\displaystyle m}}\n   from left to right corresponds to the number of names beginning with   \n\nC\n{\\displaystyle {\\displaystyle C}}\n.\n\nA function   \n\nG\n(\nn\n)\n{\\displaystyle {\\displaystyle G(n)}}\n   should return the sum of the   \n\nn\n{\\displaystyle {\\displaystyle n}}\n-th   row.\n\nDemonstrate this function by displaying:   \n\nG\n(\n23\n)\n{\\displaystyle {\\displaystyle G(23)}}\n,   \n\nG\n(\n123\n)\n{\\displaystyle {\\displaystyle G(123)}}\n,   \n\nG\n(\n1234\n)\n{\\displaystyle {\\displaystyle G(1234)}}\n,   and   \n\nG\n(\n12345\n)\n{\\displaystyle {\\displaystyle G(12345)}}\n.\n\nOptionally note that the sum of the   \n\nn\n{\\displaystyle {\\displaystyle n}}\n-th   row   \n\nP\n(\nn\n)\n{\\displaystyle {\\displaystyle P(n)}}\n   is the     integer partition function.\n\nDemonstrate this is equivalent to   \n\nG\n(\nn\n)\n{\\displaystyle {\\displaystyle G(n)}}\n   by displaying:   \n\nP\n(\n23\n)\n{\\displaystyle {\\displaystyle P(23)}}\n,   \n\nP\n(\n123\n)\n{\\displaystyle {\\displaystyle P(123)}}\n,   \n\nP\n(\n1234\n)\n{\\displaystyle {\\displaystyle P(1234)}}\n,   and   \n\nP\n(\n12345\n)\n{\\displaystyle {\\displaystyle P(12345)}}\n.\n\nExtra credit\n\nIf your environment is able, plot   \n\nP\n(\nn\n)\n{\\displaystyle {\\displaystyle P(n)}}\n   against   \n\nn\n{\\displaystyle {\\displaystyle n}}\n   for   \n\nn\n=\n1\n…\n999\n{\\displaystyle {\\displaystyle n=1\\ldots 999}}\n.\n\nRelated tasks\n\n* Partition function P" }, { "role": "assistant", "content": "(formerly Perl 6)\nTo save a bunch of memory, this algorithm throws away all the numbers that it knows it's not going to use again, on the assumption that the function will only be called with increasing values of $n. (It could easily be made to recalculate if it notices a regression.)\n\n```\nmy @todo = $[1];\nmy @sums = 0;\nsub nextrow($n) {\n for +@todo .. $n -> $l {\n my $r = [];\n for reverse ^$l -> $x {\n my @x := @todo[$x];\n if @x {\n $r.push: @sums[$x] += @x.shift;\n }\n else {\n $r.push: @sums[$x];\n }\n }\n @todo.push($r);\n }\n @todo[$n];\n}\n\nsay \"rows:\";\nsay .fmt('%2d'), \": \", nextrow($_)[] for 1..25;\n\n\nmy @names-of-God = 1, { partition-sum ++$ } … *;\nmy @names-of-God-adder = lazy [\\+] flat 1, ( (1 .. *) Z (1 .. *).map: * × 2 + 1 );\nsub partition-sum ($n) {\n sum @names-of-God[$n X- @names-of-God-adder[^(@names-of-God-adder.first: * > $n, :k)]]\n Z× (flat (1, 1, -1, -1) xx *)\n}\n\nsay \"\\nsums:\";\nfor 23, 123, 1234, 12345 {\n put $_, \"\\t\", @names-of-God[$_];\n}\n\n```\n\nOutput:\n\n```\nrows:\n 1: [1]\n 2: [1 1]\n 3: [1 1 1]\n 4: [1 2 1 1]\n 5: [1 2 2 1 1]\n 6: [1 3 3 2 1 1]\n 7: [1 3 4 3 2 1 1]\n 8: [1 4 5 5 3 2 1 1]\n 9: [1 4 7 6 5 3 2 1 1]\n10: [1 5 8 9 7 5 3 2 1 1]\n11: [1 5 10 11 10 7 5 3 2 1 1]\n12: [1 6 12 15 13 11 7 5 3 2 1 1]\n13: [1 6 14 18 18 14 11 7 5 3 2 1 1]\n14: [1 7 16 23 23 20 15 11 7 5 3 2 1 1]\n15: [1 7 19 27 30 26 21 15 11 7 5 3 2 1 1]\n16: [1 8 21 34 37 35 28 22 15 11 7 5 3 2 1 1]\n17: [1 8 24 39 47 44 38 29 22 15 11 7 5 3 2 1 1]\n18: [1 9 27 47 57 58 49 40 30 22 15 11 7 5 3 2 1 1]\n19: [1 9 30 54 70 71 65 52 41 30 22 15 11 7 5 3 2 1 1]\n20: [1 10 33 64 84 90 82 70 54 42 30 22 15 11 7 5 3 2 1 1]\n21: [1 10 37 72 101 110 105 89 73 55 42 30 22 15 11 7 5 3 2 1 1]\n22: [1 11 40 84 119 136 131 116 94 75 56 42 30 22 15 11 7 5 3 2 1 1]\n23: [1 11 44 94 141 163 164 146 123 97 76 56 42 30 22 15 11 7 5 3 2 1 1]\n24: [1 12 48 108 164 199 201 186 157 128 99 77 56 42 30 22 15 11 7 5 3 2 1 1]\n25: [1 12 52 120 192 235 248 230 201 164 131 100 77 56 42 30 22 15 11 7 5 3 2 1 1]\n\nsums:\n23\t1255\n123\t2552338241\n1234\t156978797223733228787865722354959930\n12345\t69420357953926116819562977205209384460667673094671463620270321700806074195845953959951425306140971942519870679768681736\n```" } ]
[ { "role": "user", "content": "Task\n\nDisplay the complete lyrics for the song:     **99 Bottles of Beer on the Wall**.\n\nThe beer song\n\nThe lyrics follow this form:\n\n> : : : 99 bottles of beer on the wall\n> : 99 bottles of beer\n> : Take one down, pass it around\n> : 98 bottles of beer on the wall\n>\n> : : : 98 bottles of beer on the wall\n> : 98 bottles of beer\n> : Take one down, pass it around\n> : 97 bottles of beer on the wall\n\n... and so on, until reaching   **0**     (zero).\n\nGrammatical support for   *1 bottle of beer*   is optional.\n\nAs with any puzzle, try to do it in as creative/concise/comical a way\nas possible (simple, obvious solutions allowed, too).\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet\n\nSee also\n\n* http://99-bottles-of-beer.net/\n* Category:99\\_Bottles\\_of\\_Beer\n* Category:Programming language families\n* Wikipedia 99 bottles of beer" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### A Simple Way\n\n```\nmy $b = 99;\n\nrepeat while --$b {\n say \"{b $b} on the wall\";\n say \"{b $b}\";\n say \"Take one down, pass it around\";\n say \"{b $b-1} on the wall\";\n say \"\";\n}\n\nsub b($b) {\n \"$b bottle{'s' if $b != 1} of beer\";\n}\n```\n\n### A Clearer Way\n\nSimilar to \"A Simple Way\", but with proper variable and subroutine naming, declarator documentation, strongly-typed function definition, better code reuse, and external ternary logic.\n\n```\nfor 99...1 -> $bottles {\n sing $bottles, :wall;\n sing $bottles;\n say \"Take one down, pass it around\";\n sing $bottles - 1, :wall;\n say \"\";\n}\n\n#| Prints a verse about a certain number of beers, possibly on a wall.\nsub sing(\n Int $number, #= Number of bottles of beer.\n Bool :$wall, #= Mention that the beers are on a wall?\n) {\n my $quantity = $number == 0 ?? \"No more\"  !! $number;\n my $plural = $number == 1 ?? \"\"  !! \"s\";\n my $location = $wall  ?? \" on the wall\" !! \"\";\n say \"$quantity bottle$plural of beer$location\"\n}\n```\n\n### A More Extravagant Way\n\n**Works with**: Rakudo version 2015.09\n\n```\nmy @quantities = flat (99 ... 1), 'No more', 99;\nmy @bottles = flat 'bottles' xx 98, 'bottle', 'bottles' xx 2;\nmy @actions = flat 'Take one down, pass it around' xx 99,\n 'Go to the store, buy some more';\n\nfor @quantities Z @bottles Z @actions Z\n @quantities[1 .. *] Z @bottles[1 .. *]\n -> ($a, $b, $c, $d, $e) {\n say \"$a $b of beer on the wall\";\n say \"$a $b of beer\";\n say $c;\n say \"$d $e of beer on the wall\\n\";\n}\n```" } ]
[ { "role": "user", "content": "The A\\* search algorithm is an extension of Dijkstra's algorithm useful for finding the lowest cost path between two nodes (aka vertices) of a graph. The path may traverse any number of nodes connected by edges (aka arcs) with each edge having an associated cost. The algorithm uses a heuristic which associates an estimate of the lowest cost path from this node to the goal node, such that this estimate is never greater than the actual cost.\n\nThe algorithm should not assume that all edge costs are the same. It should be possible to start and finish on any node, including ones identified as a barrier in the task.\n\nTask\n\nConsider the problem of finding a route across the diagonal of a chess board-like 8x8 grid. The rows are numbered from 0 to 7. The columns are also numbered 0 to 7. The start position is (0, 0) and the end position is (7, 7). Movement is allow by one square in any direction including diagonals, similar to a king in chess. The standard movement cost is 1. To make things slightly harder, there is a barrier that occupy certain positions of the grid. Moving into any of the barrier positions has a cost of 100.\n\nThe barrier occupies the positions (2,4), (2,5), (2,6), (3,6), (4,6), (5,6), (5,5), (5,4), (5,3), (5,2), (4,2) and (3,2).\n\nA route with the lowest cost should be found using the A\\* search algorithm (there are multiple optimal solutions with the same total cost).\n\nPrint the optimal route in text format, as well as the total cost of the route.\n\nOptionally, draw the optimal route and the barrier positions.\n\nNote: using a heuristic score of zero is equivalent to Dijkstra's algorithm and that's kind of cheating/not really A\\*!\n\n*Extra Credit*\n\nUse this algorithm to solve an 8 puzzle. Each node of the input graph will represent an arrangement of the tiles. The nodes will be connected by 4 edges representing swapping the blank tile up, down, left, or right. The cost of each edge is 1. The heuristic will be the sum of the manhatten distance of each numbered tile from its goal position. An 8 puzzle graph will have 9!/2 (181,440) nodes. The 15 puzzle has over 10 trillion nodes. This algorithm may solve simple 15 puzzles (but there are not many of those).\n\nSee also\n\n* Wikipedia webpage:   A\\* search algorithm.\n* An introduction to: Breadth First Search |> Dijkstra’s Algorithm |> A\\*\n\nRelated tasks\n\n* 15 puzzle solver\n* Dijkstra's algorithm\n* Knapsack problem/0-1" }, { "role": "assistant", "content": "**Translation of**: Sidef\n\n```\n# 20200427 Raku programming solution\n\nclass AStarGraph {\n\n has @.barriers =\n <2 4>,<2 5>,<2 6>,<3 6>,<4 6>,<5 6>,<5 5>,<5 4>,<5 3>,<5 2>,<4 2>,<3 2>;\n\n method heuristic(\\start, \\goal) {\n my (\\D1,\\D2) = 1, 1;\n my (\\dx,\\dy) = ( start.list »-« goal.list )».abs;\n return (D1 * (dx + dy)) + (D2 - 2*D1) * min dx, dy\n }\n\n method get_vertex_neighbours(\\pos) {\n gather {\n for <1 0>,<-1 0>,<0 1>,<0 -1>,<1 1>,<-1 1>,<1 -1>,<-1 -1> -> \\d {\n my (\\x2,\\y2) = pos.list »+« d.list;\n (x2 < 0 || x2 > 7 || y2 < 0 || y2 > 7) && next;\n take x2, y2;\n }\n }\n }\n\n method move_cost(\\a,\\b) { (b ~~ any self.barriers) ?? 100 !! 1 }\n}\n\nsub AStarSearch(\\start, \\end, \\graph) {\n\n my (%G,%F);\n\n %G{start.Str} = 0;\n %F{start.Str} = graph.heuristic(start, end);\n\n my @closedVertices = [];\n my @openVertices = [].push(start);\n my %cameFrom;\n\n while (@openVertices.Bool) {\n my $current = Nil; my $currentFscore = Inf;\n\n for @openVertices -> \\pos {\n if (%F{pos.Str} < $currentFscore) {\n $currentFscore = %F{pos.Str};\n $current = pos\n }\n }\n\n if $current ~~ end {\n my @path = [].push($current);\n while %cameFrom{$current.Str}:exists {\n $current = %cameFrom{$current.Str};\n @path.push($current)\n }\n return @path.reverse, %F{end.Str}\n }\n\n @openVertices .= grep: * !eqv $current;\n @closedVertices.push($current);\n\n for (graph.get_vertex_neighbours($current)) -> \\neighbour {\n next if neighbour ~~ any @closedVertices;\n my \\candidateG = %G{$current.Str}+graph.move_cost($current,neighbour);\n\n if !(neighbour ~~ any @openVertices) {\n @openVertices.push(neighbour)\n } elsif (candidateG ≥ %G{neighbour.Str}) {\n next\n }\n\n %cameFrom{neighbour.Str} = $current;\n %G{neighbour.Str} = candidateG;\n my \\H = graph.heuristic(neighbour, end);\n %F{neighbour.Str} = %G{neighbour.Str} + H;\n }\n }\n die \"A* failed to find a solution\"\n}\n\nmy \\graph = AStarGraph.new;\nmy (\\route, \\cost) = AStarSearch(<0 0>, <7 7>, graph);\n\nmy \\w = my \\h = 10;\n\nmy @grid = [ ['.' xx w ] xx h ];\nfor ^h -> \\y { @grid[y;0] = \"█\"; @grid[y;*-1] = \"█\" }\nfor ^w -> \\x { @grid[0;x] = \"█\"; @grid[*-1;x] = \"█\" }\n\nfor (graph.barriers) -> \\d { @grid[d[0]+1][d[1]+1] = \"█\" }\nfor @(route) -> \\d { @grid[d[0]+1][d[1]+1] = \"x\" }\n\n.join.say for @grid ;\n\nsay \"Path cost : \", cost, \" and route : \", route;\n\n```\n\nOutput:\n\n```\n██████████\n\n█x.......█\n█.x......█\n█..x.███.█\n█.x█...█.█\n█.x█...█.█\n█.x█████.█\n█..xxxxx.█\n█.......x█\n██████████\n\nPath cost : 11 and route : ((0 0) (1 1) (2 2) (3 1) (4 1) (5 1) (6 2) (6 3) (6 4) (6 5) (6 6) (7 7))\n```" } ]
[ { "role": "user", "content": "**A+B**   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used.\n\nTask\n\nGiven two integers,   **A** and **B**.\n\nTheir sum needs to be calculated.\n\nInput data\n\nTwo integers are written in the input stream, separated by space(s):\n\n: (\n −\n 1000\n ≤\n A\n ,\n B\n ≤\n +\n 1000\n )\n {\\displaystyle {\\displaystyle (-1000\\leq A,B\\leq +1000)}}\n\nOutput data\n\nThe required output is one integer:   the sum of **A** and **B**.\n\nExample\n\n: : | input | output |\n | --- | --- |\n | 2 2 | 4 |\n | 3 2 | 5 |" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.12\n\nShort version with very little \"line noise\":\n\n```\nget.words.sum.say;\n```\n\nReduction operator `[+]`, and `say` as a function:\n\n```\nsay [+] get.words;\n```\n\nLong version:\n\n```\nmy ($a, $b) = $*IN.get.split(\" \");\nsay $a + $b;\n```" } ]
[ { "role": "user", "content": "The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an\n \neasy way to add flexibility when specifying or using commands, sub─commands, options, etc.\n\nIt would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages   (note that there is a blank line in the list).\n\n```\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miércoles xueves vienres sábadu\nBazar_gÜnÜ Birinci_gÜn Çkinci_gÜn ÜçÜncÜ_gÜn DÖrdÜncÜ_gÜn Bes,inci_gÜn Altòncò_gÜn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mèkredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^lí úterÿ str^eda c^tvrtek pátek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaùdo Vendredo Sabato\npÜhapäev esmaspäev teisipäev kolmapäev neljapäev reede laupäev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mércores Joves Venres Sábado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npópule pó`akahi pó`alua pó`akolu pó`ahá pó`alima pó`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasárnap hétfö kedd szerda csütörtök péntek szombat\nSunnudagur Mánudagur ╞riδjudagur Miδvikudagar Fimmtudagur FÖstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDé_Domhnaigh Dé_Luain Dé_Máirt Dé_Ceadaoin Dé_ardaoin Dé_hAoine Dé_Sathairn\ndomenica lunedí martedí mercoledí giovedí venerdí sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_rì xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minòmishi mártes mièrkoles misheushi bèrnashi mishábaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsφndag mandag tirsdag onsdag torsdag fredag lφrdag\nlo_dimenge lo_diluns lo_dimarç lo_dimèrcres lo_dijòus lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabièrna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terça-feire quarta-feire quinta-feire sexta-feira såbado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminicª Luni Mart'i Miercuri Joi Vineri Sâmbªtª\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-màirt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miércoles jueves viernes sábado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsöndag måndag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLé-pài-jít Pài-it Pài-jï Pài-sañ Pài-sì Pài-gÖ. Pài-lák\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Çar,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nhâ.t Thú*_Hai Thú*_Ba Thú*_Tu* Thú*_Na'm Thú*_Sáu Thú*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gÜnÜ Bazar_ærtæsi Çærs,ænbæ_axs,amò Çærs,ænbæ_gÜnÜ CÜmæ_axs,amò CÜmæ_gÜnÜ CÜmæ_Senbæ\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sábado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tiàn xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù\ndjadomingu djaluna djamars djarason djaweps djabièrnè djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n```\n\n*Caveat:   The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.*\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\nNotes concerning the above list of words\n\n: : * each line has a list of days-of-the-week for a language, separated by at least one blank\n * the words on each line happen to be in order, from Sunday ──► Saturday\n * most lines have words in mixed case and some have all manner of accented words and other characters\n * some words were translated to the nearest character that was available to *code page*   **437**\n * the characters in the words are not restricted except that they may not have imbedded blanks\n * for this example, the use of an underscore (**\\_**) was used to indicate a blank in a word\n\nTask\n: : * The list of words   (days of the week)   needn't be verified/validated.\n * Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n * A blank line   (or a null line)   should return a null string.\n * Process and show the output for at least the first **five** lines of the file.\n * Show all output here.\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.08\n\nSaving the \"Days of Week, Also Known As\" table to a local file DoWAKA.txt. Lines that have duplicate day names will get ∞ as the minimum number of characters, as there is no amount of characters that can be entered to distinguish the days uniquely. It is somewhat unclear as to what is meant by \"return a null string\". I have chosen to return Nil.\n\nNote that this is using a previous version of the date file that has erroneous duplicate day names (see line 90). Since the effort was already expended to catch such problems, it may as well be demonstrated.\n\n```\nsub auto-abbreviate ( Str $string ) {\n return Nil unless my @words = $string.words;\n return $_ if @words».substr(0, $_).Set == @words for 1 .. @words».chars.max;\n return '∞';\n}\n\n# Testing\n say ++$, ') ', .&auto-abbreviate, ' ', $_ for './DoWAKA.txt'.IO.lines;\n\n```\n\nOutput:\n\n```\n1) 2 Sunday Monday Tuesday Wednesday Thursday Friday Saturday\n2) 2 Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\n3) 4 E_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë\n4) 2 Ehud Segno Maksegno Erob Hamus Arbe Kedame\n5) 5 Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\n6) 4 Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\n7) 2 domingu llunes martes miércoles xueves vienres sábadu\n8) 2 Bazar_gÜnÜ Birinci_gÜn Çkinci_gÜn ÜçÜncÜ_gÜn DÖrdÜncÜ_gÜn Bes,inci_gÜn Altòncò_gÜn\n9) 6 Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\n10) 4 Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\n11) 2 Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\n12) 5 Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\n13) 2 nedelia ponedelnik vtornik sriada chetvartak petak sabota\n14) 13 sing_kei_yath sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\n15) 4 Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\n16) 16 Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\n17) 6 dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\n18) 2 Dimanch Lendi Madi Mèkredi Jedi Vandredi Samdi\n19) 2 nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\n20) 2 nede^le ponde^lí úterÿ str^eda c^tvrtek pátek sobota\n21) 2 Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\n22) 2 s0ndag mandag tirsdag onsdag torsdag fredag l0rdag\n23) 2 zondag maandag dinsdag woensdag donderdag vrijdag zaterdag\n24) 2 Diman^co Lundo Mardo Merkredo ^Jaùdo Vendredo Sabato\n25) 1 pÜhapäev esmaspäev teisipäev kolmapäev neljapäev reede laupäev\n26) Nil \n27) 7 Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\n28) 2 sunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur\n29) 2 Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\n30) 2 sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\n31) 2 dimanche lundi mardi mercredi jeudi vendredi samedi\n32) 4 Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\n33) 2 Domingo Segunda_feira Martes Mércores Joves Venres Sábado\n34) 2 k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\n35) 2 Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\n36) 2 Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\n37) 3 ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\n38) 6 pópule pó`akahi pó`alua pó`akolu pó`ahá pó`alima pó`aono\n39) 7 Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\n40) 3 ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\n41) 3 vasárnap hétfö kedd szerda csütörtök péntek szombat\n42) 2 Sunnudagur Mánudagur ╞riδjudagur Miδvikudagar Fimmtudagur FÖstudagur Laugardagur\n43) 2 sundio lundio mardio merkurdio jovdio venerdio saturdio\n44) 3 Minggu Senin Selasa Rabu Kamis Jumat Sabtu\n45) 2 Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\n46) 4 Dé_Domhnaigh Dé_Luain Dé_Máirt Dé_Ceadaoin Dé_ardaoin Dé_hAoine Dé_Sathairn\n47) 2 domenica lunedí martedí mercoledí giovedí venerdí sabato\n48) 2 Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\n49) 1 Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\n50) 7 Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\n51) 3 sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\n52) 2 Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\n53) 3 Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\n54) 12 xing-_qi-_rì xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù\n55) 3 Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\n56) 3 Jabot Manre Juje Wonje Taije Balaire Jarere\n57) 5 geminrongo minòmishi mártes mièrkoles misheushi bèrnashi mishábaro\n58) 2 Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu\n59) 2 sφndag mandag tirsdag onsdag torsdag fredag lφrdag\n60) 7 lo_dimenge lo_diluns lo_dimarç lo_dimèrcres lo_dijòus lo_divendres lo_dissabte\n61) 4 djadomingo djaluna djamars djarason djaweps djabièrna djasabra\n62) 2 Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\n63) 3 Domingo segunda-feire terça-feire quarta-feire quinta-feire sexta-feira såbado\n64) 1 Domingo Lunes martes Miercoles Jueves Viernes Sabado\n65) 2 Duminicª Luni Mart'i Miercuri Joi Vineri Sâmbªtª\n66) 2 voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\n67) 4 Sunday Di-luain Di-màirt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\n68) 2 nedjelja ponedjeljak utorak sreda cxetvrtak petak subota\n69) 5 Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\n70) 2 Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\n71) 2 nedel^a pondelok utorok streda s^tvrtok piatok sobota\n72) 2 Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\n73) 2 domingo lunes martes miércoles jueves viernes sábado\n74) 2 sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\n75) 7 Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\n76) 2 söndag måndag tisdag onsdag torsdag fredag lordag\n77) 2 Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\n78) 6 Lé-pài-jít Pài-it Pài-jï Pài-sañ Pài-sì Pài-gÖ. Pài-lák\n79) 7 wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\n80) 5 Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\n81) 6 Pazar Pazartesi Sali Çar,samba Per,sembe Cuma Cumartesi\n82) 2 nedilya ponedilok vivtorok sereda chetver pyatnytsya subota\n83) 8 Chu?_Nhâ.t Thú*_Hai Thú*_Ba Thú*_Tu* Thú*_Na'm Thú*_Sáu Thú*_Ba?y\n84) 6 dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\n85) 3 Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\n86) 7 iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\n87) 2 zuntik montik dinstik mitvokh donershtik fraytik shabes\n88) 7 iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\n89) 7 Dies_Dominica Dies_Lunæ Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\n90) ∞ Bazar_gÜnÜ Bazar_ærtæsi Çærs,ænbæ_axs,amò Çærs,ænbæ_gÜnÜ CÜmæ_axs,amò CÜmæ_gÜnÜ CÜmæ_gÜnÜ\n91) 2 Sun Moon Mars Mercury Jove Venus Saturn\n92) 2 zondag maandag dinsdag woensdag donderdag vrijdag zaterdag\n93) 2 KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\n94) 5 Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\n95) 1 Domingo Luns Terza_feira Corta_feira Xoves Venres Sábado\n96) 7 Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\n97) 12 xing-_qi-_tiàn xing-_qi-_yi-. xing-_qi-_èr xing-_qi-_san-. xing-_qi-_sì xing-_qi-_wuv. xing-_qi-_liù\n98) 4 djadomingu djaluna djamars djarason djaweps djabièrnè djasabra\n99) 2 Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n```" } ]
[ { "role": "user", "content": "This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple.\n\nFor this task, the following   *command table*   will be used:\n\n```\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n```\n\nNotes concerning the above   *command table*:\n\n: : * it can be thought of as one long literal string   (with blanks at end-of-lines)\n * it may have superfluous blanks\n * it may be in any case (lower/upper/mixed)\n * the order of the words in the   *command table*   must be preserved as shown\n * the user input(s) may be in any case (upper/lower/mixed)\n * commands will be restricted to the Latin alphabet   (A ──► Z,   a ──► z)\n * A valid abbreviation is a word that has:\n\n : * at least the minimum length of the number of capital letters of the word in the *command table*\n * compares equal (regardless of case) to the leading characters of the word in the *command table*\n * a length not longer than the word in the *command table*\n\n : * **ALT**,   **aLt**,   **ALTE**,   and   **ALTER**   are all abbreviations of   **ALTer**\n * **AL**,   **ALF**,   **ALTERS**,   **TER**,   and   **A**   aren't valid abbreviations of   **ALTer**\n * The number of capital letters in   **ALTer**   indicates that any abbreviation for   **ALTer**   must be at least three letters\n * Any word longer than five characters can't be an abbreviation for   **ALTer**\n * **o**,   **ov**,   **oVe**,   **over**,   **overL**,   **overla**   are all acceptable abbreviations for   **Overlay**\n\n * if there isn't any lowercase letters in the word in the *command table*,   then there isn't an abbreviation permitted\n\nTask\n: : * The command table needn't be verified/validated.\n * Write a function to validate if the user \"words\"   (given as input)   are valid   (in the *command table*).\n * If the word   is   valid,   then return the full uppercase version of that \"word\".\n * If the word isn't valid,   then return the lowercase string:   **\\*error\\***       (7 characters).\n * A blank input   (or a null input)   should return a null string.\n * Show all output here.\n\nAn example test case to be used for this task\n\nFor a user string of:\n\n```\n riG rePEAT copies put mo rest types fup. 6 poweRin\n\n```\n\nthe computer program should return the string:\n\n```\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.08\n\nDemonstrate that inputting an empty string returns an empty string in addition to the required test input.\n\n```\n<\nAdd ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\nCOUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\nNFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\nJoin SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\nMErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\nREAD RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\nRIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n> ~~ m:g/ ((<.:Lu>+) <.:Ll>*) /;\n\nmy %abr = '' => '', |$/.map: {\n my $abbrv = .[0].Str.fc;\n |map { $abbrv.substr( 0, $_ ) => $abbrv.uc },\n .[0][0].Str.chars .. $abbrv.chars\n};\n\nsub abbr-easy ( $str ) { %abr{$str.trim.fc} // '*error*' }\n\n# Testing\nfor 'riG rePEAT copies put mo rest types fup. 6 poweRin', '' -> $str {\n put ' Input: ', $str;\n put 'Output: ', join ' ', $str.words.map: &abbr-easy;\n}\n\n```\n\nOutput:\n\n```\n Input: riG rePEAT copies put mo rest types fup. 6 poweRin\nOutput: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n Input: \nOutput: \n```" } ]
[ { "role": "user", "content": "The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an\n \neasy way to add flexibility when specifying or using commands, sub─commands, options, etc.\n\nFor this task, the following   *command table*   will be used:\n\n```\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n```\n\nNotes concerning the above   *command table*:\n\n: : * it can be thought of as one long literal string   (with blanks at end-of-lines)\n * it may have superfluous blanks\n * it may be in any case (lower/upper/mixed)\n * the order of the words in the   *command table*   must be preserved as shown\n * the user input(s) may be in any case (upper/lower/mixed)\n * commands will be restricted to the Latin alphabet   (A ──► Z,   a ──► z)\n * a command is followed by an optional number, which indicates the minimum abbreviation\n * A valid abbreviation is a word that has:\n\n : * at least the minimum length of the word's minimum number in the *command table*\n * compares equal (regardless of case) to the leading characters of the word in the *command table*\n * a length not longer than the word in the *command table*\n\n : * **ALT**,   **aLt**,   **ALTE**,   and   **ALTER**   are all abbreviations of   **ALTER 3**\n * **AL**,   **ALF**,   **ALTERS**,   **TER**,   and   **A**   aren't valid abbreviations of   **ALTER 3**\n * The   **3**   indicates that any abbreviation for   **ALTER**   must be at least three characters\n * Any word longer than five characters can't be an abbreviation for   **ALTER**\n * **o**,   **ov**,   **oVe**,   **over**,   **overL**,   **overla**   are all acceptable abbreviations for   **overlay 1**\n\n * if there isn't a number after the command,   then there isn't an abbreviation permitted\n\nTask\n: : * The command table needn't be verified/validated.\n * Write a function to validate if the user \"words\"   (given as input)   are valid   (in the *command table*).\n * If the word   is   valid,   then return the full uppercase version of that \"word\".\n * If the word isn't valid,   then return the lowercase string:   **\\*error\\***       (7 characters).\n * A blank input   (or a null input)   should return a null string.\n * Show all output here.\n\nAn example test case to be used for this task\n\nFor a user string of:\n\n```\n riG rePEAT copies put mo rest types fup. 6 poweRin\n\n```\n\nthe computer program should return the string:\n\n```\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.08\n\nDemonstrate that inputting an empty string returns an empty string in addition to the required test input.\n\n```\n<\nadd 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\ncompress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\nforward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\nlocate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\nmsg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\nrefresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n> ~~ m:g/ (<.alpha>+) \\s* (\\d*) /;\n\nmy %abr = '' => '', |$/.map: {\n my $abbrv = .[0].Str.fc;\n |map { $abbrv.substr( 0, $_ ) => $abbrv.uc },\n +(.[1].Str || .[0].Str.chars) .. .[0].Str.chars;\n};\n\nsub abbr-simple ( $str ) { %abr{$str.trim.fc} // '*error*' }\n\n# Testing\nfor 'riG rePEAT copies put mo rest types fup. 6 poweRin', '' -> $str {\n put ' Input: ', $str;\n put 'Output: ', join ' ', $str.words.map: &abbr-simple;\n}\n\n```\n\nOutput:\n\n```\n Input: riG rePEAT copies put mo rest types fup. 6 poweRin\nOutput: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n Input: \nOutput: \n```" } ]
[ { "role": "user", "content": "Taken from this video at the time stamp of 9:02\n\n**Task:**\n\nGet a string input and store it into a variable or something and compare the number of occurrences of the letters \"a\", \"b\" and \"c\".\nAll other characters MUST be ignored. If the \"a\"'s, \"b\"'s and \"c\"'s occur with exactly equal frequency, return true; otherwise return false." }, { "role": "assistant", "content": "I've elected to do 'or something' as specified in the task instructions. Rather than just feeding a few words in to check if there are equal counts of 'a', 'b', and 'c'; instead, reads in the words\\_alpha.txt word list and returns the words that have equal counts of 'a', 'b', and 'c', and, (to make things a little less verbose,) **have more than one of each**.\n\n```\n.say for 'words_alpha.txt'.IO.lines.race.grep({+(my \\b = .comb.Bag)<a> > 1 and [==] b<a b c>}) X~ \" True\";\n\n```\n\nOutput:\n\n```\nabboccato True\nbambocciade True\nbeccabunga True\nblackback True\nbombacaceous True\nbrachiocubital True\nbuccolabial True\ncabbalistic True\nsubbrachycephaly True\nsubcarbonaceous True\n\n```" } ]
[ { "role": "user", "content": "Write a routine (function, subroutine, procedure, whatever it may be called in your language,) that when given a set of three letters, (a, b, c) for instance, will identify words that contain each of those letters, in differing amounts, and where each count differs from another by exactly 1. Ignore any characters that are not in the given search group.\n\nFor example: using the letters (a, b, c) the \"word\" 'abbccc' would be valid (1(a), 2(b) & 3(c)), as would 'acodablaccab' (2(b), 3(c) & 4(a)).\n\nDo not hard code the letters to search for. Do not create three different single purpose search routines. Instead, create a generic routine that uses a given set of letters as its search criteria. Include some mechanism to limit the minimum count for the least common letter.\n\nYou may assume that the words are all lower case, or may choose to regularize the case of the words. In either case assume upper and lower case are the same. (The test files contain all and only lower case.)\n\nTask\n\nWrite a general purpose routine to identify incremental letter count words following the above description.\n\nUsing the unixdict.txt from http://wiki.puzzlers.org, find and display the words that are identified as incremental count words, or <none> if no words are found that match.\n\n: * Search for words containing (a b c) with a minimum count of 1\n * Search for words containing (t h e) with a minimum count of 1\n * Search for words containing (c i o) with a minimum count of 2\n\nShow the output here, on this page.\n\nStretch\n\nUse the same routine to search the words\\_alpha.txt file from https://github.com/dwyl/english-words using the same letter groups, but with a minimum 1 higher.\n\n: * Search for words containing (a b c) with a minimum count of 2\n * Search for words containing (t h e) with a minimum count of 2\n * Search for words containing (c i o) with a minimum count of 3\n\nRelated\n\nABC correlation" }, { "role": "assistant", "content": "```\nsay \"\\nUsing \", my $dict = 'unixdict.txt';\nmy @tests = <a b c>, 1, <t h e>, 1, <c i o>, 2;\nfilter $dict.IO.words;\n\nsay \"\\n\\nUsing \", $dict = 'words_alpha.txt';\n@tests[1,3,5]».++;\nfilter $dict.IO.words;\n\nsub filter (@words) {\n for @tests -> ($a, $b, $c), $min {\n say \"\\nLetters: ($a $b $c) -- Minimum count $min\\n\",\n @words.race.grep(&incremental).sort.join(\"\\n\") || '<none>';\n\n sub incremental ($word) {\n my @v = $word.comb.Bag{$a,$b,$c}.values.sort;\n (@v[0] >= $min) && (@v[0]+1 == @v[1]) && (@v[0]+2 == @v[2])\n }\n }\n}\n\n```\n\nOutput:\n\n```\nUsing unixdict.txt\n\nLetters: (a b c) -- Minimum count 1\nbaccarat\ncanvasback\nsabbatical\n\nLetters: (t h e) -- Minimum count 1\naesthete\nafterthought\nauthenticate\nbethlehem\ncheesecloth\ndiethylstilbestrol\neratosthenes\nheathenish\nletterhead\nliechtenstein\nmephistopheles\nnineteenth\northophosphate\nseventieth\nsweetheart\nteethe\nteethed\nthereafter\ntheretofore\nthirtieth\ntriphenylphosphine\ntwentieth\nwestchester\nwholehearted\n\nLetters: (c i o) -- Minimum count 2\nsocioeconomic\n\n\nUsing words_alpha.txt\n\nLetters: (a b c) -- Minimum count 2\n<none>\n\nLetters: (t h e) -- Minimum count 2\ndemethylchlortetracycline\ndichlorodiphenyltrichloroethane\nhyperthermesthesia\ntetrachloroethylene\nthermohyperesthesia\ntrinitrophenylmethylnitramine\n\nLetters: (c i o) -- Minimum count 3\nscleroticochorioiditis\n\n```" } ]
[ { "role": "user", "content": "You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid).\n\nThere are twenty blocks with two letters on each block.\n\nA complete alphabet is guaranteed amongst all sides of the blocks.\n\nThe sample collection of blocks:\n\n```\n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n```\n\nTask\n\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.\n\nThe rules are simple:\n\n: : 1. Once a letter on a block is used that block cannot be used again\n 2. The function should be case-insensitive\n 3. Show the output on this page for the following 7 words in the following example\n\nExample\n\n```\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\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 6.0.c\n\nBlocks are stored as precompiled regexes. We do an initial pass on the blockset to include in the list only those regexes that match somewhere in the current word. Conveniently, regexes scan the word for us.\n\n```\nmulti can-spell-word(Str $word, @blocks) {\n my @regex = @blocks.map({ my @c = .comb; rx/<@c>/ }).grep: { .ACCEPTS($word.uc) }\n can-spell-word $word.uc.comb.list, @regex;\n}\n \nmulti can-spell-word([$head,*@tail], @regex) {\n for @regex -> $re {\n if $head ~~ $re {\n return True unless @tail;\n return False if @regex == 1;\n return True if can-spell-word @tail, list @regex.grep: * !=== $re;\n }\n }\n False;\n}\n \nmy @b = <BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM>;\n \nfor <A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE> {\n say \"$_ &can-spell-word($_, @b)\";\n}\n```\n\nOutput:\n\n```\nA\tTrue\nBaRK\tTrue\nBOoK\tFalse\ntREaT\tTrue\nCOmMOn\tFalse\nSqUAD\tTrue\nCoNfuSE\tTrue\n```" } ]
[ { "role": "user", "content": "Definition\n\nA word is an   *ABC word*   if the letters  \"**a**\",  \"**b**\"  and  \"**c**\"  appear in the word in alphabetical order.\n\nIf any or all of these letters occur more than once in a word, then only the first occurrence of each letter should be used to determine whether a word is an  *ABC word*  or not.\n\nTask\n\nShow here   (on this page)   every  *ABC word*  in unixdict.txt.\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": "```\nput display 'unixdict.txt'.IO.words».fc.grep({ (.index('a')//next) < (.index('b')//next) < (.index('c')//next) }),\n  :11cols, :fmt('%-12s');\n\nsub display ($list, :$cols = 10, :$fmt = '%6d', :$title = \"{+$list} matching:\\n\" ) {\n cache $list;\n $title ~ $list.batch($cols)».fmt($fmt).join: \"\\n\"\n}\n\n```\n\nOutput:\n\n```\n55 matching:\naback abacus abc abdicate abduct abeyance abject abreact abscess abscissa abscissae \nabsence abstract abstracter abstractor adiabatic aerobacter aerobic albacore alberich albrecht algebraic \nalphabetic ambiance ambuscade aminobenzoic anaerobic arabic athabascan auerbach diabetic diabolic drawback \nfabric fabricate flashback halfback iambic lampblack leatherback metabolic nabisco paperback parabolic \nplayback prefabricate quarterback razorback roadblock sabbatical snapback strabismic syllabic tabernacle tablecloth \n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Abelian sandpile model. 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\nImplement the **Abelian sandpile model** also known as **Bak–Tang–Wiesenfeld model**. Its history, mathematical definition and properties can be found under its wikipedia article.\n\nThe task requires the creation of a 2D grid of arbitrary size on which \"piles of sand\" can be placed. Any \"pile\" that has 4 or more sand particles on it *collapses*, resulting in **four particles being subtracted from the pile** and **distributed among its neighbors.**\n\nIt is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task. \nExamples up to 2^30, wow! \njavascript running on web \n**Examples:**\n\n```\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 4 0 0 -> 0 1 0 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 1 0 0\n0 0 6 0 0 -> 0 1 2 1 0\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0\n\n0 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 2 1 2 0\n0 0 16 0 0 -> 1 1 0 1 1\n0 0 0 0 0 0 2 1 2 0\n0 0 0 0 0 0 0 1 0 0\n\n```" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n### Terminal based\n\n**Works with**: Rakudo version 2019.07.1\n\nDefaults to a stack of 1000 and showing progress. Pass in a custom stack size if desired and -hide-progress to run without displaying progress (much faster.)\n\n```\nsub cleanup { print \"\\e[0m\\e[?25h\\n\"; exit(0) }\n\nsignal(SIGINT).tap: { cleanup(); exit(0) }\n\nunit sub MAIN ($stack = 1000, :$hide-progress = False );\n\nmy @color = \"\\e[38;2;0;0;0m█\",\n \"\\e[38;2;255;0;0m█\",\n \"\\e[38;2;255;255;0m█\",\n \"\\e[38;2;0;0;255m█\",\n \"\\e[38;2;255;255;255m█\"\n  ;\n\nmy ($h, $w) = qx/stty size/.words».Int;\nmy $buf = $w * $h;\nmy @buffer = 0 xx $buf;\nmy $done;\n\n@buffer[$w * ($h div 2) + ($w div 2) - 1] = $stack;\n\nprint \"\\e[?25l\\e[48;5;232m\";\n\nrepeat {\n $done = True;\n loop (my int $row; $row < $h; $row = $row + 1) {\n my int $rs = $row * $w; # row start\n my int $re = $rs + $w; # row end\n loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {\n if @buffer[$idx] >= 4 {\n my $grains = @buffer[$idx] div 4;\n @buffer[ $idx - $w ] += $grains if $row > 0;\n @buffer[ $idx - 1 ] += $grains if $idx - 1 >= $rs;\n @buffer[ $idx + $w ] += $grains if $row < $h - 1;\n @buffer[ $idx + 1 ] += $grains if $idx + 1 < $re;\n @buffer[ $idx ] %= 4;\n $done = False;\n }\n }\n }\n unless $hide-progress {\n print \"\\e[1;1H\", @buffer.map( { @color[$_ min 4] }).join;\n }\n} until $done;\n\nprint \"\\e[1;1H\", @buffer.map( { @color[$_ min 4] }).join;\n\ncleanup;\n\n```\n\nPassing in 2048 as a stack size results in: Abelian-sandpile-model-perl6.png (offsite .png image)\n\n### SDL2 Animation\n\n```\nuse NativeCall;\nuse SDL2::Raw;\n\nmy ($width, $height) = 900, 900;\n\nunit sub MAIN ($stack = 10000);\n\nmy int ($w, $h) = 160, 160;\n\nmy $buf = $w * $h;\nmy @buffer = 0 xx $buf;\n\n@buffer[$w * ($h div 2) + ($w div 2) - 1] = $stack;\n\n\nSDL_Init(VIDEO);\n\nmy SDL_Window $window = SDL_CreateWindow(\n \"Abelian sandpile - Raku\",\n SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK,\n $width, $height,\n RESIZABLE\n);\n\nmy SDL_Renderer $renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE );\n\nmy $asp_texture = SDL_CreateTexture($renderer, %PIXELFORMAT<RGB332>, STREAMING, $w, $h);\n\nmy $pixdatabuf = CArray[int64].new(0, $w, $h, $w);\n\nmy @color = 0x00, 0xDE, 0x14, 0xAA, 0xFF;\n\nsub render {\n my int $pitch;\n my int $cursor;\n\n # work-around to pass the pointer-pointer.\n my $pixdata = nativecast(Pointer[int64], $pixdatabuf);\n SDL_LockTexture($asp_texture, SDL_Rect, $pixdata, $pitch);\n\n $pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0]));\n\n loop (my int $row; $row < $h; $row = $row + 1) {\n my int $rs = $row * $w; # row start\n my int $re = $rs + $w; # row end\n loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {\n $pixdata[$idx] = @buffer[$idx] < 4 ?? @color[@buffer[$idx]] !! @color[4];\n if @buffer[$idx] >= 4 {\n my $grains = floor @buffer[$idx] / 4;\n @buffer[ $idx - $w ] += $grains if $row > 0;\n @buffer[ $idx - 1 ] += $grains if $idx - 1 >= $rs;\n @buffer[ $idx + $w ] += $grains if $row < $h - 1;\n @buffer[ $idx + 1 ] += $grains if $idx + 1 < $re;\n @buffer[ $idx ] %= 4;\n }\n }\n }\n\n SDL_UnlockTexture($asp_texture);\n\n SDL_RenderCopy($renderer, $asp_texture, SDL_Rect, SDL_Rect.new(:x(0), :y(0), :w($width), :h($height)));\n SDL_RenderPresent($renderer);\n}\n\nmy $event = SDL_Event.new;\n\nmain: loop {\n\n while SDL_PollEvent($event) {\n my $casted_event = SDL_CastEvent($event);\n\n given $casted_event {\n when *.type == QUIT {\n last main;\n }\n }\n }\n\n render();\n print fps;\n}\n\nsay '';\n\nsub fps {\n state $fps-frames = 0;\n state $fps-now = now;\n state $fps = '';\n $fps-frames++;\n if now - $fps-now >= 1 {\n $fps = [~] \"\\b\" x 40, ' ' x 20, \"\\b\" x 20 ,\n sprintf \"FPS: %5.2f \", ($fps-frames / (now - $fps-now)).round(.01);\n $fps-frames = 0;\n $fps-now = now;\n }\n $fps\n}\n\n```\n\nPassing in a stack size of 20000 results in: Abelian-sandpile-sdl2.png (offsite .png image)" } ]
[ { "role": "user", "content": "Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that\ncontain a number from 0 to 3 inclusive. (The numbers are said to represent\ngrains of sand in each area of the sandpile).\n\nE.g. `s1` =\n\n```\n \n 1 2 0\n 2 1 1\n 0 1 3\n\n```\n\nand `s2` =\n\n```\n 2 1 3\n 1 0 1\n 0 1 0\n\n```\n\nAddition on sandpiles is done by adding numbers in corresponding grid areas,\nso for the above:\n\n```\n 1 2 0 2 1 3 3 3 3\n s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2\n 0 1 3 0 1 0 0 2 3\n\n```\n\nIf the addition would result in more than 3 \"grains of sand\" in any area then\nthose areas cause the whole sandpile to become \"unstable\" and the sandpile\nareas are \"toppled\" in an \"avalanche\" until the \"stable\" result is obtained.\n\nAny unstable area (with a number >= 4), is \"toppled\" by loosing one grain of\nsand to each of its four horizontal or vertical neighbours. Grains are lost\nat the edge of the grid, but otherwise increase the number in neighbouring\ncells by one, whilst decreasing the count in the toppled cell by four in each\ntoppling.\n\nA toppling may give an adjacent area more than four grains of sand leading to\na chain of topplings called an \"avalanche\".\nE.g.\n\n```\n \n 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0\n 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3\n 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3\n\n```\n\nThe final result is the stable sandpile on the right.\n\n**Note:** The order in which cells are toppled does not affect the final result.\n\nTask\n\n* Create a class or datastructure and functions to represent and operate on sandpiles.\n* Confirm the result of the avalanche of topplings shown above\n* Confirm that s1 + s2 == s2 + s1 # Show the stable results\n* If s3 is the sandpile with number 3 in every grid area, and s3\\_id is the following sandpile:\n\n```\n 2 1 2 \n 1 0 1 \n 2 1 2\n\n```\n\n* Show that `s3 + s3_id == s3`\n* Show that `s3_id + s3_id == s3_id`\n\nShow confirming output here, with your examples.\n\nReferences\n\n* https://www.youtube.com/watch?v=1MtEUErz7Gg\n* https://en.wikipedia.org/wiki/Abelian\\_sandpile\\_model" }, { "role": "assistant", "content": "**Works with**: Rakudo version 2020.05\n\nMost of the logic is lifted straight from the Abelian sandpile model task.\n\n```\nclass ASP {\n has $.h = 3;\n has $.w = 3;\n has @.pile = 0 xx $!w * $!h;\n\n method topple {\n my $buf = $!w * $!h;\n my $done;\n repeat {\n $done = True;\n loop (my int $row; $row < $!h; $row = $row + 1) {\n my int $rs = $row * $!w; # row start\n my int $re = $rs + $!w; # row end\n loop (my int $idx = $rs; $idx < $re; $idx = $idx + 1) {\n if self.pile[$idx] >= 4 {\n my $grain = self.pile[$idx] div 4;\n self.pile[ $idx - $!w ] += $grain if $row > 0;\n self.pile[ $idx - 1 ] += $grain if $idx - 1 >= $rs;\n self.pile[ $idx + $!w ] += $grain if $row < $!h - 1;\n self.pile[ $idx + 1 ] += $grain if $idx + 1 < $re;\n self.pile[ $idx ] %= 4;\n $done = False;\n }\n }\n }\n } until $done;\n self.pile;\n }\n}\n\n# some handy display layout modules\nuse Terminal::Boxer:ver<0.2+>;\nuse Text::Center;\n\nfor 3, (4,3,3,3,1,2,0,2,3), (2,1,2,1,0,1,2,1,2), # 3 square task example\n 3, (2,1,2,1,0,1,2,1,2), (2,1,2,1,0,1,2,1,2), # 3 square identity\n 5, (4,1,0,5,1,9,3,6,1,0,8,1,2,5,3,3,0,1,7,5,4,2,2,4,0), (2,3,2,3,2,3,2,1,2,3,2,1,0,1,2,3,2,1,2,3,2,3,2,3,2) # 5 square test\n -> $size, $pile, $identity {\n\n my $asp = ASP.new(:h($size), :w($size));\n\n $asp.pile = |$pile;\n\n my @display;\n\n my %p = :col($size), :3cw, :indent(\"\\t\");\n\n @display.push: rs-box |%p, |$identity;\n\n @display.push: rs-box |%p, $asp.pile;\n\n @display.push: rs-box |%p, $asp.topple;\n\n $asp.pile Z+= $identity.list;\n\n @display.push: rs-box |%p, $asp.pile;\n\n @display.push: rs-box |%p, $asp.topple;\n\n put %p<indent> ~ qww<identity 'test pile' toppled 'plus identity' toppled>».&center($size * 4 + 1).join: %p<indent>;\n\n .put for [Z~] @display».lines;\n\n put '';\n}\n\n```\n\nOutput:\n\n```\n\t identity \t test pile \t toppled \tplus identity\t toppled \n\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\n\t│ 2 │ 1 │ 2 │\t│ 4 │ 3 │ 3 │\t│ 2 │ 1 │ 0 │\t│ 4 │ 2 │ 2 │\t│ 2 │ 1 │ 0 │\n\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\n\t│ 1 │ 0 │ 1 │\t│ 3 │ 1 │ 2 │\t│ 0 │ 3 │ 3 │\t│ 1 │ 3 │ 4 │\t│ 0 │ 3 │ 3 │\n\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\n\t│ 2 │ 1 │ 2 │\t│ 0 │ 2 │ 3 │\t│ 1 │ 2 │ 3 │\t│ 3 │ 3 │ 5 │\t│ 1 │ 2 │ 3 │\n\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\n\n\t identity \t test pile \t toppled \tplus identity\t toppled \n\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\t╭───┬───┬───╮\n\t│ 2 │ 1 │ 2 │\t│ 2 │ 1 │ 2 │\t│ 2 │ 1 │ 2 │\t│ 4 │ 2 │ 4 │\t│ 2 │ 1 │ 2 │\n\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\n\t│ 1 │ 0 │ 1 │\t│ 1 │ 0 │ 1 │\t│ 1 │ 0 │ 1 │\t│ 2 │ 0 │ 2 │\t│ 1 │ 0 │ 1 │\n\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\t├───┼───┼───┤\n\t│ 2 │ 1 │ 2 │\t│ 2 │ 1 │ 2 │\t│ 2 │ 1 │ 2 │\t│ 4 │ 2 │ 4 │\t│ 2 │ 1 │ 2 │\n\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\t╰───┴───┴───╯\n\n\t identity \t test pile \t toppled \t plus identity \t toppled \n\t╭───┬───┬───┬───┬───╮\t╭───┬───┬───┬───┬───╮\t╭───┬───┬───┬───┬───╮\t╭───┬───┬───┬───┬───╮\t╭───┬───┬───┬───┬───╮\n\t│ 2 │ 3 │ 2 │ 3 │ 2 │\t│ 4 │ 1 │ 0 │ 5 │ 1 │\t│ 1 │ 3 │ 2 │ 1 │ 0 │\t│ 3 │ 6 │ 4 │ 4 │ 2 │\t│ 1 │ 3 │ 2 │ 1 │ 0 │\n\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\n\t│ 3 │ 2 │ 1 │ 2 │ 3 │\t│ 9 │ 3 │ 6 │ 1 │ 0 │\t│ 2 │ 2 │ 3 │ 3 │ 1 │\t│ 5 │ 4 │ 4 │ 5 │ 4 │\t│ 2 │ 2 │ 3 │ 3 │ 1 │\n\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\n\t│ 2 │ 1 │ 0 │ 1 │ 2 │\t│ 8 │ 1 │ 2 │ 5 │ 3 │\t│ 1 │ 1 │ 2 │ 0 │ 3 │\t│ 3 │ 2 │ 2 │ 1 │ 5 │\t│ 1 │ 1 │ 2 │ 0 │ 3 │\n\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\n\t│ 3 │ 2 │ 1 │ 2 │ 3 │\t│ 3 │ 0 │ 1 │ 7 │ 5 │\t│ 2 │ 0 │ 3 │ 2 │ 0 │\t│ 5 │ 2 │ 4 │ 4 │ 3 │\t│ 2 │ 0 │ 3 │ 2 │ 0 │\n\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\t├───┼───┼───┼───┼───┤\n\t│ 2 │ 3 │ 2 │ 3 │ 2 │\t│ 4 │ 2 │ 2 │ 4 │ 0 │\t│ 3 │ 2 │ 3 │ 2 │ 1 │\t│ 5 │ 5 │ 5 │ 5 │ 3 │\t│ 3 │ 2 │ 3 │ 2 │ 1 │\n\t╰───┴───┴───┴───┴───╯\t╰───┴───┴───┴───┴───╯\t╰───┴───┴───┴───┴───╯\t╰───┴───┴───┴───┴───╯\t╰───┴───┴───┴───┴───╯\n\n```" } ]
[ { "role": "user", "content": "**Abstract type** is a type without instances or without definition.\n\nFor example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called **interfaces**. In the languages that do not support multiple inheritance (Ada, Java), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like C++) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, OO languages normally prevent instantiation from them (instantiation must derived from one of their descendant classes).\n\nThe term **abstract datatype** also may denote a type, with an implementation provided by the programmer rather than directly by the language (a **built-in** or an inferred type). Here the word *abstract* means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the information hiding principle.\n\nIt is important not to confuse this *abstractness* (of implementation) with one of the **abstract type**. The latter is abstract in the sense that the set of its values is empty. In the sense of implementation abstracted away, all user-defined types are abstract.\n\nIn some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have **abstract types** that are not OO related and are not an abstractness too. These are *pure abstract types* without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter.\n\n**Task**: show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015.12\n\nRaku supports roles, which are a bit like interfaces, but unlike interfaces in Java they can also contain some implementation.\n\n```\nuse v6;\n\nrole A {\n # must be filled in by the class it is composed into\n method abstract() { ... };\n\n # can be overridden in the class, but that's not mandatory\n method concrete() { say '# 42' };\n}\n\nclass SomeClass does A {\n method abstract() {\n say \"# made concrete in class\"\n }\n}\n\nmy $obj = SomeClass.new;\n$obj.abstract();\n$obj.concrete();\n\n# output:\n# made concrete in class\n# 42\n\n```" } ]
[ { "role": "user", "content": "An Abundant number is a number **n** for which the   *sum of divisors*   **σ\n(\nn\n)\n>\n2\nn\n{\\displaystyle {\\displaystyle \\sigma (n)>2n}}**,\n \nor,   equivalently,   the   *sum of proper divisors*   (or aliquot sum)       **s\n(\nn\n)\n>\nn\n{\\displaystyle {\\displaystyle s(n)>n}}**.\n\nE.G.\n\n**12**   is abundant, it has the proper divisors     **1, 2, 3, 4 & 6**     which sum to   **16**   ( > **12** or **n**);\n \n       or alternately,   has the sigma sum of   **1, 2, 3, 4, 6 & 12**   which sum to   **28**   ( > **24** or **2n**).\n\nAbundant numbers are common, though **even** abundant numbers seem to be much more common than **odd** abundant numbers.\n\nTo make things more interesting, this task is specifically about finding   *odd abundant numbers*.\n\nTask\n\n* Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n* Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n* Find and display here: the first abundant odd number greater than one billion (\n\n 10\n\n 9\n {\\displaystyle {\\displaystyle 10^{9}}}\n ) and either its proper divisor sum or sigma sum.\n\nReferences\n: * OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n * American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\n```\nsub odd-abundant (\\x) {\n my @l = x.is-prime ?? 1 !! flat\n 1, (3 .. x.sqrt.floor).map: -> \\d {\n next unless d +& 1;\n my \\y = x div d;\n next if y * d !== x;\n d !== y ?? (d, y) !! d\n };\n @l.sum > x ?? @l.sort !! Empty;\n}\n\nsub odd-abundants (Int :$start-at is copy) {\n $start-at = ( $start-at + 2 ) div 3;\n $start-at += $start-at %% 2;\n $start-at *= 3;\n ($start-at, *+6 ... *).hyper.map: {\n next unless my $oa = cache .&odd-abundant;\n sprintf \"%6d: divisor sum: {$oa.join: ' + '} = {$oa.sum}\", $_\n }\n}\n\nput 'First 25 abundant odd numbers:';\n.put for odd-abundants( :start-at(1) )[^25];\n\nput \"\\nOne thousandth abundant odd number:\\n\" ~ odd-abundants( :start-at(1) )[999] ~\n\n\"\\n\\nFirst abundant odd number above one billion:\\n\" ~ odd-abundants( :start-at(1_000_000_000) ).head;\n\n```\n\nOutput:\n\n```\nFirst 25 abundant odd numbers:\n 945: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 105 + 135 + 189 + 315 = 975\n 1575: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 175 + 225 + 315 + 525 = 1649\n 2205: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 35 + 45 + 49 + 63 + 105 + 147 + 245 + 315 + 441 + 735 = 2241\n 2835: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 81 + 105 + 135 + 189 + 315 + 405 + 567 + 945 = 2973\n 3465: divisor sum: 1 + 3 + 5 + 7 + 9 + 11 + 15 + 21 + 33 + 35 + 45 + 55 + 63 + 77 + 99 + 105 + 165 + 231 + 315 + 385 + 495 + 693 + 1155 = 4023\n 4095: divisor sum: 1 + 3 + 5 + 7 + 9 + 13 + 15 + 21 + 35 + 39 + 45 + 63 + 65 + 91 + 105 + 117 + 195 + 273 + 315 + 455 + 585 + 819 + 1365 = 4641\n 4725: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 27 + 35 + 45 + 63 + 75 + 105 + 135 + 175 + 189 + 225 + 315 + 525 + 675 + 945 + 1575 = 5195\n 5355: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 17 + 21 + 35 + 45 + 51 + 63 + 85 + 105 + 119 + 153 + 255 + 315 + 357 + 595 + 765 + 1071 + 1785 = 5877\n 5775: divisor sum: 1 + 3 + 5 + 7 + 11 + 15 + 21 + 25 + 33 + 35 + 55 + 75 + 77 + 105 + 165 + 175 + 231 + 275 + 385 + 525 + 825 + 1155 + 1925 = 6129\n 5985: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 19 + 21 + 35 + 45 + 57 + 63 + 95 + 105 + 133 + 171 + 285 + 315 + 399 + 665 + 855 + 1197 + 1995 = 6495\n 6435: divisor sum: 1 + 3 + 5 + 9 + 11 + 13 + 15 + 33 + 39 + 45 + 55 + 65 + 99 + 117 + 143 + 165 + 195 + 429 + 495 + 585 + 715 + 1287 + 2145 = 6669\n 6615: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 49 + 63 + 105 + 135 + 147 + 189 + 245 + 315 + 441 + 735 + 945 + 1323 + 2205 = 7065\n 6825: divisor sum: 1 + 3 + 5 + 7 + 13 + 15 + 21 + 25 + 35 + 39 + 65 + 75 + 91 + 105 + 175 + 195 + 273 + 325 + 455 + 525 + 975 + 1365 + 2275 = 7063\n 7245: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 23 + 35 + 45 + 63 + 69 + 105 + 115 + 161 + 207 + 315 + 345 + 483 + 805 + 1035 + 1449 + 2415 = 7731\n 7425: divisor sum: 1 + 3 + 5 + 9 + 11 + 15 + 25 + 27 + 33 + 45 + 55 + 75 + 99 + 135 + 165 + 225 + 275 + 297 + 495 + 675 + 825 + 1485 + 2475 = 7455\n 7875: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 125 + 175 + 225 + 315 + 375 + 525 + 875 + 1125 + 1575 + 2625 = 8349\n 8085: divisor sum: 1 + 3 + 5 + 7 + 11 + 15 + 21 + 33 + 35 + 49 + 55 + 77 + 105 + 147 + 165 + 231 + 245 + 385 + 539 + 735 + 1155 + 1617 + 2695 = 8331\n 8415: divisor sum: 1 + 3 + 5 + 9 + 11 + 15 + 17 + 33 + 45 + 51 + 55 + 85 + 99 + 153 + 165 + 187 + 255 + 495 + 561 + 765 + 935 + 1683 + 2805 = 8433\n 8505: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 27 + 35 + 45 + 63 + 81 + 105 + 135 + 189 + 243 + 315 + 405 + 567 + 945 + 1215 + 1701 + 2835 = 8967\n 8925: divisor sum: 1 + 3 + 5 + 7 + 15 + 17 + 21 + 25 + 35 + 51 + 75 + 85 + 105 + 119 + 175 + 255 + 357 + 425 + 525 + 595 + 1275 + 1785 + 2975 = 8931\n 9135: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 29 + 35 + 45 + 63 + 87 + 105 + 145 + 203 + 261 + 315 + 435 + 609 + 1015 + 1305 + 1827 + 3045 = 9585\n 9555: divisor sum: 1 + 3 + 5 + 7 + 13 + 15 + 21 + 35 + 39 + 49 + 65 + 91 + 105 + 147 + 195 + 245 + 273 + 455 + 637 + 735 + 1365 + 1911 + 3185 = 9597\n 9765: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 31 + 35 + 45 + 63 + 93 + 105 + 155 + 217 + 279 + 315 + 465 + 651 + 1085 + 1395 + 1953 + 3255 = 10203\n 10395: divisor sum: 1 + 3 + 5 + 7 + 9 + 11 + 15 + 21 + 27 + 33 + 35 + 45 + 55 + 63 + 77 + 99 + 105 + 135 + 165 + 189 + 231 + 297 + 315 + 385 + 495 + 693 + 945 + 1155 + 1485 + 2079 + 3465 = 12645\n 11025: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 49 + 63 + 75 + 105 + 147 + 175 + 225 + 245 + 315 + 441 + 525 + 735 + 1225 + 1575 + 2205 + 3675 = 11946\n\nOne thousandth abundant odd number:\n492975: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 63 + 75 + 105 + 175 + 225 + 313 + 315 + 525 + 939 + 1565 + 1575 + 2191 + 2817 + 4695 + 6573 + 7825 + 10955 + 14085 + 19719 + 23475 + 32865 + 54775 + 70425 + 98595 + 164325 = 519361\n\nFirst abundant odd number above one billion:\n1000000575: divisor sum: 1 + 3 + 5 + 7 + 9 + 15 + 21 + 25 + 35 + 45 + 49 + 63 + 75 + 105 + 147 + 175 + 225 + 245 + 315 + 441 + 525 + 735 + 1225 + 1575 + 2205 + 3675 + 11025 + 90703 + 272109 + 453515 + 634921 + 816327 + 1360545 + 1904763 + 2267575 + 3174605 + 4081635 + 4444447 + 5714289 + 6802725 + 9523815 + 13333341 + 15873025 + 20408175 + 22222235 + 28571445 + 40000023 + 47619075 + 66666705 + 111111175 + 142857225 + 200000115 + 333333525 = 1083561009\n```" } ]
[ { "role": "user", "content": "These define three classifications of positive integers based on their   proper divisors.\n\nLet   P(n)   be the sum of the proper divisors of   **n**   where the proper divisors are all positive divisors of   **n**   other than   **n**   itself.\n\n```\n if P(n) < n then n is classed as deficient (OEIS A005100).\n if P(n) == n then n is classed as perfect (OEIS A000396).\n if P(n) > n then n is classed as abundant (OEIS A005101).\n\n```\n\nExample\n\n**6**   has proper divisors of   **1**,   **2**,   and   **3**.\n\n**1 + 2 + 3 = 6**,   so   **6**   is classed as a perfect number.\n\nTask\n\nCalculate how many of the integers   **1**   to   **20,000**   (inclusive) are in each of the three classes.\n\nShow the results here.\n\nRelated tasks\n\n* Aliquot sequence classifications.   (The whole series from which this task is a subset.)\n* Proper divisors\n* Amicable pairs" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.12\n\n```\nsub propdivsum (\\x) {\n my @l = 1 if x > 1;\n (2 .. x.sqrt.floor).map: -> \\d {\n unless x % d { @l.push: d; my \\y = x div d; @l.push: y if y != d }\n }\n sum @l\n}\n\nsay bag (1..20000).map: { propdivsum($_) <=> $_ }\n\n```\n\nOutput:\n\n```\nBag(Less(15043), More(4953), Same(4))\n```" } ]
[ { "role": "user", "content": "A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\nRules\n\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in *small italic text*).\n\n: Before you submit an example, make sure the function\n\n: 1. Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i). \n Although these exact function and parameter names need not be used\n 2. Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) *(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)*\n 3. Generates functions that return the sum of every number ever passed to them, not just the most recent. *(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)*\n 4. Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. *(Follow your language's conventions here.)*\n 5. Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. *(No global variables or other such things.)*\n: E.g. if after the example, you added the following code (in a made-up language) *where the factory function is called foo*:\n\n : ```\n x = foo(1); \n x(5); \n foo(3);\n print x(2.3);\n ```\n: It should print 8.3. *(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)*\n\nTask\n\nCreate a function that implements the described rules.\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nsub accum ($n is copy) { sub { $n += $^x } }\n\n#Example use:\nmy $a = accum 5;\n$a(4.5);\nsay $a(.5); # Prints \"10\".\n\n# You can also use the \"&\" sigil to create a function that behaves syntactically\n# like any other function (i.e. no sigil nor parentheses needed to call it):\n\nmy &b = accum 5;\nsay b 3; # Prints \"8\".\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Achilles number. 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\nAn **Achilles number** is a number that is powerful but imperfect. *Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.*\n\nA positive integer **n** is a powerful number if, for every prime factor **p** of **n**, **p2** is also a divisor.\n\nIn other words, every prime factor appears at least squared in the factorization.\n\nAll **Achilles numbers** are powerful. However, not all powerful numbers are **Achilles numbers**: only those that cannot be represented as **mk**, where **m** and **k** are positive integers greater than **1**.\n\nA ***strong* Achilles number** is an **Achilles number** whose **Euler totient (𝜑)** is also an **Achilles number**.\n\nE.G.\n\n**108** is a powerful number. Its prime factorization is **22 × 33**, and thus its prime factors are **2** and **3**. Both **22 = 4** and **32 = 9** are divisors of **108**. However, **108** cannot be represented as **mk**, where **m** and **k** are positive integers greater than **1**, so **108** is an **Achilles number**.\n\n**360** is *not* an **Achilles number** because it is not powerful. One of its prime factors is **5** but **360** is not divisible by **52 = 25**.\n\nFinally, **784** is *not* an **Achilles number**. It is a powerful number, because not only are **2** and **7** its only prime factors, but also **22 = 4** and **72 = 49** are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is *not* an **Achilles number**.\n\n**500 = 22 × 53** is a ***strong* Achilles number** as its Euler totient, **𝜑(500)**, is **200 = 23 × 52** which is *also* an **Achilles number**.\n\nTask\n\n* Find and show the first 50 **Achilles numbers**.\n* Find and show at least the first 20 ***strong* Achilles numbers**.\n* For at least 2 through 5, show the count of **Achilles numbers** with that many digits.\n\nSee also\n\n* Wikipedia: Achilles number * OEIS:A052486 - Achilles numbers - powerful but imperfect numbers * OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number * Related task: Powerful numbers * Related task: Totient function" }, { "role": "assistant", "content": "Timing is going to be system / OS dependent.\n\n```\nuse Prime::Factor;\nuse Math::Root;\n\nsub is-square-free (Int \\n) {\n constant @p = ^100 .map: { next unless .is-prime; .² };\n for @p -> \\p { return False if n %% p }\n True\n}\n\nsub powerful (\\n, \\k = 2) {\n my @p;\n p(1, 2*k - 1);\n sub p (\\m, \\r) {\n @p.push(m) and return if r < k;\n for 1 .. (n / m).&root(r) -> \\v {\n if r > k {\n next unless is-square-free(v);\n next unless m gcd v == 1;\n }\n p(m * v ** r, r - 1)\n }\n }\n @p\n}\n\nmy $achilles = powerful(10**9).hyper(:500batch).grep( {\n my $f = .&prime-factors.Bag;\n (+$f.keys > 1) && (1 == [gcd] $f.values) && (.sqrt.Int² !== $_)\n} ).classify: { .chars }\n\nmy \\𝜑 = 0, |(1..*).hyper.map: -> \\t { t × [×] t.&prime-factors.squish.map: { 1 - 1/$_ } }\n\nmy %as = Set.new: flat $achilles.values».list;\n\nmy $strong = lazy (flat $achilles.sort».value».list».sort).grep: { ?%as{𝜑[$_]} };\n\nput \"First 50 Achilles numbers:\";\nput (flat $achilles.sort».value».list».sort)[^50].batch(10)».fmt(\"%4d\").join(\"\\n\");\n\nput \"\\nFirst 30 strong Achilles numbers:\";\nput $strong[^30].batch(10)».fmt(\"%5d\").join(\"\\n\");\n\nput \"\\nNumber of Achilles numbers with:\";\nsay \"$_ digits: \" ~ +$achilles{$_} // 0 for 2..9;\n\nprintf \"\\n%.1f total elapsed seconds\\n\", now - INIT now;\n\n```\n\nOutput:\n\n```\nFirst 50 Achilles numbers:\n 72 108 200 288 392 432 500 648 675 800\n 864 968 972 1125 1152 1323 1352 1372 1568 1800\n1944 2000 2312 2592 2700 2888 3087 3200 3267 3456\n3528 3872 3888 4000 4232 4500 4563 4608 5000 5292\n5324 5400 5408 5488 6075 6125 6272 6728 6912 7200\n\nFirst 30 strong Achilles numbers:\n 500 864 1944 2000 2592 3456 5000 10125 10368 12348\n12500 16875 19652 19773 30375 31104 32000 33275 37044 40500\n49392 50000 52488 55296 61731 64827 67500 69984 78608 80000\n\nNumber of Achilles numbers with:\n2 digits: 1\n3 digits: 12\n4 digits: 47\n5 digits: 192\n6 digits: 664\n7 digits: 2242\n8 digits: 7395\n9 digits: 24008\n\n6.1 total elapsed seconds\n```\n\nCould go further but slows to a crawl and starts chewing up memory in short order.\n\n```\n10 digits: 77330\n11 digits: 247449\n12 digits: 788855\n\n410.4 total elapsed seconds\n\n```" } ]
[ { "role": "user", "content": "The **Ackermann function** is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.\n\nThe Ackermann function is usually defined as follows:\n\n: A\n (\n m\n ,\n n\n )\n =\n\n\n {\n\n n\n +\n 1\n\n if \n m\n =\n 0\n\n\n A\n (\n m\n −\n 1\n ,\n 1\n )\n\n if \n m\n >\n 0\n\n\n  and \n n\n =\n 0\n\n\n A\n (\n m\n −\n 1\n ,\n A\n (\n m\n ,\n n\n −\n 1\n )\n )\n\n if \n m\n >\n 0\n\n\n  and \n n\n >\n 0.\n\n {\\displaystyle {\\displaystyle A(m,n)={\\begin{cases}n+1&{\\mbox{if }}m=0\\\\A(m-1,1)&{\\mbox{if }}m>0{\\mbox{ and }}n=0\\\\A(m-1,A(m,n-1))&{\\mbox{if }}m>0{\\mbox{ and }}n>0.\\end{cases}}}}\n\nIts arguments are never negative and it always terminates.\n\nTask\n\nWrite a function which returns the value of \n\nA\n(\nm\n,\nn\n)\n{\\displaystyle {\\displaystyle A(m,n)}}\n. Arbitrary precision is preferred (since the function grows so quickly), but not required.\n\nSee also\n\n* Conway chained arrow notation for the Ackermann function." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nsub A(Int $m, Int $n) {\n if $m == 0 { $n + 1 } \n elsif $n == 0 { A($m - 1, 1) }\n else { A($m - 1, A($m, $n - 1)) }\n}\n```\n\nAn implementation using multiple dispatch:\n\n```\nmulti sub A(0, Int $n) { $n + 1 }\nmulti sub A(Int $m, 0 ) { A($m - 1, 1) }\nmulti sub A(Int $m, Int $n) { A($m - 1, A($m, $n - 1)) }\n```\n\nNote that in either case, Int is defined to be arbitrary precision in Raku.\n\nHere's a caching version of that, written in the sigilless style, with liberal use of Unicode, and the extra optimizing terms to make A(4,2) possible:\n\n```\nproto A(Int \\𝑚, Int \\𝑛) { (state @)[𝑚][𝑛] //= {*} }\n\nmulti A(0, Int \\𝑛) { 𝑛 + 1 }\nmulti A(1, Int \\𝑛) { 𝑛 + 2 }\nmulti A(2, Int \\𝑛) { 3 + 2 * 𝑛 }\nmulti A(3, Int \\𝑛) { 5 + 8 * (2 ** 𝑛 - 1) }\n\nmulti A(Int \\𝑚, 0 ) { A(𝑚 - 1, 1) }\nmulti A(Int \\𝑚, Int \\𝑛) { A(𝑚 - 1, A(𝑚, 𝑛 - 1)) }\n\n# Testing:\nsay A(4,1);\nsay .chars, \" digits starting with \", .substr(0,50), \"...\" given A(4,2);\n```\n\nOutput:\n\n```\n65533\n19729 digits starting with 20035299304068464649790723515602557504478254755697...\n```" } ]
[ { "role": "user", "content": "The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server." }, { "role": "assistant", "content": "(formerly Perl 6)\n\nUsing module LMDB - bindings to the openLDAP library. Requires an LDAP instance.\n\n```\nuse LMDB;\n\nmy %DB := LMDB::DB.open(:path<some-dir>, %connection-parameters);\n\n```\n\n%DB may be accessed, read from and written to like a native hash." } ]
[ { "role": "user", "content": "Make sure you Connect to Active Directory" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\n# 20190718 Raku programming solution\n# https://github.com/perl6/doc/issues/2898\n# https://www.facebook.com/groups/perl6/permalink/2379873082279037/\n\n# Reference:\n# https://github.com/Altai-man/cro-ldap\n# https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/\n\nuse v6.d;\nuse Cro::LDAP::Client;\n\nmy $client = await Cro::LDAP::Client.connect('ldap://ldap.forumsys.com');\n\nmy $bind = await $client.bind(\n name=>'cn=read-only-admin,dc=example,dc=com',password=>'password'\n);\ndie $bind.error-message if $bind.result-code;\n\nmy $resp = $client.search(\n  :dn<dc=example,dc=com>, base=>\"ou=mathematicians\", filter=>'(&(uid=gauss))'\n);\n\nreact {\n whenever $resp -> $entry {\n for $entry.attributes.kv -> $k, $v {\n my $value-str = $v ~~ Blob ?? $v.decode !! $v.map(*.decode);\n note \"$k -> $value-str\";\n }\n }\n}\n\n```\n\nOutput:\n\n```\nobjectClass -> inetOrgPerson organizationalPerson top person\nmail -> [email protected]\nuid -> gauss\ncn -> Carl Friedrich Gauss\nsn -> Gauss\n\n```" } ]
[ { "role": "user", "content": "In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain synchronization mechanism with the encapsulated task in order to prevent object's state corruption.\n\nA typical instance of an active object is an animation widget. The widget state changes with the time, while as an object it has all properties of a normal widget.\n\n**The task**\n\nImplement an active integrator object. The object has an input and output. The input can be set using the method *Input*. The input is a function of time. The output can be queried using the method *Output*. The object integrates its input over the time and the result becomes the object's output. So if the input is *K*(*t*) and the output is *S*, the object state *S* is changed to *S* + (*K*(*t*1) + *K*(*t*0)) \\* (*t*1 - *t*0) / 2, i.e. it integrates *K* using the trapeze method. Initially *K* is constant 0 and *S* is 0.\n\nIn order to test the object:\n\n1. set its input to sin (2π *f t*), where the frequency *f*=0.5Hz. The phase is irrelevant.\n2. wait 2s\n3. set the input to constant 0\n4. wait 0.5s\n\nVerify that now the object's output is approximately 0 (the sine has the period of 2s). The accuracy of the result will depend on the OS scheduler time slicing and the accuracy of the clock." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.12\n\nThere is some jitter in the timer, but it is typically accurate to within a few thousandths of a second.\n\n```\nclass Integrator {\n has $.f is rw = sub ($t) { 0 };\n has $.now is rw;\n has $.value is rw = 0;\n has $.integrator is rw;\n\n method init() {\n self.value = &(self.f)(0);\n self.integrator = Thread.new(\n  :code({\n loop {\n my $t1 = now;\n self.value += (&(self.f)(self.now) + &(self.f)($t1)) * ($t1 - self.now) / 2;\n self.now = $t1;\n sleep .001;\n }\n }),\n  :app_lifetime(True)\n ).run\n }\n\n method Input (&f-of-t) {\n self.f = &f-of-t;\n self.now = now;\n self.init;\n }\n\n method Output { self.value }\n}\n\nmy $a = Integrator.new;\n\n$a.Input( sub ($t) { sin(2 * π * .5 * $t) } );\n\nsay \"Initial value: \", $a.Output;\n\nsleep 2;\n\nsay \"After 2 seconds: \", $a.Output;\n\n$a.Input( sub ($t) { 0 } );\n\nsleep .5;\n\nsay \"f(0): \", $a.Output;\n\n```\n\nTypical output:\n\n```\nInitial value: 0\nAfter 2 seconds: -0.0005555887464620366\nf(0): 0\n```" } ]
[ { "role": "user", "content": "Demonstrate how to dynamically add variables to an object (a class instance) at runtime.\n\nThis is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as \"monkeypatching\" by Pythonistas and some others." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nYou can add variables/methods to a class at runtime by composing in a role. The role only affects that instance, though it is inheritable. An object created from an existing object will inherit any roles composed in with values set to those at the time the role was created. If you want to keep changed values in the new object, clone it instead.\n\n```\nclass Bar { } # an empty class\n\nmy $object = Bar.new; # new instance\n\nrole a_role { # role to add a variable: foo,\n has $.foo is rw = 2; # with an initial value of 2\n}\n\n$object does a_role; # compose in the role\n\nsay $object.foo; # prints: 2\n$object.foo = 5; # change the variable\nsay $object.foo; # prints: 5\n\nmy $ohno = Bar.new; # new Bar object\n#say $ohno.foo; # runtime error, base Bar class doesn't have the variable foo\n\nmy $this = $object.new; # instantiate a new Bar derived from $object\nsay $this.foo; # prints: 2 - original role value\n\nmy $that = $object.clone; # instantiate a new Bar derived from $object copying any variables\nsay $that.foo; # 5 - value from the cloned object\n\n```\n\nThat's what's going on underneath, but often people just mix in an anonymous role directly using the but operator. Here we'll mix an attribute into a normal integer.\n\n```\nmy $lue = 42 but role { has $.answer = \"Life, the Universe, and Everything\" }\n\nsay $lue; # 42\nsay $lue.answer; # Life, the Universe, and Everything\n\n```\n\nOn the other hand, mixins are frowned upon when it is possible to compose roles directly into classes (as with Smalltalk traits), so that you get method collision detection at compile time. If you want to change a class at run time, you can also use monkey patching:\n\n```\nuse MONKEY-TYPING;\naugment class Int {\n method answer { \"Life, the Universe, and Everything\" }\n}\nsay 42.answer; # Life, the Universe, and Everything\n\n```\n\nThis practice, though allowed, is considered to be Evil Action at a Distance." } ]
[ { "role": "user", "content": "An addition chain of length r for n is a sequence 1 = a(0) < a(1) < a(2) ... < a(r) = n , such as a(k) = a(i) + a(j) ( i < k and j < k , i may be = j) . Each member is the sum of two earlier members, not necessarily distincts.\n\nA Brauer chain for n is an addition chain where a(k) = a(k-1) + a(j) with j < k. Each member uses the previous member as a summand.\n\nWe are interested in chains of minimal length L(n).\n\n**Task**\n\nFor each n in {7,14,21,29,32,42,64} display the following : L(n), the count of Brauer chains of length L(n), an example of such a Brauer chain, the count of non-brauer chains of length L(n), an example of such a chain. (NB: counts may be 0 ).\n\nExtra-credit: Same task for n in {47, 79, 191, 382 , 379, 12509}\n\n**References**\n\n* OEIS sequences A079301, A079302. [1]\n* Richard K. Guy - Unsolved problems in Number Theory - C6 - Addition chains.\n\n**Example**\n\n* minimal chain length l(19) = 6\n* brauer-chains(19) : count = 31 Ex: ( 1 2 3 4 8 11 19)\n* non-brauer-chains(19) : count = 2 Ex: ( 1 2 3 6 7 12 19)" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Translation of**: Kotlin\n\n```\nmy @Example = ();\n\nsub check-Sequence($pos, @seq, $n, $minLen --> List) {\n if ($pos > $minLen or @seq[0] > $n) {\n return $minLen, 0;\n } elsif (@seq[0] == $n) {\n @Example = @seq;\n return $pos, 1;\n } elsif ($pos < $minLen) {\n return try-Permutation 0, $pos, @seq, $n, $minLen;\n } else {\n return $minLen, 0;\n }\n}\n\nmulti sub try-Permutation($i, $pos, @seq, $n, $minLen --> List) {\n return $minLen, 0 if $i > $pos;\n my @res1 = check-Sequence $pos+1, (@seq[0]+@seq[$i],@seq).flat, $n, $minLen;\n my @res2 = try-Permutation $i+1, $pos, @seq, $n, @res1[0];\n if (@res2[0] < @res1[0]) {\n return @res2[0], @res2[1];\n } elsif (@res2[0] == @res1[0]) {\n return @res2[0], @res1[1]+@res2[1];\n } else {\n note \"Error in try-Permutation\";\n return 0, 0;\n }\n}\n\nmulti sub try-Permutation($x, $minLen --> List) {\n return try-Permutation 0, 0, [1], $x, $minLen;\n}\n\nsub find-Brauer($num, $minLen, $nbLimit) {\n my ($actualMin, $brauer) = try-Permutation $num, $minLen;\n say \"\\nN = \", $num;\n say \"Minimum length of chains : L($num) = $actualMin\";\n say \"Number of minimum length Brauer chains : \", $brauer;\n say \"Brauer example : \", @Example.reverse if $brauer > 0;\n @Example = ();\n if ($num ≤ $nbLimit) {\n my $nonBrauer = find-Non-Brauer $num, $actualMin+1, $brauer;\n say \"Number of minimum length non-Brauer chains : \", $nonBrauer;\n say \"Non-Brauer example : \", @Example if $nonBrauer > 0;\n @Example = ();\n } else {\n say \"Non-Brauer analysis suppressed\";\n }\n}\n\nsub is-Addition-Chain(@a --> Bool) {\n for 2 .. @a.end -> $i {\n return False if @a[$i] > @a[$i-1]*2 ;\n my $ok = False;\n for $i-1 … 0 -> $j {\n for $j … 0 -> $k {\n { $ok = True; last } if @a[$j]+@a[$k] == @a[$i];\n }\n }\n return False unless $ok;\n }\n\n @Example = @a unless @Example or is-Brauer @a;\n return True;\n}\n\nsub is-Brauer(@a --> Bool) {\n for 2 .. @a.end -> $i {\n my $ok = False;\n for $i-1 … 0 -> $j {\n { $ok = True; last } if @a[$i-1]+@a[$j] == @a[$i];\n }\n return False unless $ok;\n }\n return True;\n}\n\nsub find-Non-Brauer($num, $len, $brauer --> Int) {\n my @seq = flat 1 .. $len-1, $num;\n my $count = is-Addition-Chain(@seq) ?? 1 !! 0;\n\n sub next-Chains($index) {\n loop {\n next-Chains $index+1 if $index < $len-1;\n return if @seq[$index]+$len-1-$index ≥ @seq[$len-1];\n @seq[$index]++;\n for $index^..^$len-1 { @seq[$_] = @seq[$_-1] + 1 }\n $count++ if is-Addition-Chain @seq;\n }\n }\n\n next-Chains 2;\n return $count - $brauer;\n}\n\nsay \"Searching for Brauer chains up to a minimum length of 12:\";\nfind-Brauer $_, 12, 79 for 7, 14, 21, 29, 32, 42, 64 #, 47, 79, 191, 382, 379, 379, 12509 # un-comment for extra-credit\n\n```\n\nOutput:\n\n```\nSearching for Brauer chains up to a minimum length of 12:\n\nN = 7\nMinimum length of chains : L(7) = 4\nNumber of minimum length Brauer chains : 5\nBrauer example : (1 2 3 4 7)\nNumber of minimum length non-Brauer chains : 0\n\nN = 14\nMinimum length of chains : L(14) = 5\nNumber of minimum length Brauer chains : 14\nBrauer example : (1 2 3 4 7 14)\nNumber of minimum length non-Brauer chains : 0\n\nN = 21\nMinimum length of chains : L(21) = 6\nNumber of minimum length Brauer chains : 26\nBrauer example : (1 2 3 4 7 14 21)\nNumber of minimum length non-Brauer chains : 3\nNon-Brauer example : [1 2 4 5 8 13 21]\n\nN = 29\nMinimum length of chains : L(29) = 7\nNumber of minimum length Brauer chains : 114\nBrauer example : (1 2 3 4 7 11 18 29)\nNumber of minimum length non-Brauer chains : 18\nNon-Brauer example : [1 2 3 6 9 11 18 29]\n\nN = 32\nMinimum length of chains : L(32) = 5\nNumber of minimum length Brauer chains : 1\nBrauer example : (1 2 4 8 16 32)\nNumber of minimum length non-Brauer chains : 0\n\nN = 42\nMinimum length of chains : L(42) = 7\nNumber of minimum length Brauer chains : 78\nBrauer example : (1 2 3 4 7 14 21 42)\nNumber of minimum length non-Brauer chains : 6\nNon-Brauer example : [1 2 4 5 8 13 21 42]\n\nN = 64\nMinimum length of chains : L(64) = 6\nNumber of minimum length Brauer chains : 1\nBrauer example : (1 2 4 8 16 32 64)\nNumber of minimum length non-Brauer chains : 0\n```" } ]
[ { "role": "user", "content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Addition-chain exponentiation. 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 cases of special objects (such as with matrices) the operation of multiplication can be excessively expensive. In these cases the operation of multiplication should be avoided or reduced to a minimum.\n\nIn mathematics and computer science, optimal **addition-chain exponentiation** is a method of exponentiation by positive integer powers that requires a minimal number of multiplications. It works by creating a shortest addition chain that generates the desired exponent. Each exponentiation in the chain can be evaluated by multiplying two of the earlier exponentiation results. More generally, *addition-chain exponentiation* may also refer to exponentiation by non-minimal addition chains constructed by a variety of algorithms (since a shortest addition chain is very difficult to find).\n\nThe shortest addition-chain algorithm requires no more multiplications than binary exponentiation and usually less. The first example of where it does better is for \n\na\n\n15\n{\\displaystyle {\\displaystyle a^{15}}}\n, where the binary method needs six multiplies but a shortest addition chain requires only five:\n\n: a\n\n 15\n =\n a\n ×\n (\n a\n ×\n [\n a\n ×\n\n a\n\n 2\n\n ]\n\n 2\n\n )\n\n 2\n\n {\\displaystyle {\\displaystyle a^{15}=a\\times (a\\times [a\\times a^{2}]^{2})^{2}\\!}}\n (binary, 6 multiplications)\n: a\n\n 15\n =\n\n a\n\n 3\n ×\n (\n [\n\n a\n\n 3\n\n ]\n\n 2\n\n )\n\n 2\n\n {\\displaystyle {\\displaystyle a^{15}=a^{3}\\times ([a^{3}]^{2})^{2}\\!}}\n (shortest addition chain, 5 multiplications)\n\nOn the other hand, the addition-chain method is much more complicated, since the determination of a shortest addition chain seems quite difficult: no efficient optimal methods are currently known for arbitrary exponents, and the related problem of finding a shortest addition chain for a given set of exponents has been proven NP-complete.\n\nTable demonstrating how to do *Exponentiation* using *Addition Chains*\n\n| Number of Multiplications | Actual Exponentiation | Specific implementation of *Addition Chains* to do Exponentiation |\n| --- | --- | --- |\n| 0 | a1 | a |\n| 1 | a2 | a × a |\n| 2 | a3 | a × a × a |\n| 2 | a4 | (a × a→b) × b |\n| 3 | a5 | (a × a→b) × b × a |\n| 3 | a6 | (a × a→b) × b × b |\n| 4 | a7 | (a × a→b) × b × b × a |\n| 3 | a8 | ((a × a→b) × b→d) × d |\n| 4 | a9 | (a × a × a→c) × c × c |\n| 4 | a10 | ((a × a→b) × b→d) × d × b |\n| 5 | a11 | ((a × a→b) × b→d) × d × b × a |\n| 4 | a12 | ((a × a→b) × b→d) × d × d |\n| 5 | a13 | ((a × a→b) × b→d) × d × d × a |\n| 5 | a14 | ((a × a→b) × b→d) × d × d × b |\n| 5 | a15 | ((a × a→b) × b × a→e) × e × e |\n| 4 | a16 | (((a × a→b) × b→d) × d→h) × h |\n\nThe number of multiplications required follows this sequence:\n0, 1, 2, 2, 3, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 4, 5, 5, 6, 5,\n6, 6, 6, 5, 6, 6, 6, 6, 7, 6, 7, 5, 6, 6, 7, 6, 7, 7, 7, 6,\n7, 7, 7, 7, 7, 7, 8, 6, 7, 7, 7, 7, 8, 7, 8, 7, 8, 8, 8, 7,\n8, 8, 8, 6, 7, 7, 8, 7, 8, 8, 9, 7, 8, 8, 8, 8, 8, 8, 9, 7,\n8, 8, 8, 8, 8, 8, 9, 8, 9, 8, 9, 8, 9, 9, 9, 7, 8, 8, 8, 8...\n\nThis sequence can be found at: http://oeis.org/A003313\n\n**Task requirements:**\n\nUsing the following values:\n\nA\n=\n\n\n[\n\n1\n2\n\n0\n\n1\n2\n\n0\n\n0\n\n0\n\n0\n\n1\n2\n\n0\n\n1\n2\n\n0\n\n0\n\n0\n\n1\n2\n\n0\n\n−\n\n1\n2\n\n0\n\n0\n\n−\n\n1\n2\n\n0\n\n1\n2\n\n0\n\n0\n\n0\n\n0\n\n0\n\n0\n\n0\n\n0\n\n1\n\n0\n\n0\n\n0\n\n0\n\n1\n\n0\n\n]\n{\\displaystyle {\\displaystyle A={\\begin{bmatrix}{\\sqrt {\\frac {1}{2}}}&0&{\\sqrt {\\frac {1}{2}}}&0&0&0&\\\\0&{\\sqrt {\\frac {1}{2}}}&0&{\\sqrt {\\frac {1}{2}}}&0&0&\\\\0&{\\sqrt {\\frac {1}{2}}}&0&-{\\sqrt {\\frac {1}{2}}}&0&0&\\\\-{\\sqrt {\\frac {1}{2}}}&0&{\\sqrt {\\frac {1}{2}}}&0&0&0&\\\\0&0&0&0&0&1&\\\\0&0&0&0&1&0&\\\\\\end{bmatrix}}}}\n \n\nm\n=\n31415\n{\\displaystyle {\\displaystyle m=31415}}\n and \n\nn\n=\n27182\n{\\displaystyle {\\displaystyle n=27182}}\n\nRepeat task Matrix-exponentiation operator, except use **addition-chain exponentiation** to better calculate:\n\n: A\n\n m\n {\\displaystyle {\\displaystyle A^{m}}}\n , \n\n A\n\n n\n {\\displaystyle {\\displaystyle A^{n}}}\n and \n\n A\n\n n\n ×\n m\n {\\displaystyle {\\displaystyle A^{n\\times m}}}\n .\n\nAs an easier alternative to doing the matrix manipulation above, generate the *addition-chains* for 12509, 31415 and 27182 and use *addition-chain exponentiation* to calculate these two equations:\n\n* 1.0000220644541631415\n* 1.0000255005525127182\n\nAlso: Display a count of how many multiplications were done in each case.\n\nNote: There are two ways to approach this task:\n\n* Brute force - try every permutation possible and pick one with the least number of multiplications. If the brute force is a simpler algorithm, then present it as a subtask under the subtitle \"Brute force\", eg ===Brute Force===.\n* Some clever algorithm - the wikipedia page has some hints, subtitle the code with the name of algorithm.\n\nNote: Binary exponentiation does not usually produce the best solution. Provide only optimal solutions.\n\nKudos (κῦδος) for providing a routine that generate sequence A003313 in the output.\n\nAlso, see the Rosetta Code task:   [http://rosettacode.org/wiki/Knuth%27s\\_power\\_tree\nKnuth's power tree]." }, { "role": "assistant", "content": "**Translation of**: Python\n\n```\n# 20230327 Raku programming solution\n\nuse Math::Matrix;\n\nclass AdditionChains { has ( $.idx, $.pos, @.chains, @.lvl, %.pat ) is rw; \n\n method add_chain { \n # method 1: add chains depth then breadth first until done \n return gather given self { \n take my $newchain = .chains[.idx].clone.append: \n .chains[.idx][*-1] + .chains[.idx][.pos];\n\t .chains.append: $newchain;\n .pos == +.chains[.idx]-1 ?? ( .idx += 1 && .pos = 0 ) !! .pos += 1;\n }\n }\n\n method find_chain(\\nexp where nexp > 0) {\n # method 1 interface: search for chain ending with n, adding more as needed\n return ([1],) if nexp == 1;\n my @chn = self.chains.grep: *.[*-1] == nexp // [];\n unless @chn.Bool { \n repeat { @chn = self.add_chain } until @chn[*-1][*-1] == nexp \n }\n return @chn\n }\n\n method knuth_path(\\ngoal) {\n # method 2: knuth method, uses memoization to search for a shorter chain\n return [] if ngoal < 1; \n until self.pat{ngoal}:exists {\n self.lvl[0] = [ gather for self.lvl[0].Array -> \\i {\n for self.knuth_path(i).Array -> \\j {\n unless self.pat{i + j}:exists {\n self.pat{i + j} = i and take i + j\n }\n }\n } ] \n }\n return self.knuth_path(self.pat{ngoal}).append: ngoal\n }\n\n multi method cpow(\\xbase, \\chain) {\n# raise xbase by an addition exponentiation chain for what becomes x**chain[-1]\n my ($pows, %products) = 0, 1 => xbase;\n\n %products{0} = xbase ~~ Math::Matrix \n  ?? Math::Matrix.new([ [ 1 xx xbase.size[1] ] xx xbase.size[0] ]) !! 1;\n\n for chain.Array -> \\i {\n %products{i} = %products{$pows} * %products{i - $pows};\n $pows = i\n }\n return %products{ chain[*-1] }\n }\n}\n\nmy $chn = AdditionChains.new( idx => 0, pos => 0, \n chains => ([1],), lvl => ([1],), pat => {1=>0} );\n\nsay 'First one hundred addition chain lengths:';\n.Str.say for ( (1..100).map: { +$chn.find_chain($_)[0] - 1 } ).rotor: 10;\n\nmy %chns = (31415, 27182).map: { $_ => $chn.knuth_path: $_ };\n\nsay \"\\nKnuth chains for addition chains of 31415 and 27182:\";\nsay \"Exponent: $_\\n Addition Chain: %chns{$_}[0..*-2]\" for %chns.keys;\nsay '1.00002206445416^31415 = ', $chn.cpow(1.00002206445416, %chns{31415});\nsay '1.00002550055251^27182 = ', $chn.cpow(1.00002550055251, %chns{27182});\nsay '(1.000025 + 0.000058i)^27182 = ', $chn.cpow: 1.000025+0.000058i, %chns{27182};\nsay '(1.000022 + 0.000050i)^31415 = ', $chn.cpow: 1.000022+0.000050i, %chns{31415};\n\nmy \\sq05 = 0.5.sqrt;\nmy \\mat = Math::Matrix.new( [[sq05, 0, sq05, 0, 0, 0], \n [ 0, sq05, 0, sq05, 0, 0], \n [ 0, sq05, 0, -sq05, 0, 0],\n [-sq05, 0, sq05, 0, 0, 0], \n [ 0, 0, 0, 0, 0, 1], \n [ 0, 0, 0, 0, 1, 0]] );\n\nsay 'matrix A ^ 27182 =';\nsay my $res27182 = $chn.cpow(mat, %chns{27182});\nsay 'matrix A ^ 31415 =';\nsay $chn.cpow(mat, %chns{31415});\nsay '(matrix A ** 27182) ** 31415 =';\nsay $chn.cpow($res27182, %chns{31415});\n\n```\n\nOutput:\n\n```\nFirst one hundred addition chain lengths:\n0 1 2 2 3 3 4 3 4 4\n5 4 5 5 5 4 5 5 6 5\n6 6 6 5 6 6 6 6 7 6\n7 5 6 6 7 6 7 7 7 6\n7 7 7 7 7 7 8 6 7 7\n7 7 8 7 8 7 8 8 8 7\n8 8 8 6 7 7 8 7 8 8\n9 7 8 8 8 8 8 8 9 7\n8 8 8 8 8 8 9 8 9 8\n9 8 9 9 9 7 8 8 8 8\n\nKnuth chains for addition chains of 31415 and 27182:\nExponent: 27182\n Addition Chain: 1 2 3 5 7 14 21 35 70 140 143 283 566 849 1698 3396 6792 6799 13591\nExponent: 31415\n Addition Chain: 1 2 3 5 7 14 28 56 61 122 244 488 976 1952 3904 7808 15616 15677 31293\n1.00002206445416^31415 = 1.9999999998924638\n1.00002550055251^27182 = 1.999999999974053\n(1.000025 + 0.000058i)^27182 = -0.01128636963542673+1.9730308496660347i\n(1.000022 + 0.000050i)^31415 = 0.00016144681325535107+1.9960329014194498i\nmatrix A ^ 27182 =\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 1\n 0 0 0 0 1 0\nmatrix A ^ 31415 =\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 -0 0 0\n -0 0 0 0 0 0\n 0 0 0 0 0 1\n 0 0 0 0 1 0\n(matrix A ** 27182) ** 31415 =\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 0\n 0 0 0 0 0 1\n 0 0 0 0 1 0\n```" } ]
[ { "role": "user", "content": "Definitions\n\nIn mathematics, **additive primes** are prime numbers for which the sum of their decimal digits are also primes.\n\nTask\n\nWrite a program to determine (and show here) all **additive primes** less than **500**.\n\nOptionally, show the **number** of additive primes.\n\nAlso see\n: * the OEIS entry:   A046704 additive primes.\n * the prime-numbers entry:   additive primes.\n * the geeks for geeks entry: additive prime number.\n * the prime-numbers fandom: additive primes." }, { "role": "assistant", "content": "```\nunit sub MAIN ($limit = 500);\nsay \"{+$_} additive primes < $limit:\\n{$_».fmt(\"%\" ~ $limit.chars ~ \"d\").batch(10).join(\"\\n\")}\",\n with ^$limit .grep: { .is-prime && .comb.sum.is-prime }\n\n```\n\nOutput:\n\n```\n54 additive primes < 500:\n 2 3 5 7 11 23 29 41 43 47\n 61 67 83 89 101 113 131 137 139 151\n157 173 179 191 193 197 199 223 227 229\n241 263 269 281 283 311 313 317 331 337\n353 359 373 379 397 401 409 421 443 449\n461 463 467 487\n```" } ]
[ { "role": "user", "content": "Task\n\nDemonstrate how to get the address of a variable and how to set the address of a variable." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n```\nmy $x;\nsay $x.WHERE;\n\nmy $y := $x; # alias\nsay $y.WHERE; # same address as $x\n\nsay \"Same variable\" if $y =:= $x;\n$x = 42;\nsay $y; # 42\n\n```\n\nOutput:\n\n```\n7857931379550584425\n```\n\nHow you set the address of a variable (or any other object) is outside the purview of Raku, but the language supports pluggable object representations, and any given representation scheme could conceivably allow an existing address to be treated as an object candidate where that makes sense. Memory-mapped structs are not unreasonable and are likely to be supported on VMs that allow it." } ]
[ { "role": "user", "content": "Description\n\nThe ADFGVX cipher was a manually applied field cipher used by the German Army during World War I. It was broken in 1918 by the French cryptanalyst Georges Painvin.\n\nThe workings of the cipher are described in the Wikipedia article, linked to above, and so will not be repeated here.\n\nTask\n\nWrite routines, functions etc. in your language to:\n\n1. Encrypt *suitable* plaintext and decrypt the resulting cipher text using the ADFGVX cipher algorithm given a Polybius square (see 2. below) and a *suitable* key. For this purpose *suitable* means text consisting solely of ASCII upper case letters or digits.\n\n2. Create a 6 x 6 Polybius square using a random combination of the letters A to Z and the digits 0 to 9 and then display it.\n\n3. Given the number of letters (between 7 and 12 say) to use, create a key by selecting a *suitable* word at random from unixdict.txt and then display it. The word selected should be such that none of its characters are repeated.\n\nUse these routines to create a Polybius square and a 9 letter key.\n\nThese should then be used to encrypt the plaintext: **ATTACKAT1200AM** and decrypt the resulting cipher text. Display here the results of both operations.\n\nNote\n\nAs it's unclear from the Wikipedia article how to handle a final row with fewer elements than the number of characters in the key, either of the methods mentioned in Columnar transposition may be used. In the case of the second method, it is also acceptable to fill any gaps after shuffling by moving elements to the left which makes decipherment harder." }, { "role": "assistant", "content": "Slightly different results from every other entry so far. See discussion page for reasons. It is impossible to tell from casual observation which column comes first in the Raku example. In every other (so far), the sub group with 4 characters is the first column.\n\n```\nsrand 123456; # For repeatability\n\nmy @header = < A D F G V X >;\nmy $polybius = (flat 'A'..'Z', 0..9).pick(*).join;\n\nmy $key-length = 9;\nmy $key = uc 'unixdict.txt'.IO.words.grep( { (.chars == $key-length) && (+.comb.Set == +.comb) } ).roll;\n\nmy %cypher = (@header X~ @header) Z=> $polybius.comb;\n\nmy $message = 'Attack at 1200AM';\n\nuse Terminal::Boxer;\nsay \"Key: $key\\n\";\nsay \"Polybius square:\\n\", ss-box :7col, :3cw, :indent(\"\\t\"), '', |@header, |(@header Z $polybius.comb.batch: 6);\nsay \"Message to encode: $message\";\nsay \"\\nEncoded: \" ~ my $encoded = encode $message;\nsay \"\\nDecoded: \" ~ decode $encoded;\n\nsub encode ($text is copy) {\n $text = $text.uc.comb(/<[A..Z 0..9]>/).join;\n my @order = $key.comb.pairs.sort( *.value )».key;\n my @encode = %cypher.invert.hash{ $text.comb }.join.comb.batch($key-length).map: { [$_] };\n ((^$key-length).map: { @encode».[@order]».grep( *.defined )».[$_].grep( *.defined ).join }).Str;\n}\n\nsub decode ($text is copy) {\n my @text = $text.split(' ')».comb;\n my $chars = @text[0].chars;\n $_ = flat |$_, ' ' if .chars < $chars for @text;\n my @order = $key.comb.pairs.sort( *.value )».key.pairs.sort( *.value )».key;\n %cypher{ ( grep { /\\w/ }, flat [Z] @order.map( { |@text.batch($key-length)».[$_] } ) ).batch(2)».join }.join;\n}\n\n```\n\nOutput:\n\n```\nKey: GHOSTLIKE\n\nPolybius square:\n\t┌───┬───┬───┬───┬───┬───┬───┐\n\t│ │ A │ D │ F │ G │ V │ X │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ A │ H │ O │ S │ 5 │ 7 │ Q │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ D │ 0 │ I │ 6 │ J │ C │ V │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ F │ 4 │ 8 │ R │ X │ G │ A │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ G │ Y │ F │ P │ B │ Z │ 3 │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ V │ M │ W │ 9 │ D │ 1 │ N │\n\t├───┼───┼───┼───┼───┼───┼───┤\n\t│ X │ 2 │ E │ U │ T │ L │ K │\n\t└───┴───┴───┴───┴───┴───┴───┘\n\nMessage to encode: Attack at 1200AM\n\nEncoded: DVVA FVX XXA FGF XVX GXA XXD GFA XXD\n\n```" } ]
[ { "role": "user", "content": "In astronomy **air mass** is a measure of the amount of atmosphere between the observer and the object being observed. It is a function of the *zenith angle* (the angle between the line of sight an vertical) and the altitude of the observer. It is defined as the integral of the atmospheric density along the line of sight and is usually expressed relative to the air mass at zenith. Thus, looking straight up gives an air mass of one (regardless of observer's altitude) and viewing at any zenith angle greater than zero gives higher values.\n\nYou will need to integrate \n\nρ\n{\\displaystyle {\\displaystyle \\rho }}\n(h(a,z,x)) where \n\nρ\n{\\displaystyle {\\displaystyle \\rho }}\n(h) is the atmospheric density for a given height above sea level, and h(a,z,x) is the height above sea level for a point at distance x along the line of sight. Determining this last function requires some trigonometry.\n\nFor this task you can assume:\n\n: * The density of Earth's atmosphere is proportional to exp(-a/8500 metres)\n * The Earth is a perfect sphere of radius 6371 km.\n\nTask\n: * Write a function that calculates the air mass for an observer at a given altitude   ***a***   above sea level and zenith angle   ***z.***\n * Show the air mass for zenith angles **0** to **90** in steps of **5** degrees for an observer at sea level.\n * Do the same for the   NASA SOFIA infrared telescope,   which has a cruising altitude of 13,700 meters   (about 8.3 miles),\n\n : it flies in a specially retrofitted Boeing 747 about four flights a week." }, { "role": "assistant", "content": "**Translation of**: FreeBASIC\n\n```\nconstant DEG = pi/180; # degrees to radians\nconstant RE = 6371000; # Earth radius in meters\nconstant dd = 0.001; # integrate in this fraction of the distance already covered\nconstant FIN = 10000000; # integrate only to a height of 10000km, effectively infinity\n\n#| Density of air as a function of height above sea level\nsub rho ( \\a ) { exp( -a / 8500 ) }\n\nsub height ( \\a, \\z, \\d ) {\n # a = altitude of observer\n # z = zenith angle (in degrees)\n # d = distance along line of sight\n my \\AA = RE + a;\n sqrt( AA² + d² - 2*d*AA*cos((180-z)*DEG) ) - AA;\n}\n\n#| Integrates density along the line of sight\nsub column_density ( \\a, \\z ) {\n my $sum = 0;\n my $d = 0;\n while $d < FIN {\n my \\delta = max(dd, (dd)*$d); # Adaptive step size to avoid it taking forever\n $sum += rho(height(a, z, $d + delta/2))*delta;\n $d += delta;\n }\n $sum;\n}\n\nsub airmass ( \\a, \\z ) {\n column_density( a, z ) /\n column_density( a, 0 )\n}\n\nsay 'Angle 0 m 13700 m';\nsay '------------------------------------';\nsay join \"\\n\", (0, 5 ... 90).hyper(:3batch).map: -> \\z {\n sprintf \"%2d %11.8f %11.8f\", z, airmass( 0, z), airmass(13700, z);\n}\n\n```\n\nOutput:\n\n```\nAngle 0 m 13700 m\n------------------------------------\n 0 1.00000000 1.00000000\n 5 1.00380963 1.00380965\n10 1.01538466 1.01538475\n15 1.03517744 1.03517765\n20 1.06399053 1.06399093\n25 1.10305937 1.10306005\n30 1.15418974 1.15419083\n35 1.21998076 1.21998246\n40 1.30418931 1.30419190\n45 1.41234169 1.41234567\n50 1.55280404 1.55281025\n55 1.73875921 1.73876915\n60 1.99212000 1.99213665\n65 2.35199740 2.35202722\n70 2.89531368 2.89537287\n75 3.79582352 3.79596149\n80 5.53885809 5.53928113\n85 10.07896219 10.08115981\n90 34.32981136 34.36666557\n```" } ]
[ { "role": "user", "content": "The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles.\n\nThe theorem on which the test is based can be stated as follows:\n\n* a number   \n\n p\n {\\displaystyle {\\displaystyle p}}\n   is prime   if and only if   all the coefficients of the polynomial expansion of\n\n: : : (\n x\n −\n 1\n\n )\n\n p\n −\n (\n\n x\n\n p\n −\n 1\n )\n {\\displaystyle {\\displaystyle (x-1)^{p}-(x^{p}-1)}}\n\nare divisible by   \n\np\n{\\displaystyle {\\displaystyle p}}\n.\n\nExample\n\nUsing   \n\np\n=\n3\n{\\displaystyle {\\displaystyle p=3}}\n:\n\n```\n (x-1)^3 - (x^3 - 1)\n = (x^3 - 3x^2 + 3x - 1) - (x^3 - 1)\n = -3x^2 + 3x\n\n```\n\nAnd all the coefficients are divisible by **3**,   so **3** is prime.\n\n| |\n| --- |\n| **Note:** This task is **not** the AKS primality test.   It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation. |\n\nTask\n\n1. Create a function/subroutine/method that given   \n\n p\n {\\displaystyle {\\displaystyle p}}\n   generates the coefficients of the expanded polynomial representation of   \n\n (\n x\n −\n 1\n\n )\n\n p\n {\\displaystyle {\\displaystyle (x-1)^{p}}}\n .\n2. Use the function to show here the polynomial expansions of   \n\n (\n x\n −\n 1\n\n )\n\n p\n {\\displaystyle {\\displaystyle (x-1)^{p}}}\n   for   \n\n p\n {\\displaystyle {\\displaystyle p}}\n   in the range   **0**   to at least   **7**,   inclusive.\n3. Use the previous function in creating another function that when given   \n\n p\n {\\displaystyle {\\displaystyle p}}\n   returns whether   \n\n p\n {\\displaystyle {\\displaystyle p}}\n   is prime using the theorem.\n4. Use your test to generate a list of all primes *under*   **35**.\n5. **As a stretch goal**,   generate all primes under   **50**   (needs integers larger than 31-bit).\n\nReferences\n\n* Agrawal-Kayal-Saxena (AKS) primality test (Wikipedia)\n* Fool-Proof Test for Primes - Numberphile (Video). The accuracy of this video is disputed -- at best it is an oversimplification." }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015-12\n\nThe expansions are generated similarly to how most FP languages generate sequences that resemble Pascal's triangle, using a zipwith meta-operator (Z) with subtraction, applied between two lists that add a 0 on either end to the prior list. Here we define a constant infinite sequence using the ... sequence operator with a \"whatever\" endpoint. In fact, the second term [1,-1] could have been generated from the first term, but we put it in there for documentation so the reader can see what direction things are going.\n\nThe polyprime function pretty much reads like the original description. Is it \"so\" that the p'th expansion's coefficients are all divisible by p? The .[1 ..^ \\*/2] slice is done simply to weed out divisions by 1 or by factors we've already tested (since the coefficients are symmetrical in terms of divisibility). If we wanted to write polyprime even more idiomatically, we could have made it another infinite constant list that is just a mapping of the first list, but we decided that would just be showing off. :-)\n\n```\nconstant expansions = [1], [1,-1], -> @prior { [|@prior,0 Z- 0,|@prior] } ... *;\n\nsub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p }\n\n# Showing the expansions:\n\nsay ' p: (x-1)ᵖ';\nsay '-----------';\n\nsub super ($n) {\n $n.trans: '0123456789'\n => '⁰¹²³⁴⁵⁶⁷⁸⁹';\n}\n\nfor ^13 -> $d {\n say $d.fmt('%2i: '), (\n expansions[$d].kv.map: -> $i, $n {\n my $p = $d - $i;\n [~] gather {\n take < + - >[$n < 0] ~ ' ' unless $p == $d;\n take $n.abs unless $p == $d > 0;\n take 'x' if $p > 0;\n take super $p - $i if $p > 1;\n }\n }\n )\n}\n\n# And testing the function:\n\nprint \"\\nPrimes up to 100:\\n { grep &polyprime, 2..100 }\\n\";\n\n```\n\nOutput:\n\n```\n p: (x-1)ᵖ\n-----------\n 0: 1\n 1: x - 1\n 2: x² - 2x + 1\n 3: x³ - 3x² + 3x - 1\n 4: x⁴ - 4x³ + 6x² - 4x + 1\n 5: x⁵ - 5x⁴ + 10x³ - 10x² + 5x - 1\n 6: x⁶ - 6x⁵ + 15x⁴ - 20x³ + 15x² - 6x + 1\n 7: x⁷ - 7x⁶ + 21x⁵ - 35x⁴ + 35x³ - 21x² + 7x - 1\n 8: x⁸ - 8x⁷ + 28x⁶ - 56x⁵ + 70x⁴ - 56x³ + 28x² - 8x + 1\n 9: x⁹ - 9x⁸ + 36x⁷ - 84x⁶ + 126x⁵ - 126x⁴ + 84x³ - 36x² + 9x - 1\n10: x¹⁰ - 10x⁹ + 45x⁸ - 120x⁷ + 210x⁶ - 252x⁵ + 210x⁴ - 120x³ + 45x² - 10x + 1\n11: x¹¹ - 11x¹⁰ + 55x⁹ - 165x⁸ + 330x⁷ - 462x⁶ + 462x⁵ - 330x⁴ + 165x³ - 55x² + 11x - 1\n12: x¹² - 12x¹¹ + 66x¹⁰ - 220x⁹ + 495x⁸ - 792x⁷ + 924x⁶ - 792x⁵ + 495x⁴ - 220x³ + 66x² - 12x + 1\n\nPrimes up to 100:\n 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97\n```" } ]
[ { "role": "user", "content": "Some languages offer direct support for algebraic data types and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly.\n\nTask\n\nAs an example, implement insertion in a red-black-tree.\n\nA red-black-tree is a binary tree where each internal node has a color attribute *red* or *black*. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion.\n\nReference\n\nRed-Black Trees in a Functional Setting" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.11\n\nRaku doesn't have algebraic data types (yet), but it does have pretty good pattern matching in multi signatures.\n\n```\nenum RedBlack <R B>;\n\nmulti balance(B,[R,[R,$a,$x,$b],$y,$c],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }\nmulti balance(B,[R,$a,$x,[R,$b,$y,$c]],$z,$d) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }\nmulti balance(B,$a,$x,[R,[R,$b,$y,$c],$z,$d]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }\nmulti balance(B,$a,$x,[R,$b,$y,[R,$c,$z,$d]]) { [R,[B,$a,$x,$b],$y,[B,$c,$z,$d]] }\n\nmulti balance($col, $a, $x, $b) { [$col, $a, $x, $b] }\n \nmulti ins( $x, @s [$col, $a, $y, $b] ) {\n when $x before $y { balance $col, ins($x, $a), $y, $b }\n when $x after $y { balance $col, $a, $y, ins($x, $b) }\n default { @s }\n}\nmulti ins( $x, Any:U ) { [R, Any, $x, Any] }\n\nmulti insert( $x, $s ) {\n [B, |ins($x,$s)[1..3]];\n}\n\nsub MAIN {\n my $t = Any;\n $t = insert($_, $t) for (1..10).pick(*);\n say $t.gist;\n}\n\n```\n\nThis code uses generic comparison operators before and after, so it should work on any ordered type.\n\nOutput:\n\n```\n[B [B [B (Any) 1 [R (Any) 2 (Any)]] 3 [B (Any) 4 [R (Any) 5 (Any)]]] 6 [B [B (Any) 7 (Any)] 8 [B [R (Any) 9 (Any)] 10 (Any)]]]\n```" } ]
[ { "role": "user", "content": "Given a text file of many lines, where fields within a line\nare delineated by a single 'dollar' character, write a program\nthat aligns each column of fields by ensuring that words in each\ncolumn are separated by at least one space.\nFurther, allow for each word in a column to be either left\njustified, right justified, or center justified within its column.\n\nUse the following text to test your programs:\n\n```\nGiven$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\n```\n\nNote that:\n\n1. The example input texts lines may, or may not, have trailing dollar characters.\n2. All columns should share the same alignment.\n3. Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.\n4. Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal.\n5. The minimum space between columns should be computed from the text and not hard-coded.\n6. It is *not* a requirement to add separating characters between or around columns.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string  (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff  (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet" }, { "role": "assistant", "content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nCall with parameter left (default), center or right.\n\n```\nmy @lines = \nq|Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\n|.lines;\n\nmy @widths;\n \nfor @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } }\nfor @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ \" \"; } }\n \nsub align($column_width, $word, $aligment = @*ARGS[0]) {\n my $lr = $column_width - $word.chars;\n my $c = $lr / 2;\n given ($aligment) {\n when \"center\" { \" \" x $c.ceiling ~ $word ~ \" \" x $c.floor }\n when \"right\" { \" \" x $lr ~ $word }\n default { $word ~ \" \" x $lr }\n }\n}\n\n```\n\nOr a more functional version, called like `./align.p6 left input.txt`, which however only supports left and right alignment (not center):\n\n```\nsub MAIN ($alignment where 'left'|'right', $file) {\n my @lines := $file.IO.lines.map(*.split('$').cache).cache;\n my @widths = roundrobin(|@lines).map(*».chars.max);\n my $align = {left=>'-', right=>''}{$alignment};\n my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ \"\\n\";\n printf $format, |$_ for @lines;\n}\n\n```" } ]
End of preview. Expand in Data Studio

Rosetta Code Raku Questions & Answers

About the Dataset

This dataset is scraped from RosettaCode, it is the full set of tasks from the Raku section (minus <10 that failed to parse) with no cleanup or vetting attempted.

License

This data is licensed under the GFDL, all questions and answers belong to the original authors.

I make no claim to have authored this data.

Format

The dataset is formatted as sharegpt.

Goals

This dataset is part of a larger collection designed to teach LLMs to write a niche programming language. In this case, Raku (perl 6).

Downloads last month
108