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».¢er) ~ '│' }\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».¢er) ~ '│' }\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>».¢er($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```"
}
]
|
[
{
"role": "user",
"content": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the Proper divisors of the previous term.\n\n: * If the terms eventually reach 0 then the series for K is said to **terminate**.\n\n: There are several classifications for non termination:\n\n * If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called **perfect**.\n * If the third term *would* be repeating K then the sequence repeats with period 2 and K is called **amicable**.\n * If the Nth term *would* be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called **sociable**.\n: Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n\n * Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence `95, 25, 6, 6, 6, ...` such K are called **aspiring**.\n * K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence `562, 284, 220, 284, 220, ...` such K are called **cyclic**.\n\n: And finally:\n\n * Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called **non-terminating**. \n For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating **16** terms or if any term of the sequence is greater than 2\\*\\*47 = 140,737,488,355,328.\n\nTask\n\n1. Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n2. Use it to display the classification and sequences of the numbers one to ten inclusive.\n3. Use it to show the classification and sequences of the following integers, in order:\n\n: : 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\nRelated tasks\n\n* Abundant, deficient and perfect number classifications. (Classifications from only the first two members of the whole sequence).\n* Proper divisors\n* Amicable pairs\n\nExternal links\n\n* An amazing thing about 276, Numberphile"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.10\n\n```\nsub propdivsum (\\x) {\n my @l = x > 1;\n (2 .. x.sqrt.floor).map: -> \\d {\n unless x % d { my \\y = x div d; y == d ?? @l.push: d !! @l.append: d,y }\n }\n sum @l;\n}\n\nmulti quality (0,1) { 'perfect ' }\nmulti quality (0,2) { 'amicable' }\nmulti quality (0,$n) { \"sociable-$n\" }\nmulti quality ($,1) { 'aspiring' }\nmulti quality ($,$n) { \"cyclic-$n\" }\n\nsub aliquotidian ($x) {\n my %seen;\n my @seq = $x, &propdivsum ... *;\n for 0..16 -> $to {\n my $this = @seq[$to] or return \"$x\\tterminating\\t[@seq[^$to]]\";\n last if $this > 140737488355328;\n if %seen{$this}:exists {\n my $from = %seen{$this};\n return \"$x\\t&quality($from, $to-$from)\\t[@seq[^$to]]\";\n }\n %seen{$this} = $to;\n }\n \"$x non-terminating\\t[{@seq}]\";\n}\n\naliquotidian($_).say for flat\n 1..10,\n 11, 12, 28, 496, 220, 1184, 12496, 1264460,\n 790, 909, 562, 1064, 1488,\n 15355717786080;\n\n```\n\nOutput:\n\n```\n1\tterminating\t[1]\n2\tterminating\t[2 1]\n3\tterminating\t[3 1]\n4\tterminating\t[4 3 1]\n5\tterminating\t[5 1]\n6\tperfect \t[6]\n7\tterminating\t[7 1]\n8\tterminating\t[8 7 1]\n9\tterminating\t[9 4 3 1]\n10\tterminating\t[10 8 7 1]\n11\tterminating\t[11 1]\n12\tterminating\t[12 16 15 9 4 3 1]\n28\tperfect \t[28]\n496\tperfect \t[496]\n220\tamicable\t[220 284]\n1184\tamicable\t[1184 1210]\n12496\tsociable-5\t[12496 14288 15472 14536 14264]\n1264460\tsociable-4\t[1264460 1547860 1727636 1305184]\n790\taspiring\t[790 650 652 496]\n909\taspiring\t[909 417 143 25 6]\n562\tcyclic-2\t[562 284 220]\n1064\tcyclic-2\t[1064 1336 1184 1210]\n1488 non-terminating\t[1488 2480 3472 4464 8432 9424 10416 21328 22320 55056 95728 96720 236592 459792 881392 882384 1474608 ...]\n15355717786080 non-terminating\t[15355717786080 44534663601120 144940087464480 ...]\n\n```"
}
]
|
[
{
"role": "user",
"content": "The Almkvist-Giullera formula for calculating \n\n1\n\nπ\n\n2\n{\\displaystyle {\\displaystyle {\\frac {1}{\\pi ^{2}}}}}\n is based on the Calabi-Yau\ndifferential equations of order 4 and 5, which were originally used to describe certain manifolds\nin string theory.\n\nThe formula is:\n\n: 1\n\n π\n\n 2\n =\n 32\n\n ∑\n\n n\n =\n 0\n\n ∞\n\n (\n 6\n n\n )\n !\n\n 3\n ⋅\n n\n\n !\n\n 6\n (\n 532\n\n n\n\n 2\n +\n 126\n n\n +\n 9\n )\n\n\n 1\n\n 10\n\n 6\n n\n +\n 3\n {\\displaystyle {\\displaystyle {\\frac {1}{\\pi ^{2}}}=32\\sum \\_{n=0}^{\\infty }{\\frac {(6n)!}{3\\cdot n!^{6}}}(532n^{2}+126n+9){\\frac {1}{10^{6n+3}}}}}\n\nThis formula can be used to calculate the constant \n\n1\n\nπ\n\n2\n{\\displaystyle {\\displaystyle {\\frac {1}{\\pi ^{2}}}}}\n, and thus to calculate \n\nπ\n{\\displaystyle {\\displaystyle \\pi }}\n.\n\nNote that, because the product of all terms but the power of 1000 can be calculated as an integer,\nthe terms in the series can be separated into a large integer term:\n\n: 32\n (\n 6\n n\n )\n !\n\n 3\n ⋅\n n\n\n !\n\n 6\n (\n 532\n\n n\n\n 2\n +\n 126\n n\n +\n 9\n )\n {\\displaystyle {\\displaystyle {\\frac {32(6n)!}{3\\cdot n!^{6}}}(532n^{2}+126n+9)}}\n\nmultiplied by a negative integer power of 10:\n\n: 10\n\n −\n (\n 6\n n\n +\n 3\n )\n {\\displaystyle {\\displaystyle 10^{-(6n+3)}}}\n\nTask\n: * Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.\n * Use the complete formula to calculate and print \n\n π\n {\\displaystyle {\\displaystyle \\pi }}\n to 70 decimal digits of precision.\n\nReference\n: * Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1."
},
{
"role": "assistant",
"content": "```\n# 20201013 Raku programming solution\n\nuse BigRoot;\nuse Rat::Precise;\nuse experimental :cached;\n\nBigRoot.precision = 75 ;\nmy $Precision = 70 ;\nmy $AGcache = 0 ;\n\nsub postfix:<!>(Int $n --> Int) is cached { [*] 1 .. $n }\n\nsub Integral(Int $n --> Int) is cached {\n (2⁵*(6*$n)! * (532*$n² + 126*$n + 9)) div (3*($n!)⁶)\n}\n\nsub A-G(Int $n --> FatRat) is cached { # Almkvist-Giullera\n Integral($n).FatRat / (10**(6*$n + 3)).FatRat\n}\n\nsub Pi(Int $n --> Str) {\n (1/(BigRoot.newton's-sqrt: $AGcache += A-G $n)).precise($Precision)\n}\n\nsay \"First 10 integer portions : \";\nsay $_, \"\\t\", Integral $_ for ^10;\n\nmy $target = Pi my $Nth = 0;\n\nloop { $target eq ( my $next = Pi ++$Nth ) ?? ( last ) !! $target = $next }\n\nsay \"π to $Precision decimal places is :\\n$target\"\n\n```\n\nOutput:\n\n```\nFirst 10 integer portions :\n0 96\n1 5122560\n2 190722470400\n3 7574824857600000\n4 312546150372456000000\n5 13207874703225491420651520\n6 567273919793089083292259942400\n7 24650600248172987140112763715584000\n8 1080657854354639453670407474439566400000\n9 47701779391594966287470570490839978880000000\nπ to 70 decimal places is :\n3.1415926535897932384626433832795028841971693993751058209749445923078164\n```"
}
]
|
[
{
"role": "user",
"content": "A k-Almost-prime is a natural number \n\nn\n{\\displaystyle {\\displaystyle n}}\n that is the product of \n\nk\n{\\displaystyle {\\displaystyle k}}\n (possibly identical) primes.\n\nExample\n\n1-almost-primes, where \n\nk\n=\n1\n{\\displaystyle {\\displaystyle k=1}}\n, are the prime numbers themselves.\n \n2-almost-primes, where \n\nk\n=\n2\n{\\displaystyle {\\displaystyle k=2}}\n, are the semiprimes.\n\nTask\n\nWrite a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for \n\n1\n≤\nK\n≤\n5\n{\\displaystyle {\\displaystyle 1\\leq K\\leq 5}}\n.\n\nRelated tasks\n\n* Semiprime\n* Category:Prime Numbers"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: C\n\n**Works with**: Rakudo version 2015.12\n\n```\nsub is-k-almost-prime($n is copy, $k) returns Bool {\n loop (my ($p, $f) = 2, 0; $f < $k && $p*$p <= $n; $p++) {\n $n /= $p, $f++ while $n %% $p;\n }\n $f + ($n > 1) == $k;\n}\n\nfor 1 .. 5 -> $k {\n say ~.[^10]\n given grep { is-k-almost-prime($_, $k) }, 2 .. *\n}\n\n```\n\nOutput:\n\n```\n2 3 5 7 11 13 17 19 23 29\n4 6 9 10 14 15 21 22 25 26\n8 12 18 20 27 28 30 42 44 45\n16 24 36 40 54 56 60 81 84 88\n32 48 72 80 108 112 120 162 168 176\n```\n\nHere is a solution with identical output based on the factors routine from Count\\_in\\_factors#Raku (to be included manually until we decide where in the distribution to put it).\n\n```\nconstant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;\n\nmulti sub factors(1) { 1 }\nmulti sub factors(Int $remainder is copy) {\n gather for @primes -> $factor {\n # if remainder < factor², we're done\n if $factor * $factor > $remainder {\n take $remainder if $remainder > 1;\n last;\n }\n # How many times can we divide by this prime?\n while $remainder %% $factor {\n take $factor;\n last if ($remainder div= $factor) === 1;\n }\n }\n}\n\nconstant @factory = lazy 0..* Z=> flat (0, 0, map { +factors($_) }, 2..*);\n\nsub almost($n) { map *.key, grep *.value == $n, @factory }\n\nput almost($_)[^10] for 1..5;\n\n```"
}
]
|
[
{
"role": "user",
"content": "An alternade is a word whose alternating letters themselves form two words.\n\nExample\n\nThe word **lounge** contains the word **lug** (**l**o**u**n**g**e) and the word **one** (l**o**u**n**g**e**).\n\nFor a word to be an alternade, all its letters must be used.\n\nThe two words that form an alternade don't need to be the same length; for example, the word **board** is an alternade made up of the words **bad** (**b**o**a**r**d**) and **or** (b**o**a**r**d).\n\nTask\n\nPrint out every alternade in unixdict.txt whose length is **6** or greater, also showing both the words that make up the alternade.\n\nSee also\n: * Wikipedia entry: Alternade\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": "```\nunit sub MAIN ($file = 'unixdict.txt', :$min = 6);\n\nmy %words = $file.IO.slurp.words.map: * => 1;\n\nmy @alternades;\n\nfor %words {\n next if .key.chars < $min;\n my @letters = .key.comb;\n my @alts = @letters[0,2 … *].join, @letters[1,3 … *].join;\n @alternades.push(.key => @alts) if %words{@alts[0]} && %words{@alts[1]};\n}\n\n@alternades.=sort;\n\nsay \"{+@alternades} alternades longer than {$min-1} characters found in $file:\";\n\n.say for @alternades > 10\n ?? (flat @alternades.head(5), '...', @alternades.tail(5))\n !! @alternades;\n\n```\n\nOutput:\n\n```\n58 alternades longer than 5 characters found in unixdict.txt:\naccost => [acs cot]\naccuse => [acs cue]\nafield => [ail fed]\nagleam => [ala gem]\nalcott => [act lot]\n...\ntriode => [tid roe]\ntriune => [tin rue]\ntroupe => [top rue]\ntruant => [tun rat]\ntwirly => [til wry]\n```"
}
]
|
[
{
"role": "user",
"content": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.\n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x \\* y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\n```\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n```\n\nThe output is `2 4` because `Amb(1, 2, 3)` correctly chooses the future in which `x` has value `2`, `Amb(7, 6, 4, 5)` chooses `4` and consequently `Amb(x * y = 8)` produces a success.\n\nAlternatively, failure could be represented using strictly `Amb()`:\n\n```\nunless x * y = 8 do Amb()\n```\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\n```\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n```\n\nwhere `Ambassert` behaves like `Amb()` if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n1. `\"the\" \"that\" \"a\"`\n2. `\"frog\" \"elephant\" \"thing\"`\n3. `\"walked\" \"treaded\" \"grows\"`\n4. `\"slowly\" \"quickly\"`\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is `\"that thing grows slowly\"`; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Using Junctions\n\nJunctions are a construct that behave similarly to the wanted Amb operator. The only difference is, that they don't preserve the state that was True inside any control structure (like an if).\n\nThere is currently a trick, how you only get the \"true\" values from a Junction for any test: return from a subroutine. Because of DeMorgans Law, you'll have to switch and and or, since you want to return on falseness. Just look at 'all' in combination with the sub(){return unless test} as the amb operator.\n\n```\n#| an array of four words, that have more possible values. \n#| Normally we would want `any' to signify we want any of the values, but well negate later and thus we need `all'\nmy @a =\n(all «the that a»),\n(all «frog elephant thing»),\n(all «walked treaded grows»),\n(all «slowly quickly»);\n\nsub test (Str $l, Str $r) {\n $l.ends-with($r.substr(0,1))\n}\n\n(sub ($w1, $w2, $w3, $w4){\n # return if the values are false\n return unless [and] test($w1, $w2), test($w2, $w3),test($w3, $w4);\n # say the results. If there is one more Container layer around them this doesn't work, this is why we need the arguments here.\n say \"$w1 $w2 $w3 $w4\"\n})(|@a); # supply the array as argumetns\n\n```\n\n### Using the Regex Engine\n\nBy using a reduction metaoperator to calculate all possible combinations, we can Amb any number of sets with no arbitrary limits. A simple regex pattern can find out if a certain combination is correct or not.\n\n```\n# The Task #\nmy @firstSet = «the that a»;\nmy @secondSet = «frog elephant thing»;\nmy @thirdSet = «walked treaded grows»;\nmy @fourthSet = «slowly quickly»;\n\n.say for doAmb [@firstSet, @secondSet, @thirdSet, @fourthSet];\n\n\nsub doAmb( @lol ) {\t# Takes out the correct sentences.\n\tmy @sentences = map *.join(\" \"), [X] @lol;\n\tgrep &isAmb, @sentences;\n}\n\nsub isAmb( $sentence ) {\t# Checks `$sentence` for correctness.\n\t$sentence !~~ / (.) \" \" (.)\t<!{$0 eq $1}> /\t# <https://docs.raku.org/language/regexes#Regex_boolean_condition_check>\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Two integers \n\nN\n{\\displaystyle {\\displaystyle N}}\n and \n\nM\n{\\displaystyle {\\displaystyle M}}\n are said to be amicable pairs if \n\nN\n≠\nM\n{\\displaystyle {\\displaystyle N\\neq M}}\n and the sum of the proper divisors of \n\nN\n{\\displaystyle {\\displaystyle N}}\n (\n\ns\nu\nm\n(\n\np\nr\no\np\nD\ni\nv\ns\n(\nN\n)\n)\n{\\displaystyle {\\displaystyle \\mathrm {sum} (\\mathrm {propDivs} (N))}}\n) \n\n=\nM\n{\\displaystyle {\\displaystyle =M}}\n as well as \n\ns\nu\nm\n(\n\np\nr\no\np\nD\ni\nv\ns\n(\nM\n)\n)\n=\nN\n{\\displaystyle {\\displaystyle \\mathrm {sum} (\\mathrm {propDivs} (M))=N}}\n.\n\nExample\n\n**1184** and **1210** are an amicable pair, with proper divisors:\n\n* 1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and\n* 1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.\n\nTask\n\nCalculate and show here the Amicable pairs below 20,000; (there are eight).\n\nRelated tasks\n\n* Proper divisors\n* Abundant, deficient and perfect number classifications\n* Aliquot sequence classifications and its amicable *classification*."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03.1\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\n(1..20000).race.map: -> $i {\n my $j = propdivsum($i);\n say \"$i $j\" if $j > $i and $i == propdivsum($j);\n}\n\n```\n\nOutput:\n\n```\n220 284\n1184 1210\n2620 2924\n5020 5564\n6232 6368\n10744 10856\n12285 14595\n17296 18416\n```"
}
]
|
[
{
"role": "user",
"content": "An anadrome is similar to a palindrome except, rather than spelling the *same* word or phrase when reversed, it spells a *different* word or phrase. An anadrome is a special case of an anagram.\n\n*Anadrome is a portmanteau of the words anagram and palindrome.*\n\nFor instance, **regal** and **lager** are anadromes.\n\nTask\n\nUsing the words.txt file from https://github.com/dwyl/english-words, find and display all of the anadrome pairs with more than 6 characters.\n\nEach word pair should only show up one time in the list.\n\nAlternate download location."
},
{
"role": "assistant",
"content": "```\nmy @words = 'words.txt'.IO.slurp.words.grep: *.chars > 6;\n\nmy %words = @words.pairs.invert;\n\nput join \"\\n\", @words.map: { %words{$_}:delete and sprintf \"%10s ↔ %s\", $_, .flip if ($_ ne .flip) && %words{.flip} }\n\n```\n\nOutput:\n\n```\n amaroid ↔ diorama\n degener ↔ reneged\n deifier ↔ reified\n deliver ↔ reviled\n dessert ↔ tressed\n desserts ↔ stressed\n deviler ↔ relived\n dioramas ↔ samaroid\n gateman ↔ nametag\n leveler ↔ relevel\n pat-pat ↔ tap-tap\n redrawer ↔ rewarder\n reknits ↔ stinker\n relever ↔ reveler\n reliver ↔ reviler\n revotes ↔ setover\n sallets ↔ stellas\n```"
}
]
|
[
{
"role": "user",
"content": "There are already other tasks relating to *finding* **existing** anagrams. This one is about **creating** them.\n\nWrite a (set of) routine(s) that, when given a word list to work from, and word or phrase as a seed, generates anagrams of that word or phrase. Feel free to ignore letter case, white-space, punctuation and symbols. Probably best to avoid numerics too, but feel free to include them if that floats your boat.\n\nIt is not necessary to (only) generate anagrams that make sense. That is a hard problem, much more difficult than can realistically be done in a small program; though again, if you feel the need, you are invited to amaze your peers.\n\nIn general, try to form phrases made up of longer words. Feel free to manually reorder output words or add punctuation and/or case changes to get a better meaning.\n\nTask\n\nWrite an anagram generator program.\n\nUse a publicly and freely available word file as its word list.\n\n: unixdict.txt from http://wiki.puzzlers.org is a popular, though somewhat limited choice.\n: A much larger word list: words\\_alpha.txt file from https://github.com/dwyl/english-words. May be better as far as coverage but may return unreasonably large results.\n\nUse your program to generate anagrams of some words / phrases / names of your choice. No need to show **all** the output. It is likely to be very large. Just pick out one or two of the best results and show the seed word/phrase and anagram.\n\nFor example, show the seed and one or two of the best anagrams:\n\n: **Purefox -> Fur expo**\n: **Petelomax -> Metal expo**\n\n*.oO(hmmm. Seem to be detecting something of a trend here...)*"
},
{
"role": "assistant",
"content": "Using the unixdict.txt word file by default.\n\n```\nunit sub MAIN ($in is copy = '', :$dict = 'unixdict.txt');\n\nsay 'Enter a word or phrase to be anagramed. (Loading dictionary)' unless $in.chars;\n\n# Load the words into a word / Bag hash\nmy %words = $dict.IO.slurp.lc.words.race.map: { .comb(/\\w/).join => .comb(/\\w/).Bag };\n\n# Declare some globals\nmy ($phrase, $count, $bag);\n\nloop {\n ($phrase, $count, $bag) = get-phrase;\n find-anagram Hash.new: %words.grep: { .value ⊆ $bag };\n}\n\nsub get-phrase {\n my $prompt = $in.chars ?? $in !! prompt \"\\nword or phrase? (press Enter to quit) \";\n $in = '';\n exit unless $prompt;\n $prompt,\n +$prompt.comb(/\\w/),\n $prompt.lc.comb(/\\w/).Bag;\n}\n\nsub find-anagram (%subset, $phrase is copy = '', $last = Inf) {\n my $remain = $bag ∖ $phrase.comb(/\\w/).Bag; # Find the remaining letters\n my %filtered = %subset.grep: { .value ⊆ $remain }; # Find words using the remaining letters\n my $sofar = +$phrase.comb(/\\w/); # Get the count of the letters used so far\n for %filtered.sort: { -.key.chars, ~.key } { # Sort by length then alphabetically then iterate\n my $maybe = +.key.comb(/\\w/); # Get the letter count of the maybe addition\n next if $maybe > $last; # Next if it is longer than last - only consider descending length words\n next if $maybe == 1 and $last == 1; # Only allow one one character word\n next if $count - $sofar - $maybe > $maybe; # Try to balance word lengths\n if $sofar + $maybe == $count { # It's an anagram\n say $phrase ~ ' ' ~ .key and next; # Display it and move on\n } else { # Not yet a full anagram, recurse\n find-anagram %filtered, $phrase ~ ' ' ~ .key, $maybe;\n }\n }\n}\n\n```\n\nTruncated to only show the best few as subjectively determined by me:\n\n*Punctuation, capitalization and (in some cases) word order manually massaged.*\n\n```\nEnter a word or phrase to be anagramed. (Loading dictionary)\n\nword or phrase? (press Enter to quit) Rosettacode\ndoctor tease\n\nword or phrase? (press Enter to quit) thundergnat\ndragnet hunt\nGent? Nah, turd.\n\nword or phrase? (press Enter to quit) Clint Eastwood\ndowncast eliot\nI contest waldo\nnose to wildcat\n```"
}
]
|
[
{
"role": "user",
"content": "When two or more words are composed of the same characters, but in a different order, they are called anagrams.\n\nTask\n\nUsing the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,\n \nfind the sets of words that share the same characters that contain the most words in them.\n\nRelated tasks\n\n* | | | | | | |\n | --- | --- | --- | --- | --- | --- |\n | | Word plays | | | --- | --- | | | | Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams | | |\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 2016.08\n\n```\nmy @anagrams = 'unixdict.txt'.IO.words.classify(*.comb.sort.join).values;\n \nmy $max = @anagrams».elems.max;\n\n.put for @anagrams.grep(*.elems == $max);\n```\n\nOutput:\n\n```\ncaret carte cater crate trace\nangel angle galen glean lange\nalger glare lager large regal\nelan lane lean lena neal\nevil levi live veil vile\nabel able bale bela elba\n\n```\n\nJust for the fun of it, here's a one-liner that uses no temporaries. Since it would be rather long, we've oriented it vertically:\n\n**Works with**: Rakudo version 2016.08\n\n```\n.put for # print each element of the array made this way:\n 'unixdict.txt'.IO.words # load words from file\n .classify(*.comb.sort.join) # group by common anagram\n .classify(*.value.elems) # group by number of anagrams in a group\n .max(*.key).value # get the group with highest number of anagrams\n .map(*.value) # get all groups of anagrams in the group just selected\n```"
}
]
|
[
{
"role": "user",
"content": "Two or more words are said to be anagrams if they have the same characters, but in a different order.\n\nBy analogy with derangements we define a *deranged anagram* as two words with the same characters, but in which the same character does *not* appear in the same position in both words.\n\nTask\n\nUse the word list at unixdict to find and display the longest deranged anagram.\n\nRelated\n\n* Permutations/Derangements\n* Best shuffle\n\n* | | | | | | |\n | --- | --- | --- | --- | --- | --- |\n | | Word plays | | | --- | --- | | | | Ordered words Palindrome detection Semordnilap Anagrams Anagrams/Deranged anagrams | | |\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 2016.08\n\n```\nmy @anagrams = 'unixdict.txt'.IO.words\n .map(*.comb.cache) # explode words into lists of characters\n .classify(*.sort.join).values # group words with the same characters\n .grep(* > 1) # only take groups with more than one word\n .sort(-*[0]) # sort by length of the first word\n;\n\nfor @anagrams -> @group {\n for @group.combinations(2) -> [@a, @b] {\n if none @a Zeq @b {\n say \"{@a.join} {@b.join}\";\n exit;\n }\n }\n}\n\n```\n\nOutput:\n\n```\nexcitation intoxicate\n```"
}
]
|
[
{
"role": "user",
"content": "Anaprimes are prime numbers that are anagrams of each other, i.e. they use exactly the same digits with the same frequency but in a different order.\n\nAnaprimes are *very* common. To illustrate this, we will investigate the sizes of the equivalence classes defined by the \"is an anagram of\" relation.\n\nFor example, the equivalence class of 149 has four anaprimes: {149, 419, 491, 941}. It turns out that there is no larger equivalence class of 3-digit anaprimes.\n\nTask\n\n* Find prime numbers that are anagrams of each other.\n* Find the **largest** anagram group of prime numbers and display the count, and minimum and maximum members for prime numbers:\n + up to three digits long (before 1,000)\n + up to four digits long (before 10,000)\n + up to five digits long (before 100,000)\n + up to six digits long (before 1,000,000)\n\nStretch\n\n* Find the **largest** anagram group and display the count, and smallest and largest members for prime numbers:\n + up to seven digits long (before 10,000,000)\n + up to eight digits long (before 100,000,000)\n + up to nine digits long (before 1,000,000,000)\n + ???!\n\nRelated tasks\n\n* Circular primes * Ormiston pairs * Emirp primes"
},
{
"role": "assistant",
"content": "9 digit is slooow. I didn't have the patience for 10.\n\n```\nuse Lingua::EN::Numbers;\nuse Math::Primesieve;\nuse List::Allmax;\n\nmy $p = Math::Primesieve.new;\n\nfor 3 .. 9 {\n my @largest = $p.primes(10**($_-1), 10**$_).classify(*.comb.sort.join).List.&all-max(:by(+*.value)).values;\n\n put \"\\nLargest group of anaprimes before {cardinal 10 ** $_}: {+@largest[0].value} members.\";\n put 'First: ', ' Last: ' Z~ .value[0, *-1] for sort @largest;\n}\n\n```\n\nOutput:\n\n```\nLargest group of anaprimes before one thousand: 4 members.\nFirst: 149 Last: 941\nFirst: 179 Last: 971\nFirst: 379 Last: 937\n\nLargest group of anaprimes before ten thousand: 11 members.\nFirst: 1237 Last: 7321\nFirst: 1279 Last: 9721\n\nLargest group of anaprimes before one hundred thousand: 39 members.\nFirst: 13789 Last: 98731\n\nLargest group of anaprimes before one million: 148 members.\nFirst: 123479 Last: 974213\n\nLargest group of anaprimes before ten million: 731 members.\nFirst: 1235789 Last: 9875321\n\nLargest group of anaprimes before one hundred million: 4,333 members.\nFirst: 12345769 Last: 97654321\n\nLargest group of anaprimes before one billion: 26,519 members.\nFirst: 102345697 Last: 976542103\n```"
}
]
|
[
{
"role": "user",
"content": "Finding the angle between two bearings is often confusing.[1]\n\nTask\n\nFind the angle which is the result of the subtraction **b2 - b1**, where **b1** and **b2** are the bearings.\n\nInput bearings are expressed in the range **-180** to **+180** degrees.\n \nThe result is also expressed in the range **-180** to **+180** degrees.\n\nCompute the angle for the following pairs:\n\n* 20 degrees (**b1**) and 45 degrees (**b2**)\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\nOptional extra\n\nAllow the input bearings to be any (finite) value.\n\nTest cases\n\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.11\n\n```\nsub infix:<∠> (Real $b1, Real $b2) {\n (my $b = ($b2 - $b1 + 720) % 360) > 180 ?? $b - 360 !! $b;\n}\n\nfor 20, 45,\n -45, 45,\n -85, 90,\n -95, 90,\n -45, 125,\n -45, 145,\n 29.4803, -88.6381,\n -78.3251, -159.036,\n -70099.74233810938, 29840.67437876723,\n -165313.6666297357, 33693.9894517456,\n 1174.8380510598456, -154146.66490124757,\n 60175.77306795546, 42213.07192354373\n\n -> $b1, $b2 { printf \"%10.2f %10.2f = %8.2f\\n\", $b1, $b2, $b1 ∠ $b2 }\n\n```\n\nOutput:\n\n```\n 20.00 45.00 = 25.00\n -45.00 45.00 = 90.00\n -85.00 90.00 = 175.00\n -95.00 90.00 = -175.00\n -45.00 125.00 = 170.00\n -45.00 145.00 = -170.00\n 29.48 -88.64 = -118.12\n -78.33 -159.04 = -80.71\n -70099.74 29840.67 = -139.58\n-165313.67 33693.99 = -72.34\n 1174.84 -154146.66 = -161.50\n 60175.77 42213.07 = 37.30\n```"
}
]
|
[
{
"role": "user",
"content": "This task is about the normalization and/or conversion of (geometric) angles using\nsome common scales.\n\nThe angular scales that will be used in this task are:\n\n: : * degree\n * gradian\n * mil\n * radian\n\nDefinitions\n\nThe angular scales used or referenced here:\n\n: : * **turn** is a full turn or 360 degrees, also shown as 360º\n * **degree** is **1/360** of a turn\n * **gradian** is **1/400** of a turn\n * **mil** is **1/6400** of a turn\n * **radian** is **1/2\n\n π\n {\\displaystyle {\\displaystyle \\pi }}** of a turn (or **0.5/π\n {\\displaystyle {\\displaystyle \\pi }}** of a turn)\n\nOr, to put it another way, for a full circle:\n\n: : * there are **360** degrees\n * there are **400** gradians\n * there are **6,400** mils\n * there are **2\n\n π\n {\\displaystyle {\\displaystyle \\pi }}** radians (roughly equal to **6.283+**)\n\nA **mil** is approximately equal to a *milliradian* (which is **1/1000** of a radian).\n\nThere is another definition of a **mil** which\nis **1/1000** of a radian ─── this\ndefinition won't be used in this Rosetta Code task.\n\n**Turns** are sometimes known or shown as:\n\n: : : * turn(s)\n * 360 degrees\n * unit circle\n * a (full) circle\n\n**Degrees** are sometimes known or shown as:\n\n: : : * degree(s)\n * deg\n * º (a symbol)\n * ° (another symbol)\n\n**Gradians** are sometimes known or shown as:\n\n: : : * gradian(s)\n * grad(s)\n * grade(s)\n * gon(s)\n * metric degree(s)\n * (Note that **centigrade** was used for 1/100th of a grade, see the note below.)\n\n**Mils** are sometimes known or shown as:\n\n: : : * mil(s)\n * NATO mil(s)\n\n**Radians** are sometimes known or shown as:\n\n: : : * radian(s)\n * rad(s)\n\nNotes\n\nIn continental Europe, the French term **centigrade** was used\nfor **1/100** of a grad (grade); this was\none reason for the adoption of the term **Celsius** to\nreplace **centigrade** as the name of a temperature scale.\n\nGradians were commonly used in civil engineering.\n\nMils were normally used for artillery (elevations of the gun barrel for ranging).\n\nPositive and negative angles\n\nAlthough the definition of the measurement of an angle doesn't support the\nconcept of a negative angle, it's frequently useful to impose a convention that\nallows positive and negative angular values to represent orientations and/or rotations\nin opposite directions relative to some reference. It is this reason that\nnegative angles will keep their sign and not be normalized to positive angles.\n\nNormalization\n\nNormalization (for this Rosetta Code task) will keep the same\nsign, but it will reduce the magnitude to less than a full circle; in\nother words, less than 360º.\n\nNormalization shouldn't change **-45º** to **315º**,\n\nAn angle of **0º**, **+0º**, **0.000000**, or **-0º** should be\nshown as **0º**.\n\nTask\n: : * write a function (or equivalent) to do the normalization for each scale\n\n : : : * Suggested names:\n * **d2d**, **g2g**, **m2m**, and **r2r**\n\n * write a function (or equivalent) to convert one scale to another\n\n : : : * Suggested names for comparison of different computer language function names:\n * **d2g**, **d2m**, and **d2r** for degrees\n * **g2d**, **g2m**, and **g2r** for gradians\n * **m2d**, **m2g**, and **m2r** for mils\n * **r2d**, **r2g**, and **r2m** for radians\n\n * normalize all angles used (except for the \"original\" or \"base\" angle)\n * show the angles in every scale and convert them to all other scales\n * show all output here on this page\n\nFor the (above) conversions, use these dozen numbers (in the order shown):\n\n: * **-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy @units =\n { code => 'd', name => 'degrees' , number => 360 },\n { code => 'g', name => 'gradians', number => 400 },\n { code => 'm', name => 'mills' , number => 6400 },\n { code => 'r', name => 'radians' , number => tau },\n;\n\nmy Code %cvt = (@units X @units).map: -> ($a, $b) {\n \"{$a.<code>}2{$b.<code>}\" => sub ($angle) {\n my $norm = $angle % $a.<number>\n - ( $a.<number> if $angle < 0 );\n $norm * $b.<number> / $a.<number>\n }\n}\n\nsay ' Angle Unit ', @units».<name>».tc.fmt('%11s');\n\nfor -2, -1, 0, 1, 2, tau, 16, 360/tau, 360-1, 400-1, 6400-1, 1_000_000 -> $angle {\n say '';\n for @units -> $from {\n my @sub_keys = @units.map: { \"{$from.<code>}2{.<code>}\" };\n\n my @results = %cvt{@sub_keys}».($angle);\n\n say join ' ', $angle .fmt('%10g'),\n $from.<name>.fmt('%-8s'),\n @results .fmt('%11g');\n }\n}\n\n```\n\nOutput:\n\n```\n Angle Unit Degrees Gradians Mills Radians\n\n -2 degrees -2 -2.22222 -35.5556 -0.0349066\n -2 gradians -1.8 -2 -32 -0.0314159\n -2 mills -0.1125 -0.125 -2 -0.0019635\n -2 radians -114.592 -127.324 -2037.18 -2\n\n -1 degrees -1 -1.11111 -17.7778 -0.0174533\n -1 gradians -0.9 -1 -16 -0.015708\n -1 mills -0.05625 -0.0625 -1 -0.000981748\n -1 radians -57.2958 -63.662 -1018.59 -1\n\n 0 degrees 0 0 0 0\n 0 gradians 0 0 0 0\n 0 mills 0 0 0 0\n 0 radians 0 0 0 0\n\n 1 degrees 1 1.11111 17.7778 0.0174533\n 1 gradians 0.9 1 16 0.015708\n 1 mills 0.05625 0.0625 1 0.000981748\n 1 radians 57.2958 63.662 1018.59 1\n\n 2 degrees 2 2.22222 35.5556 0.0349066\n 2 gradians 1.8 2 32 0.0314159\n 2 mills 0.1125 0.125 2 0.0019635\n 2 radians 114.592 127.324 2037.18 2\n\n 6.28319 degrees 6.28319 6.98132 111.701 0.109662\n 6.28319 gradians 5.65487 6.28319 100.531 0.098696\n 6.28319 mills 0.353429 0.392699 6.28319 0.0061685\n 6.28319 radians 0 0 0 0\n\n 16 degrees 16 17.7778 284.444 0.279253\n 16 gradians 14.4 16 256 0.251327\n 16 mills 0.9 1 16 0.015708\n 16 radians 196.732 218.592 3497.47 3.43363\n\n 57.2958 degrees 57.2958 63.662 1018.59 1\n 57.2958 gradians 51.5662 57.2958 916.732 0.9\n 57.2958 mills 3.22289 3.58099 57.2958 0.05625\n 57.2958 radians 42.8064 47.5626 761.002 0.747112\n\n 359 degrees 359 398.889 6382.22 6.26573\n 359 gradians 323.1 359 5744 5.63916\n 359 mills 20.1938 22.4375 359 0.352447\n 359 radians 49.1848 54.6498 874.397 0.858437\n\n 399 degrees 39 43.3333 693.333 0.680678\n 399 gradians 359.1 399 6384 6.26748\n 399 mills 22.4438 24.9375 399 0.391717\n 399 radians 181.016 201.129 3218.06 3.15933\n\n 6399 degrees 279 310 4960 4.86947\n 6399 gradians 359.1 399 6384 6.26748\n 6399 mills 359.944 399.938 6399 6.2822\n 6399 radians 155.693 172.992 2767.88 2.71736\n\n 1000000 degrees 280 311.111 4977.78 4.88692\n 1000000 gradians 0 0 0 0\n 1000000 mills 90 100 1600 1.5708\n 1000000 radians 339.513 377.237 6035.79 5.92562\n```\n\nAlternately, implemented as a series of postfix operators:\n\n*(Much of the complexity is due to the requirement that negative angles must normalize to a negative number.)*\n\n```\nsub postfix:<t>( $t ) { my $a = $t % 1 * τ; $t >=0 ?? $a !! $a - τ }\nsub postfix:<d>( $d ) { my $a = $d % 360 * τ / 360; $d >=0 ?? $a !! $a - τ }\nsub postfix:<g>( $g ) { my $a = $g % 400 * τ / 400; $g >=0 ?? $a !! $a - τ }\nsub postfix:<m>( $m ) { my $a = $m % 6400 * τ / 6400; $m >=0 ?? $a !! $a - τ }\nsub postfix:<r>( $r ) { my $a = $r % τ; $r >=0 ?? $a !! $a - τ }\n\nsub postfix:«->t» ($angle) { my $a = $angle / τ; ($angle < 0 and $a == -1) ?? -0 !! $a }\nsub postfix:«->d» ($angle) { my $a = $angle / τ * 360; ($angle < 0 and $a == -360) ?? -0 !! $a }\nsub postfix:«->g» ($angle) { my $a = $angle / τ * 400; ($angle < 0 and $a == -400) ?? -0 !! $a }\nsub postfix:«->m» ($angle) { my $a = $angle / τ * 6400; ($angle < 0 and $a == -6400) ?? -0 !! $a }\nsub postfix:«->r» ($angle) { my $a = $angle; ($angle < 0 and $a == -τ) ?? -0 !! $a }\n\nfor <-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000> -> $a {\n say '';\n say ' Quantity Unit ', <turns degrees gradians mils radians>.fmt('%15s');\n for 'turns', &postfix:«t», 'degrees', &postfix:«d», 'gradians', &postfix:«g»,\n 'mils', &postfix:«m», 'radians', &postfix:«r»\n -> $unit, &f {\n printf \"%10s %-10s %15s %15s %15s %15s %15s\\n\", $a, $unit,\n |($a.&f->t, $a.&f->d, $a.&f->g, $a.&f->m, $a.&f->r)».round(.00000001);\n }\n}\n\n```\n\n```\n Quantity Unit turns degrees gradians mils radians\n -2 turns 0 0 0 0 0\n -2 degrees -0.00555556 -2 -2.22222222 -35.55555556 -0.03490659\n -2 gradians -0.005 -1.8 -2 -32 -0.03141593\n -2 mils -0.000313 -0.1125 -0.125 -2 -0.0019635\n -2 radians -0.31830989 -114.59155903 -127.32395447 -2037.18327158 -2\n\n Quantity Unit turns degrees gradians mils radians\n -1 turns 0 0 0 0 0\n -1 degrees -0.00277778 -1 -1.11111111 -17.77777778 -0.01745329\n -1 gradians -0.0025 -0.9 -1 -16 -0.01570796\n -1 mils -0.000156 -0.05625 -0.0625 -1 -0.00098175\n -1 radians -0.15915494 -57.29577951 -63.66197724 -1018.59163579 -1\n\n Quantity Unit turns degrees gradians mils radians\n 0 turns 0 0 0 0 0\n 0 degrees 0 0 0 0 0\n 0 gradians 0 0 0 0 0\n 0 mils 0 0 0 0 0\n 0 radians 0 0 0 0 0\n\n Quantity Unit turns degrees gradians mils radians\n 1 turns 0 0 0 0 0\n 1 degrees 0.00277778 1 1.11111111 17.77777778 0.01745329\n 1 gradians 0.0025 0.9 1 16 0.01570796\n 1 mils 0.000156 0.05625 0.0625 1 0.00098175\n 1 radians 0.15915494 57.29577951 63.66197724 1018.59163579 1\n\n Quantity Unit turns degrees gradians mils radians\n 2 turns 0 0 0 0 0\n 2 degrees 0.00555556 2 2.22222222 35.55555556 0.03490659\n 2 gradians 0.005 1.8 2 32 0.03141593\n 2 mils 0.000313 0.1125 0.125 2 0.0019635\n 2 radians 0.31830989 114.59155903 127.32395447 2037.18327158 2\n\n Quantity Unit turns degrees gradians mils radians\n 6.2831853 turns 0.2831853 101.946708 113.27412 1812.38592 1.77930572\n 6.2831853 degrees 0.01745329 6.2831853 6.981317 111.701072 0.10966227\n 6.2831853 gradians 0.01570796 5.65486677 6.2831853 100.5309648 0.09869604\n 6.2831853 mils 0.00098175 0.35342917 0.39269908 6.2831853 0.0061685\n 6.2831853 radians 1 359.99999959 399.99999954 6399.99999269 6.2831853\n\n Quantity Unit turns degrees gradians mils radians\n 16 turns 0 0 0 0 0\n 16 degrees 0.04444444 16 17.77777778 284.44444444 0.27925268\n 16 gradians 0.04 14.4 16 256 0.25132741\n 16 mils 0.0025 0.9 1 16 0.01570796\n 16 radians 0.54647909 196.73247221 218.59163579 3497.46617261 3.43362939\n\n Quantity Unit turns degrees gradians mils radians\n57.2957795 turns 0.2957795 106.48062 118.3118 1892.9888 1.85843741\n57.2957795 degrees 0.15915494 57.2957795 63.66197722 1018.59163556 1\n57.2957795 gradians 0.14323945 51.56620155 57.2957795 916.732472 0.9\n57.2957795 mils 0.00895247 3.2228876 3.58098622 57.2957795 0.05625\n57.2957795 radians 0.11890653 42.80634926 47.56261029 761.00176466 0.74711174\n\n Quantity Unit turns degrees gradians mils radians\n 359 turns 0 0 0 0 0\n 359 degrees 0.99722222 359 398.88888889 6382.22222222 6.26573201\n 359 gradians 0.8975 323.1 359 5744 5.63915881\n 359 mils 0.056094 20.19375 22.4375 359 0.35244743\n 359 radians 0.13662457 49.1848452 54.649828 874.39724794 0.85843749\n\n Quantity Unit turns degrees gradians mils radians\n 399 turns 0 0 0 0 0\n 399 degrees 0.10833333 39 43.33333333 693.33333333 0.68067841\n 399 gradians 0.9975 359.1 399 6384 6.26747734\n 399 mils 0.062344 22.44375 24.9375 399 0.39171733\n 399 radians 0.50282229 181.01602572 201.12891747 3218.06267946 3.15932565\n\n Quantity Unit turns degrees gradians mils radians\n 6399 turns 0 0 0 0 0\n 6399 degrees 0.775 279 310 4960 4.86946861\n 6399 gradians 0.9975 359.1 399 6384 6.26747734\n 6399 mils 0.999844 359.94375 399.9375 6399 6.28220356\n 6399 radians 0.43248085 155.69310421 172.99233802 2767.87740825 2.71735729\n\n Quantity Unit turns degrees gradians mils radians\n 1000000 turns 0 0 0 0 0\n 1000000 degrees 0.77777778 280 311.11111111 4977.77777778 4.88692191\n 1000000 gradians 0 0 0 0 0\n 1000000 mils 0.25 90 100 1600 1.57079633\n 1000000 radians 0.9430919 339.51308233 377.23675814 6035.78813022 5.92562114\n```"
}
]
|
[
{
"role": "user",
"content": "Capture of the Oz version.\n\nOne good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.\n\nThe classic such physical system is a simple gravity pendulum.\n\nTask\n\nCreate a simple physical model of a pendulum and animate it."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.09\n\nHandles window resizing, modifies pendulum length and period as window height changes. May need to tweek $ppi scaling to get good looking animation.\n\n```\nuse SDL2::Raw;\nuse Cairo;\n\nmy $width = 1000;\nmy $height = 400;\n\nSDL_Init(VIDEO);\n\nmy $window = SDL_CreateWindow(\n 'Pendulum - Raku',\n SDL_WINDOWPOS_CENTERED_MASK,\n SDL_WINDOWPOS_CENTERED_MASK,\n $width, $height, RESIZABLE\n);\n\nmy $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);\n\nmy $bob = Cairo::Image.create( Cairo::FORMAT_ARGB32, 32, 32 );\ngiven Cairo::Context.new($bob) {\n my Cairo::Pattern::Gradient::Radial $sphere .=\n create(13.3, 12.8, 3.2, 12.8, 12.8, 32);\n $sphere.add_color_stop_rgba(0, 1, 1, .698, 1);\n $sphere.add_color_stop_rgba(1, .623, .669, .144, 1);\n .pattern($sphere);\n .arc(16, 16, 15, 0, 2 * pi);\n .fill;\n $sphere.destroy;\n}\n\nmy $bob_texture = SDL_CreateTexture(\n $render, %PIXELFORMAT<ARGB8888>,\n STATIC, 32, 32\n);\n\nSDL_UpdateTexture(\n $bob_texture,\n SDL_Rect.new(:x(0), :y(0), :w(32), :h(32)),\n $bob.data, $bob.stride // 32\n);\n\nSDL_SetTextureBlendMode($bob_texture, 1);\n\nSDL_SetRenderDrawBlendMode($render, 1);\n\nmy $event = SDL_Event.new;\n\nmy $now = now; # time\nmy $Θ = -π/3; # start angle\nmy $ppi = 500; # scale\nmy $g = -9.81; # accelaration of gravity\nmy $ax = $width/2; # anchor x\nmy $ay = 25; # anchor y\nmy $len = $height - 75; # 'rope' length\nmy $vel; # velocity\nmy $dt; # delta time\n\nmain: loop {\n while SDL_PollEvent($event) {\n my $casted_event = SDL_CastEvent($event);\n given $casted_event {\n when *.type == QUIT { last main }\n when *.type == WINDOWEVENT {\n if .event == 5 {\n $width = .data1;\n $height = .data2;\n $ax = $width/2;\n $len = $height - 75;\n }\n }\n }\n }\n\n $dt = now - $now;\n $now = now;\n $vel += $g / $len * sin($Θ) * $ppi * $dt;\n $Θ += $vel * $dt;\n my $bx = $ax + sin($Θ) * $len;\n my $by = $ay + cos($Θ) * $len;\n\n SDL_SetRenderDrawColor($render, 255, 255, 255, 255);\n SDL_RenderDrawLine($render, |($ax, $ay, $bx, $by)».round);\n SDL_RenderCopy( $render, $bob_texture, Nil,\n SDL_Rect.new($bx - 16, $by - 16, 32, 32)\n );\n SDL_RenderPresent($render);\n SDL_SetRenderDrawColor($render, 0, 0, 0, 0);\n SDL_RenderClear($render);\n}\n\nSDL_Quit();\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate and display five spinners.\nOne spinner in the middle and four spinners surrounding it.\nEach spinner is created by drawing radius lines around a center axis and then looping through the drawing to simulate a moving clock hand.\nWhen the loop is sped up, the illusion of a spinner is created.\nNOTE: The animated GIF example is actually slower than what you should be able to create. A fast animation will fill in more radial lines with a pleasing appearance.\n\nStretch goal\n\nExtra credit for offsetting the spinners with mouse movement.\n\n| | | |\n| --- | --- | --- |\n| Slow Spinners | Fast Spinners | Spinners offset with mouse movement |"
},
{
"role": "assistant",
"content": "```\n# 20250206 Raku programming solution\n\nuse NativeCall;\n\nclass Window is repr('CPointer') {}\nclass Monitor is repr('CPointer') {}\n\nconstant $lib = ('glfw', v3);\nconstant $gllib = 'GL';\n\nsub glfwInit(--> int32) is native($lib) {*}\nsub glfwCreateWindow(int32, int32, Str, Monitor, Window --> Window) is native($lib) {*}\nsub glfwTerminate() is native($lib) {*}\nsub glfwMakeContextCurrent(Window) is native($lib) {*}\nsub glfwWindowShouldClose(Window --> int32) is native($lib) {*}\nsub glfwSwapBuffers(Window) is native($lib) {*}\nsub glfwSwapInterval(int32) is native($lib) {*}\nsub glfwPollEvents() is native($lib) {*}\n\nsub glClear(int32) is native($gllib) {*}\nsub glLoadIdentity() is native($gllib) {*}\nsub glTranslatef(num32, num32, num32) is native($gllib) {*}\nsub glRotatef(num32, num32, num32, num32) is native($gllib) {*}\nsub glColor4f(num32, num32, num32, num32) is native($gllib) {*}\nsub glBegin(int32) is native($gllib) {*}\nsub glVertex2f(num32, num32) is native($gllib) {*}\nsub glEnd() is native($gllib) {*}\nsub glPushMatrix() is native($gllib) {*}\nsub glPopMatrix() is native($gllib) {*}\n\nenum PrimitiveMode( GL_LINES => 0x0001 );\nconstant GL_COLOR_BUFFER_BIT = 0x00004000;\n\nmy (\\NUM_LINES,\\INNER_RADIUS,\\OUTER_RADIUS,\\ROTATION_SPEED) = 1, 0.0, 0.5, 2.0; \n\nsub drawLine($angle, $opacity, $centerX, $centerY) {\n glPushMatrix();\n glTranslatef($centerX, $centerY, 0e0);\n glRotatef($angle, 0e0, 0e0, 1e0);\n glColor4f(1e0, 1e0, 1e0, $opacity);\n\n glBegin(GL_LINES);\n (INNER_RADIUS, OUTER_RADIUS)>>.Num.map: { glVertex2f($_, 0e0) };\n glEnd();\n\n glPopMatrix();\n}\n\ndie 'Failed to initialize GLFW' unless glfwInit().so;\n\nmy $w = glfwCreateWindow(640, 480, \"Spinners\", Nil, Nil);\nwithout $w { glfwTerminate(); die 'Failed to create window' }\n\nglfwMakeContextCurrent($w);\nglfwSwapInterval(1);\n\nmy @angles = 0.0 xx 5; \nmy @positions = (<0 0>, <-.5 .5>, <.5 .5>, <-.5 -.5>, <.5 -.5>).map: *>>.Num;\n\nuntil glfwWindowShouldClose($w) {\n glClear(GL_COLOR_BUFFER_BIT);\n glLoadIdentity();\n\n for 0 ..^ NUM_LINES -> $i {\n my $opacity = 1.0e0 - ($i / NUM_LINES);\n for @positions.kv -> $index, $pos {\n drawLine((@angles[$index] + 360 / NUM_LINES * $i).Num, $opacity, $pos[0], $pos[1]);\n }\n }\n\n glfwSwapBuffers($w);\n glfwPollEvents();\n\n for 0 ..^ 5 -> $i {\n @angles[$i] += (ROTATION_SPEED * (1 / 60).Num);\n @angles[$i] -= 360 if @angles[$i] >= 360;\n }\n}\n\nglfwTerminate();\n\n```"
}
]
|
[
{
"role": "user",
"content": "**Animation** is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.\n\nTask\n\nCreate a window containing the string \"`Hello World!` \" (the trailing space is significant).\n\nMake the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.\n\nWhen the user clicks on the (windowed) text, it should reverse its direction."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\n```\nuse GTK::Simple;\nuse GTK::Simple::App;\n\nmy $app = GTK::Simple::App.new(:title<Animation>);\nmy $button = GTK::Simple::Button.new(label => 'Hello World! ');\nmy $vbox = GTK::Simple::VBox.new($button);\n\nmy $repeat = $app.g-timeout(100); # milliseconds\n\nmy $dir = 1;\n$button.clicked.tap({ $dir *= -1 });\n\n$repeat.tap( &{$button.label = $button.label.comb.List.rotate($dir).join} );\n\n$app.set-content($vbox);\n\n$app.run;\n\n```"
}
]
|
[
{
"role": "user",
"content": "While implementing a recursive function, it often happens that we must resort to a separate *helper function* to handle the actual recursion.\n\nThis is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.\n\nSo we end up inventing some silly name like **foo2** or **foo\\_helper**. I have always found it painful to come up with a proper name, and see some disadvantages:\n\n: : * You have to think up a name, which then pollutes the namespace\n * Function is created which is called from nowhere else\n * The program flow in the source code is interrupted\n\nSome languages allow you to embed recursion directly in-place. This might work via a label, a local *gosub* instruction, or some special keyword.\n\nAnonymous recursion can also be accomplished using the Y combinator.\n\nTask\n\nIf possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.\n\nRelated tasks\n: * Y combinator"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nIn addition to the methods in the Perl entry above, and the Y-combinator described in Y\\_combinator, you may also refer to an anonymous block or function from the inside:\n\n```\nsub fib($n) {\n die \"Naughty fib\" if $n < 0;\n return {\n $_ < 2\n ?? $_\n !! &?BLOCK($_-1) + &?BLOCK($_-2);\n }($n);\n}\n\nsay fib(10);\n```\n\nHowever, using any of these methods is insane, when Raku provides a sort of inside-out combinator that lets you define lazy infinite constants, where the demand for a particular value is divorced from dependencies on more primitive values. This operator, known as the sequence operator, does in a sense provide anonymous recursion to a closure that refers to more primitive values.\n\n```\nconstant @fib = 0, 1, *+* ... *;\nsay @fib[10];\n```\n\nHere the closure, \\*+\\*, is just a quick way to write a lambda, -> $a, $b { $a + $b }. The sequence operator implicitly maps the two arguments to the -2nd and -1st elements of the sequence. So the sequence operator certainly applies an anonymous lambda, but whether it's recursion or not depends on whether you view a sequence as iteration or as simply a convenient way of memoizing a recursion. Either view is justifiable.\n\nAt this point someone may complain that the solution is doesn't fit the specified task because the sequence operator doesn't do the check for negative. True, but the sequence operator is not the whole of the solution; this check is supplied by the subscripting operator itself when you ask for @fib[-1]. Instead of scattering all kinds of arbitrary boundary conditions throughout your functions, the sequence operator maps them quite naturally to the boundary of definedness at the start of a list."
}
]
|
[
{
"role": "user",
"content": "The anti-primes\n(or highly composite numbers, sequence A002182 in the OEIS)\nare the natural numbers with more factors than any smaller than itself.\n\nTask\n\nGenerate and show here, the first twenty anti-primes.\n\nRelated tasks\n: * Factors of an integer\n * Sieve of Eratosthenes"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.11\n\nAt its heart, this task is almost exactly the same as Proper\\_Divisors, it is just asking for slightly different results. Much of this code is lifted straight from there.\n\nImplemented as an auto-extending lazy list. Displaying the count of anti-primes less than 5e5 also because... why not.\n\n```\nsub propdiv (\\x) {\n my @l = 1 if x > 1;\n (2 .. x.sqrt.floor).map: -> \\d {\n unless x % d { @l.push: d; my \\y = x div d; @l.push: y if y != d }\n }\n @l\n}\n\nmy $last = 0;\n\nmy @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c {\n my \\mx = +propdiv($c);\n next if mx <= $last;\n $last = mx;\n $c\n}\n\nmy $upto = 5e5;\n\nput \"First 20 anti-primes:\\n{ @anti-primes[^20] }\";\n\nput \"\\nCount of anti-primes <= $upto: {+@anti-primes[^(@anti-primes.first: * > $upto, :k)]}\";\n\n```\n\nOutput:\n\n```\nFirst 20 anti-primes:\n1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560\n\nCount of anti-primes <= 500000: 35\n```"
}
]
|
[
{
"role": "user",
"content": "Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment.\n\nThis feature is most useful in the case of log files, where many jobs may be appending to the log file at the same time, or where care *must* be taken to avoid concurrently overwriting the same record from another job.\n\nTask\n\nGiven a two record sample for a mythical \"passwd\" file:\n\n* Write these records out in the typical system format.\n + Ideally these records will have named fields of various types.\n* Close the file, then reopen the file for append.\n + **Append** a new record to the file and close the file again.\n + Take appropriate care to avoid concurrently overwrites from another job.\n* Open the file and demonstrate the new record has indeed written to the end.\n\nSource record field types and contents.\n\n| account | password | UID | GID | fullname,office,extension,homephone,email | directory | shell |\n| --- | --- | --- | --- | --- | --- | --- |\n| string | string | int | int | struct(string,string,string,string,string) | string | string |\n| jsmith | x | 1001 | 1000 | Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected] | /home/jsmith | /bin/bash |\n| jdoe | x | 1002 | 1000 | Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected] | /home/jdoe | /bin/bash |\n\nRecord to be appended.\n\n| account | password | UID | GID | fullname,office,extension,homephone,email | directory | shell |\n| --- | --- | --- | --- | --- | --- | --- |\n| string | string | int | int | struct(string,string,string,string,string) | string | string |\n| xyz | x | 1003 | 1000 | X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected] | /home/xyz | /bin/bash |\n\n**Resulting file format:** should mimic Linux's /etc/passwd file format with particular attention to the \",\" separator used in the GECOS field. But if the specific language has a particular or unique format of storing records in text file, then this format should be named and demonstrated with an additional example.\n\n**Expected output:**\n\n```\nAppended record: xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash\n\n```\n\n**Finally:** Provide a summary of the language's \"append record\" capabilities in a table. eg.\n\nAppend Capabilities.\n\n| Data Representation | | IO Library | Append Possible | Automatic Append | Multi-tasking Safe |\n| --- | --- | --- | --- | --- | --- |\n| In core | On disk |\n| C struct | CSV text file | glibc/stdio | ☑ | ☑ | ☑ (Not all, eg NFS) |\n\nAlternatively: If the language's appends can not guarantee its writes will **always** append, then note this restriction in the table. If possible, provide an actual code example (possibly using file/record locking) to guarantee correct concurrent appends."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nThis is kind of silly as it takes a string, converts it to a record, and then instantly converts it back to a string to write out to a file. Most of the \"record handling\" code is just demonstrating a possible way to store records in memory. It really has nothing to do with appending a string to a file.\n\n```\nclass record {\n has $.name;\n has $.password;\n has $.UID;\n has $.GID;\n has $.fullname;\n has $.office;\n has $.extension;\n has $.homephone;\n has $.email;\n has $.directory;\n has $.shell;\n\n method gecos { join ',', $.fullname, $.office, $.extension, $.homephone, $.email }\n\n method gist {\n join ':',\n $.name,\n $.password,\n $.UID,\n $.GID,\n self.gecos,\n $.directory,\n $.shell;\n }\n};\n\nmy $fname = 'foo.fil';\n\ngiven $fname.IO.open(:w) { .close }; # clear file\n\nsub append ($file, $line){\n my $fh = $file.IO.open(:a) or fail \"Unable to open $file\";\n given $fh {\n # Get a lock on the file, waits until lock is active\n .lock;\n # seek to the end in case some other process wrote to\n # the file while we were waiting for the lock\n .seek(0, SeekType::SeekFromEnd);\n # write the record\n .say: $line;\n .close;\n }\n}\n\nsub str-to-record ($str) {\n my %rec = <name password UID GID fullname office extension\n homephone email directory shell> Z=> $str.split(/<[:,]>/);\n my $user = record.new(|%rec);\n}\n\nfor\n 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash',\n 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash'\n-> $line {\n my $thisuser = str-to-record $line;\n $fname.&append: $thisuser.gist;\n}\n\nput \"Last line of $fname before append:\";\nput $fname.IO.lines.tail;\n\n$fname.&append: str-to-record('xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash').gist;\n\nput \"Last line of $fname after append:\";\nput $fname.IO.lines.tail;\n\n```\n\nOutput:\n\n```\nLast line of foo.fil before append:\njdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash\nLast line of foo.fil after append:\nxyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash\n```\n\nAppend Capabilities.\n\n| Data Representation | | IO Library | Append Possible | Automatic Append | Multi-tasking Safe |\n| --- | --- | --- | --- | --- | --- |\n| In core | On disk |\n| Class | Text file | Whichever is provided by the underlying VM | ☑ | ☑ | ☑ Advisory lock Depends on OS and VM |\n\nNote that advisory locks do not prevent some other program (if it doesn't use flock) from unexpectedly writing to the file."
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven three lists:\n \nlist1 = [1,2,3,4,5,6,7,8,9]\n \nlist2 = [10,11,12,13,14,15,16,17,18]\n \nlist3 = [19,20,21,22,23,24,25,26,27]\n \nAt each index, turn the numbers into strings and concatenate them.\n \nThe result should be:\n \nlist = [11019,21120,31221,41322,51423,61524,71625,81726,91827]"
},
{
"role": "assistant",
"content": "Various manipulations.\n\n```\nmy @lists = 1..9, 10..18, 19..27;\nput [Z~] @lists; # the task\nput [Z~] @lists».flip; # each component reversed\nput [RZ~] @lists; # in reversed order\nput ([Z~] @lists)».flip; # reversed components in reverse order\n\n```\n\nOutput:\n\n```\n11019 21120 31221 41322 51423 61524 71625 81726 91827\n10191 21102 32112 43122 54132 65142 76152 87162 98172\n19101 20112 21123 22134 23145 24156 25167 26178 27189\n91011 02112 12213 22314 32415 42516 52617 62718 72819\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nTake a combined set of elements and apply a function to each element."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.10-11\n\n```\nsub function { 2 * $^x + 3 };\nmy @array = 1 .. 5;\n\n# via map function\n.say for map &function, @array;\n\n# via map method\n.say for @array.map(&function);\n\n# via for loop\nfor @array {\n say function($_);\n}\n\n# via the \"hyper\" metaoperator and method indirection\nsay @array».&function;\n\n# we neither need a variable for the array nor for the function\nsay [1,2,3]>>.&({ $^x + 1});\n```"
}
]
|
[
{
"role": "user",
"content": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1]\n\nTask\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\nSee also\n\n[Wikipedia on Butterworth filters]"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.11\n\n**Translation of**: zkl\n\n```\nsub TDF-II-filter ( @signal, @a, @b ) {\n my @out = 0 xx @signal;\n for ^@signal -> $i {\n my $this;\n $this += @b[$_] * @signal[$i-$_] if $i-$_ >= 0 for ^@b;\n $this -= @a[$_] * @out[$i-$_] if $i-$_ >= 0 for ^@a;\n @out[$i] = $this / @a[0];\n }\n @out\n}\n\nmy @signal = [\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589\n];\nmy @a = [ 1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ];\nmy @b = [ 0.16666667, 0.5, 0.5, 0.16666667 ];\n\nsay TDF-II-filter(@signal, @a, @b)».fmt(\"% 0.8f\")\n Z~ flat (', ' xx 4, \",\\n\") xx *;\n\n```\n\nOutput:\n\n```\n(-0.15297399, -0.43525783, -0.13604340, 0.69750333, 0.65644469,\n -0.43548245, -1.08923946, -0.53767655, 0.51704999, 1.05224975,\n 0.96185430, 0.69569009, 0.42435630, 0.19626223, -0.02783512,\n -0.21172192, -0.17474556, 0.06925841, 0.38544587, 0.65177084,\n)\n```"
}
]
|
[
{
"role": "user",
"content": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant.\n\nFor example, a difference between **32** bit and **64** bit floating point calculations may appear by\nabout the 8th significant digit in base 10 arithmetic.\n\nTask\n\nCreate a function which returns true if two floating point numbers are approximately equal.\n\nThe function should allow for differences in the magnitude of numbers, so that, for example,\n \n**100000000000000.01** may be approximately equal to **100000000000000.011**,\n \neven though **100.01** is not approximately equal to **100.011**.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n\n: 1. 100000000000000.01, 100000000000000.011 (note: should return *true*)\n 2. 100.01, 100.011 (note: should return *false*)\n 3. 10000000000000.001 / 10000.0, 1000000000.0000001000\n 4. 0.001, 0.0010000001\n 5. 0.000000000000000000000101, 0.0\n 6. sqrt(2) \\* sqrt(2), 2.0\n 7. -sqrt(2) \\* sqrt(2), -2.0\n 8. 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nIs approximately equal to is a built-in operator in Raku. Unicode ≅, or the ASCII equivalent: =~=. By default it uses a tolerance of 1e-15 times the order of magnitude of the larger comparand, though that is adjustable by setting the dynamic variable $\\*TOLERANCE to the desired value. Probably a good idea to localize the changed $\\*TOLERANCE as it will affect all comparisons within its scope.\n\nMost of the following tests are somewhat pointless in Raku. To a large extent, when dealing with Rational values, you don't really need to worry about \"approximately equal to\", and all of the test values below, with the exception of `sqrt(2)`, are Rats by default, and exact. You would have to specifically coerce them to Nums (floating point) to lose the precision.\n\nFor example, in Raku, the sum of .1, .2, .3, & .4 is *identically* equal to 1.\n\n```\nsay 0.1 + 0.2 + 0.3 + 0.4 === 1.0000000000000000000000000000000000000000000000000000000000000000000000000; # True\n\n```\n\nIt's also *approximately* equal to 1 but... ¯\\\\_(ツ)\\_/¯\n\n```\nfor\n 100000000000000.01, 100000000000000.011,\n 100.01, 100.011,\n 10000000000000.001 / 10000.0, 1000000000.0000001000,\n 0.001, 0.0010000001,\n 0.000000000000000000000101, 0.0,\n sqrt(2) * sqrt(2), 2.0,\n -sqrt(2) * sqrt(2), -2.0,\n 100000000000000003.0, 100000000000000004.0,\n 3.14159265358979323846, 3.14159265358979324\n\n -> $a, $b {\n say \"$a ≅ $b: \", $a ≅ $b;\n}\n\nsay \"\\nTolerance may be adjusted.\";\n\nsay 22/7, \" ≅ \", π, \": \", 22/7 ≅ π;\n{ # Localize the tolerance to only this block\n my $*TOLERANCE = .001;\n say 22/7, \" ≅ \", π, \": \", 22/7 ≅ π;\n}\n\n```\n\nOutput:\n\n```\n100000000000000.01 ≅ 100000000000000.011: True\n100.01 ≅ 100.011: False\n1000000000.0000001 ≅ 1000000000.0000001: True\n0.001 ≅ 0.0010000001: False\n0.000000000000000000000101 ≅ 0: True\n2.0000000000000004 ≅ 2: True\n-2.0000000000000004 ≅ -2: True\n100000000000000003 ≅ 100000000000000004: True\n3.141592653589793226752 ≅ 3.14159265358979324: True\n\nTolerance may be adjusted.\n3.142857 ≅ 3.141592653589793: False\n3.142857 ≅ 3.141592653589793: True\n```"
}
]
|
[
{
"role": "user",
"content": "Apéry's constant is the sum of the reciprocals of the positive cubes.\n\nThat is, it is defined as the number \n\nζ\n(\n3\n)\n=\n\n∑\n\nk\n=\n1\n\n∞\n\n\n1\n\nk\n\n3\n,\n{\\displaystyle {\\displaystyle \\zeta (3)=\\sum \\_{k=1}^{\\infty }{\\frac {1}{k^{3}}},}}\n *where ζ is the Riemann zeta function*.\n\nApproximately equal to:\n\n: **1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581**\n\nThis constant was known and studied by many early mathematicians, but was not named until 1978, after Roger Apéry, who was first to prove it was an irrational number.\n\nζ\n(\n3\n)\n{\\displaystyle {\\displaystyle \\zeta (3)}}\n by summing reciprocal cubes is easy to calculate, but converges very slowly. The first 1000 terms are only accurate to 6 decimal places.\n\nThere have been many fast convergence representations developed / discovered that generate correct digits much more quickly.\n\nOne of the earliest, discovered in the late 1800s by A. Markov and later widely published by Apéry is:\n\n: ζ\n (\n 3\n )\n =\n\n\n 5\n 2\n\n ∑\n\n k\n =\n 1\n\n ∞\n (\n −\n 1\n\n )\n\n k\n −\n 1\n\n k\n\n !\n\n 2\n\n (\n 2\n k\n )\n !\n\n k\n\n 3\n .\n {\\displaystyle {\\displaystyle \\zeta (3)={\\frac {5}{2}}\\sum \\_{k=1}^{\\infty }(-1)^{k-1}{\\frac {k!^{2}}{(2k)!k^{3}}}.}}\n\nMuch better than direct calculation of \n\nζ\n(\n3\n)\n{\\displaystyle {\\displaystyle \\zeta (3)}}\n, but still only yielding about .63 correct digits per iteration.\n\nSeveral even faster converging representions are available. The fastest known to date, yielding about 5.04 correct digits per term, is by Sebastian Wedeniwski.\n\n: ζ\n (\n 3\n )\n =\n\n\n 1\n 24\n\n ∑\n\n k\n =\n 0\n\n ∞\n (\n −\n 1\n\n )\n\n k\n\n (\n 2\n k\n +\n 1\n )\n\n !\n\n 3\n (\n 2\n k\n )\n\n !\n\n 3\n k\n\n !\n\n 3\n (\n 126392\n\n k\n\n 5\n +\n 412708\n\n k\n\n 4\n +\n 531578\n\n k\n\n 3\n +\n 336367\n\n k\n\n 2\n +\n 104000\n k\n +\n 12463\n )\n\n (\n 3\n k\n +\n 2\n )\n !\n (\n 4\n k\n +\n 3\n )\n\n !\n\n 3\n .\n {\\displaystyle {\\displaystyle \\zeta (3)={\\frac {1}{24}}\\sum \\_{k=0}^{\\infty }(-1)^{k}{\\frac {(2k+1)!^{3}(2k)!^{3}k!^{3}(126392k^{5}+412708k^{4}+531578k^{3}+336367k^{2}+104000k+12463)}{(3k+2)!(4k+3)!^{3}}}.}}\n\nTask\n\n* Show the value of Apéry's constant calculated at least three different ways.\n\n: 1. Show the value of at least the first 1000 terms of \n\n ζ\n (\n 3\n )\n {\\displaystyle {\\displaystyle \\zeta (3)}}\n by direct summing of reciprocal cubes, truncated to 100 decimal digits.\n 2. Show the value of the first 158 terms of Markov / Apéry representation truncated to 100 decimal digits.\n 3. Show the value of the first 20 terms of Wedeniwski representation truncated to 100 decimal digits.\n\nSee also\n\n* Wikipedia: Apéry's constant * OEIS:A002117 - Decimal expansion of zeta(3)"
},
{
"role": "assistant",
"content": "```\nsub postfix:<!> (Int $n) { (constant f = 1, |[\\×] 1..*)[$n] }\n\nsay 'Actual value to 100 decimal places:';\nsay '1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581';\n\nsay \"\\nFirst 1000 terms of ζ(3) truncated to 100 decimal places. (accurate to 6 decimal places):\";\nsay (1..1000).map({FatRat.new: 1, .³}).sum.substr: 0, 102;\n\nsay \"\\nFirst 158 terms of Markov / Apéry representation truncated to 100 decimal places:\";\nsay (5/2 × (1..158).map( -> \\k { (-1)**(k-1) × FatRat.new: k!², ((2×k)! × k³) } ).sum).substr: 0, 102;\n\nsay \"\\nFirst 20 terms of Wedeniwski representation truncated to 100 decimal places:\";\nsay (1/24 × ((^20).map: -> \\k {\n (-1)**k × FatRat.new: (2×k+1)!³ × (2×k)!³ × k!³ × (126392×k⁵ + 412708×k⁴ + 531578×k³ + 336367×k² + 104000×k + 12463), (3×k+2)! × (4×k+3)!³\n}).sum).substr: 0, 102;\n\n```\n\nOutput:\n\nActual value to 100 decimal places:\n\n1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581\n\nFirst 1000 terms of ζ(3) truncated to 100 decimal places. (accurate to 6 decimal places):\n1.2020564036593442854830714115115999903483212709031775135036540966118572571921400836130084123260473111\n\nFirst 158 terms of Markov / Apéry representation truncated to 100 decimal places:\n1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581\n\nFirst 20 terms of Wedeniwski representation truncated to 100 decimal places:\n1.2020569031595942853997381615114499907649862923404988817922715553418382057863130901864558736093352581"
}
]
|
[
{
"role": "user",
"content": "Using the in-built capabilities of your language, calculate the integer value of:\n\n```\n \n \n \n \n \n \n \n 5\n \n \n 4\n \n \n 3\n \n 2\n \n \n \n \n \n \n \n \n \n \n {\\displaystyle {\\displaystyle 5^{4^{3^{2}}}}}\n \n\n\n```\n\n* Confirm that the first and last twenty digits of the answer are:\n\n```\n 62060698786608744707...92256259918212890625\n\n```\n\n* Find and show the number of decimal digits in the answer.\n\nNote:\n\n* Do not submit an *implementation* of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that *may* be used instead.\n* Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the **only** recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.\n\nRelated tasks\n\n* Long multiplication\n* Exponentiation order\n* exponentiation operator\n* Exponentiation with infix operators in (or operating on) the base"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2022.07\n\n```\ngiven [**] 5, 4, 3, 2 {\n use Test;\n ok /^ 62060698786608744707 <digit>* 92256259918212890625 $/,\n '5**4**3**2 has expected first and last twenty digits';\n printf 'This number has %d digits', .chars;\n}\n\n```\n\nOutput:\n\n```\nok 1 - 5**4**3**2 has expected first and last twenty digits\nThis number has 183231 digits\n```"
}
]
|
[
{
"role": "user",
"content": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.\n\nAn Archimedean spiral can be described by the equation:\n\n: r\n =\n a\n +\n b\n θ\n {\\displaystyle {\\displaystyle \\,r=a+b\\theta }}\n\nwith real numbers *a* and *b*.\n\nTask\n\nDraw an Archimedean spiral."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.10\n\n```\nuse Image::PNG::Portable;\n\nmy ($w, $h) = (400, 400);\n\nmy $png = Image::PNG::Portable.new: :width($w), :height($h);\n\n(0, .025 ... 52*π).race.map: -> \\Θ {\n $png.set: |((cis( Θ / π ) * Θ).reals »+« ($w/2, $h/2))».Int, 255, 0, 255;\n}\n\n$png.write: 'Archimedean-spiral-perl6.png';\n\n```"
}
]
|
[
{
"role": "user",
"content": "Dynamically allocated objects take their memory from a heap.\n\nThe memory for an object is provided by an **allocator** which maintains the storage pool used for the heap.\n\nOften a call to allocator is denoted as\n\n```\nP := new T\n\n```\n\nwhere **T** is the type of an allocated object, and **P** is a reference to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n\n* the object type **T**\n* the type of pointer **P**\n\nIn the former case objects can be allocated only in one storage pool.\n\nIn the latter case objects of the type can be allocated in any storage pool or on the stack.\n\nTask\n\nThe task is to show how allocators and user-defined storage pools are supported by the language.\n\nIn particular:\n\n1. define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n2. allocate some objects (e.g., integers) in the pool.\n\nExplain what controls the storage pool choice in the language."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku is a high level language where, to a first approximation, everything is an object. Raku dynamically allocates memory as objects are created and does automatic garbage collection and freeing of memory as objects go out of scope. There is almost no high level control over how memory is managed, it is considered to be an implementation detail of the virtual machine on which it is running.\n\nIf you absolutely must take manual control over memory management you would need to use the foreign function interface to call into a language that provides the capability, but even that would only affect items in the scope of that function, not anything in the mainline process.\n\nThere is some ability to specify data types for various objects which allows for (but does not guarantee) more efficient memory layout, but again, it is considered to be an implementation detail, the use that the virtual machine makes of that information varies by implementation maturity and capabilities."
}
]
|
[
{
"role": "user",
"content": "Arithmetic coding is a form of entropy encoding used in lossless data compression. Normally, a string of characters such as the words \"hello there\" is represented using a fixed number of bits per character, as in the ASCII code. When a string is converted to arithmetic encoding, frequently used characters will be stored with fewer bits and not-so-frequently occurring characters will be stored with more bits, resulting in fewer bits used in total. Arithmetic coding differs from other forms of entropy encoding, such as Huffman coding, in that rather than separating the input into component symbols and replacing each with a code, arithmetic coding encodes the entire message into a single number.\n\nTask\n\nCreate a program which implements the arithmetic coding as a generalized change of radix.\n\nShow the results, in base 10, for all the following strings:\n\n* \"DABDDB\"\n* \"DABDDBBDDBA\"\n* \"ABRACADABRA\"\n* \"TOBEORNOTTOBEORTOBEORNOT\"\n\nVerify the implementation by decoding the results back into strings and checking for equality with the given strings."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub cumulative_freq(%freq) {\n my %cf;\n my $total = 0;\n for %freq.keys.sort -> $c {\n %cf{$c} = $total;\n $total += %freq{$c};\n }\n return %cf;\n}\n\nsub arithmethic_coding($str, $radix) {\n my @chars = $str.comb;\n\n # The frequency characters\n my %freq;\n %freq{$_}++ for @chars;\n\n # The cumulative frequency table\n my %cf = cumulative_freq(%freq);\n\n # Base\n my $base = @chars.elems;\n\n # Lower bound\n my $L = 0;\n\n # Product of all frequencies\n my $pf = 1;\n\n # Each term is multiplied by the product of the\n # frequencies of all previously occurring symbols\n for @chars -> $c {\n $L = $L*$base + %cf{$c}*$pf;\n $pf *= %freq{$c};\n }\n\n # Upper bound\n my $U = $L + $pf;\n\n my $pow = 0;\n loop {\n $pf div= $radix;\n last if $pf == 0;\n ++$pow;\n }\n\n my $enc = ($U - 1) div ($radix ** $pow);\n ($enc, $pow, %freq);\n}\n\nsub arithmethic_decoding($encoding, $radix, $pow, %freq) {\n\n # Multiply encoding by radix^pow\n my $enc = $encoding * $radix**$pow;\n\n # Base\n my $base = [+] %freq.values;\n\n # Create the cumulative frequency table\n my %cf = cumulative_freq(%freq);\n\n # Create the dictionary\n my %dict;\n for %cf.kv -> $k,$v {\n %dict{$v} = $k;\n }\n\n # Fill the gaps in the dictionary\n my $lchar;\n for ^$base -> $i {\n if (%dict{$i}:exists) {\n $lchar = %dict{$i};\n }\n elsif (defined $lchar) {\n %dict{$i} = $lchar;\n }\n }\n\n # Decode the input number\n my $decoded = '';\n for reverse(^$base) -> $i {\n\n my $pow = $base**$i;\n my $div = $enc div $pow;\n\n my $c = %dict{$div};\n my $fv = %freq{$c};\n my $cv = %cf{$c};\n\n my $rem = ($enc - $pow*$cv) div $fv;\n\n $enc = $rem;\n $decoded ~= $c;\n }\n\n # Return the decoded output\n return $decoded;\n}\n\nmy $radix = 10; # can be any integer greater or equal with 2\n\nfor <DABDDB DABDDBBDDBA ABRACADABRA TOBEORNOTTOBEORTOBEORNOT> -> $str {\n my ($enc, $pow, %freq) = arithmethic_coding($str, $radix);\n my $dec = arithmethic_decoding($enc, $radix, $pow, %freq);\n\n printf(\"%-25s=> %19s * %d^%s\\n\", $str, $enc, $radix, $pow);\n\n if ($str ne $dec) {\n die \"\\tHowever that is incorrect!\";\n }\n}\n\n```\n\nOutput:\n\n```\nDABDDB => 251 * 10^2\nDABDDBBDDBA => 167351 * 10^6\nABRACADABRA => 7954170 * 10^4\nTOBEORNOTTOBEORTOBEORNOT => 1150764267498783364 * 10^15\n\n```"
}
]
|
[
{
"role": "user",
"content": "The **arithmetic derivative** of an integer (more specifically, the\n**Lagarias arithmetic derivative**) is a function defined for integers, based on prime\nfactorization, by analogy with the product rule for the derivative of a function that is\nused in mathematical analysis. Accordingly, for natural numbers n, the arithmetic\nderivative D(n) is defined as follows:\n\n* D ( 0 ) = D ( 1 ) = 0 {\\displaystyle {\\displaystyle D(0)=D(1)=0}} . * D ( p ) = 1 for any prime p {\\displaystyle {\\displaystyle D(p)=1\\;{\\text{for any prime}}\\;p}} . * D ( m n ) = D ( m ) n + m D ( n ) for any m , n ∈ N {\\displaystyle {\\displaystyle D(mn)=D(m)n+mD(n)\\;{\\text{for any}}\\;m,n\\in N}} . (Leibniz rule for derivatives).\n\nAdditionally, for negative integers the arithmetic derivative may be defined as \n\n−\nD\n(\n−\nn\n)\n\n\nfor\n\n(\nn\n<\n0\n)\n{\\displaystyle {\\displaystyle -D(-n)\\;{\\text{for}}\\;(n<0)}}\n.\n\nExamples\n\nD\n(\n2\n)\n=\n1\n{\\displaystyle {\\displaystyle D(2)=1}}\n and \n\nD\n(\n3\n)\n=\n1\n{\\displaystyle {\\displaystyle D(3)=1}}\n (both are prime) so if \n\nm\nn\n=\n2\n⋅\n3\n{\\displaystyle {\\displaystyle mn=2\\cdot 3}}\n, then \n\nD\n(\n6\n)\n=\nD\n(\n2\n⋅\n3\n)\n=\nD\n(\n2\n)\n⋅\n3\n+\n2\n⋅\nD\n(\n3\n)\n=\n1\n⋅\n3\n+\n2\n⋅\n1\n=\n5\n{\\displaystyle {\\displaystyle D(6)=D(2\\cdot 3)=D(2)\\cdot 3+2\\cdot D(3)=1\\cdot 3+2\\cdot 1=5}}\n.\n\nD\n(\n9\n)\n=\nD\n(\n3\n)\n⋅\n3\n+\n3\n⋅\nD\n(\n3\n)\n=\n1\n⋅\n3\n+\n3\n⋅\n1\n=\n6\n{\\displaystyle {\\displaystyle D(9)=D(3)\\cdot 3+3\\cdot D(3)=1\\cdot 3+3\\cdot 1=6}}\n\nD\n(\n27\n)\n=\nD\n(\n3\n)\n⋅\n9\n+\n3\n⋅\nD\n(\n9\n)\n=\n1\n⋅\n9\n+\n3\n⋅\n6\n=\n27\n{\\displaystyle {\\displaystyle D(27)=D(3)\\cdot 9+3\\cdot D(9)=1\\cdot 9+3\\cdot 6=27}}\n\nD\n(\n30\n)\n=\nD\n(\n5\n)\n⋅\n6\n+\n5\n⋅\nD\n(\n6\n)\n=\n1\n⋅\n6\n+\n5\n⋅\n5\n=\n31\n{\\displaystyle {\\displaystyle D(30)=D(5)\\cdot 6+5\\cdot D(6)=1\\cdot 6+5\\cdot 5=31}}\n.\n\nTask\n\nFind and show the arithmetic derivatives for -99 through 100.\n\nStretch task\n\nFind (the arithmetic derivative of \n\n10\n\nm\n{\\displaystyle {\\displaystyle 10^{m}}}\n) then divided by 7, where m is from 1 to 20.\n\nSee also\n\n* OEIS:A003415 - a(n) = n' = arithmetic derivative of n. * Wikipedia: Arithmetic Derivative"
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor;\n\nmulti D (0) { 0 }\nmulti D (1) { 0 }\nmulti D ($n where &is-prime) { 1 }\nmulti D ($n where * < 0 ) { -D -$n }\nmulti D ($n) { sum $n.&prime-factors.Bag.map: { $n × .value / .key } }\n\n\nput (-99 .. 100).map(&D).batch(10)».fmt(\"%4d\").join: \"\\n\";\n\nput '';\n\nput join \"\\n\", (1..20).map: { sprintf \"D(10**%-2d) / 7 == %d\", $_, D(10**$_) / 7 }\n\n```\n\nOutput:\n\n```\n -75 -77 -1 -272 -24 -49 -34 -96 -20 -123\n -1 -140 -32 -45 -22 -124 -1 -43 -108 -176\n -1 -71 -18 -80 -55 -39 -1 -156 -1 -59\n -26 -72 -1 -61 -18 -192 -51 -33 -1 -92\n -1 -31 -22 -92 -16 -81 -1 -56 -20 -45\n -14 -112 -1 -25 -39 -48 -1 -41 -1 -68\n -16 -21 -1 -60 -12 -19 -14 -80 -1 -31\n -1 -32 -27 -15 -10 -44 -1 -13 -10 -24\n -1 -21 -1 -32 -8 -9 -1 -16 -1 -7\n -6 -12 -1 -5 -1 -4 -1 -1 0 0\n 0 1 1 4 1 5 1 12 6 7\n 1 16 1 9 8 32 1 21 1 24\n 10 13 1 44 10 15 27 32 1 31\n 1 80 14 19 12 60 1 21 16 68\n 1 41 1 48 39 25 1 112 14 45\n 20 56 1 81 16 92 22 31 1 92\n 1 33 51 192 18 61 1 72 26 59\n 1 156 1 39 55 80 18 71 1 176\n 108 43 1 124 22 45 32 140 1 123\n 20 96 34 49 24 272 1 77 75 140\n\nD(10**1 ) / 7 == 1\nD(10**2 ) / 7 == 20\nD(10**3 ) / 7 == 300\nD(10**4 ) / 7 == 4000\nD(10**5 ) / 7 == 50000\nD(10**6 ) / 7 == 600000\nD(10**7 ) / 7 == 7000000\nD(10**8 ) / 7 == 80000000\nD(10**9 ) / 7 == 900000000\nD(10**10) / 7 == 10000000000\nD(10**11) / 7 == 110000000000\nD(10**12) / 7 == 1200000000000\nD(10**13) / 7 == 13000000000000\nD(10**14) / 7 == 140000000000000\nD(10**15) / 7 == 1500000000000000\nD(10**16) / 7 == 16000000000000000\nD(10**17) / 7 == 170000000000000000\nD(10**18) / 7 == 1800000000000000000\nD(10**19) / 7 == 19000000000000000000\nD(10**20) / 7 == 200000000000000000000\n```"
}
]
|
[
{
"role": "user",
"content": "Create a program which parses and evaluates arithmetic expressions.\n\nRequirements\n\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input.\n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)\n* The expression will be a string or list of symbols like \"(1+3)\\*7\".\n* The four symbols + - \\* / must be supported as binary operators with conventional precedence rules.\n* Precedence-control parentheses must also be supported.\n\nNote\n\nFor those who don't remember, mathematical precedence is as follows:\n\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\nC.f\n\n* 24 game Player.\n* Parsing/RPN calculator algorithm.\n* Parsing/RPN to infix conversion."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nsub ev (Str $s --> Numeric) {\n\n grammar expr {\n token TOP { ^ <sum> $ }\n token sum { <product> (('+' || '-') <product>)* }\n token product { <factor> (('*' || '/') <factor>)* }\n token factor { <unary_minus>? [ <parens> || <literal> ] }\n token unary_minus { '-' }\n token parens { '(' <sum> ')' }\n token literal { \\d+ ['.' \\d+]? || '.' \\d+ }\n }\n \n my sub minus ($b) { $b ?? -1 !! +1 }\n\n my sub sum ($x) {\n [+] flat product($x<product>), map\n { minus($^y[0] eq '-') * product $^y<product> },\n |($x[0] or [])\n }\n \n my sub product ($x) {\n [*] flat factor($x<factor>), map\n { factor($^y<factor>) ** minus($^y[0] eq '/') },\n |($x[0] or [])\n }\n \n my sub factor ($x) {\n minus($x<unary_minus>) * ($x<parens>\n ?? sum $x<parens><sum>\n !! $x<literal>)\n }\n\n expr.parse([~] split /\\s+/, $s);\n $/ or fail 'No parse.';\n sum $/<sum>;\n\n}\n\n# Testing:\n\nsay ev '5'; # 5\nsay ev '1 + 2 - 3 * 4 / 5'; # 0.6\nsay ev '1 + 5*3.4 - .5 -4 / -2 * (3+4) -6'; # 25.5\nsay ev '((11+15)*15)* 2 + (3) * -4 *1'; # 768\n\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nA positive integer **n** is an arithmetic number if the average of its positive divisors is also an integer.\n\nClearly all odd primes **p** must be arithmetic numbers because their only divisors are **1** and **p** whose sum is even and hence their average must be an integer. However, the prime number **2** is not an arithmetic number because the average of its divisors is 1.5.\n\nExample\n\n30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer.\n\nTask\n\nCalculate and show here:\n\n1. The first 100 arithmetic numbers.\n\n2. The **x**th arithmetic number where **x** = 1,000 and **x** = 10,000.\n\n3. How many of the first **x** arithmetic numbers are composite.\n\nNote that, technically, the arithmetic number **1** is neither prime nor composite.\n\nStretch\n\nCarry out the same exercise in 2. and 3. above for **x** = 100,000 and **x** = 1,000,000.\n\nReferences\n\n* Wikipedia: Arithmetic number\n* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer"
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor;\nuse Lingua::EN::Numbers;\n\nmy @arithmetic = lazy (1..∞).hyper.grep: { my @div = .&divisors; @div.sum %% @div }\n\nsay \"The first { .Int.&cardinal } arithmetic numbers:\\n\", @arithmetic[^$_].batch(10)».fmt(\"%{.chars}d\").join: \"\\n\" given 1e2;\n\nfor 1e3, 1e4, 1e5, 1e6 {\n say \"\\nThe { .Int.&ordinal }: { comma @arithmetic[$_-1] }\";\n say \"Composite arithmetic numbers ≤ { comma @arithmetic[$_-1] }: { comma +@arithmetic[^$_].grep({!.is-prime}) - 1 }\";\n}\n\n```\n\n```\nThe first one hundred arithmetic numbers:\n 1 3 5 6 7 11 13 14 15 17\n 19 20 21 22 23 27 29 30 31 33\n 35 37 38 39 41 42 43 44 45 46\n 47 49 51 53 54 55 56 57 59 60\n 61 62 65 66 67 68 69 70 71 73\n 77 78 79 83 85 86 87 89 91 92\n 93 94 95 96 97 99 101 102 103 105\n107 109 110 111 113 114 115 116 118 119\n123 125 126 127 129 131 132 133 134 135\n137 138 139 140 141 142 143 145 147 149\n\nThe one thousandth: 1,361\nComposite arithmetic numbers ≤ 1,361: 782\n\nThe ten thousandth: 12,953\nComposite arithmetic numbers ≤ 12,953: 8,458\n\nThe one hundred thousandth: 125,587\nComposite arithmetic numbers ≤ 125,587: 88,219\n\nThe one millionth: 1,228,663\nComposite arithmetic numbers ≤ 1,228,663: 905,043\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nTask\n\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \n\na\ng\nm\n(\na\n,\ng\n)\n{\\displaystyle {\\displaystyle \\mathrm {agm} (a,g)}}\n, and is equal to the limit of the sequence:\n\n: a\n\n 0\n =\n a\n ;\n\n\n g\n\n 0\n =\n g\n {\\displaystyle {\\displaystyle a\\_{0}=a;\\qquad g\\_{0}=g}}\n: a\n\n n\n +\n 1\n =\n\n 1\n 2\n (\n\n a\n\n n\n +\n\n g\n\n n\n )\n ;\n\n\n g\n\n n\n +\n 1\n =\n\n a\n\n n\n\n g\n\n n\n .\n {\\displaystyle {\\displaystyle a\\_{n+1}={\\tfrac {1}{2}}(a\\_{n}+g\\_{n});\\quad g\\_{n+1}={\\sqrt {a\\_{n}g\\_{n}}}.}}\n\nSince the limit of \n\na\n\nn\n−\n\ng\n\nn\n{\\displaystyle {\\displaystyle a\\_{n}-g\\_{n}}}\n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n\n: a\n g\n m\n (\n 1\n ,\n 1\n\n /\n\n\n 2\n )\n {\\displaystyle {\\displaystyle \\mathrm {agm} (1,1/{\\sqrt {2}})}}\n\nAlso see\n\n* mathworld.wolfram.com/Arithmetic-Geometric Mean"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub agm( $a is copy, $g is copy ) {\n ($a, $g) = ($a + $g)/2, sqrt $a * $g until $a ≅ $g;\n return $a;\n}\n \nsay agm 1, 1/sqrt 2;\n```\n\nOutput:\n\n```\n0.84721308479397917\n```\n\nIt's also possible to write it recursively:\n\n```\nsub agm( $a, $g ) {\n $a ≅ $g ?? $a !! agm(|@$_)\n given ($a + $g)/2, sqrt $a * $g;\n}\n\nsay agm 1, 1/sqrt 2;\n```\n\nWe can also get a bit fancy and use a converging sequence of complex numbers:\n\n```\nsub agm {\n ($^z, {(.re+.im)/2 + (.re*.im).sqrt*1i} ... * ≅ *)\n .tail.re\n}\n \nsay agm 1 + 1i/2.sqrt\n```"
}
]
|
[
{
"role": "user",
"content": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \n\nπ\n{\\displaystyle {\\displaystyle \\pi }}\n.\n\nWith the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:\n\nπ\n=\n\n4\n\n\na\ng\nm\n(\n1\n,\n1\n\n/\n\n\n2\n\n)\n\n2\n\n1\n−\n\n∑\n\nn\n=\n1\n\n∞\n\n2\n\nn\n+\n1\n(\n\na\n\nn\n\n2\n−\n\ng\n\nn\n\n2\n)\n{\\displaystyle {\\displaystyle \\pi ={\\frac {4\\;\\mathrm {agm} (1,1/{\\sqrt {2}})^{2}}{1-\\sum \\limits \\_{n=1}^{\\infty }2^{n+1}(a\\_{n}^{2}-g\\_{n}^{2})}}}}\n\nThis allows you to make the approximation, for any large **N**:\n\nπ\n≈\n\n4\n\n\na\n\nN\n\n2\n\n1\n−\n\n∑\n\nk\n=\n1\n\nN\n\n2\n\nk\n+\n1\n(\n\na\n\nk\n\n2\n−\n\ng\n\nk\n\n2\n)\n{\\displaystyle {\\displaystyle \\pi \\approx {\\frac {4\\;a\\_{N}^{2}}{1-\\sum \\limits \\_{k=1}^{N}2^{k+1}(a\\_{k}^{2}-g\\_{k}^{2})}}}}\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \n\nπ\n{\\displaystyle {\\displaystyle \\pi }}\n."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Ruby\n\nThere is not yet a FixDecimal type module in Raku, and using FatRat all along would be too slow and would be coerced to Num when computing the square root anyway, so we'll use a custom definition of the square root for Int and FatRat, with a limitation to the number of decimals. We'll show all the intermediate results.\n\nThe trick to compute the square root of a rational \n\nn\nd\n{\\displaystyle {\\displaystyle n \\over d}}\n up to a certain amount of decimals N is to write:\n\nn\nd\n=\n\nn\n\n10\n\n2\nN\n\n/\nd\n\nd\n\n10\n\n2\nN\n\n/\nd\n=\n\nn\n\n10\n\n2\nN\n\n/\nd\n\n10\n\nN\n{\\displaystyle {\\displaystyle {\\sqrt {\\frac {n}{d}}}={\\sqrt {\\frac {n10^{2N}/d}{d10^{2N}/d}}}={\\frac {\\sqrt {n10^{2N}/d}}{10^{N}}}}}\n\nso that what we need is one square root of a big number that we'll truncate to its integer part. We'll use the method described in Integer roots to compute the square root of this big integer.\n\nNotice that we don't get the exact number of decimals required : the last two decimals or so can be wrong. This is because we don't need \n\na\n\nn\n{\\displaystyle {\\displaystyle a\\_{n}}}\n, but rather \n\na\n\nn\n\n2\n{\\displaystyle {\\displaystyle a\\_{n}^{2}}}\n. Elevating to the square makes us lose a bit of precision. It could be compensated by choosing a slightly higher value of N (in a way that could be precisely calculated), but that would probably be overkill.\n\n```\nconstant number-of-decimals = 100;\n\nmulti sqrt(Int $n) {\n (10**($n.chars div 2), { ($_ + $n div $_) div 2 } ... * == *).tail\n}\n\nmulti sqrt(FatRat $r --> FatRat) {\n return FatRat.new:\n sqrt($r.numerator * 10**(number-of-decimals*2) div $r.denominator),\n 10**number-of-decimals;\n}\n\nmy FatRat ($a, $n) = 1.FatRat xx 2;\nmy FatRat $g = sqrt(1/2.FatRat);\nmy $z = .25;\n\nfor ^10 {\n given [ ($a + $g)/2, sqrt($a * $g) ] {\n $z -= (.[0] - $a)**2 * $n;\n $n += $n;\n ($a, $g) = @$_;\n say ($a ** 2 / $z).substr: 0, 2 + number-of-decimals;\n }\n}\n\n```\n\nOutput:\n\n```\n3.1876726427121086272019299705253692326510535718593692264876339862751228325281223301147286106601617972\n3.1416802932976532939180704245600093827957194388154028326441894631956630010102553193888894275152646100\n3.1415926538954464960029147588180434861088792372613115896511013576846530795030865017740975862898631567\n3.1415926535897932384663606027066313217577024113424293564868460152384109486069277582680622007332762125\n3.1415926535897932384626433832795028841971699491647266058346961259487480060953290058518515759317101932\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280468522286541140\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170668\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170665\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170664\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170663\n\n```"
}
]
|
[
{
"role": "user",
"content": "A **complex number** is a number which can be written as:\n\na\n+\nb\n×\ni\n{\\displaystyle {\\displaystyle a+b\\times i}}\n(sometimes shown as:\n\nb\n+\na\n×\ni\n{\\displaystyle {\\displaystyle b+a\\times i}}\nwhere \n\na\n{\\displaystyle {\\displaystyle a}}\n and \n\nb\n{\\displaystyle {\\displaystyle b}}\n are real numbers, and \ni\n{\\displaystyle {\\displaystyle i}}\n is √ -1 \n\nTypically, complex numbers are represented as a pair of real numbers called the \"imaginary part\" and \"real part\", where the imaginary part is the number to be multiplied by \n\ni\n{\\displaystyle {\\displaystyle i}}\n.\n\nTask\n\n* Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)\n* Print the results for each operation tested.\n* *Optional:* Show complex conjugation.\n\nBy definition, the complex conjugate of\n\na\n+\nb\ni\n{\\displaystyle {\\displaystyle a+bi}}\nis\n\na\n−\nb\ni\n{\\displaystyle {\\displaystyle a-bi}}\n\nSome languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy $a = 1 + i;\nmy $b = pi + 1.25i;\n\n.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj;\n.say for $a.abs, $a.sqrt, $a.re, $a.im;\n\n```\n\nOutput:\n\n(precision varies with different implementations)\n\n```\n4.1415926535897931+2.25i\n1.8915926535897931+4.3915926535897931i\n-1-1i\n0.5-0.5i\n1-1i\n1.4142135623730951\n1.0986841134678098+0.45508986056222733i\n1\n1\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGet two integers from the user, and then (for those two integers), display their:\n\n: : : : * sum\n * difference\n * product\n * integer quotient\n * remainder\n * exponentiation (if the operator exists)\n\nDon't include error handling.\n\nFor quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).\n\nFor remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.\n\nBonus: Include an example of the integer `divmod` operator. For example: as in #Haskell, #Python and #ALGOL 68"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nNote that `div` **requires** integer arguments. If you want integer division with other types, say `floor($a/$b)`.\n\n```\nmy Int $a = get.floor;\nmy Int $b = get.floor;\n\nsay 'sum: ', $a + $b;\nsay 'difference: ', $a - $b;\nsay 'product: ', $a * $b;\nsay 'integer quotient: ', $a div $b;\nsay 'remainder: ', $a % $b;\nsay 'exponentiation: ', $a**$b;\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.\n\nExample\n\nDefine a new type called **frac** with binary operator \"//\" of two integers that returns a **structure** made up of the numerator and the denominator (as per a rational number).\n\nFurther define the appropriate rational unary **operators** **abs** and '-', with the binary **operators** for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').\n\nDefine standard coercion **operators** for casting **int** to **frac** etc.\n\nIf space allows, define standard increment and decrement **operators** (e.g. '+:=' & '-:=' etc.).\n\nFinally test the operators:\nUse the new type **frac** to find all perfect numbers less than 219 by summing the reciprocal of the factors.\n\nRelated tasks\n\n* Perfect Numbers\n* Check Machin-like formulas"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.08\n\nRaku supports rational arithmetic natively.\n\n```\n(2..2**19).hyper.map: -> $candidate {\n my $sum = 1 / $candidate;\n for 2 .. ceiling(sqrt($candidate)) -> $factor {\n if $candidate %% $factor {\n $sum += 1 / $factor + 1 / ($candidate / $factor);\n }\n }\n if $sum.nude[1] == 1 {\n say \"Sum of reciprocal factors of $candidate = $sum exactly\", ($sum == 1 ?? \", perfect!\" !! \".\");\n }\n}\n\n```\n\nNote also that ordinary decimal literals are stored as Rats, so the following loop always stops exactly on 10 despite 0.1 not being exactly representable in floating point:\n\n```\nfor 1.0, 1.1, 1.2 ... 10 { .say }\n\n```\n\nThe arithmetic is all done in rationals, which are converted to floating-point just before display so that people don't have to puzzle out what 53/10 means."
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow how to concatenate two arrays in your language.\n\nIf this is as simple as `array1 + array2`, so be it."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\n```\nmy @array1 = 1, 2, 3;\nmy @array2 = 4, 5, 6;\n\n# If you want to concatenate two array to form a third,\n# either use the slip operator \"|\", to flatten each array.\n\nmy @array3 = |@array1, |@array2;\nsay @array3;\n\n# or just flatten both arrays in one fell swoop\n\n@array3 = flat @array1, @array2;\nsay @array3;\n\n# On the other hand, if you just want to add the elements\n# of the second array to the first, use the .append method.\n\nsay @array1.append: @array2;\n```\n\nOutput:\n\n```\n[1 2 3 4 5 6]\n[1 2 3 4 5 6]\n[1 2 3 4 5 6]\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDetermine the number of elements in an array.\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.04\n\nTo get the number of elements of an array in Raku you put the array in a coercing Numeric context, or call `elems` on it.\n\n```\nmy @array = <apple orange>;\n\nsay @array.elems; # 2\nsay elems @array; # 2\nsay + @array; # 2\nsay @array + 0; # 2\n```\n\nWatch out for infinite/lazy arrays though. You can't get the length of those.\n\n```\nmy @infinite = 1 .. Inf; # 1, 2, 3, 4, ...\n\nsay @infinite[5000]; # 5001\nsay @infinite.elems; # Throws exception \"Cannot .elems a lazy list\"\n```"
}
]
|
[
{
"role": "user",
"content": "This task is about arrays.\n\nFor hashes or associative arrays, please see Creating an Associative Array.\n\nFor a definition and in-depth discussion of what an array is, see Array.\n\nTask\n\nShow basic array syntax in your language.\n\nBasically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and\ndynamic arrays, pushing a value into it).\n\nPlease discuss at Village Pump: Arrays.\n\nPlease merge code in from these obsolete tasks:\n\n: : : * Creating an Array\n * Assigning Values to an Array\n * Retrieving an Element of an Array\n\nRelated tasks\n\n* Collections\n* Creating an Associative Array\n* Two-dimensional array (runtime)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nAt its most basic, an array in Raku is quite similar to an array in Perl 5.\n\n```\nmy @arr;\n \npush @arr, 1;\npush @arr, 3;\n \n@arr[0] = 2;\n \nsay @arr[0];\n```\n\n### Some further exposition:\n\nIn Raku, arrays have a very specific definition: \"A collection of Scalar containers that do the Positional Role.\" Scalar container means it is mutable and may contain any object; an Integer, a Rational number, a String, another Array, whatever... literally any other object that can be instantiated in Raku. The Positional Role means that it uses integer indexing for access. The index must be a positive integer, an expression that evaluates to a positive integer, or something that can be coerced to a positive integer. Arrays are always indexed from 0. The starting index can not be changed.\n\nArrays are unconstrained by default. They may hold any number of any type of object up to available memory. They do not need to be pre-allocated. Simply assigning (or even referring in some cases) to an index slot is enough to autovivify the container and allocate enough memory to hold the assigned object. Memory will automatically be allocated and will grow and shrink as necessary to hold the values assigned.\n\nValues may be pushed onto the end of an array, popped off of the end, shifted off of the front or unshifted onto the front, and spliced into or out of the interior.\n\n```\n @array.push: 'value';\n my $value = @array.pop;\n @array.unshift: 'value';\n my $value = @array.shift;\n @array.splice(2,3, <some arbitrary string values>);\n\n```\n\nArrays may be constrained to only accept a certain number of objects or only a certain type of object.\n\n```\n my Int @array; # can only hold Integer objects. Assigning any other type will cause an exception.\n my @array[9]; # can only 10 objects (zero indexed). Trying to assign to an index greater than 9 with cause an exception. \n\n```\n\nArrays are constructed with square brackets, an explicit constructor, or by coercing some other object either explicitly using a coercer or implicitly by simply assigning to an array variable. These are all arrays:\n\n```\n [1, 2, 3, 4]\n ['a', 'b', 'c', 'd']\n Array.new<this is an array of words>\n ('as', 'is', 'this').Array\n my @implicit = <yep, this too>\n\n```\n\nArray variables in Raku are variables whose names bear the @ sigil, and are expected to contain some sort of list-like object. Of course, other variables may also contain these objects, but @-sigiled variables always do, and are expected to act the part. Array storage slots are accessed through postcircumfix square bracket notation. Unlike Perl 5, @-sigiled variables are invariant on access, whether you are accessing one slot, many slots, or all of the slots. The first slot in @array is @array[0] not $array[0]. @array and $array are two different unconnected variables.\n\n```\n @array[1] # a single value in the 2nd slot\n @array[*-1] # a single value in the last slot\n @array[1..5] # an array slice, 2nd through 6th slots\n @array[1,3,7] # slice, 2nd, 4th and 8th slot\n @array[8,5,2] # can be in any order\n @array[*] # all the slots\n @array[] # all the slots (zen slice)\n @array[^10] # first 10 slots (upto 10 or 0..9)\n @array.head(5) # first 5 slots\n @array.tail(2) # last two\n\n```\n\nMulti-dimensioned arrays also use postcircumfix square brackets for access. If the array is not ragged, (every sub array is the same size) you may use semicolon subscripting.\n\n```\n @array[1][1] # 2nd item in the second slot\n @array[1;1] # same thing, implies rectangular (non-ragged) arrays\n\n```\n\nThere are several objects that have an Iterable Role and a PositionalBindFailover Role which makes them act similar to arrays and allows them to be used nearly interchangeably in read-only applications. (Raku is big on duck typing. \"If it looks like a duck and quacks like a duck and waddles like a duck, it's a duck.\") These constructs are ordered and use integer indexing and are often used in similar circumstances as arrays, however, **they are immutable**. Values in slots can not be changed. They can not be pushed to, popped from or spliced. They can easily converted to arrays by simply assigning them to an array variable.\n\n**List**: A fixed Iterable collection of immutable values. Lists are constructed similarly to arrays:\n\n```\n (1, 2, 3, 4)\n ('a', 'b', 'c', 'd')\n List.new(<this is a list of words>)\n ('as', 'is', 'this').List\n my @not-a-list = (<oops, this isn't>)\n my @implicit := (<but this is>) # note the values are bound := not assigned =\n\n```\n\n**Range**: Iterable list of consecutive numbers or strings with a lower and an upper boundary. (That boundary may be infinite.) Reified on demand.\n\n```\n 2..20 # integers two through twenty\n 1..Inf # natural numbers\n 'a'..'z' # lowercase latin letters\n\n```\n\n**Sequence**: Iterable list of objects with some method to determine the next (or previous) item in the list. Reified on demand. Will try to automatically deduce simple arithmetic or geometric sequences. Pass in a code object to calculate more complex sequences.\n\n```\n 0,2,4 ... 64 # even numbers up to 64\n 1,2,4 ... 64 # geometric increase\n 1,1, *+* ... * # infinite Fibonacci sequence\n 1,1,{$^n2 + $^n1 + 1} ... * # infinite Leonardo numbers\n\n```\n\nPostcircumfix indexing works for any object that has a Positional (or PositionalBindFailover) role, it need not be in a @-sigiled variable, or indeed, in a variable at all.\n\n```\n [2,4,6,8,10][1] # 4 - anonymous array\n <my dog has fleas>[*-2] # 'has' - anonymous list\n sub a {(^Inf).grep: *.is-prime}; a()[99]; # 541 - (100th prime) subroutine returning a sequence\n my $lol = ((1,2), (3,4), (5,6)); $lol[1]; # (3 4) - list of lists in a Scalar variable\n\n```"
}
]
|
[
{
"role": "user",
"content": "Generate and show all primes with strictly ascending decimal digits.\n\nAside: Try solving without peeking at existing solutions. I had a weird idea for generating\na prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial\nbut generating them quickly is at least mildly interesting.\nTip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is\nat least one significantly better and much faster way, needing a mere 511 odd/prime tests.\n\nSee also\n\n* OEIS:A052015 - Primes with distinct digits in ascending order\n\nRelated\n\n* Primes with digits in nondecreasing order (infinite series allowing duplicate digits, whereas this isn't and doesn't)\n* Pandigital prime (whereas this is the smallest, with gaps in the used digits being permitted)\n* Descending primes"
},
{
"role": "assistant",
"content": "```\nput (flat 2, 3, 5, 7, sort +*, gather (1..8).map: &recurse ).batch(10)».fmt(\"%8d\").join: \"\\n\";\n\nsub recurse ($str) {\n .take for ($str X~ (3, 7, 9)).grep: { .is-prime && [<] .comb };\n recurse $str × 10 + $_ for $str % 10 ^.. 9;\n}\n\nprintf \"%.3f seconds\", now - INIT now;\n\n```\n\nOutput:\n\n```\n 2 3 5 7 13 17 19 23 29 37\n 47 59 67 79 89 127 137 139 149 157\n 167 179 239 257 269 347 349 359 367 379\n 389 457 467 479 569 1237 1249 1259 1279 1289\n 1367 1459 1489 1567 1579 1789 2347 2357 2389 2459\n 2467 2579 2689 2789 3457 3467 3469 4567 4679 4789\n 5689 12347 12379 12457 12479 12569 12589 12689 13457 13469\n 13567 13679 13789 15679 23459 23567 23689 23789 25679 34589\n 34679 123457 123479 124567 124679 125789 134789 145679 234589 235679\n 235789 245789 345679 345689 1234789 1235789 1245689 1456789 12356789 23456789\n0.075 seconds\n```"
}
]
|
[
{
"role": "user",
"content": "Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:\nhttp://www.ietf.org/rfc/rfc1035.txt\n\n```\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ID |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n|QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| QDCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ANCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| NSCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n| ARCOUNT |\n+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\n```\n\nWhere (every column of the table is 1 bit):\n\n```\nID is 16 bits\nQR = Query (0) or Response (1)\nOpcode = Four bits defining kind of query:\n 0: a standard query (QUERY)\n 1: an inverse query (IQUERY)\n 2: a server status request (STATUS)\n 3-15: reserved for future use\nAA = Authoritative Answer bit\nTC = Truncation bit\nRD = Recursion Desired bit\nRA = Recursion Available bit\nZ = Reserved\nRCODE = Response code\nQC = Question Count\nANC = Answer Count\nAUC = Authority Count\nADC = Additional Count\n\n```\n\nWrite a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.\n\nIf your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.\n\nSuch \"Header\" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars \"+--+\". The code should perform a little of validation of the input string, but for brevity a full validation is not required.\n\nBonus: perform a thoroughly validation of the input string."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\n```\ngrammar RFC1025 {\n rule TOP { <.line-separator> [<line> <.line-separator>]+ }\n rule line-separator { <.ws> '+--'+ '+' }\n token line { <.ws> '|' +%% <field> }\n token field { \\s* <label> \\s* }\n token label { \\w+[\\s+\\w+]* }\n}\n\nsub bits ($item) { ($item.chars + 1) div 3 }\n\nsub deconstruct ($bits, %struct) {\n map { $bits.substr(.<from>, .<bits>) }, @(%struct<fields>);\n}\n\nsub interpret ($header) {\n my $datagram = RFC1025.parse($header);\n my %struct;\n for $datagram.<line> -> $line {\n FIRST %struct<line-width> = $line.&bits;\n state $from = 0;\n %struct<fields>.push: %(:bits(.&bits), :ID(.<label>.Str), :from($from.clone), :to(($from+=.&bits)-1))\n for $line<field>;\n }\n %struct\n}\n\nuse experimental :pack;\n\nmy $diagram = q:to/END/;\n\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ID |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | QDCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ANCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | NSCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n | ARCOUNT |\n +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n\nEND\n\nmy %structure = interpret($diagram);\n\nsay 'Line width: ', %structure<line-width>, ' bits';\nprintf(\"Name: %7s, bit count: %2d, bit %2d to bit %2d\\n\", .<ID>, .<bits>, .<from>, .<to>) for @(%structure<fields>);\nsay \"\\nGenerate a random 12 byte \\\"header\\\"\";\nsay my $buf = Buf.new((^0xFF .roll) xx 12);\nsay \"\\nShow it converted to a bit string\";\nsay my $bitstr = $buf.unpack('C*')».fmt(\"%08b\").join;\nsay \"\\nAnd unpack it\";\nprintf(\"%7s, %02d bits: %s\\n\", %structure<fields>[$_]<ID>, %structure<fields>[$_]<bits>,\n deconstruct($bitstr, %structure)[$_]) for ^@(%structure<fields>);\n\n```\n\nOutput:\n\n```\nLine width: 16 bits\nName: ID, bit count: 16, bit 0 to bit 15\nName: QR, bit count: 1, bit 16 to bit 16\nName: Opcode, bit count: 4, bit 17 to bit 20\nName: AA, bit count: 1, bit 21 to bit 21\nName: TC, bit count: 1, bit 22 to bit 22\nName: RD, bit count: 1, bit 23 to bit 23\nName: RA, bit count: 1, bit 24 to bit 24\nName: Z, bit count: 3, bit 25 to bit 27\nName: RCODE, bit count: 4, bit 28 to bit 31\nName: QDCOUNT, bit count: 16, bit 32 to bit 47\nName: ANCOUNT, bit count: 16, bit 48 to bit 63\nName: NSCOUNT, bit count: 16, bit 64 to bit 79\nName: ARCOUNT, bit count: 16, bit 80 to bit 95\n\nGenerate a random 12 byte \"header\"\nBuf:0x<78 47 7b bf 54 96 e1 2e 1b f1 69 a4>\n\nShow it converted to a bit string\n011110000100011101111011101111110101010010010110111000010010111000011011111100010110100110100100\n\nAnd unpack it\n ID, 16 bits: 0111100001000111\n QR, 01 bits: 0\n Opcode, 04 bits: 1111\n AA, 01 bits: 0\n TC, 01 bits: 1\n RD, 01 bits: 1\n RA, 01 bits: 1\n Z, 03 bits: 011\n RCODE, 04 bits: 1111\nQDCOUNT, 16 bits: 0101010010010110\nANCOUNT, 16 bits: 1110000100101110\nNSCOUNT, 16 bits: 0001101111110001\nARCOUNT, 16 bits: 0110100110100100\n```"
}
]
|
[
{
"role": "user",
"content": "ASCII is the American Standard Code for Information Interchange. There are 128 ASCII characters of which the first 32 and the last are 'control characters'.\n\nTask\n\nShow how your language might treat control characters *en bloc* by using an enum, an enum like structure or other approach to associate their names with their ASCII values thereby enabling them to be retrieved or listed by name.\n\nTechnically, the 33rd character 'space' is a printable character, not a control character, though you may treat it as the latter for the purposes of this task.\n\nReference\n\n* Wikipedia: ASCII"
},
{
"role": "assistant",
"content": "There doesn't seem to really be a point or a purpose to this task other than creating a enumeration...\n\n'space' is absolutely **NOT** a control character. Pretending it is is just completely incorrect.\n\n```\nenum C0 (|(^32).map({ (0x2400 + $_).chr => $_ }), '␡' => 127);\n\nprintf \"Ord: %3d, Unicode: %s, Enum: %s\\n\", $_, .uniname, C0($_)\n for (^128).grep: {.chr ~~ /<:Cc>/}\n\n```\n\nOutput:\n\n```\nOrd: 0, Unicode: <control-0000>, Enum: ␀\nOrd: 1, Unicode: <control-0001>, Enum: ␁\nOrd: 2, Unicode: <control-0002>, Enum: ␂\nOrd: 3, Unicode: <control-0003>, Enum: ␃\nOrd: 4, Unicode: <control-0004>, Enum: ␄\nOrd: 5, Unicode: <control-0005>, Enum: ␅\nOrd: 6, Unicode: <control-0006>, Enum: ␆\nOrd: 7, Unicode: <control-0007>, Enum: ␇\nOrd: 8, Unicode: <control-0008>, Enum: ␈\nOrd: 9, Unicode: <control-0009>, Enum: ␉\nOrd: 10, Unicode: <control-000A>, Enum: ␊\nOrd: 11, Unicode: <control-000B>, Enum: ␋\nOrd: 12, Unicode: <control-000C>, Enum: ␌\nOrd: 13, Unicode: <control-000D>, Enum: ␍\nOrd: 14, Unicode: <control-000E>, Enum: ␎\nOrd: 15, Unicode: <control-000F>, Enum: ␏\nOrd: 16, Unicode: <control-0010>, Enum: ␐\nOrd: 17, Unicode: <control-0011>, Enum: ␑\nOrd: 18, Unicode: <control-0012>, Enum: ␒\nOrd: 19, Unicode: <control-0013>, Enum: ␓\nOrd: 20, Unicode: <control-0014>, Enum: ␔\nOrd: 21, Unicode: <control-0015>, Enum: ␕\nOrd: 22, Unicode: <control-0016>, Enum: ␖\nOrd: 23, Unicode: <control-0017>, Enum: ␗\nOrd: 24, Unicode: <control-0018>, Enum: ␘\nOrd: 25, Unicode: <control-0019>, Enum: ␙\nOrd: 26, Unicode: <control-001A>, Enum: ␚\nOrd: 27, Unicode: <control-001B>, Enum: ␛\nOrd: 28, Unicode: <control-001C>, Enum: ␜\nOrd: 29, Unicode: <control-001D>, Enum: ␝\nOrd: 30, Unicode: <control-001E>, Enum: ␞\nOrd: 31, Unicode: <control-001F>, Enum: ␟\nOrd: 127, Unicode: <control-007F>, Enum: ␡\n\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.\n\nThe main goal of Aspect Oriented Programming (AOP) is to keep all the code relating to a single feature in one module of code.\n\nThere are a variety of ways to achieve this with object-oriented programming and functional programming, including inheritance, decorators and configuration trees.\n\nIn Aspect Oriented Programming existing code is extended with new behaviors invisibly, by means of stealthy instrumentation. There are some similarities between this concept and some debugging tools, such as Linux Kernel Probes. In fact, one obvious application for AOP is to add detailed tracing, with access to data, without touching the instrumented code. An aspect could be used to capture the calls to an entire API and log the arguments and return values.\n\nThe idea is that when the instrumented function is executes, either prior the execution of function, or at its point of return, or both, a block of code in instrumenting module is able to gain control. It can obtain access to the function arguments almost as if it were its own arguments, execute its own logic, and even decide whether or not the instrumented function will run at all, and with what argument values, and what it shall return.\n\nFurthermore, there can be additional refinements, such as instrumenting calls to some function A, but only when it is directly called by function B. Or only when function B is somewhere in the activation chain, etc.\n\nAlso part of AOP is the idea of instrumenting data structures such as classes. An \"aspect\" is a hidden extension to some existing set of classes, which adds hidden new instance variables to the class. These variables are not accessible by the class itself, only by the instrumenting Aspect code. An object-oriented Aspect resembles a class, except that its instance variables are injected into another class (or classes!), and its methods are instrumenting hooks that capture control from the methods of other classes.\n\nAn Aspect Oriented Programming System provides the abstractions to make this happen: a way to write aspects which specify what classes and methods they instrument, and the code, data and activation rules for doing it.\n\nAOP introduces some new terms. A \"join point\" is a place in the control flow where code is instrumented, like a function call or return. A \"point cut\" is a selection of join points according to some query, which are tied to a common instrumenting code. (A single instrumenting function can handle a large point cut of different join points.)\n\nAOP allows for a \"separation of concerns\" because new features are introduced as aspects tied to the execution of existing code, but without touching any of it, thereby keeping code bases completely separate. For instance, a mutex locking discipline can be added to a class without touching any of its code. An aspect identifies the methods that need locking, introduces the mutex variable into every instance of every instrumented class, and gains control around the invocations of the targetted methods to manage the mutex. Without AOP, the concern for locking is spread everywhere. Mutex lock/unlock calls have to be written or at the very least, methods have to be declared as synchronized, and this is repeated in every class that requires locking.\n\nTask\n\nThe task is to describe or show how, or to what extent, a given programming language implements, or is able to implement or simulate, Aspect Oriented Programming."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nAll methods in Raku are really just routines under the control of the meta-object protocol for purposes of dispatch, so there are several ways to subvert the system in order to deal with aspects. First, you could intercept the MOP calls, or you could install alternate metaclasses. More likely, since methods are really just routines in disguise, and since a routine can be wrapped (in place) in an outer routine via the .wrap method, you'd just wrap all the methods and other routines that share a cross-cutting concern.\n\nNote that the optimizer is free to assume routines are immutable after CHECK time (the end of compilation), so while you can always wrap routines during compile time, you might need a \"use soft\" declaration or some such to enable wrapping at run time, that is, in order to keep considering the routine to be mutable. (Only code doing the Routine role is ever mutable in Raku—bare blocks and other lambdas are considered immutable from the start.) Note that keeping routines mutable is likely to pessimize spots where the optimizer might otherwise be able to inline the code.\n\nOf course, you can also simply redefine Raku on the fly to be any language you want in the current lexical scope, so you are really only limited by your imagination in how you wish to express these \"aspects\", whatever you might mean by that term…"
}
]
|
[
{
"role": "user",
"content": "Assertions are a way of breaking out of code when there is an error or an unexpected input.\n\nSome languages throw exceptions and some treat it as a break point.\n\nTask\n\nShow an assertion in your language by asserting that an integer variable is equal to **42**."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $a = (1..100).pick;\n$a == 42 or die '$a ain\\'t 42';\n\n```"
}
]
|
[
{
"role": "user",
"content": "According to Wikipedia; assertions can function as a form of documentation: they can describe the state the code expects to find before it runs (its preconditions), and the state the code expects to result in when it is finished running (postconditions); they can also specify invariants of a class.\n\nTask\n\nShow in the program language of your choice an example of the use of assertions as a form of documentation."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\nMost of theses entries seem to have missed the point. This isn't about how to implement or use assertions, it is about how the language uses design-by-contract to help the programmer get correct results.\n\nRaku doesn't have an assert routine in CORE. You could easily add one; several modules geared toward unit testing supply various \"assertion\" routines, though I'm not aware of any actually specifically named \"assert()\".\n\nRaku core has subroutine signatures, multi-dispatch and exceptions to implement design-by-contract.\n\nSubroutine signature allow the programmer to make the parameters supplied to a routine be checked to make sure they are the of correct quantity, type, and value and can constrain the returned value(s) to a particular type. See the below snippet for a brief demonstration. Raku does some static analysis to trap errors at compile time, but traps many errors at run time since it is often impossible to tell if a variable is of the correct type before the program is run.\n\nWhen Raku encounters a design-by-contract violation, it will fail with an error message telling where the problem occurred, what it expected and what it actually got. Some failures are trappable and resumeable. Failures may be trapped by adding a CATCH { } block in the current scope. Failures will transfer execution to the CATCH block where the failure may be analysed and further action taken. Depending on the failure type, execution may be resumable. Some failures cause execution to halt unavoidably.\n\nIn this snippet, the routine repeat takes one Integer that must be greater than 1, a String and returns a String. (Note that as written, it is incorrect since it actually returns a boolean.)\n\n```\nsub repeat ( Int $repeat where * > 1, Str $message, --> Str ) {\n say $message x $repeat;\n True # wrong return type\n}\n\nrepeat( 2, 'A' ); # parameters ok, return type check error\n\nrepeat( 4, 2 ); # wrong second parameter type\n\nrepeat( 'B', 3 ); # wrong first (and second) parameter type\n\nrepeat( 1, 'C' ); # constraint check fail\n\nrepeat( ); # wrong number of parameters\n\nCATCH {\n default {\n say \"Error trapped: $_\";\n .resume;\n }\n}\n\n```\n\nOutput:\n\n```\nAA\nError trapped: Type check failed for return value; expected Str but got Bool (Bool::True)\nError trapped: Type check failed in binding to parameter '$message'; expected Str but got Int (2)\nError trapped: Type check failed in binding to parameter '$repeat'; expected Int but got Str (\"B\")\nError trapped: Constraint type check failed in binding to parameter '$repeat'; expected anonymous constraint to be met but got Int (1)\nError trapped: Too few positionals passed; expected 2 arguments but got 0\nThis exception is not resumable\n in block at contract.p6 line 19\n in block <unit> at contract.p6 line 14\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nThe goal is to create an associative array (also known as a dictionary, map, or hash).\n\nRelated tasks:\n\n* Associative arrays/Iteration\n* Hash from two arrays\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nThe fatarrow, `=>`, is no longer just a quoting comma; it now constructs a `Pair` object. But you can still define a hash with an ordinary list of even length.\n\n```\nmy %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';\nmy %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';\n\n# Creating a hash from two lists using a metaoperator.\n\nmy @a = 1..5;\nmy @b = 'a'..'e';\nmy %h = @a Z=> @b;\n\n# Hash elements and hash slices now use the same sigil as the whole hash. This is construed as a feature.\n# Curly braces no longer auto-quote, but Raku's qw (shortcut < ... >) now auto-subscripts.\n\nsay %h1{'key1'};\nsay %h1<key1>;\n%h1<key1> = 'val1';\n%h1<key1 three> = 'val1', -238.83;\n\n# Special syntax is no longer necessary to access a hash stored in a scalar.\n\nmy $h = {key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'};\nsay $h<key1>;\n\n# Keys are of type Str or Int by default. The type of the key can be provided.\n\nmy %hash{Any}; # same as %hash{*}\nclass C {};\nmy %cash{C};\n%cash{C.new} = 1;\n```"
}
]
|
[
{
"role": "user",
"content": "Show how to iterate over the key-value pairs of an associative array, and print each pair out.\n\nAlso show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\n```\nmy %pairs = hello => 13, world => 31, '!' => 71;\n \nfor %pairs.kv -> $k, $v {\n say \"(k,v) = ($k, $v)\";\n}\n\n# Stable order\nfor %pairs.sort(*.value)>>.kv -> ($k, $v) {\n say \"(k,v) = ($k, $v)\";\n}\n\n{ say \"$^a => $^b\" } for %pairs.kv;\n\nsay \"key = $_\" for %pairs.keys;\n\nsay \"value = $_\" for %pairs.values;\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDefine two associative arrays, where one represents the following \"base\" data:\n\n: : : : : | | |\n | --- | --- |\n | **Key** | **Value** |\n | \"name\" | \"Rocket Skates\" |\n | \"price\" | 12.75 |\n | \"color\" | \"yellow\" |\n\nAnd the other represents \"update\" data:\n\n: : : : : | | |\n | --- | --- |\n | **Key** | **Value** |\n | \"price\" | 15.25 |\n | \"color\" | \"red\" |\n | \"year\" | 1974 |\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n: : : : : | | |\n | --- | --- |\n | **Key** | **Value** |\n | \"name\" | \"Rocket Skates\" |\n | \"price\" | 15.25 |\n | \"color\" | \"red\" |\n | \"year\" | 1974 |"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.11\n\nI must say I somewhat disagree with the terminology. The requested operation is an update not a merge. Demonstrate both an update and a merge. Associative arrays are commonly called hashes in Raku.\n\n```\n# Show original hashes\nsay my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;\nsay my %update = :price<15.25>, :color<red>, :year<1974>;\n\n# Need to assign to anonymous hash to get the desired results and avoid mutating\n# TIMTOWTDI\nsay \"\\nUpdate:\\n\", join \"\\n\", sort %=%base, %update;\n# Same\nsay \"\\nUpdate:\\n\", {%base, %update}.sort.join: \"\\n\";\n\nsay \"\\nMerge:\\n\", join \"\\n\", sort ((%=%base).push: %update)».join: ', ';\n# Same\nsay \"\\nMerge:\\n\", ({%base}.push: %update)».join(', ').sort.join: \"\\n\";\n\n# Demonstrate unmutated hashes\nsay \"\\n\", %base, \"\\n\", %update;\n\n```\n\nOutput:\n\n```\n{color => yellow, name => Rocket Skates, price => 12.75}\n{color => red, price => 15.25, year => 1974}\n\nUpdate:\ncolor\tred\nname\tRocket Skates\nprice\t15.25\nyear\t1974\n\nUpdate:\ncolor\tred\nname\tRocket Skates\nprice\t15.25\nyear\t1974\n\nMerge:\ncolor\tyellow, red\nname\tRocket Skates\nprice\t12.75, 15.25\nyear\t1974\n\nMerge:\ncolor\tyellow, red\nname\tRocket Skates\nprice\t12.75, 15.25\nyear\t1974\n\n{color => yellow, name => Rocket Skates, price => 12.75}\n{color => red, price => 15.25, year => 1974}\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDefine a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to:\n\n1. get the current value of any bucket\n2. remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the transferred amount to ensure the values remain non-negative\n\n---\n\nIn order to exercise this data type, create one set of buckets, and start three concurrent tasks:\n\n1. As often as possible, pick two buckets and make their values closer to equal.\n2. As often as possible, pick two buckets and arbitrarily redistribute their values.\n3. At whatever rate is convenient, display (by any means) the total value and, optionally, the individual values of each bucket.\n\nThe display task need not be explicit; use of e.g. a debugger or trace tool is acceptable provided it is simple to set up to provide the display.\n\n---\n\nThis task is intended as an exercise in *atomic* operations. The sum of the bucket values must be preserved even if the two tasks attempt to perform transfers simultaneously, and a straightforward solution is to ensure that at any time, only one transfer is actually occurring — that the transfer operation is *atomic*."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Ruby\n\n**Works with**: Rakudo version 2016.07\n\n```\n#| A collection of non-negative integers, with atomic operations.\nclass BucketStore {\n \n has $.elems is required;\n has @!buckets = ^1024 .pick xx $!elems;\n has $lock = Lock.new;\n \n #| Returns an array with the contents of all buckets.\n method buckets {\n $lock.protect: { [@!buckets] }\n }\n \n #| Transfers $amount from bucket at index $from, to bucket at index $to.\n method transfer ($amount, :$from!, :$to!) {\n return if $from == $to;\n \n $lock.protect: {\n my $clamped = $amount min @!buckets[$from];\n \n @!buckets[$from] -= $clamped;\n @!buckets[$to] += $clamped;\n }\n }\n}\n\n# Create bucket store\nmy $bucket-store = BucketStore.new: elems => 8;\nmy $initial-sum = $bucket-store.buckets.sum;\n\n# Start a thread to equalize buckets\nThread.start: {\n loop {\n my @buckets = $bucket-store.buckets;\n \n # Pick 2 buckets, so that $to has not more than $from\n my ($to, $from) = @buckets.keys.pick(2).sort({ @buckets[$_] });\n \n # Transfer half of the difference, rounded down\n $bucket-store.transfer: ([-] @buckets[$from, $to]) div 2, :$from, :$to;\n }\n}\n\n# Start a thread to distribute values among buckets\nThread.start: {\n loop {\n my @buckets = $bucket-store.buckets;\n \n # Pick 2 buckets\n my ($to, $from) = @buckets.keys.pick(2);\n \n # Transfer a random portion\n $bucket-store.transfer: ^@buckets[$from] .pick, :$from, :$to;\n }\n}\n\n# Loop to display buckets\nloop {\n sleep 1;\n \n my @buckets = $bucket-store.buckets;\n my $sum = @buckets.sum;\n \n say \"{@buckets.fmt: '%4d'}, total $sum\";\n \n if $sum != $initial-sum {\n note \"ERROR: Total changed from $initial-sum to $sum\";\n exit 1;\n }\n}\n\n```\n\nOutput:\n\n```\n 23 52 831 195 1407 809 813 20, total 4150\n1172 83 336 306 751 468 615 419, total 4150\n 734 103 1086 88 313 136 1252 438, total 4150\n 512 323 544 165 200 3 2155 248, total 4150\n...\n\n```"
}
]
|
[
{
"role": "user",
"content": "A number is an *attractive number* if the number of its prime factors (whether distinct or not) is also prime.\n\nExample\n\nThe number **20**, whose prime decomposition is **2 × 2 × 5**, is an *attractive number* because the number of its prime factors (**3**) is also prime.\n\nTask\n\nShow sequence items up to **120**.\n\nReference\n: * The OEIS entry: A063989: Numbers with a prime number of prime divisors."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.03\n\nThis algorithm is concise but not really well suited to finding large quantities of consecutive attractive numbers. It works, but isn't especially speedy. More than a hundred thousand or so gets tedious. There are other, much faster (though more verbose) algorithms that *could* be used. This algorithm **is** well suited to finding **arbitrary** attractive numbers though.\n\n```\nuse Lingua::EN::Numbers;\nuse ntheory:from<Perl5> <factor is_prime>;\n\nsub display ($n,$m) { ($n..$m).grep: (~*).&factor.elems.&is_prime }\n\nsub count ($n,$m) { +($n..$m).grep: (~*).&factor.elems.&is_prime }\n\n# The Task\nput \"Attractive numbers from 1 to 120:\\n\" ~\ndisplay(1, 120)».fmt(\"%3d\").rotor(20, :partial).join: \"\\n\";\n\n# Robusto!\nfor 1, 1000, 1, 10000, 1, 100000, 2**73 + 1, 2**73 + 100 -> $a, $b {\n put \"\\nCount of attractive numbers from {comma $a} to {comma $b}:\\n\" ~\n comma count $a, $b\n}\n\n```\n\nOutput:\n\n```\nAttractive numbers from 1 to 120:\n 4 6 8 9 10 12 14 15 18 20 21 22 25 26 27 28 30 32 33 34\n 35 38 39 42 44 45 46 48 49 50 51 52 55 57 58 62 63 65 66 68\n 69 70 72 74 75 76 77 78 80 82 85 86 87 91 92 93 94 95 98 99\n102 105 106 108 110 111 112 114 115 116 117 118 119 120\n\nCount of attractive numbers from 1 to 1,000:\n636\n\nCount of attractive numbers from 1 to 10,000:\n6,396\n\nCount of attractive numbers from 1 to 100,000:\n63,255\n\nCount of attractive numbers from 9,444,732,965,739,290,427,393 to 9,444,732,965,739,290,427,492:\n58\n```"
}
]
|
[
{
"role": "user",
"content": "**AudioAlarm** is a program that asks the user to enter a certain number, representing a number of seconds. After the user enters the number, the program will ask the user to enter the name of an MP3 audio file (without the .mp3 file extension). The program will then display a (usually blank) page. After the time (indicated by the number) is up, a sound (indicated by the MP3 file) will go off. Useful for timers and alarm clocks. The app must be installed in its own folder, preferrably with a name like *AudioAlarm*. To install a sound on the app, just copy the MP3 to the app folder you set up. Then, when the app asks you for the filename, you just type in the name without an extension."
},
{
"role": "assistant",
"content": "requires mpg123 to be installed.\n\n```\n# 20221111 Raku programming solution\n\nloop (my $wait; $wait !~~ Int;) { $wait=prompt('enter seconds to wait: ') }\n\nloop (my $mp3='';!\"$mp3.mp3\".IO.e;) { $mp3=prompt('enter filename to play: ') }\n\nrun '/usr/bin/clear';\n\nsleep($wait);\n\nrun '/usr/bin/mpg123', \"$mp3.mp3\";\n\n```"
}
]
|
[
{
"role": "user",
"content": "An audio frequency generator produces a continual audible monotone at a set frequency and level of volume.\nThere are controls to adjust the frequency and the volume up and down as desired.\nSome also have a selector to switch the waveform type between sine wave, square wave and triangular sawtooth.\n\nThe task is to emulate an audio frequency generator.\nIt is permissible to use an inbuilt computer speaker\nif the system does not have the facility to utilize dedicated sound hardware.\n\nThe solution should include:\n\n* A demonstration of how to check for availability of sound hardware on the system (on systems where this is possible)\n* A demonstration of how to produce a continual audible monotone (on sound hardware this would typically be a sine wave)\n* A method of adjusting the frequency and volume of the monotone. (one way would be to use left and right arrow keys to increase or decrease frequency, and up and down keys to increase or decrease the volume)\n* A method to silence or reset the sound hardware on exit.\n\nOptionally the solution can also include:\n\n* A demonstration of how to fall back to internal speaker, if sound hardware is not available\n* A facility to switch between sine wave, square wave and triangular sawtooth\n\nLanguages that provide no facilities for utilizing sound hardware of any kind should be omitted."
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n```\n# 20240130 Raku programming solution\n\nmy ($kindS, $kind, $freq, $vol, $dur) = 'sine', |(0 xx *);\n\nwhile $freq < 40 || $freq > 10000 {\n print \"Enter frequency in Hz (40 to 10000) : \";\n $freq = prompt().Int;\n}\n\nwhile $vol < 1 || $vol > 50 {\n print \"Enter volume in dB (1 to 50) : \";\n $vol = prompt().Int;\n}\n\nwhile $dur < 2 || $dur > 10 {\n print \"Enter duration in seconds (2 to 10) : \";\n $dur = prompt().Int;\n}\n\nwhile $kind < 1 || $kind > 3 {\n print 'Enter kind (1 = Sine, 2 = Square, 3 = Sawtooth) : ';\n given $kind = prompt().Int {\n when $kind == 2 { $kindS = 'square' }\n when $kind == 3 { $kindS = 'sawtooth' }\n }\n}\n\nmy @args = \"-n\", \"synth\", $dur, $kindS, $freq, \"vol\", $vol, \"dB\";\nrun 'play', @args, :out('/dev/null'), :err('/dev/null');\n\n```"
}
]
|
[
{
"role": "user",
"content": "**Audio Overlap Loop** is a program that produces an \"echo chamber\" effect by playing an audio file several times in an overlapping loop. A repetition level determines the number of times that the file is looped. For the purpose of this task, write a program that takes a parameter for the number of repetitions and plays the file *loop.wav* in an overlapping loop according to the number of repetitions.\n\nOptionally take parameters for delay between repetitions, and decay (fractional volume reduction between consecutive repetitions)."
},
{
"role": "assistant",
"content": "**Translation of**: Julia\n\n```\n# 20241230 Raku programming solution\n\nmy $soundfile = \"notes.wav\";\nmy $repetitions;\n\nif @*ARGS.elems < 1 {\n say \"Usage: give number of repetitions in echo effect as argument to the program.\"\n} else {\n given $*KERNEL.cpu-cores { $repetitions = @*ARGS[0] < $_ ?? @*ARGS[0] !! $_ }\n}\n\nfor 0.0, 0.1 ... (($repetitions - 1) * 0.1) -> $seconds {\n sleep $seconds;\n my $proc = Proc::Async.new('play', '--no-show-progress', $soundfile);\n $proc.start\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\nAn **autogram** is a sentence that describes itself in the sense of providing an inventory of its own characters. An essential feature is the use of full cardinal number names such as \"one\", \"two\", etc., in recording character counts.\n\nAutograms are also called 'self-enumerating' or 'self-documenting' sentences. Whilst they usually just count letters of the alphabet, they can also count punctuation symbols as well.\n\nExample\n\nIf punctuation is ignored, the following sentence is an autogram:\n\n```\nThis sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's, twenty-three t's, six v's, ten w's, two x's, five y's, and one z.\n\n```\n\nTask\n\nWrite a routine in your language to check whether or not a given sentence is an autogram and use it to test the above example (Sentence 1.) and also the following sentences:\n\n2. This sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty three t's, six v's, ten w's, two x's, five y's, and one z.\n\n3. Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !\n\n4. This pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven is, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss, eighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z.\n\n5. This sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's, thirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's, twenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z.\n\n6. Thirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty s's, twelve t's, three u's, four v's, six w's, four x's, two y's.\n\n7. Fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's.\n\n8. Sixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's, eight t's, three u's, three v's, two w's, four z's.\n\nPunctuation should be ignored in all cases except for sentences number 3. and 7. For task 3 and 7, punctuation counts must be checked, and some ('comma', 'apostrophe', 'hyphen') punctuation may be represented in the autogram using the spelled out english names for the punctuation and the checker must respect the inconsistent use of apostrophes in the spellings of the counts (while still counting apostrophes accurately) and must accept 'single' as a synonym for 'one'.\n\nNote that the only difference between sentences 1. and 2. is that there are no hyphens in the latter.\n\nAssumptions\n\n* Ignore capitalization.\n\n* Never count spaces or full stops.\n\nIf it helps you may also make the following simplifying assumptions:\n\n* No sentence will be such that there are more than 99 instances of any countable character.\n\n* If punctuation is to be allowed for, only commas, hyphens, apostrophes and exclamation marks need be counted.\n\nReference\n\n* Wikipedia: Autogram\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": "Slightly fragile, especially for non-letter character counts, but good enough for here.\n\nUsing Text::Wrap from the ecosystem. Install command: `zef install -v git://github.com/jkramer/p6-Text-Wrap.git`.\n\n```\nmy %nums = :0zero, :1one, :2two, :3three, :4four, :5five, :6six, :7seven, :8eight, :9nine, :10ten, :11eleven,\n :12twelve, :13thirteen, :14fourteen, :15fifteen, :16sixteen, :17seventeen, :18eighteen, :19nineteen,\n :20twenty, :30thirty, :40forty, :50fifty, :60sixty, :70seventy, :80eighty, :90ninety, :100hundred, :1single;\n\nsub whitespace { $^a.subst(:g, /\\s|'.'/, '') }\nsub non-letters { $^a.subst(:g, /\\W/, '') }\n\nmy @tests =\n (&non-letters, \"This sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's, twenty-three t's, six v's, ten w's, two x's, five y's, and one z.\"),\n (&non-letters, \"This sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's, eleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty three t's, six v's, ten w's, two x's, five y's, and one z.\"),\n (&whitespace, \"Only the fool would take trouble to verify that his sentence was composed of ten a's, three b's, four c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine l's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven t's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three apostrophes, seven hyphens and, last but not least, a single !\"),\n (&non-letters, \"This pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven is, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss, eighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z.\"),\n (&non-letters, \"This sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's, thirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's, twenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z.\"),\n (&non-letters, \"Thirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty s's, twelve t's, three u's, four v's, six w's, four x's, two y's.\"),\n (&whitespace, \"Fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's.\"),\n (&non-letters, \"Sixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's, eight t's, three u's, three v's, two w's, four z's.\")\n;\n\nuse Text::Wrap;\n\nsay '=' x 100;\n\nfor @tests -> (&filter, $text) {\n\n # Original\n say wrap-text :100width, $text;\n\n say \"\\nFiltering out \" ~ &filter.name ~ ':';\n\n # Semi-bogus and somewhat fragile names to numbers conversion.\n my $str = $text.lc;\n for %nums.kv -> $word, $number { $str ~~ s:g/ <|w> $word <|w> /$number/ }\n $str ~~ s:g/ (\\d)<ws>['and'|'-']<ws>(\\d) /$0 $1/;\n $str ~~ s:g/ <|w>(\\d ** 2)<ws>(\\d ** 2) <|w> /{ $0 × 100 + $1}/;\n $str ~~ s:g/ ( [\\d+<ws>]* \\d+ ) /{[+] $0.split: ' '}/;\n\n # Build a hash of claimed characters.\n my %claim = flat $str.lc.match(:g, /\\d+ <:ws> ['comma'|'apostrophe'|'hyphen'|.]/)».split(' ')»[1,0]».pairup;\n for <comma , hyphen - apostrophe '> #`['] -> $word, $symbol { %claim{$symbol} = %claim{$word}:delete if %claim{$word} }\n say \"\\nClaimed character counts:\\n\" ~ wrap-text :100width, %claim.sort( ~*.key ).map( { sprintf \"%s\\(%d)\", .key, .value } ).join: ' ';\n\n # And of the actual character counts.\n my %count = &filter($text).lc.comb.Bag.hash;\n say \"\\nActual:\\n\" ~ wrap-text :100width, %count.sort( ~*.key ).map( { sprintf \"%s\\(%d)\", .key, .value } ).join: ' ';\n\n # And compare them\n say \"\\nAutogram? \" ~\n quietly (so all %count.map: { .value == %claim{.key} }) && (so all %claim.map: { .value == %count{.key} });\n\n say '=' x 100;\n}\n\n```\n\nOutput:\n\n```\n====================================================================================================\nThis sentence employs two a's, two c's, two d's, twenty-eight e's, five f's, three g's, eight h's,\neleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty-five s's,\ntwenty-three t's, six v's, ten w's, two x's, five y's, and one z.\n\nFiltering out non-letters:\n\nClaimed character counts:\na(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)\ny(5) z(1)\n\nActual:\na(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)\ny(5) z(1)\n\nAutogram? True\n====================================================================================================\nThis sentence employs two a's, two c's, two d's, twenty eight e's, five f's, three g's, eight h's,\neleven i's, three l's, two m's, thirteen n's, nine o's, two p's, five r's, twenty five s's, twenty\nthree t's, six v's, ten w's, two x's, five y's, and one z.\n\nFiltering out non-letters:\n\nClaimed character counts:\na(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)\ny(5) z(1)\n\nActual:\na(2) c(2) d(2) e(28) f(5) g(3) h(8) i(11) l(3) m(2) n(13) o(9) p(2) r(5) s(25) t(23) v(6) w(10) x(2)\ny(5) z(1)\n\nAutogram? True\n====================================================================================================\nOnly the fool would take trouble to verify that his sentence was composed of ten a's, three b's,\nfour c's, four d's, forty-six e's, sixteen f's, four g's, thirteen h's, fifteen i's, two k's, nine\nl's, four m's, twenty-five n's, twenty-four o's, five p's, sixteen r's, forty-one s's, thirty-seven\nt's, ten u's, eight v's, eight w's, four x's, eleven y's, twenty-seven commas, twenty-three\napostrophes, seven hyphens and, last but not least, a single !\n\nFiltering out whitespace:\n\nClaimed character counts:\n!(1) '(23) ,(27) -(7) a(10) b(3) c(4) d(4) e(46) f(16) g(4) h(13) i(15) k(2) l(9) m(4) n(25) o(24)\np(5) r(16) s(41) t(37) u(10) v(8) w(8) x(4) y(11)\n\nActual:\n!(1) '(23) ,(27) -(7) a(10) b(3) c(4) d(4) e(46) f(16) g(4) h(13) i(15) k(2) l(9) m(4) n(25) o(24)\np(5) r(16) s(41) t(37) u(10) v(8) w(8) x(4) y(11)\n\nAutogram? True\n====================================================================================================\nThis pangram contains four as, one b, two cs, one d, thirty es, six fs, five gs, seven hs, eleven\nis, one j, one k, two ls, two ms, eighteen ns, fifteen os, two ps, one q, five rs, twenty-seven ss,\neighteen ts, two us, seven vs, eight ws, two xs, three ys, & one z.\n\nFiltering out non-letters:\n\nClaimed character counts:\na(4) b(1) c(2) d(1) e(30) f(6) g(5) h(7) i(11) j(1) k(1) l(2) m(2) n(18) o(15) p(2) q(1) r(5) s(27)\nt(18) u(2) v(7) w(8) x(2) y(3) z(1)\n\nActual:\na(4) b(1) c(2) d(1) e(30) f(6) g(5) h(7) i(11) j(1) k(1) l(2) m(2) n(18) o(15) p(2) q(1) r(5) s(27)\nt(18) u(2) v(7) w(8) x(2) y(3) z(1)\n\nAutogram? True\n====================================================================================================\nThis sentence contains one hundred and ninety-seven letters: four a's, one b, three c's, five d's,\nthirty-four e's, seven f's, one g, six h's, twelve i's, three l's, twenty-six n's, ten o's, ten r's,\ntwenty-nine s's, nineteen t's, six u's, seven v's, four w's, four x's, five y's, and one z.\n\nFiltering out non-letters:\n\nClaimed character counts:\na(4) b(1) c(3) d(5) e(34) f(7) g(1) h(6) i(12) l(3) n(26) o(10) r(10) s(29) t(19) u(6) v(7) w(4)\nx(4) y(5) z(1)\n\nActual:\na(4) b(1) c(3) d(5) e(34) f(7) g(1) h(6) i(12) l(3) n(26) o(10) r(10) s(29) t(19) u(6) v(7) w(4)\nx(4) y(5) z(1)\n\nAutogram? True\n====================================================================================================\nThirteen e's, five f's, two g's, five h's, eight i's, two l's, three n's, six o's, six r's, twenty\ns's, twelve t's, three u's, four v's, six w's, four x's, two y's.\n\nFiltering out non-letters:\n\nClaimed character counts:\ne(13) f(5) g(2) h(5) i(8) l(2) n(3) o(6) r(6) s(20) t(12) u(3) v(4) w(6) x(4) y(2)\n\nActual:\ne(13) f(5) g(2) h(5) i(8) l(2) n(3) o(6) r(6) s(20) t(12) u(3) v(4) w(6) x(4) y(2)\n\nAutogram? True\n====================================================================================================\nFifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's,\neight t's, four u's, three v's, two w's, three x's.\n\nFiltering out whitespace:\n\nClaimed character counts:\ne(15) f(7) g(4) h(6) i(8) n(4) o(5) r(6) s(18) t(8) u(4) v(3) w(2) x(3)\n\nActual:\n'(14) ,(13) e(15) f(7) g(4) h(6) i(8) n(4) o(5) r(6) s(18) t(8) u(4) v(3) w(2) x(3)\n\nAutogram? False\n====================================================================================================\nSixteen e's, five f's, three g's, six h's, nine i's, five n's, four o's, six r's, eighteen s's,\neight t's, three u's, three v's, two w's, four z's.\n\nFiltering out non-letters:\n\nClaimed character counts:\ne(16) f(5) g(3) h(6) i(9) n(5) o(4) r(6) s(18) t(8) u(3) v(3) w(2) z(4)\n\nActual:\ne(16) f(5) g(3) h(6) i(9) n(5) o(4) r(6) s(18) t(8) u(3) v(3) w(2) x(3) z(1)\n\nAutogram? False\n====================================================================================================\n```"
}
]
|
[
{
"role": "user",
"content": "Let `f` be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence `1, f(1), f(f(1))...` will contain a *repetition*, a number that occurring for the second time in the sequence.\n\nTask\n\nWrite a program or a script that estimates, for each `N`, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n```\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nconstant MAX_N = 20;\nconstant TRIALS = 100;\n \nfor 1 .. MAX_N -> $N {\n my $empiric = TRIALS R/ [+] find-loop(random-mapping $N).elems xx TRIALS;\n my $theoric = [+]\n map -> $k { $N ** ($k + 1) R/ [×] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;\n \n FIRST say \" N empiric theoric (error)\";\n FIRST say \"=== ========= ============ =========\";\n \n printf \"%3d %9.4f %12.4f (%4.2f%%)\\n\",\n $N, $empiric, $theoric, 100 × abs($theoric - $empiric) / $theoric;\n}\n \nsub random-mapping { hash .list Z=> .roll($_) given ^$^size }\nsub find-loop { 0, | %^mapping{*} ...^ { (%){$_}++ } }\n\n```\n\nExample:\n\n```\n N empiric theoric (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 (0.00%)\n 2 1.5600 1.5000 (4.00%)\n 3 1.7800 1.8889 (5.76%)\n 4 2.1800 2.2188 (1.75%)\n 5 2.6200 2.5104 (4.37%)\n 6 2.8300 2.7747 (1.99%)\n 7 3.1200 3.0181 (3.37%)\n 8 3.1400 3.2450 (3.24%)\n 9 3.4500 3.4583 (0.24%)\n 10 3.6700 3.6602 (0.27%)\n 11 3.8300 3.8524 (0.58%)\n 12 4.3600 4.0361 (8.03%)\n 13 3.9000 4.2123 (7.42%)\n 14 4.4900 4.3820 (2.46%)\n 15 4.9500 4.5458 (8.89%)\n 16 4.9800 4.7043 (5.86%)\n 17 4.9100 4.8579 (1.07%)\n 18 4.9700 5.0071 (0.74%)\n 19 5.1000 5.1522 (1.01%)\n 20 5.2300 5.2936 (1.20%)\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a program to find the mean (arithmetic average) of a numeric vector.\n\nIn case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.10-11\n\n```\nmulti mean([]){ Failure.new('mean on empty list is not defined') }; # Failure-objects are lazy exceptions\nmulti mean (@a) { ([+] @a) / @a }\n```"
}
]
|
[
{
"role": "user",
"content": "When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle.\n\nIf one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the second was of 10 degrees then the average of the numbers is 180 degrees, whereas if you can note that 350 degrees is equivalent to -10 degrees and so you have two readings at 10 degrees either side of zero degrees leading to a more fitting mean angle of zero degrees.\n\nTo calculate the mean angle of several angles:\n\n1. Assume all angles are on the unit circle and convert them to complex numbers expressed in real and imaginary form.\n2. Compute the mean of the complex numbers.\n3. Convert the complex mean to polar coordinates whereupon the phase of the complex mean is the required angular mean.\n\n(Note that, since the mean is the sum divided by the number of numbers, and division by a positive real number does not affect the angle, you can also simply compute the sum for step 2.)\n\nYou can alternatively use this formula:\n\n: Given the angles \n\n α\n\n 1\n ,\n …\n ,\n\n α\n\n n\n {\\displaystyle {\\displaystyle \\alpha \\_{1},\\dots ,\\alpha \\_{n}}}\n the mean is computed by\n\n: : α\n ¯\n =\n atan2\n \n\n (\n\n 1\n n\n ⋅\n\n ∑\n\n j\n =\n 1\n\n n\n sin\n \n\n α\n\n j\n ,\n\n\n 1\n n\n ⋅\n\n ∑\n\n j\n =\n 1\n\n n\n cos\n \n\n α\n\n j\n )\n {\\displaystyle {\\displaystyle {\\bar {\\alpha }}=\\operatorname {atan2} \\left({\\frac {1}{n}}\\cdot \\sum \\_{j=1}^{n}\\sin \\alpha \\_{j},{\\frac {1}{n}}\\cdot \\sum \\_{j=1}^{n}\\cos \\alpha \\_{j}\\right)}}\n\nTask\n\n1. write a function/method/subroutine/... that given a list of angles in degrees returns their mean angle. \n (You should use a built-in function if you have one that does this for degrees or radians).\n2. Use the function to compute the means of these lists of angles (in degrees):\n * [350, 10]\n * [90, 180, 270, 360]\n * [10, 20, 30]\n3. Show your output here.\n\nSee also\n\n| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n| | Tasks for calculating statistical measures | | | --- | --- | | | | | | | | | | | --- | --- | --- | --- | --- | | | | in one go | moving *(sliding window)* | moving *(cumulative)* | | Mean | Arithmetic | Statistics/Basic Averages/Arithmetic mean Averages/Pythagorean means | Averages/Simple moving average | | | Geometric | Averages/Pythagorean means | | | | Harmonic | Averages/Pythagorean means | | | | Quadratic | Averages/Root mean square | | | | Circular | Averages/Mean angle Averages/Mean time of day | | | | Median | | Averages/Median | | | | Mode | | Averages/Mode | | | | Standard deviation | | Statistics/Basic | | Cumulative standard deviation | | | |\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2015.12\n\nThis solution refuses to return an answer when the angles cancel out to a tiny magnitude.\n\n```\n# Of course, you can still use pi and 180.\nsub deg2rad { $^d * tau / 360 }\nsub rad2deg { $^r * 360 / tau }\n\nsub phase ($c) {\n my ($mag,$ang) = $c.polar;\n return NaN if $mag < 1e-16;\n $ang;\n}\n\nsub meanAngle { rad2deg phase [+] map { cis deg2rad $_ }, @^angles }\n\nsay meanAngle($_).fmt(\"%.2f\\tis the mean angle of \"), $_ for\n [350, 10],\n [90, 180, 270, 360],\n [10, 20, 30];\n\n```\n\nOutput:\n\n```\n-0.00\tis the mean angle of 350 10\nNaN\tis the mean angle of 90 180 270 360\n20.00\tis the mean angle of 10 20 30\n```"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.