messages
listlengths 2
2
|
---|
[
{
"role": "user",
"content": "Task\n\nFind the smallest (decimal integer) squares that begin with **n** for 0 < **n** < 50"
},
{
"role": "assistant",
"content": "```\n# 20210319 Raku programming solution\n\nmy @needles = (1..49);\nmy @haystack = (1..*) Z× (1..*);\n# my @haystack = ( 1, 4, -> \\a, \\b { 2*b - a + 2 } ... * );\n# my @haystack = ( 1, { (++$)² } ... * );\nfor @needles -> \\needle {\n for @haystack -> \\hay {\n { say needle, \" => \", hay and last } if hay.starts-with: needle\n }\n}\n\n```\n\nOutput:\n\n```\n1 => 1\n2 => 25\n3 => 36\n4 => 4\n5 => 529\n6 => 64\n7 => 729\n8 => 81\n9 => 9\n10 => 100\n11 => 1156\n12 => 121\n13 => 1369\n14 => 144\n15 => 1521\n16 => 16\n17 => 1764\n18 => 1849\n19 => 196\n20 => 2025\n21 => 2116\n22 => 225\n23 => 2304\n24 => 2401\n25 => 25\n26 => 2601\n27 => 2704\n28 => 289\n29 => 2916\n30 => 3025\n31 => 3136\n32 => 324\n33 => 3364\n34 => 3481\n35 => 35344\n36 => 36\n37 => 3721\n38 => 3844\n39 => 3969\n40 => 400\n41 => 41209\n42 => 4225\n43 => 4356\n44 => 441\n45 => 45369\n46 => 4624\n47 => 4761\n48 => 484\n49 => 49\n\n```\n\nAs the desired range is so small, there is not much gained by caching the squares. Less efficient, but less verbose:\n\n```\nsay $_ => ^Inf .map(*²).first: *.starts-with: $_ for 1..49;\n\n```\n\nSame output."
}
]
|
[
{
"role": "user",
"content": "The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.\n\nFor example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.\n\nTask\n\n* Show the first 25 SPDS primes.\n* Show the hundredth SPDS prime.\n\nSee also\n\n* OEIS A019546: Primes whose digits are primes.\n* https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Library:** ntheory\n\n```\nuse Lingua::EN::Numbers;\nuse ntheory:from<Perl5> <:all>;\n\n# Implemented as a lazy, extendable list\nmy $spds = grep { .&is_prime }, flat [2,3,5,7], [23,27,33,37,53,57,73,77], -> $p\n { state $o++; my $oom = 10**(1+$o); [ flat (2,3,5,7).map: -> $l { (|$p).map: $l×$oom + * } ] } … *;\n\nsay 'Smarandache prime-digitals:';\nprintf \"%22s: %s\\n\", ordinal(1+$_).tclc, comma $spds[$_] for flat ^25, 99, 999, 9999, 99999;\n\n```\n\nOutput:\n\n```\nSmarandache prime-digitals:\n First: 2\n Second: 3\n Third: 5\n Fourth: 7\n Fifth: 23\n Sixth: 37\n Seventh: 53\n Eighth: 73\n Ninth: 223\n Tenth: 227\n Eleventh: 233\n Twelfth: 257\n Thirteenth: 277\n Fourteenth: 337\n Fifteenth: 353\n Sixteenth: 373\n Seventeenth: 523\n Eighteenth: 557\n Nineteenth: 577\n Twentieth: 727\n Twenty-first: 733\n Twenty-second: 757\n Twenty-third: 773\n Twenty-fourth: 2,237\n Twenty-fifth: 2,273\n One hundredth: 33,223\n One thousandth: 3,273,527\n Ten thousandth: 273,322,727\nOne hundred thousandth: 23,325,232,253\n```"
}
]
|
[
{
"role": "user",
"content": "Definitions\n\nA **Smarandache-Wellin number** (S-W number for short) is an integer that in a given base is the concatenation of the first n prime numbers written in that base. A base of 10 will be assumed for this task.\n\nA **Derived S-W number** (not an 'official' term) is an integer formed from a S-W number by working out the number of times each of the digits 0 to 9 occurs in that number, concatenating those frequencies in the same order (i.e. frequency of '0' first, frequency of '1' second etc) and removing any leading zeros.\n\nExamples\n\n'23571113' is the sixth S-W number formed by concatenating the first 6 primes: 2, 3, 5, 7, 11 and 13.\n\nThe corresponding Derived S-W number is '312010100' because '1' occurs 3 times, '3' occurs twice and '2', '5' and '7' all occur once.\n\nTask\n\n* Find and show the first three S-W numbers which are prime.\n\n* Find and show the first three Derived S-W numbers which are prime.\n\nStretch (requires 'big integer' support)\n\nFind and show the index in the sequence (starting from 1), the total number of digits and the last prime used to form the fourth, fifth, sixth, seventh and (optionally) the eighth S-W numbers which are prime or probably prime with reasonable certainty. It is unknown whether there are any more but, if you fancy searching for one, good luck! You can start from an index of 22,077.\n\nAlso find and show up to the first twenty Derived S-W numbers which are prime and their index in the sequence.\n\nReferences\n\n* Wikipedia: Smarandache-Wellin number\n* OEIS:A019518 - Smarandache-Wellin numbers\n* OEIS:A069151 - Smarandache-Wellin primes"
},
{
"role": "assistant",
"content": "The first seven Smarandache-Wellin primes are found in a few seconds on my system. The eighth adds over five minutes to the run time.\n\n```\nuse Lingua::EN::Numbers;\n\nmy @primes = (^∞).grep: &is-prime;\n\nmy @Smarandache-Wellin = [\\~] @primes;\n\nsink @Smarandache-Wellin[1500]; # pre-reify for concurrency\n\nsub derived ($n) { my %digits = $n.comb.Bag; (0..9).map({ %digits{$_} // 0 }).join }\n\nsub abbr ($_) { .chars < 41 ?? $_ !! .substr(0,20) ~ '…' ~ .substr(*-20) ~ \" ({.chars} digits)\" }\n\nsay \"Smarandache-Wellin primes:\";\nsay ordinal-digit(++$,:u).fmt(\"%4s\") ~ $_ for (^∞).hyper(:4batch).map({\n next unless (my $sw = @Smarandache-Wellin[$_]).is-prime;\n sprintf \": Index: %4d, Last prime: %5d, %s\", $_, @primes[$_], $sw.&abbr\n})[^8];\n\nsay \"\\nSmarandache-Wellin derived primes:\";\nsay ordinal-digit(++$,:u).fmt(\"%4s\") ~ $_ for (^∞).hyper(:8batch).map({\n next unless (my $sw = @Smarandache-Wellin[$_].&derived).is-prime;\n sprintf \": Index: %4d, %s\", $_, $sw\n})[^20];\n\n```\n\nOutput:\n\n```\nSmarandache-Wellin primes:\n 1ˢᵗ: Index: 0, Last prime: 2, 2\n 2ⁿᵈ: Index: 1, Last prime: 3, 23\n 3ʳᵈ: Index: 3, Last prime: 7, 2357\n 4ᵗʰ: Index: 127, Last prime: 719, 23571113171923293137…73677683691701709719 (355 digits)\n 5ᵗʰ: Index: 173, Last prime: 1033, 23571113171923293137…10131019102110311033 (499 digits)\n 6ᵗʰ: Index: 341, Last prime: 2297, 23571113171923293137…22732281228722932297 (1171 digits)\n 7ᵗʰ: Index: 434, Last prime: 3037, 23571113171923293137…30013011301930233037 (1543 digits)\n 8ᵗʰ: Index: 1428, Last prime: 11927, 23571113171923293137…11903119091192311927 (5719 digits)\n\nSmarandache-Wellin derived primes:\n 1ˢᵗ: Index: 31, 4194123321127\n 2ⁿᵈ: Index: 71, 547233879626521\n 3ʳᵈ: Index: 72, 547233979727521\n 4ᵗʰ: Index: 133, 13672766322929571043\n 5ᵗʰ: Index: 224, 3916856106393739943689\n 6ᵗʰ: Index: 302, 462696313560586013558131\n 7ᵗʰ: Index: 308, 532727113760586013758133\n 8ᵗʰ: Index: 362, 6430314317473636515467149\n 9ᵗʰ: Index: 461, 8734722823685889120488197\n10ᵗʰ: Index: 489, 9035923128899919621189209\n11ᵗʰ: Index: 494, 9036023329699969621389211\n12ᵗʰ: Index: 521, 9337023533410210710923191219\n13ᵗʰ: Index: 537, 94374237357103109113243102223\n14ᵗʰ: Index: 623, 117416265406198131121272110263\n15ᵗʰ: Index: 720, 141459282456260193137317129313\n16ᵗʰ: Index: 737, 144466284461264224139325131317\n17ᵗʰ: Index: 789, 156483290479273277162351153339\n18ᵗʰ: Index: 851, 164518312512286294233375158359\n19ᵗʰ: Index: 1086, 208614364610327343341589284471\n20ᵗʰ: Index: 1187, 229667386663354357356628334581\n```"
}
]
|
[
{
"role": "user",
"content": "Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.\n\nBy definition, all primes are *excluded* as they (naturally) satisfy this condition!\n\nSmith numbers are also known as *joke* numbers.\n\nExample\n\nUsing the number **166** \nFind the prime factors of **166** which are: **2** x **83** \nThen, take those two prime factors and sum all their decimal digits: **2 + 8 + 3** which is **13** \nThen, take the decimal digits of **166** and add their decimal digits: **1 + 6 + 6** which is **13** \nTherefore, the number **166** is a Smith number.\n\nTask\n\nWrite a program to find all Smith numbers *below* 10000.\n\nSee also\n\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number].\n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n].\n* from The Prime pages: [Smith numbers]."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nconstant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;\n \nmulti factors ( 1 ) { 1 }\nmulti factors ( Int $remainder is copy ) {\n gather for @primes -> $factor {\n \n # if remainder < factor², we're done\n if $factor * $factor > $remainder {\n take $remainder if $remainder > 1;\n last;\n }\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# Code above here is verbatim from RC:Count_in_factors#Raku\n\nsub is_smith_number ( Int $n ) {\n (!$n.is-prime) and ( [+] $n.comb ) == ( [+] factors($n).join.comb );\n}\n\nmy @s = grep &is_smith_number, 2 ..^ 10_000;\nsay \"{@s.elems} Smith numbers below 10_000\";\nsay 'First 10: ', @s[ ^10 ];\nsay 'Last 10: ', @s[ *-10 .. * ];\n\n```\n\nOutput:\n\n```\n376 Smith numbers below 10_000\nFirst 10: (4 22 27 58 85 94 121 166 202 265)\nLast 10: (9843 9849 9861 9880 9895 9924 9942 9968 9975 9985)\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Snake\\_(video\\_game). 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\nSnake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.\n\nTask\n\nImplement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.\n\nEach item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.\n\nThe game ends when the snake attempts to eat himself."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2016.08\n\nThis is a variation of a demo script included in the examples folder for the Raku SDL2::Raw library bindings.\n\n```\nuse SDL2::Raw;\nuse Cairo;\n\nconstant W = 1280;\nconstant H = 960;\n\nconstant FIELDW = W div 32;\nconstant FIELDH = H div 32;\n\nSDL_Init(VIDEO);\n\nmy $window = SDL_CreateWindow(\n 'Snake',\n SDL_WINDOWPOS_CENTERED_MASK,\n SDL_WINDOWPOS_CENTERED_MASK,\n W, H,\n OPENGL\n);\n\nmy $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);\n\nmy $snake_image = Cairo::Image.record(\n -> $_ {\n .save;\n .rectangle: 0, 0, 64, 64;\n .clip;\n .rgb: 0, 1, 0;\n .rectangle: 0, 0, 64, 64;\n .fill :preserve;\n .rgb: 0, 0, 0;\n .stroke;\n .restore;\n\n .save;\n .translate: 64, 0;\n .rectangle: 0, 0, 64, 64;\n .clip;\n .rgb: 1, 0, 0;\n .arc: 32, 32, 30, 0, 2 * pi;\n .fill :preserve;\n .rgb: 0, 0, 0;\n .stroke;\n .restore;\n }, 128, 128, Cairo::FORMAT_ARGB32);\n\nmy $snake_texture = SDL_CreateTexture(\n $render,\n %PIXELFORMAT<ARGB8888>,\n STATIC,\n 128,\n 128\n);\n\nSDL_UpdateTexture(\n $snake_texture,\n SDL_Rect.new(\n :x(0),\n :y(0),\n :w(128),\n :h(128)\n ),\n $snake_image.data,\n $snake_image.stride // 128 * 4\n);\n\nSDL_SetTextureBlendMode($snake_texture, 1);\n\nSDL_SetRenderDrawBlendMode($render, 1);\n\nmy $snakepiece_srcrect = SDL_Rect.new(:w(64), :h(64));\nmy $nompiece_srcrect = SDL_Rect.new(:w(64), :h(64), :x(64));\n\nmy $event = SDL_Event.new;\n\nenum GAME_KEYS (\n K_UP => 82,\n K_DOWN => 81,\n K_LEFT => 80,\n K_RIGHT => 79,\n);\n\nmy Complex @snakepieces = 10+10i;\nmy Complex @noms;\nmy Complex $snakedir = 1+0i;\nmy $nomspawn = 0;\nmy $snakespeed = 0.1;\nmy $snakestep = 0;\nmy $nom = 4;\n\nmy $last_frame_start = now;\nmain: loop {\n my $start = now;\n my $dt = $start - $last_frame_start // 0.00001;\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 == KEYDOWN {\n if GAME_KEYS(.scancode) -> $comm {\n given $comm {\n when 'K_LEFT' { $snakedir = -1+0i unless $snakedir == 1+0i }\n when 'K_RIGHT' { $snakedir = 1+0i unless $snakedir == -1+0i }\n when 'K_UP' { $snakedir = 0-1i unless $snakedir == 0+1i }\n when 'K_DOWN' { $snakedir = 0+1i unless $snakedir == 0-1i }\n }\n }\n }\n }\n }\n\n if ($nomspawn -= $dt) < 0 {\n $nomspawn += 1;\n @noms.push: (^FIELDW).pick + (^FIELDH).pick * i unless @noms > 3;\n @noms.pop if @noms[*-1] == any(@snakepieces);\n }\n\n if ($snakestep -= $dt) < 0 {\n $snakestep += $snakespeed;\n\n @snakepieces.unshift: do given @snakepieces[0] {\n ($_.re + $snakedir.re) % FIELDW\n + (($_.im + $snakedir.im) % FIELDH) * i\n }\n\n if @snakepieces[2..*].first( * == @snakepieces[0], :k ) -> $idx {\n @snakepieces = @snakepieces[0..($idx + 1)];\n }\n\n @noms .= grep(\n { $^piece == @snakepieces[0] ?? ($nom += 1) && False !! True }\n );\n\n if $nom == 0 {\n @snakepieces.pop;\n } else {\n $nom = $nom - 1;\n }\n }\n\n for @snakepieces {\n SDL_SetTextureColorMod(\n $snake_texture,\n 255,\n (cos((++$) / 2) * 100 + 155).round,\n 255\n );\n\n SDL_RenderCopy(\n $render,\n $snake_texture,\n $snakepiece_srcrect,\n SDL_Rect.new(.re * 32, .im * 32, 32, 32)\n );\n }\n\n SDL_SetTextureColorMod($snake_texture, 255, 255, 255);\n\n for @noms {\n SDL_RenderCopy(\n $render,\n $snake_texture,\n $nompiece_srcrect,\n SDL_Rect.new(.re * 32, .im * 32, 32, 32)\n )\n }\n\n SDL_RenderPresent($render);\n SDL_SetRenderDrawColor($render, 0, 0, 0, 0);\n SDL_RenderClear($render);\n\n $last_frame_start = $start;\n sleep(1 / 50);\n}\n\nSDL_Quit();\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a Snakes and Ladders game where the computer plays against a human player.\n\nThis game is also known as **Chutes and Ladders**.\n\nFor a board example you can use this image here: snakes & ledders.\n\n(A **ledder** is the Old English word for a **ladder**.)\n\nThe way you'll represent the board and the players' tokens is totally up to you: graphics or ASCII graphics or even just text.\n\nHappy coding."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.01\n\nSnakes and ladders is entirely chance based, so human interaction is not really required. This version allows up to one human player against any number of computer players and asks for input... but doesn't really *need* or even *use* it. I didn't bother to implement a graphical interface.\n\n```\n # board layout\nmy %snl = 4, 14, 9, 31, 17, 7, 20, 38, 28, 84, 40, 59, 51, 67, 54, 34,\n 62, 19, 63, 81, 64, 60, 71, 91, 87, 24, 93, 73, 95, 75, 99, 78;\n\nmy @players = 1, 1, 1; # three players, starting on square 1\nmy $human = 1; # player 1 is human. set to 0 for all computer players\n\nloop {\n for ^@players -> $player {\n turn(@players[$player], $player + 1);\n }\n say '';\n}\n\nsub turn ($square is rw, $player) {\n if $player == $human {\n prompt \"You are on square $square. Hit enter to roll the die.\";\n }\n my $roll = (1..6).roll;\n my $turn = $square + $roll;\n printf \"Player $player on square %2d rolls a $roll\", $square;\n if $turn > 100 {\n say \" but cannot move. Next players turn.\";\n return $square;\n }\n if %snl{$turn} {\n $square = %snl{$turn};\n if $turn > $square {\n say \". Oops! Landed on a snake. Slither down to $square.\"\n } else {\n say \". Yay! Landed on a ladder. Climb up to $square.\"\n }\n } else {\n $square = $turn;\n say \" and moves to square $square\";\n }\n say \"Player $player wins!\" and exit if $square == 100;\n return $square;\n}\n\n```\n\nSample output:\n\n```\nYou are on square 1. Hit enter to roll the die.\nPlayer 1 on square 1 rolls a 1 and moves to square 2\nPlayer 2 on square 1 rolls a 4 and moves to square 5\nPlayer 3 on square 1 rolls a 1 and moves to square 2\n\nYou are on square 2. Hit enter to roll the die.\nPlayer 1 on square 2 rolls a 1 and moves to square 3\nPlayer 2 on square 5 rolls a 2 and moves to square 7\nPlayer 3 on square 2 rolls a 3 and moves to square 5\n\nYou are on square 3. Hit enter to roll the die.\nPlayer 1 on square 3 rolls a 4 and moves to square 7\nPlayer 2 on square 7 rolls a 1 and moves to square 8\nPlayer 3 on square 5 rolls a 2 and moves to square 7\n\nYou are on square 7. Hit enter to roll the die.\nPlayer 1 on square 7 rolls a 2. Yay! Landed on a ladder. Climb up to 31.\nPlayer 2 on square 8 rolls a 3 and moves to square 11\nPlayer 3 on square 7 rolls a 2. Yay! Landed on a ladder. Climb up to 31.\n\n ... about 15 turns omitted ...\n\nYou are on square 90. Hit enter to roll the die.\nPlayer 1 on square 90 rolls a 3. Oops! Landed on a snake. Slither down to 73.\nPlayer 2 on square 55 rolls a 3 and moves to square 58\nPlayer 3 on square 90 rolls a 4 and moves to square 94\n\nYou are on square 73. Hit enter to roll the die.\nPlayer 1 on square 73 rolls a 6 and moves to square 79\nPlayer 2 on square 58 rolls a 5. Yay! Landed on a ladder. Climb up to 81.\nPlayer 3 on square 94 rolls a 3 and moves to square 97\n\nYou are on square 79. Hit enter to roll the die.\nPlayer 1 on square 79 rolls a 3 and moves to square 82\nPlayer 2 on square 81 rolls a 6. Oops! Landed on a snake. Slither down to 24.\nPlayer 3 on square 97 rolls a 5 but cannot move. Next players turn.\n\nYou are on square 82. Hit enter to roll the die.\nPlayer 1 on square 82 rolls a 5. Oops! Landed on a snake. Slither down to 24.\nPlayer 2 on square 24 rolls a 6 and moves to square 30\nPlayer 3 on square 97 rolls a 4 but cannot move. Next players turn.\n\nYou are on square 24. Hit enter to roll the die.\nPlayer 1 on square 24 rolls a 4. Yay! Landed on a ladder. Climb up to 84.\nPlayer 2 on square 30 rolls a 5 and moves to square 35\nPlayer 3 on square 97 rolls a 4 but cannot move. Next players turn.\n\nYou are on square 84. Hit enter to roll the die.\nPlayer 1 on square 84 rolls a 1 and moves to square 85\nPlayer 2 on square 35 rolls a 2 and moves to square 37\nPlayer 3 on square 97 rolls a 3 and moves to square 100\nPlayer 3 wins!\n```"
}
]
|
[
{
"role": "user",
"content": "In this task, the goal is to create a SOAP client which accesses functions defined at **http://example.com/soap/wsdl**, and calls the functions **soapFunc( )** and **anotherSoapFunc( )**.\n\nThis 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."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n# Reference:\n# https://github.com/retupmoca/P6-SOAP\n# http://wiki.dreamfactory.com/DreamFactory/Tutorials/Temp_Conversion_SOAP_API\n\nuse v6;\nuse SOAP::Client;\n\nmy $request = SOAP::Client.new('http://www.w3schools.com/xml/tempconvert.asmx?WSDL') or die;\n\nsay $request.call('CelsiusToFahrenheit', Celsius => 100 ) or die;\n\nsay $request.call('FahrenheitToCelsius', Fahrenheit => 212 ) or die;\n\n```\n\nOutput:\n\n```\n{CelsiusToFahrenheitResult => [212]}\n{FahrenheitToCelsiusResult => [100]}\n\n```"
}
]
|
[
{
"role": "user",
"content": "For this exercise a program is open a socket to localhost on port 256 and send the message \"hello socket world\" before closing the socket.\n\nCatching any exceptions or errors is not required."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.03\n\nWill fail with a connect error if there is not a socket server of some kind available on the specified host and port.\n\n```\nmy $host = '127.0.0.1';\nmy $port = 256;\n\nmy $client = IO::Socket::INET.new(:$host, :$port);\n$client.print( 'hello socket world' );\n$client.close;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.\n\nSokoban levels are usually stored as a character array where\n\n* *space* is an empty square\n* # is a wall\n* @ is the player\n* $ is a box\n* . is a goal\n* + is the player on a goal\n* \\* is a box on a goal\n\n```\n#######\n# #\n# #\n#. # #\n#. $$ #\n#.$$ #\n#.# @#\n#######\n\n```\n\nSokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (**l**eft, **u**p, **r**ight, **d**own) direction and capital LURD represents a push.\n\nPlease state if you use some other format for either the input or output, and why.\n\nFor more information, see the Sokoban wiki."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Go\n\n```\nsub MAIN() {\n my $level = q:to//;\n#######\n# #\n# #\n#. # #\n#. $$ #\n#.$$ #\n#.# @#\n#######\n\n say 'level:';\n print $level;\n say 'solution:';\n say solve($level);\n} \n \nclass State {\n has Str $.board;\n has Str $.sol;\n has Int $.pos;\n\n method move(Int $delta --> Str) {\n my $new = $!board;\n if $new.substr($!pos,1) eq '@' {\n substr-rw($new,$!pos,1) = ' ';\n } else {\n substr-rw($new,$!pos,1) = '.';\n }\n my $pos := $!pos + $delta;\n if $new.substr($pos,1) eq ' ' {\n substr-rw($new,$pos,1) = '@';\n } else {\n substr-rw($new,$pos,1) = '+';\n }\n return $new;\n }\n \n method push(Int $delta --> Str) {\n my $pos := $!pos + $delta;\n my $box := $pos + $delta;\n return '' unless $!board.substr($box,1) eq ' ' | '.';\n my $new = $!board;\n if $new.substr($!pos,1) eq '@' {\n substr-rw($new,$!pos,1) = ' ';\n } else {\n substr-rw($new,$!pos,1) = '.';\n }\n if $new.substr($pos,1) eq '$' {\n substr-rw($new,$pos,1) = '@';\n } else {\n substr-rw($new,$pos,1) = '+';\n }\n if $new.substr($box,1) eq ' ' {\n substr-rw($new,$box,1) = '$';\n } else {\n substr-rw($new,$box,1) = '*';\n }\n return $new;\n }\n}\n \nsub solve(Str $start --> Str) {\n my $board = $start;\n my $width = $board.lines[0].chars + 1;\n my @dirs =\n [\"u\", \"U\", -$width],\n [\"r\", \"R\", 1],\n [\"d\", \"D\", $width],\n [\"l\", \"L\", -1];\n\n my %visited = $board => True;\n\n my $pos = $board.index('@');\n my @open = State.new(:$board, :sol(''), :$pos);\n while @open {\n my $state = @open.shift;\n for @dirs -> [$move, $push, $delta] {\n my $board;\n my $sol;\n my $pos = $state.pos + $delta;\n given $state.board.substr($pos,1) {\n when '$' | '*' {\n $board = $state.push($delta);\n next if $board eq \"\" || %visited{$board};\n $sol = $state.sol ~ $push;\n return $sol unless $board ~~ /<[ . + ]>/;\n }\n when ' ' | '.' {\n $board = $state.move($delta);\n next if %visited{$board};\n $sol = $state.sol ~ $move;\n }\n default { next }\n }\n @open.push: State.new: :$board, :$sol, :$pos;\n %visited{$board} = True;\n }\n }\n return \"No solution\";\n}\n\n```\n\nOutput:\n\n```\nLevel:\n#######\n# #\n# #\n#. # #\n#. $$ #\n#.$$ #\n#.# @#\n#######\nSolution:\nulULLulDDurrrddlULrruLLrrUruLLLulD\n```"
}
]
|
[
{
"role": "user",
"content": "Soloway's Recurring Rainfall is commonly used to assess general programming knowledge by requiring basic program structure, input/output, and program exit procedure.\n\n**The problem:**\n\nWrite a program that will read in integers and output their average. Stop reading when the value 99999 is input.\n\nFor languages that aren't traditionally interactive, the program can read in values as makes sense and stopping once 99999 is encountered. The classic rainfall problem comes from identifying success of Computer Science programs with their students, so the original problem statement is written above -- though it may not strictly apply to a given language in the modern era.\n\n**Implementation Details:**\n\n* Only Integers are to be accepted as input\n* Output should be floating point\n* Rainfall can be negative (https://www.geographyrealm.com/what-is-negative-rainfall/)\n* For languages where the user is inputting data, the number of data inputs can be \"infinite\"\n* A complete implementation should handle error cases reasonably (asking the user for more input, skipping the bad value when encountered, etc)\n\nThe purpose of this problem, as originally proposed in the 1980's through its continued use today, is to just show fundamentals of CS: iteration, branching, program structure, termination, management of data types, input/output (where applicable), etc with things like input validation or management of numerical limits being more \"advanced\". It isn't meant to literally be a rainfall calculator so implementations should strive to implement the solution clearly and simply.\n\n**References:**\n\n* http://cs.brown.edu/~kfisler/Pubs/icer14-rainfall/icer14.pdf\n* https://www.curriculumonline.ie/getmedia/8bb01bff-509e-48ed-991e-3ab5dad74a78/Seppletal-2015-DoweknowhowdifficulttheRainfallProblemis.pdf\n* https://en.wikipedia.org/wiki/Moving\\_average#Cumulative\\_average"
},
{
"role": "assistant",
"content": "This task seems to be more about following (kind of vague) instructions and anticipating error conditions rather than solving a rather simple problem.\n\nI notice that units are specified for neither measurement; time nor rainfall accumulation. Time is assumed to always increment in units of one, rainfall in some non-negative integer. \"Integer\" gets a little leeway in this entry. Floating point numbers or Rational numbers that are exactly equal to an Integer are allowed, even if they are technically not integers.\n\n#### After update to spec:\n\nNot going to bother to allow negative rainfall amounts. The \"Negative rainfall\" cited in the linked article references \"total accumulated groundwater\" **NOT** precipitation. Evaporation isn't rainfall. Much like dew or fog is not rainfall.\n\n**Further**, the linked reference article for Soloway's Recurring Rainfall ***SPECIFICALLY*** discusses marking an implementation as incorrect, or at least lacking, if it doesn't ignore and discard negative entries. You can't have it both ways.\n\n```\n# Write a program that will read in integers and\n# output their average. Stop reading when the\n# value 99999 is input.\n\n\nmy ($periods, $accumulation, $rainfall) = 0, 0;\n\nloop {\n loop {\n $rainfall = prompt 'Integer units of rainfall in this time period? (999999 to finalize and exit)>: ';\n last if $rainfall.chars and $rainfall.Numeric !~~ Failure and $rainfall.narrow ~~ Int and $rainfall ≥ 0;\n say 'Invalid input, try again.';\n }\n last if $rainfall == 999999;\n ++$periods;\n $accumulation += $rainfall;\n say-it;\n}\n\nsay-it;\n\nsub say-it { printf \"Average rainfall %.2f units over %d time periods.\\n\", ($accumulation / $periods) || 0, $periods }\n\n```\n\nOutput:\n\n```\n# Normal operation\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 0\nAverage rainfall 0.00 units over 1 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 2\nAverage rainfall 1.00 units over 2 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 4\nAverage rainfall 2.00 units over 3 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 6\nAverage rainfall 3.00 units over 4 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 8\nAverage rainfall 4.00 units over 5 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 999999\nAverage rainfall 4.00 units over 5 time periods.\n\n\n# Invalid entries and valid but not traditional \"Integer\" entries demonstrated \nInteger units of rainfall in this time period? (999999 to finalize and exit)>: a\nInvalid input, try again.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 1.1\nInvalid input, try again.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>:\nInvalid input, try again.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 2.0\nAverage rainfall 2.00 units over 1 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: .3e1\nAverage rainfall 2.50 units over 2 time periods.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 999999\nAverage rainfall 2.50 units over 2 time periods.\n\n\n# Valid summary with no entries demonstrated.\nInteger units of rainfall in this time period? (999999 to finalize and exit)>: 999999\nAverage rainfall 0.00 units over 0 time periods.\n```"
}
]
|
[
{
"role": "user",
"content": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n + The grid is not necessarily rectangular.\n + The grid may have holes in it.\n + The grid is always connected.\n + The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n + It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n + Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n + A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\n\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\nRelated tasks\n\n* A\\* search algorithm\n* N-queens problem\n* Solve a Holy Knight's tour\n* Knight's tour\n* Solve a Hopido puzzle\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle;"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis uses a Warnsdorff solver, which cuts down the number of tries by more than a factor of six over the brute force approach. This same solver is used in:\n\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle\n\n```\nmy @adjacent = [-1, -1], [-1, 0], [-1, 1],\n [ 0, -1], [ 0, 1],\n [ 1, -1], [ 1, 0], [ 1, 1];\n\nsolveboard q:to/END/;\n __ 33 35 __ __ .. .. ..\n __ __ 24 22 __ .. .. ..\n __ __ __ 21 __ __ .. ..\n __ 26 __ 13 40 11 .. ..\n 27 __ __ __ 9 __ 1 ..\n .. .. __ __ 18 __ __ ..\n .. .. .. .. __ 7 __ __\n .. .. .. .. .. .. 5 __\n END\n \nsub solveboard($board) {\n my $max = +$board.comb(/\\w+/);\n my $width = $max.chars;\n\n my @grid;\n my @known;\n my @neigh;\n my @degree;\n \n @grid = $board.lines.map: -> $line {\n [ $line.words.map: { /^_/ ?? 0 !! /^\\./ ?? Rat !! $_ } ]\n }\n \n sub neighbors($y,$x --> List) {\n eager gather for @adjacent {\n my $y1 = $y + .[0];\n my $x1 = $x + .[1];\n take [$y1,$x1] if defined @grid[$y1][$x1];\n }\n }\n\n for ^@grid -> $y {\n for ^@grid[$y] -> $x {\n if @grid[$y][$x] -> $v {\n @known[$v] = [$y,$x];\n }\n if @grid[$y][$x].defined {\n @neigh[$y][$x] = neighbors($y,$x);\n @degree[$y][$x] = +@neigh[$y][$x];\n }\n }\n }\n print \"\\e[0H\\e[0J\";\n\n my $tries = 0;\n\n try_fill 1, @known[1];\n\n sub try_fill($v, $coord [$y,$x] --> Bool) {\n return True if $v > $max;\n $tries++;\n\n my $old = @grid[$y][$x];\n\n return False if +$old and $old != $v;\n return False if @known[$v] and @known[$v] !eqv $coord;\n\n @grid[$y][$x] = $v; # conjecture grid value\n\n print \"\\e[0H\"; # show conjectured board\n for @grid -> $r {\n say do for @$r {\n when Rat { ' ' x $width }\n when 0 { '_' x $width }\n default { .fmt(\"%{$width}d\") }\n }\n }\n\n\n my @neighbors = @neigh[$y][$x][];\n\n my @degrees;\n for @neighbors -> \\n [$yy,$xx] {\n my $d = --@degree[$yy][$xx]; # conjecture new degrees\n push @degrees[$d], n; # and categorize by degree\n }\n\n for @degrees.grep(*.defined) -> @ties {\n for @ties.reverse { # reverse works better for this hidato anyway\n return True if try_fill $v + 1, $_;\n }\n }\n\n for @neighbors -> [$yy,$xx] {\n ++@degree[$yy][$xx]; # undo degree conjectures\n }\n\n @grid[$y][$x] = $old; # undo grid value conjecture\n return False;\n }\n \n say \"$tries tries\";\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.\n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\nExample\n\n```\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n```\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\nRelated tasks\n\n* A\\* search algorithm\n* Knight's tour\n* N-queens problem\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis uses a Warnsdorff solver, which cuts down the number of tries by more than a factor of six over the brute force approach. This same solver is used in:\n\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle\n\n```\nmy @adjacent =\n [ -2, -1], [ -2, 1],\n [-1,-2], [-1,+2],\n [+1,-2], [+1,+2],\n [ +2, -1], [ +2, 1];\n\nput \"\\n\" xx 60;\n\nsolveboard q:to/END/;\n . 0 0 0\n . 0 . 0 0\n . 0 0 0 0 0 0 0\n 0 0 0 . . 0 . 0\n 0 . 0 . . 0 0 0\n 1 0 0 0 0 0 0\n . . 0 0 . 0\n . . . 0 0 0\n END\n\nsub solveboard($board) {\n my $max = +$board.comb(/\\w+/);\n my $width = $max.chars;\n\n my @grid;\n my @known;\n my @neigh;\n my @degree;\n \n @grid = $board.lines.map: -> $line {\n [ $line.words.map: { /^_/ ?? 0 !! /^\\./ ?? Rat !! $_ } ]\n }\n \n sub neighbors($y,$x --> List) {\n eager gather for @adjacent {\n my $y1 = $y + .[0];\n my $x1 = $x + .[1];\n take [$y1,$x1] if defined @grid[$y1][$x1];\n }\n }\n\n for ^@grid -> $y {\n for ^@grid[$y] -> $x {\n if @grid[$y][$x] -> $v {\n @known[$v] = [$y,$x];\n }\n if @grid[$y][$x].defined {\n @neigh[$y][$x] = neighbors($y,$x);\n @degree[$y][$x] = +@neigh[$y][$x];\n }\n }\n }\n print \"\\e[0H\\e[0J\";\n\n my $tries = 0;\n\n try_fill 1, @known[1];\n\n sub try_fill($v, $coord [$y,$x] --> Bool) {\n return True if $v > $max;\n $tries++;\n\n my $old = @grid[$y][$x];\n\n return False if +$old and $old != $v;\n return False if @known[$v] and @known[$v] !eqv $coord;\n\n @grid[$y][$x] = $v; # conjecture grid value\n\n print \"\\e[0H\"; # show conjectured board\n for @grid -> $r {\n say do for @$r {\n when Rat { ' ' x $width }\n when 0 { '_' x $width }\n default { .fmt(\"%{$width}d\") }\n }\n }\n\n\n my @neighbors = @neigh[$y][$x][];\n\n my @degrees;\n for @neighbors -> \\n [$yy,$xx] {\n my $d = --@degree[$yy][$xx]; # conjecture new degrees\n push @degrees[$d], n; # and categorize by degree\n }\n\n for @degrees.grep(*.defined) -> @ties {\n for @ties.reverse { # reverse works better for this hidato anyway\n return True if try_fill $v + 1, $_;\n }\n }\n\n for @neighbors -> [$yy,$xx] {\n ++@degree[$yy][$xx]; # undo degree conjectures\n }\n\n @grid[$y][$x] = $old; # undo grid value conjecture\n return False;\n }\n \n say \"$tries tries\";\n}\n\n```\n\nOutput:\n\n```\n 25 14 27\n 36 24 15\n 31 26 13 28 23 6 17\n35 12 29 16 22\n30 32 7 18 5\n 1 34 11 8 19 4 21\n 2 33 9\n 10 3 20\n84 tries\n```"
}
]
|
[
{
"role": "user",
"content": "Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:\n\n\"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!\"\n\nKnowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.\n\nExample:\n\n```\n. 0 0 . 0 0 .\n0 0 0 0 0 0 0\n0 0 0 0 0 0 0\n. 0 0 0 0 0 .\n. . 0 0 0 . .\n. . . 0 . . .\n\n```\n\nExtra credits are available for other interesting designs.\n\nRelated tasks\n\n* A\\* search algorithm\n* Solve a Holy Knight's tour\n* Knight's tour\n* N-queens problem\n* Solve a Hidato puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis uses a Warnsdorff solver, which cuts down the number of tries by more than a factor of six over the brute force approach. This same solver is used in:\n\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle\n\n```\nmy @adjacent = [3, 0],\n [2, -2], [2, 2],\n [0, -3], [0, 3],\n [-2, -2], [-2, 2],\n [-3, 0];\n\nsolveboard q:to/END/;\n . _ _ . _ _ .\n _ _ _ _ _ _ _\n _ _ _ _ _ _ _\n . _ _ _ _ _ .\n . . _ _ _ . .\n . . . 1 . . .\n END\n\nsub solveboard($board) {\n my $max = +$board.comb(/\\w+/);\n my $width = $max.chars;\n\n my @grid;\n my @known;\n my @neigh;\n my @degree;\n \n @grid = $board.lines.map: -> $line {\n [ $line.words.map: { /^_/ ?? 0 !! /^\\./ ?? Rat !! $_ } ]\n }\n \n sub neighbors($y,$x --> List) {\n eager gather for @adjacent {\n my $y1 = $y + .[0];\n my $x1 = $x + .[1];\n take [$y1,$x1] if defined @grid[$y1][$x1];\n }\n }\n\n for ^@grid -> $y {\n for ^@grid[$y] -> $x {\n if @grid[$y][$x] -> $v {\n @known[$v] = [$y,$x];\n }\n if @grid[$y][$x].defined {\n @neigh[$y][$x] = neighbors($y,$x);\n @degree[$y][$x] = +@neigh[$y][$x];\n }\n }\n }\n print \"\\e[0H\\e[0J\";\n\n my $tries = 0;\n\n try_fill 1, @known[1];\n\n sub try_fill($v, $coord [$y,$x] --> Bool) {\n return True if $v > $max;\n $tries++;\n\n my $old = @grid[$y][$x];\n\n return False if +$old and $old != $v;\n return False if @known[$v] and @known[$v] !eqv $coord;\n\n @grid[$y][$x] = $v; # conjecture grid value\n\n print \"\\e[0H\"; # show conjectured board\n for @grid -> $r {\n say do for @$r {\n when Rat { ' ' x $width }\n when 0 { '_' x $width }\n default { .fmt(\"%{$width}d\") }\n }\n }\n\n\n my @neighbors = @neigh[$y][$x][];\n\n my @degrees;\n for @neighbors -> \\n [$yy,$xx] {\n my $d = --@degree[$yy][$xx]; # conjecture new degrees\n push @degrees[$d], n; # and categorize by degree\n }\n\n for @degrees.grep(*.defined) -> @ties {\n for @ties.reverse { # reverse works better for this hidato anyway\n return True if try_fill $v + 1, $_;\n }\n }\n\n for @neighbors -> [$yy,$xx] {\n ++@degree[$yy][$xx]; # undo degree conjectures\n }\n\n @grid[$y][$x] = $old; # undo grid value conjecture\n return False;\n }\n \n say \"$tries tries\";\n}\n\n```\n\nOutput:\n\n```\n 21 4 20 3 \n26 12 15 25 11 14 24\n17 6 9 18 5 8 19\n 22 27 13 23 2 \n 16 7 10 \n 1 \n59 tries\n```"
}
]
|
[
{
"role": "user",
"content": "Numbrix puzzles are similar to Hidato.\nThe most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).\nPublished puzzles also tend not to have holes in the grid and may not always indicate the end node.\nTwo examples follow:\n\nExample 1\n\nProblem.\n\n```\n 0 0 0 0 0 0 0 0 0\n 0 0 46 45 0 55 74 0 0\n 0 38 0 0 43 0 0 78 0\n 0 35 0 0 0 0 0 71 0\n 0 0 33 0 0 0 59 0 0\n 0 17 0 0 0 0 0 67 0\n 0 18 0 0 11 0 0 64 0\n 0 0 24 21 0 1 2 0 0\n 0 0 0 0 0 0 0 0 0\n\n```\n\nSolution.\n\n```\n 49 50 51 52 53 54 75 76 81\n 48 47 46 45 44 55 74 77 80\n 37 38 39 40 43 56 73 78 79\n 36 35 34 41 42 57 72 71 70\n 31 32 33 14 13 58 59 68 69\n 30 17 16 15 12 61 60 67 66\n 29 18 19 20 11 62 63 64 65\n 28 25 24 21 10 1 2 3 4\n 27 26 23 22 9 8 7 6 5\n\n```\n\nExample 2\n\nProblem.\n\n```\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n\n```\n\nSolution.\n\n```\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n 34 33 4 3 24 23 58 57 68\n 35 32 31 2 25 54 55 56 69\n 36 37 30 1 26 53 74 73 70\n 39 38 29 28 27 52 75 72 71\n 40 43 44 47 48 51 76 77 78\n 41 42 45 46 49 50 81 80 79\n\n```\n\nTask\n\nWrite a program to solve puzzles of this ilk,\ndemonstrating your program by solving the above examples.\nExtra credit for other interesting examples.\n\nRelated tasks\n\n* A\\* search algorithm\n* Solve a Holy Knight's tour\n* Knight's tour\n* N-queens problem\n* Solve a Hidato puzzle\n* Solve a Holy Knight's tour\n* Solve a Hopido puzzle\n* Solve the no connection puzzle"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis uses a Warnsdorff solver, which cuts down the number of tries by more than a factor of six over the brute force approach. This same solver is used in:\n\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle\n\n```\nmy @adjacent = [-1, 0],\n [ 0, -1], [ 0, 1],\n [ 1, 0];\nput \"\\n\" xx 60;\n\nsolveboard q:to/END/;\n __ __ __ __ __ __ __ __ __\n __ __ 46 45 __ 55 74 __ __\n __ 38 __ __ 43 __ __ 78 __\n __ 35 __ __ __ __ __ 71 __\n __ __ 33 __ __ __ 59 __ __\n __ 17 __ __ __ __ __ 67 __\n __ 18 __ __ 11 __ __ 64 __\n __ __ 24 21 __ 1 2 __ __\n __ __ __ __ __ __ __ __ __\n END\n\n# And\nput \"\\n\" xx 60;\n\nsolveboard q:to/END/;\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n END\n\n\nsub solveboard($board) {\n my $max = +$board.comb(/\\w+/);\n my $width = $max.chars;\n\n my @grid;\n my @known;\n my @neigh;\n my @degree;\n\n @grid = $board.lines.map: -> $line {\n [ $line.words.map: { /^_/ ?? 0 !! /^\\./ ?? Rat !! $_ } ]\n }\n\n sub neighbors($y,$x --> List) {\n eager gather for @adjacent {\n my $y1 = $y + .[0];\n my $x1 = $x + .[1];\n take [$y1,$x1] if defined @grid[$y1][$x1];\n }\n }\n\n for ^@grid -> $y {\n for ^@grid[$y] -> $x {\n if @grid[$y][$x] -> $v {\n @known[$v] = [$y,$x];\n }\n if @grid[$y][$x].defined {\n @neigh[$y][$x] = neighbors($y,$x);\n @degree[$y][$x] = +@neigh[$y][$x];\n }\n }\n }\n print \"\\e[0H\\e[0J\";\n\n my $tries = 0;\n\n try_fill 1, @known[1];\n\n sub try_fill($v, $coord [$y,$x] --> Bool) {\n return True if $v > $max;\n $tries++;\n\n my $old = @grid[$y][$x];\n\n return False if +$old and $old != $v;\n return False if @known[$v] and @known[$v] !eqv $coord;\n\n @grid[$y][$x] = $v; # conjecture grid value\n\n print \"\\e[0H\"; # show conjectured board\n for @grid -> $r {\n say do for @$r {\n when Rat { ' ' x $width }\n when 0 { '_' x $width }\n default { .fmt(\"%{$width}d\") }\n }\n }\n\n\n my @neighbors = @neigh[$y][$x][];\n\n my @degrees;\n for @neighbors -> \\n [$yy,$xx] {\n my $d = --@degree[$yy][$xx]; # conjecture new degrees\n push @degrees[$d], n; # and categorize by degree\n }\n\n for @degrees.grep(*.defined) -> @ties {\n for @ties.reverse { # reverse works better for this hidato anyway\n return True if try_fill $v + 1, $_;\n }\n }\n\n for @neighbors -> [$yy,$xx] {\n ++@degree[$yy][$xx]; # undo degree conjectures\n }\n\n @grid[$y][$x] = $old; # undo grid value conjecture\n return False;\n }\n\n say \"$tries tries\";\n}\n\n```\n\nOutput:\n\n```\n49 50 51 52 53 54 75 76 81\n48 47 46 45 44 55 74 77 80\n37 38 39 40 43 56 73 78 79\n36 35 34 41 42 57 72 71 70\n31 32 33 14 13 58 59 68 69\n30 17 16 15 12 61 60 67 66\n29 18 19 20 11 62 63 64 65\n28 25 24 21 10 1 2 3 4\n27 26 23 22 9 8 7 6 5\n1275 tries\n\n\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n34 33 4 3 24 23 58 57 68\n35 32 31 2 25 54 55 56 69\n36 37 30 1 26 53 74 73 70\n39 38 29 28 27 52 75 72 71\n40 43 44 47 48 51 76 77 78\n41 42 45 46 49 50 81 80 79\n4631 tries\n```\n\nOddly, reversing the tiebreaker rule that makes hidato run twice as fast causes this last example to run four times slower. Go figure..."
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a program that is capable of solving a Rubik's Cube as efficiently as possible.\n\nOther names are:\n\n: : * Magic Cube\n * Speed Cube\n * Puzzle Cube\n * Cube\n\nYou may use any sort of input you wish."
},
{
"role": "assistant",
"content": "This is a translation of the Perl competition code, by Stefan Pochmann.\n\n```\n# 20230401 Raku programming solution\n\nmy @data=<UL DL RF UB FD BR DB UF DR UR BL FL FDR BLU DLB URB RUF FLD BRD FUL>;\nmy @goal=<UF UR UB UL DF DR DB DL FR FL BR BL UFR URB UBL ULF DRF DFL DLB DBR>;\n\nsub printAlg ($x) { #--- Algorithms.\n\n my $algo = 'x0F0DN0EB0H00N0B0R0KB0L0QB0G1A1M11C1I1E1OFI2'~\n 'DN2IEOB2H22N2B2GRM2MKGB2GLM2QBK23D3EN3E3B3N33H3';\n $algo ~~ s:g \n !(\\D*)(\\d)!{ \n $0 ~ <ILOFCLKHRNQCL OBIRALOBIRAL CEJHPEIMIG DFNRHRDKMQ>[$1] \n # ~ [~] reverse map { TR/G..R/M..X/ }, \" $0\".comb }!;\n ~ \" $0\".trans( ['G'..'R'] => ['M'..'X'] ).flip }!;\n\n my @algo = $algo.split: ' ';\n\n #`[[[ or use the following to save some CPU power and time # my @algo = < \n xILOFCLKHRNQCLx FILOFCLKHRNQCLF DNILOFCLKHRNQCLTD EBILOFCLKHRNQCLBE \n HILOFCLKHRNQCLN ILOFCLKHRNQCL NILOFCLKHRNQCLT BILOFCLKHRNQCLB \n RILOFCLKHRNQCLX KBILOFCLKHRNQCLBQ LILOFCLKHRNQCLR QBILOFCLKHRNQCLBW \n GOBIRALOBIRALM AOBIRALOBIRALA MOBIRALOBIRALS OBIRALOBIRAL \n COBIRALOBIRALC IOBIRALOBIRALO EOBIRALOBIRALE OFICEJHPEIMIGOFU \n DNCEJHPEIMIGTD IEOBCEJHPEIMIGBUEO HCEJHPEIMIGN CEJHPEIMIG \n NCEJHPEIMIGT BCEJHPEIMIGB GRMCEJHPEIMIGSXM MKGBCEJHPEIMIGBMQS \n GLMCEJHPEIMIGSRM QBKCEJHPEIMIGQBW DFNRHRDKMQ DDFNRHRDKMQD \n ENDFNRHRDKMQTE EDFNRHRDKMQE BDFNRHRDKMQB NDFNRHRDKMQT \n DFNRHRDKMQ HDFNRHRDKMQN >; #]]]\n\n say [~] my @moves = map { \n substr('UDFBLR', (my $ord=.ord-65) % 6, 1) ~ substr(\"2 '\", $ord div 6, 1)\n }, @algo[$x].comb; \n \n return @moves.elems\n}\n\nmy $total = 0;\n\nfor 1..18 -> $x { #--- Orient.\n until @data[$x] ∈ @goal {\n $total += printAlg $x;\n @data[$x] ~~ s/(.)(.+)/$1$0/;\n @data[$x < 12 ?? 0 !! 19] ~~ s/(.+)(.)/$1$0/;\n } \n}\n\nfor ^41 { #--- Permute.\n for ^20 -> $w { \n next if @data[$w] eq @goal[$w];\n my $x = 0;\n until @data[$w] eq @goal[$x] { $x++ };\n $x < 12 ?? ( @data[0,$x,12,15] = @data[$x,0,15,12] ) \n !! ( @data[12,$x] = @data[$x,12] );\n $total += printAlg $x+=18 and last\n }\n}\n\nsay \"\\nTotal number of moves : $total\";\n\n```\n\nOutput:\n\n```\nB2D'F R F'R2F2R L D R'D'L'F2R DB2\nD F R F'R2F2R L D R'D'L'F2R D'\nU F'D2F R'U2R F'D2F R'U2R U'\nU2F'D2F R'U2R F'D2F R'U2R U2\nU2F'D2F R'U2R F'D2F R'U2R U2\nF2F'D2F R'U2R F'D2F R'U2R F2\nF F'D2F R'U2R F'D2F R'U2R F'\nF F'D2F R'U2R F'D2F R'U2R F'\nL2F'D2F R'U2R F'D2F R'U2R L2\nL2F'D2F R'U2R F'D2F R'U2R L2\nF L2F'D2F2L2B D B'L2F U'F U D2FL2F'\nB2D'F2L2B D B'L2F U'F U DB2\nU R'U'F2L2B D B'L2F U'F U URU'\nF2L2B D B'L2F U'F U \nU R U'F2L2B D B'L2F U'F U UR'U'\nL'D2L F2L2B D B'L2F U'F U L'D2L\nU'L U D2F2L2B D B'L2F U'F U D2U'L'U\nF'R2F F2L2B D B'L2F U'F U F'R2F\nD2F2L2B D B'L2F U'F U D2\nB2B2R2D'R'D R'B2L U'L'B2\nL2D'B2R2D'R'D R'B2L U'L'DL2\nB2R2D'R'D R'B2L U'L'\nD B2R2D'R'D R'B2L U'L'D'\nL2B2R2D'R'D R'B2L U'L'L2\nD2B2R2D'R'D R'B2L U'L'D2\n\nTotal number of moves : 352\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nLet given equations:\n \n3x + y = -1 and 2x - 3y = -19\n \nSolve it with substitution method.\n\nSee related\n\n* Reduced row echelon form\n* Gaussian elimination"
},
{
"role": "assistant",
"content": "```\nsub solve-system-of-two-linear-equations ( [ \\a1, \\b1, \\c1 ], [ \\a2, \\b2, \\c2 ] ) {\n my \\X = ( b2 * c1 - b1 * c2 )\n / ( b2 * a1 - b1 * a2 );\n\n my \\Y = ( a1 * X - c1 ) / -b1;\n\n return X, Y;\n}\nsay solve-system-of-two-linear-equations( (3,1,-1), (2,-3,-19) );\n\n```\n\nOutput:\n\n```\n(-2 5)\n```"
}
]
|
[
{
"role": "user",
"content": "There are some columns of lanterns hanging from the ceiling. If you remove the lanterns one at a time, at each step removing the bottommost lantern from one column, how many legal sequences will let you take all of the lanterns down?\n\nFor example, there are some lanterns hanging like this:\n\n```\n🏮 🏮 🏮\n 🏮 🏮\n 🏮\n\n```\n\nIf we number the lanterns like so:\n\n```\n1 2 4\n 3 5\n 6\n\n```\n\nYou can take like this: [6,3,5,2,4,1] or [3,1,6,5,2,4] \nBut not like this: [6,3,2,4,5,1], because at that time 5 is under 4.\n\nIn total, there are 60 ways to take them down.\n\n---\n\nTask\n\n**Input:** \nFirst an integer (n): the number of columns. \nThen n integers: the number of lanterns in each column. \n**Output:** \nAn integer: the number of sequences.\n\nFor example, the input of the example above could be:\n\n```\n3\n1\n2\n3\n\n```\n\nAnd the output is:\n\n```\n60\n\n```\n\n---\n\nOptional task\n\nOutput all the sequences using this format:\n\n```\n[1,2,3,…]\n[2,1,3,…]\n……\n\n```\n\nRelated\n\n* Permutations\\_with\\_some\\_identical\\_elements"
},
{
"role": "assistant",
"content": "Note: All of these solutions accept the list of column sizes as command-line arguments and infer the number of columns from the number of sizes provided, rather than requiring that a count be supplied as an extra distinct parameter.\n\n### Directly computing the count\n\n**Translation of**: Pascal\n\nIf all we need is the count, then we can compute that directly:\n\n```\nunit sub MAIN(*@columns);\n\nsub postfix:<!>($n) { [*] 1..$n }\n\nsay [+](@columns)! / [*](@columns»!);\n\n```\n\nOutput:\n\n```\n$ raku lanterns.raku 1 2 3\n60\n```\n\n### Sequence as column numbers\n\n**Translation of**: Julia\n\nIf we want to list all of the sequences, we have to do some more work. This version outputs the sequences as lists of column numbers (assigned from 1 to N left to right); at each step the bottommost lantern from the numbered column is removed.\n\n```\nunit sub MAIN(*@columns, :v(:$verbose)=False);\n\nmy @sequences = @columns\n . pairs\n . map({ (.key+1) xx .value })\n . flat\n . permutations\n . map( *.join(',') )\n . unique;\n\nif ($verbose) {\n say \"There are {+@sequences} possible takedown sequences:\";\n say \"[$_]\" for @sequences;\n} else {\n say +@sequences;\n}\n\n```\n\nOutput:\n\n```\n$ raku lanterns.raku --verbose 1 2 3\nThere are 60 possible takedown sequences:\n[1,2,2,3,3,3]\n[1,2,3,2,3,3]\n[1,2,3,3,2,3]\n[1,2,3,3,3,2]\n[1,3,2,2,3,3]\n[1,3,2,3,2,3]\n...\n[3,3,2,2,3,1]\n[3,3,2,3,1,2]\n[3,3,2,3,2,1]\n[3,3,3,1,2,2]\n[3,3,3,2,1,2]\n[3,3,3,2,2,1]\n```\n\n### Sequence as lantern numbers\n\nIf we want individually-numbered lanterns in the sequence instead of column numbers, as in the example given in the task description, that requires yet more work:\n\n```\nunit sub MAIN(*@columns, :v(:$verbose)=False);\n\nmy @sequences = @columns\n . pairs\n . map({ (.key+1) xx .value })\n . flat\n . permutations\n . map( *.join(',') )\n . unique;\n\nif ($verbose) {\n my @offsets = |0,|(1..@columns).map: { [+] @columns[0..$_-1] };\n my @matrix;\n for ^@columns.max -> $i {\n for ^@columns -> $j {\n my $value = $i < @columns[$j] ?? ($i+@offsets[$j]+1) !! Nil;\n @matrix[$j][$i] = $value if $value;;\n print \"\\t\" ~ ($value // \" \");\n }\n say '';\n }\n say \"There are {+@sequences} possible takedown sequences:\";\n for @sequences».split(',') -> @seq {\n my @work = @matrix».clone;\n my $seq = '[';\n for @seq -> $col {\n $seq ~= @work[$col-1].pop ~ ',';\n }\n $seq ~~ s/','$/]/;\n say $seq;\n }\n} else {\n say +@sequences;\n}\n\n```\n\nOutput:\n\n```\n$ raku lanterns.raku -v 1 2 3 \n 1 2 4\n 3 5\n 6\nThere are 60 possible takedown sequences:\n[1,3,2,6,5,4]\n[1,3,6,2,5,4]\n[1,3,6,5,2,4]\n...\n[6,5,4,1,3,2]\n[6,5,4,3,1,2]\n[6,5,4,3,2,1]\n```"
}
]
|
[
{
"role": "user",
"content": "You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:\n\n```\n A B\n /│\\ /│\\\n / │ X │ \\\n / │/ \\│ \\\n C───D───E───F\n \\ │\\ /│ /\n \\ │ X │ /\n \\│/ \\│/\n G H\n\n```\n\nYou are also given eight pegs numbered 1-to-8.\n\nObjective\n\nPlace the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.\n\nExample\n\nIn this attempt:\n\n```\n 4 7\n /│\\ /│\\\n / │ X │ \\\n / │/ \\│ \\\n 8───1───6───2\n \\ │\\ /│ /\n \\ │ X │ /\n \\│/ \\│/\n 3 5\n\n```\n\nNote that **7** and **6** are connected and have a difference of **1**, so it is *not* a solution.\n\nTask\n\nProduce and show here *one* solution to the puzzle.\n\nRelated tasks\n: * A\\* search algorithm\n * Solve a Holy Knight's tour\n * Knight's tour\n * N-queens problem\n * Solve a Hidato puzzle\n * Solve a Holy Knight's tour\n * Solve a Hopido puzzle\n * Solve a Numbrix puzzle\n * 4-rings or 4-squares puzzle\n\nSee also\n\nNo Connection Puzzle (youtube)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThis uses a Warnsdorff solver, which cuts down the number of tries by more than a factor of six over the brute force approach. This same solver is used in:\n\n* Solve a Hidato puzzle\n* Solve a Hopido puzzle\n* Solve a Holy Knight's tour\n* Solve a Numbrix puzzle\n* Solve the no connection puzzle\n\nThe idiosyncratic adjacency diagram is dealt with by the simple expedient of bending the two vertical lines || into two bows )(, such that adjacency can be calculated simply as a distance of 2 or less.\n\n```\nmy @adjacent = gather -> $y, $x {\n take [$y,$x] if abs($x|$y) > 2;\n} for flat -5 .. 5 X -5 .. 5;\n\nsolveboard q:to/END/;\n . _ . . _ .\n . . . . . .\n _ . _ 1 . _\n . . . . . .\n . _ . . _ .\n END\n \nsub solveboard($board) {\n my $max = +$board.comb(/\\w+/);\n my $width = $max.chars;\n\n my @grid;\n my @known;\n my @neigh;\n my @degree;\n \n @grid = $board.lines.map: -> $line {\n [ $line.words.map: { /^_/ ?? 0 !! /^\\./ ?? Rat !! $_ } ]\n }\n \n sub neighbors($y,$x --> List) {\n eager gather for @adjacent {\n my $y1 = $y + .[0];\n my $x1 = $x + .[1];\n take [$y1,$x1] if defined @grid[$y1][$x1];\n }\n }\n\n for ^@grid -> $y {\n for ^@grid[$y] -> $x {\n if @grid[$y][$x] -> $v {\n @known[$v] = [$y,$x];\n }\n if @grid[$y][$x].defined {\n @neigh[$y][$x] = neighbors($y,$x);\n @degree[$y][$x] = +@neigh[$y][$x];\n }\n }\n }\n print \"\\e[0H\\e[0J\";\n\n my $tries = 0;\n\n try_fill 1, @known[1];\n\n sub try_fill($v, $coord [$y,$x] --> Bool) {\n return True if $v > $max;\n $tries++;\n\n my $old = @grid[$y][$x];\n\n return False if +$old and $old != $v;\n return False if @known[$v] and @known[$v] !eqv $coord;\n\n @grid[$y][$x] = $v; # conjecture grid value\n\n print \"\\e[0H\"; # show conjectured board\n for @grid -> $r {\n say do for @$r {\n when Rat { ' ' x $width }\n when 0 { '_' x $width }\n default { .fmt(\"%{$width}d\") }\n }\n }\n\n\n my @neighbors = @neigh[$y][$x][];\n\n my @degrees;\n for @neighbors -> \\n [$yy,$xx] {\n my $d = --@degree[$yy][$xx]; # conjecture new degrees\n push @degrees[$d], n; # and categorize by degree\n }\n\n for @degrees.grep(*.defined) -> @ties {\n for @ties.reverse { # reverse works better for this hidato anyway\n return True if try_fill $v + 1, $_;\n }\n }\n\n for @neighbors -> [$yy,$xx] {\n ++@degree[$yy][$xx]; # undo degree conjectures\n }\n\n @grid[$y][$x] = $old; # undo grid value conjecture\n return False;\n }\n \n say \"$tries tries\";\n}\n\n```\n\nOutput:\n\n```\n 4 3 \n \n2 8 1 7\n \n 6 5 \n18 tries\n```"
}
]
|
[
{
"role": "user",
"content": "An IQ Puzzle is a triangle of 15 golf tee's.\n\nThis puzzle is typically seen at Cracker Barrel (a USA sales store) where one tee is missing and the remaining tees jump over each other (with removal of the jumped tee, like checkers) until one tee is left.\n\nThe fewer tees left, the higher the IQ score.\n\nPeg #1 is the top centre through to the bottom row which are pegs 11 through to 15.\n\n```\n ^\n / \\ \n / \\\n / \\\n / 1 \\ \n / 2 3 \\\n / 4 5 6 \\ \n / 7 8 9 10 \\\n /11 12 13 14 15\\\n/_________________\\\n\n```\n\nReference picture: http://www.joenord.com/puzzles/peggame/\n \nUpdated link (June 2021): \nhttps://www.joenord.com/triangle-peg-board-game-solutions-to-amaze-your-friends/\n\nTask\n\nPrint a solution to solve the puzzle leaving one peg not implemented variations.\n\nStart with empty peg in **X** and solve with one peg in position **Y**."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.05\n\n**Translation of**: Sidef\n\n```\nconstant @start = <\n 0\n 1 1\n 1 1 1\n 1 1 1 1\n 1 1 1 1 1\n>».Int;\n\nconstant @moves =\n [ 0, 1, 3],[ 0, 2, 5],[ 1, 3, 6],\n [ 1, 4, 8],[ 2, 4, 7],[ 2, 5, 9],\n [ 3, 4, 5],[ 3, 6,10],[ 3, 7,12],\n [ 4, 7,11],[ 4, 8,13],[ 5, 8,12],\n [ 5, 9,14],[ 6, 7, 8],[ 7, 8, 9],\n [10,11,12],[11,12,13],[12,13,14];\n\nmy $format = (1..5).map: {' ' x 5-$_, \"%d \" x $_, \"\\n\"};\n\nsub solve(@board, @move) {\n return \" Solved\" if @board.sum == 1;\n return Nil if @board[@move[1]] == 0;\n my $valid = do given @board[@move[0]] {\n when 0 {\n return Nil if @board[@move[2]] == 0;\n \"move {@move[2]} to {@move[0]}\\n \";\n }\n default {\n return Nil if @board[@move[2]] == 1;\n \"move {@move[0]} to {@move[2]}\\n \";\n }\n }\n\n my @new-layout = @board;\n @new-layout[$_] = 1 - @new-layout[$_] for @move;\n my $result;\n for @moves -> @this-move {\n $result = solve(@new-layout, @this-move);\n last if $result\n }\n $result ?? \"$valid\\n \" ~ sprintf($format, |@new-layout) ~ $result !! $result\n}\n\nprint \"Starting with\\n \", sprintf($format, |@start);\n\nmy $result;\nfor @moves -> @this-move {\n $result = solve(@start, @this-move);\n last if $result\n};\nsay $result ?? $result !! \"No solution found\";\n\n```\n\nOutput:\n\n```\nStarting with\n 0 \n 1 1 \n 1 1 1 \n 1 1 1 1 \n 1 1 1 1 1 \nmove 3 to 0\n \n 1 \n 0 1 \n 0 1 1 \n 1 1 1 1 \n 1 1 1 1 1 \nmove 8 to 1\n \n 1 \n 1 1 \n 0 0 1 \n 1 1 0 1 \n 1 1 1 1 1 \nmove 10 to 3\n \n 1 \n 1 1 \n 1 0 1 \n 0 1 0 1 \n 0 1 1 1 1 \nmove 1 to 6\n \n 1 \n 0 1 \n 0 0 1 \n 1 1 0 1 \n 0 1 1 1 1 \nmove 11 to 4\n \n 1 \n 0 1 \n 0 1 1 \n 1 0 0 1 \n 0 0 1 1 1 \nmove 2 to 7\n \n 1 \n 0 0 \n 0 0 1 \n 1 1 0 1 \n 0 0 1 1 1 \nmove 9 to 2\n \n 1 \n 0 1 \n 0 0 0 \n 1 1 0 0 \n 0 0 1 1 1 \nmove 0 to 5\n \n 0 \n 0 0 \n 0 0 1 \n 1 1 0 0 \n 0 0 1 1 1 \nmove 6 to 8\n \n 0 \n 0 0 \n 0 0 1 \n 0 0 1 0 \n 0 0 1 1 1 \nmove 13 to 11\n \n 0 \n 0 0 \n 0 0 1 \n 0 0 1 0 \n 0 1 0 0 1 \nmove 5 to 12\n \n 0 \n 0 0 \n 0 0 0 \n 0 0 0 0 \n 0 1 1 0 1 \nmove 11 to 13\n \n 0 \n 0 0 \n 0 0 0 \n 0 0 0 0 \n 0 0 0 1 1 \nmove 14 to 12\n \n 0 \n 0 0 \n 0 0 0 \n 0 0 0 0 \n 0 0 1 0 0 \n Solved\n\n```"
}
]
|
[
{
"role": "user",
"content": "The Sørensen–Dice coefficient, also known as the Sørensen–Dice index (or sdi, or sometimes by one of the individual names: sorensen or dice) is a statistic used to gauge the similarity of two population samples.\n\nThe original use was in botany as a measure of similarity between populations of flora and fauna in different areas, but it has uses in other fields as well. It can be used as a text similarity function somewhat similar to the Levenshtein edit distance function, though its characteristics are quite different.\n\nLevenshtein can be useful for spelling correction, but relies on the tested word or phrase being quite similar to the desired one, and can be very slow for long words or phrases.\n\nSørensen–Dice is more useful for 'fuzzy' matching partial and poorly spelled words or phrases, possibly in improper order.\n\nThere are several different methods to tokenize objects for Sørensen–Dice comparisons. The most typical tokenizing scheme for text is to break the words up into bi-grams: groups of two consecutive letters.\n\nFor instance, the word 'differ' would be tokenized to the group:\n\n```\n di if ff fe er\n\n```\n\nDifferent implementations may do slightly different transforms. For our purposes, fold case so that all characters are the same case, split words, and ignore white-space, but keep punctuation.\n\nThe phrase \"Don't Panic!\" will be tokenized to the bi-grams:\n\n```\n do on n' 't pa an ni ic c! \n\n\n```\n\nSørensen–Dice measures the similarity of two groups by dividing twice the intersection token count by the total token count of both groups:\n\n```\n SDC = 2 × |A∩B| / (|A| + |B|)\n\n```\n\nwhere A, B and A∩B are to be understood as multisets, and that if an item, x, has multiplicity a in A and b in B, then it will have multiplicity min(a,b) in A∩B.\n\nThe Sørensen–Dice coefficient is thus a ratio between 0.0 and 1.0 giving the \"percent similarity\" between the two populations.\n\nSDC *can* by used for spellchecking, but it's not really good at it, especially for short words. Where it really shines is for fuzzy matching of short phrases like book or movie titles. It may not return exactly what you are looking for, but often gets remarkably close with some pretty poor inputs.\n\nTask\n\n* Use the list of Rosetta Code task and draft task names as your \"dictionary\" to search.\n* Using that dictionary, search for the mangled task names: '**Primordial primes'**, '**Sunkist-Giuliani formula'**, '**Sieve of Euripides'**, '**Chowder numbers'**.\n* Show the search term and the coefficient / match for the five closest, most similar matches.\n\nHow you get the task names is peripheral to the task. You can web-scrape them or download them to a file, whatever.\n\nIf there is a built-in or easily, freely available library implementation for Sørensen–Dice coefficient calculations, it is acceptable to use that with a pointer to where it may be obtained."
},
{
"role": "assistant",
"content": "Using the library Text::Sorensen from the Raku ecosystem.\n\nSee the Raku entry for Text completion for a bespoke implementation of Sorenson-Dice. (Which is *very* similar to the library implementation.)\n\n```\nuse Text::Sorensen :sdi;\n\nmy %tasks = './tasks.txt'.IO.slurp.lines.race.map: { $_ => .&bi-gram };\n\nsub fuzzy-search (Str $string) { sdi($string, %tasks, :ge(.2) ).head(5).join: \"\\n\" }\n\nsay \"\\n$_ >\\n\" ~ .&fuzzy-search for\n 'Primordial primes',\n 'Sunkist-Giuliani formula',\n 'Sieve of Euripides',\n 'Chowder numbers';\n\n```\n\nOutput:\n\n```\nPrimordial primes >\n0.685714 Sequence of primorial primes\n0.666667 Factorial primes\n0.571429 Primorial numbers\n0.545455 Prime words\n0.521739 Almost prime\n\nSunkist-Giuliani formula >\n0.565217 Almkvist-Giullera formula for pi\n0.378378 Faulhaber's formula\n0.342857 Haversine formula\n0.333333 Check Machin-like formulas\n0.307692 Resistance calculator\n\nSieve of Euripides >\n0.461538 Four sides of square\n0.461538 Sieve of Pritchard\n0.413793 Sieve of Eratosthenes\n0.4 Piprimes\n0.384615 Sierpinski curve\n\nChowder numbers >\n0.782609 Chowla numbers\n0.64 Powerful numbers\n0.608696 Fermat numbers\n0.608696 Rhonda numbers\n0.6 Lah numbers\n```"
}
]
|
[
{
"role": "user",
"content": "Object identifiers (OID) are strings used to identify objects in network data.\n\nTask\n\nShow how to sort a list of OIDs, in their natural sort order.\n\nDetails\n\n* An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.\n* Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.\n\nTest case\n\n: : : : | Input *(list of strings)* | Output *(list of strings)* |\n | --- | --- |\n | `1.3.6.1.4.1.11.2.17.19.3.4.0.10` `1.3.6.1.4.1.11.2.17.5.2.0.79` `1.3.6.1.4.1.11.2.17.19.3.4.0.4` `1.3.6.1.4.1.11150.3.4.0.1` `1.3.6.1.4.1.11.2.17.19.3.4.0.1` `1.3.6.1.4.1.11150.3.4.0` | `1.3.6.1.4.1.11.2.17.5.2.0.79` `1.3.6.1.4.1.11.2.17.19.3.4.0.1` `1.3.6.1.4.1.11.2.17.19.3.4.0.4` `1.3.6.1.4.1.11.2.17.19.3.4.0.10` `1.3.6.1.4.1.11150.3.4.0` `1.3.6.1.4.1.11150.3.4.0.1` |\n\nRelated tasks\n\n* Natural sorting\n* Sort using a custom comparator\n\n---"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThe sort routine accepts a sort key callback as the first argument. Here we generate a list of integers as the sort key for each OID, which gets sorted lexicographically with numeric comparison by default.\n\n```\n.say for sort *.comb(/\\d+/)».Int, <\n 1.3.6.1.4.1.11.2.17.19.3.4.0.10\n 1.3.6.1.4.1.11.2.17.5.2.0.79\n 1.3.6.1.4.1.11.2.17.19.3.4.0.4\n 1.3.6.1.4.1.11150.3.4.0.1\n 1.3.6.1.4.1.11.2.17.19.3.4.0.1\n 1.3.6.1.4.1.11150.3.4.0\n>;\n\n```\n\nOutput:\n\n```\n1.3.6.1.4.1.11.2.17.5.2.0.79\n1.3.6.1.4.1.11.2.17.19.3.4.0.1\n1.3.6.1.4.1.11.2.17.19.3.4.0.4\n1.3.6.1.4.1.11.2.17.19.3.4.0.10\n1.3.6.1.4.1.11150.3.4.0\n1.3.6.1.4.1.11150.3.4.0.1\n\n```\n\nAlternatively, using the sprintf-based approach used by the Perl solution, for comparison *(input elided)*:\n\n```\n.say for sort *.split('.').fmt('%08d'), <...>;\n\n```\n\nOr if using a third-party module is acceptable:\n\n```\nuse Sort::Naturally;\n\n.say for sort &naturally, <...>;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Sort an array of composite structures by a key.\n\nFor example, if you define a composite structure that presents a name-value pair (in pseudo-code):\n\n```\nDefine structure pair such that: \n name as a string\n value as a string\n\n```\n\nand an array of such pairs:\n\n```\n x: array of pairs\n\n```\n\nthen define a sort routine that sorts the array *x* by the key *name*.\n\nThis task can always be accomplished with Sorting Using a Custom Comparator.\n\nIf your language is not listed here, please see the other article."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.05\n\n```\nmy class Employee {\n has Str $.name;\n has Rat $.wage;\n}\n\nmy $boss = Employee.new( name => \"Frank Myers\" , wage => 6755.85 );\nmy $driver = Employee.new( name => \"Aaron Fast\" , wage => 2530.40 );\nmy $worker = Employee.new( name => \"John Dude\" , wage => 2200.00 );\nmy $salesman = Employee.new( name => \"Frank Mileeater\" , wage => 4590.12 );\n\nmy @team = $boss, $driver, $worker, $salesman;\n\nmy @orderedByName = @team.sort( *.name )».name;\nmy @orderedByWage = @team.sort( *.wage )».name;\n\nsay \"Team ordered by name (ascending order):\";\nsay @orderedByName.join(' ');\nsay \"Team ordered by wage (ascending order):\";\nsay @orderedByWage.join(' ');\n\n```\n\nthis produces the following output:\n\n```\nTeam ordered by name (ascending order): \nAaron Fast Frank Mileeater Frank Myers John Dude \nTeam ordered by wage (ascending order): \nJohn Dude Aaron Fast Frank Mileeater Frank Myers \n\n```\n\nNote that when the sort receives a unary function, it automatically generates an appropriate comparison function based on the type of the data."
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array (or list) of integers in ascending numerical order.\n\nUse a sorting facility provided by the language/library if possible."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nIf `@a` contains only numbers:\n\n```\nmy @sorted = sort @a;\n\n```\n\nFor an in-place sort:\n\n```\n@a .= sort;\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite and test a function over an indented plain text outline which either:\n\n1. Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or\n2. reports that the indentation characters or widths are not consistent enough to make the outline structure clear.\n\nYour code should detect and warn of at least two types of inconsistent indentation:\n\n* inconsistent use of whitespace characters (e.g. mixed use of tabs and spaces)\n* inconsistent indent widths. For example, an indentation with an odd number of spaces in an outline in which the unit indent appears to be 2 spaces, or 4 spaces.\n\nYour code should be able to detect and handle both tab-indented, and space-indented (e.g. 4 space, 2 space etc) outlines, without being given any advance warning of the indent characters used, or the size of the indent units.\n\nYou should also be able to specify different types of sort, for example, as a minimum, both ascending and descending lexical sorts.\n\nYour sort should not alter the type or size of the indentation units used in the input outline.\n\n(For an application of Indent Respectful Sort, see the Sublime Text package of that name. The Python source text [1] is available for inspection on Github).\n\n**Tests**\n\n* Sort every level of the (4 space indented) outline below lexically, once ascending and once descending.\n\n```\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n```\n\n* Do the same with a tab-indented equivalent of the same outline.\n\n```\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n```\n\nThe output sequence of an ascending lexical sort of each level should be:\n\n```\nalpha\n epsilon\n iota\n theta\nzeta\n beta\n delta\n gamma\n kappa\n lambda\n mu\n```\n\nThe output sequence of a descending lexical sort of each level should be:\n\n```\nzeta\n gamma\n mu\n lambda\n kappa\n delta\n beta\nalpha\n theta\n iota\n epsilon\n```\n\n* Attempt to separately sort each of the following two outlines, reporting any inconsistencies detected in their indentations by your validation code.\n\n```\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu\n```\n\n```\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n```\n\nRelated tasks\n\n: * Functional\\_coverage\\_tree\n * Display\\_an\\_outline\\_as\\_a\\_nested\\_table"
},
{
"role": "assistant",
"content": "Rather than a monolithic verify-and-sort-and-print routine, implement as a series of routines that can be chained together or used separately as desired.\n\n* Routine to check indent characters and return the indent white-space if it is consistent.\n\n* Routine to import a text \"outline\" into a native data structure\n\n* Routine(s) to output the data structure in the desire sort order.\n\n```\nmy @tests = q:to/END/.split( /\\n\\n+/ )».trim;\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu\n\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\nEND\n\nfor @tests -> $t {\n say \"{'=' x 55}\\nUnsorted:\\n$t\";\n my $indent = try detect-indent $t;\n next unless $indent;\n say \"\\nSorted ascending:\";\n pretty-print import($t, :level($indent) ).List, :ws($indent);\n say \"\\nSorted descending:\";\n pretty-print import($t, :level($indent) ).List, :ws($indent), :desc;\n}\n\nsub detect-indent ($text) {\n my $consistent = $text.lines.map(* ~~ / ^ (\\h*) /).join.comb.Set;\n note \"\\nUnwilling to continue; Inconsistent indent characters.\" and return '' if +$consistent > 1;\n my @ws = $text.lines.map: (* ~~ / ^ (\\h*) /)».Str;\n my $indent = @ws.grep( *.chars > 0 ).min.first;\n note \"\\nUnwilling to continue; Inconsistent indentation.\" and return '' unless all\n @ws.map: { next unless .[0]; (.[0].chars %% $indent.chars) }\n $indent\n}\n\nsub import (Str $trees, :$level) {\n my $forest = '[';\n my $last = -Inf;\n for $trees.lines -> $branch {\n $branch ~~ / ($($level))* /;\n my $this = +$0;\n $forest ~= do {\n given $this cmp $last {\n when More { (?$this ?? q[ => \\[ ] !! \"\" )~ \"'{$branch.trim}'\" }\n when Same { \", '{$branch.trim}'\" }\n when Less { \"{']' x $last - $this}, '{$branch.trim}' \" }\n }\n }\n $last = $this;\n }\n $forest ~= ']' x 1 + $last;\n use MONKEY-SEE-NO-EVAL;\n $forest.EVAL;\n}\n\nmulti pretty-print (List $struct, :$level = 0, :$ws = ' ', :$desc = False) {\n if $desc {\n pretty-print($_, :level($level), :$ws, :$desc ) for $struct.flat.sort.reverse.List\n } else {\n pretty-print($_, :level($level), :$ws, :$desc ) for $struct.flat.sort.List\n }\n}\n\nmulti pretty-print (Pair $struct, :$level = 0, :$ws = ' ', :$desc = False) {\n say $ws x $level, $struct.key;\n pretty-print( $struct.value.sort( ).List, :level($level + 1), :$ws, :$desc )\n}\n\nmulti pretty-print (Str $struct, :$level = 0, :$ws = ' ', :$desc = False) {\n say $ws x $level , $struct;\n}\n\n```\n\nOutput:\n\n```\n=======================================================\nUnsorted:\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\nSorted ascending:\nalpha\n epsilon\n iota\n theta\nzeta\n beta\n delta\n gamma\n kappa\n lambda\n mu\n\nSorted descending:\nzeta\n gamma\n mu\n lambda\n kappa\n delta\n beta\nalpha\n theta\n iota\n epsilon\n=======================================================\nUnsorted:\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n\nSorted ascending:\nalpha\n\tepsilon\n\tiota\n\ttheta\nzeta\n\tbeta\n\tdelta\n\tgamma\n\t\tkappa\n\t\tlambda\n\t\tmu\n\nSorted descending:\nzeta\n\tgamma\n\t\tmu\n\t\tlambda\n\t\tkappa\n\tdelta\n\tbeta\nalpha\n\ttheta\n\tiota\n\tepsilon\n=======================================================\nUnsorted:\nalpha\n epsilon\n\tiota\n theta\nzeta\n beta\n delta\n gamma\n \tkappa\n lambda\n mu\n\nUnwilling to continue; Inconsistent indent characters.\n=======================================================\nUnsorted:\nzeta\n beta\n gamma\n lambda\n kappa\n mu\n delta\nalpha\n theta\n iota\n epsilon\n\nUnwilling to continue; Inconsistent indentation.\n```"
}
]
|
[
{
"role": "user",
"content": "Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.\n\nMake your example work with the following list of values and set of indices:\n\n: : Values: `[7, 6, 5, 4, 3, 2, 1, 0]`\n\n: : Indices: `{6, 1, 7}`\n\nWhere the correct result would be:\n\n: : `[7, 0, 5, 4, 3, 2, 1, 6]`.\n\nIn case of one-based indexing, rather than the zero-based indexing above, you would use the indices `{7, 2, 8}` instead.\n\nThe indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.\n\nCf.\n\n* Order disjoint list items"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2020.08.1\n\n### Inline\n\nUsing L-value slice of the array, and `sort` as a mutating method:\n\n```\nmy @values = 7, 6, 5, 4, 3, 2, 1, 0;\nmy @indices = 6, 1, 7;\n\n@values[ @indices.sort ] .= sort;\n\nsay @values;\n\n```\n\nOutput:\n\n```\n[7, 0, 5, 4, 3, 2, 1, 6]\n```\n\n### Iterative\n\n```\nsub disjointSort( @values, @indices --> List ) {\n my @sortedValues = @values[ @indices ].sort ;\n for @indices.sort -> $insert {\n @values[ $insert ] = @sortedValues.shift ;\n }\n return @values ;\n}\n\nmy @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ;\nmy @indices = ( 6 , 1 , 7 ) ;\nmy @sortedValues = disjointSort( @values , @indices ) ;\nsay @sortedValues ;\n\n```\n\nOutput:\n\n```\n[7, 0, 5, 4, 3, 2, 1, 6]\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nGiven an integer **n**, return **1──►n** (inclusive) in lexicographical order.\n\nShow all output here on this page.\n\nExample\n\nGiven **13**,\n \nreturn: **[1,10,11,12,13,2,3,4,5,6,7,8,9].**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\nIt is somewhat odd that the task name is sort **numbers** lexicographically but immediately backtracks in the task header to sorting **integers** lexicographically. Why only integers? This will sort ANY real numbers lexicographically. For a non-integer, assumes that the given number is a hard boundary and 1 is a \"soft\" boundary. E.G. The given number is definitely included; 1 is only a threshold, it is included if it matches exactly. (Could be the other way around, this it the way I choose.)\n\n```\nsub lex (Real $n, $step = 1) {\n ($n < 1 ?? ($n, * + $step …^ * > 1)\n !! ($n, * - $step …^ * < 1)).sort: ~*\n}\n\n# TESTING\nfor 13, 21, -22, (6, .333), (-4, .25), (-5*π, e) {\n my ($bound, $step) = |$_, 1;\n say \"Boundary:$bound, Step:$step >> \", lex($bound, $step).join: ', ';\n}\n\n```\n\nOutput:\n\n```\nBoundary:13, Step:1 >> 1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9\nBoundary:21, Step:1 >> 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 3, 4, 5, 6, 7, 8, 9\nBoundary:-22, Step:1 >> -1, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -2, -20, -21, -22, -3, -4, -5, -6, -7, -8, -9, 0, 1\nBoundary:6, Step:0.333 >> 1.005, 1.338, 1.671, 2.004, 2.337, 2.67, 3.003, 3.336, 3.669, 4.002, 4.335, 4.668, 5.001, 5.334, 5.667, 6\nBoundary:-4, Step:0.25 >> -0.25, -0.5, -0.75, -1, -1.25, -1.5, -1.75, -2, -2.25, -2.5, -2.75, -3, -3.25, -3.5, -3.75, -4, 0, 0.25, 0.5, 0.75, 1\nBoundary:-15.707963267948966, Step:2.718281828459045 >> -10.271399611030876, -12.989681439489921, -15.707963267948966, -2.116554125653742, -4.834835954112787, -7.553117782571832, 0.6017277028053032\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nLet given list:\n \nPrimes = [2,43,81,122,63,13,7,95,103]\n \nShow on this page the ascending ordered list of primes from given list."
},
{
"role": "assistant",
"content": "```\nput <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort\n\n```\n\nOutput:\n\n```\n2 7 13 43 103\n```\n\n*Of course \"ascending\" is a little ambiguous. That ^^^ is numerically. This vvv is lexicographically.*\n\n```\nput <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort: ~*\n\n```\n\nOutput:\n\n```\n103 13 2 43 7\n```"
}
]
|
[
{
"role": "user",
"content": "When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key.\n\nExample\n\nIn this table of countries and cities, a stable sort on the *second* column, the cities, would keep the **US Birmingham** above the **UK Birmingham**.\n\n(Although an unstable sort *might*, in this case, place the **US Birmingham** above the **UK Birmingham**, a stable sort routine would *guarantee* it).\n\n```\nUK London\nUS New York\nUS Birmingham\nUK Birmingham\n\n```\n\nSimilarly, stable sorting on just the first column would generate **UK London** as the first item and **US Birmingham** as the last item (since the order of the elements having the same first word – **UK** or **US** – would be maintained).\n\nTask\n: 1. Examine the documentation on any in-built sort routines supplied by a language.\n 2. Indicate if an in-built routine is supplied\n 3. If supplied, indicate whether or not the in-built routine is stable.\n\n(This Wikipedia table shows the stability of some common sort routines)."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThe sort built-in (available as sub and method) is stable.\n\nShort demonstration for sorting only on the second item of each array:\n\n```\nuse v6;\nmy @cities =\n ['UK', 'London'],\n ['US', 'New York'],\n ['US', 'Birmingham'],\n ['UK', 'Birmingham'],\n ;\n\n.say for @cities.sort: { .[1] };\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a function/program/subroutine/procedure to sort the characters of a string in lexicographical order.\n\nA *character* for this purpose should be whatever is natural for your language.\n\nShow the results here on this page. White-space may be optionally removed.\n\nThe case (uppercase and lowercase) of any letters should be preserved.\n\nWrite the function even if your language has a built-in function for it."
},
{
"role": "assistant",
"content": "### Semi-realistic version\n\n```\nsub sort_within_string ( $_ is copy ) {\n constant @lexographic_order = sort *.fc, map &chr, 1..255;\n\n return join '', gather for @lexographic_order -> $l {\n my $count = s:g/$l//;\n take $l x $count;\n LAST { warn \"Original string had non-ASCII chars: {.raku}\" if .chars }\n }\n}\nsay trim .&sort_within_string for q:to/END/.lines;\nThe quick brown fox jumps over the lazy dog, apparently\nNow is the time for all good men to come to the aid of their country.\nEND\n\n```\n\nOutput:\n\n```\n,aaabcdeeeefghhijkllmnnoooopppqrrrsTttuuvwxyyz\n.aaccddeeeeeeffghhhiiiillmmmNnnooooooooorrrstttttttuwy\n\n```\n\n### Following the actual task title / description\n\nFollowing a strict interpretation of the actual task title and description.\n\n* Sorts letters. Only letters. Into alphabetical order. Regardless of case. **EVERYTHING** else is ignored / pushed to the end of the \"sorted\" string. Not **ASCII** order. Not **EBCDIC** order. Only **alphabetical** order. If it ain't in the alphabet, it ain't sorted.\n* Sorts letters of the string two characters at a time **as a string**. No breaking up the string into a list or array, sorting that then joining back together; or picking characters out of a string to generate a new string. Sorts a string, as a string, in place.\n\nSorted output is wrapped in double guillemots to make it easier to see where it starts and ends.\n\n```\nsub moronic-sort ($string is copy) {\n my $chars = $string.chars;\n loop {\n for ^$chars {\n if ($string.substr($_, 1).fc gt $string.substr($_ + 1, 1).fc and $string.substr($_ + 1, 1) ~~ /<:L>/)\n or $string.substr($_, 1) ~~ /<:!L>/ {\n $string = $string.substr(0, $_) ~ $string.substr($_ , 2).flip ~ $string.substr($_ + 2 min $chars);\n }\n }\n last if $++ >= $chars;\n }\n $string\n}\n\nsub wrap ($whatever) { '»»' ~ $whatever ~ '««' }\n\n\n# Test sort the exact string as specified in the task title.\nsay \"moronic-sort 'string'\\n\" ~ wrap moronic-sort 'string';\n\n\n# Other tests demonstrating the extent of the stupidity of this task.\nsay \"\\nLonger test sentence\\n\" ~ \nwrap moronic-sort q[This is a moronic sort. It's only concerned with sorting letters, so everything else is pretty much ignored / pushed to the end. It also doesn't much care about letter case, so there is no upper / lower case differentiation.];\n\n\nsay \"\\nExtended test string:\\n\" ~ my $test = (32..126)».chr.pick(*).join;\nsay wrap moronic-sort $test;\n\n```\n\nOutput:\n\n```\nmoronic-sort 'string'\n»»ginrst««\n\nLonger test sentence\n»»aaaaaaabccccccccddddddeeeeeeeeeeeeeeeeeeeeeeeeeffggghhhhhhhhiiiIiiiiiIiiiillllllmmmnnnnnnnnnnnnoooooooooooooooopppprrrrrrrrrrrrrrssssssssssssssssTtttttttttttttttttttuuuuuvwwyyy , / . . ' , / . ' ««\n\nExtended test string:\n!kjyxAa+,LGh_8?3lXEwW-D]Ku|SY[@VF\\.op{=q>MT 1tJ/$nN(Z*%&9^v57\")`PCiOHQe'RUb<gs;6}#cfmrzd42B~0I:\n»»AabBCcDdEeFfGghHiIjJkKLlMmnNoOpPqQRrSsTtuUVvwWxXyYZz[@\\.{=> 1/$(*%&9^57\")`'<;6}#42~0:!+,_8?3-]|««\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort (the values of) three variables (**X**, **Y**, and **Z**) that contain any value (numbers and/or literals).\n\nIf that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).\n\nI.E.: (for the three variables **x**, **y**, and **z**), where:\n\n```\n x = 'lions, tigers, and'\n y = 'bears, oh my!'\n z = '(from the \"Wizard of OZ\")'\n\n```\n\nAfter sorting, the three variables would hold:\n\n```\n x = '(from the \"Wizard of OZ\")'\n y = 'bears, oh my!'\n z = 'lions, tigers, and'\n\n```\n\nFor numeric value sorting, use:\nI.E.: (for the three variables **x**, **y**, and **z**), where:\n\n```\n x = 77444\n y = -12\n z = 0\n\n```\n\nAfter sorting, the three variables would hold:\n\n```\n x = -12\n y = 0\n z = 77444\n\n```\n\nThe variables should contain some form of a number, but specify if the algorithm\nused can be for floating point or integers. Note any limitations.\n\nThe values may or may not be unique.\n\nThe method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.\n\nMore than one algorithm could be shown if one isn't clearly the better choice.\n\nOne algorithm could be:\n\n```\n • store the three variables x, y, and z\n into an array (or a list) A\n \n • sort (the three elements of) the array A\n \n • extract the three elements from the array and place them in the\n variables x, y, and z in order of extraction\n\n```\n\nAnother algorithm (only for numeric values):\n\n```\n x= 77444 \n y= -12 \n z= 0 \n low= x \n mid= y \n high= z \n x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ \n z= max(low, mid, high) /* \" \" highest \" \" \" \" \" */ \n y= low + mid + high - x - z /* \" \" middle \" \" \" \" \" */ \n\n```\n\nShow the results of the sort here on this page using at least the values of those shown above."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku has a built in sort routine which uses a variation of quicksort. The built in sort routine will automatically select a numeric sort if given a list of Real numeric items and a lexical Unicode sort if given a list that contains strings. The default numeric sort won't sort complex numbers unless you give it a custom comparator. It is trivial to modify the sort comparator function to get whatever ordering you want though.\n\nThe list (77444, -12, 0) is a poor choice to demonstrate numeric sort since it will sort the same numerically or lexically. Instead we'll use (7.7444e4, -12, 18/2). ( A Num, an Int, and a Rat. )\n\n```\n# Sorting strings. Added a vertical bar between strings to make them discernable\nmy ($a, $b, $c) = 'lions, tigers, and', 'bears, oh my!', '(from \"The Wizard of Oz\")';\nsay \"sorting: {($a, $b, $c).join('|')}\";\nsay ($a, $b, $c).sort.join('|'), ' - standard lexical string sort';\n\n# Sorting numeric things\nmy ($x, $y, $z) = 7.7444e4, -12, 18/2;\nsay \"\\nsorting: $x $y $z\";\nsay ($x, $y, $z).sort, ' - standard numeric sort, low to high';\n\n# Or, with a modified comparitor:\nfor -*, ' - numeric sort high to low',\n ~*, ' - lexical \"string\" sort',\n *.chars, ' - sort by string length short to long',\n -*.chars, ' - or long to short'\n -> $comparitor, $type {\n my ($x, $y, $z) = 7.7444e4, -12, 18/2;\n say ($x, $y, $z).sort( &$comparitor ), $type;\n}\nsay '';\n\n# sort ALL THE THINGS\n# sorts by lexical order with numeric values by magnitude.\n.say for ($a, $b, $c, $x, $y, $z).sort;\n\n```\n\nOutput:\n\n```\nsorting: lions, tigers, and|bears, oh my!|(from \"The Wizard of Oz\")\n(from \"The Wizard of Oz\")|bears, oh my!|lions, tigers, and - standard lexical string sort\n\nsorting: 77444 -12 9\n(-12 9 77444) - standard numeric sort, low to high\n(77444 9 -12) - numeric sort high to low\n(-12 77444 9) - lexical \"string\" sort\n(9 -12 77444) - sort by string length short to long\n(77444 -12 9) - or long to short\n\n(from \"The Wizard of Oz\")\n-12\n9\n77444\nbears, oh my!\nlions, tigers, and\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.\n\nUse a sorting facility provided by the language/library, combined with your own callback comparison function.\n\n**Note:** Lexicographic order is case-insensitive."
},
{
"role": "assistant",
"content": "(formerly Perl 6) \nPrimary sort by length of string, then break ties by sorting alphabetically (ignoring case).\n\n```\nmy @strings = <Here are some sample strings to be sorted>;\nput @strings.sort:{.chars, .lc};\nput sort -> $x { $x.chars, $x.lc }, @strings;\n\n```\n\nOutput:\n\n```\nbe to are Here some sample sorted strings\nbe to are Here some sample sorted strings\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array of positive integers using the Bead Sort Algorithm.\n\nA *bead sort* is also known as a *gravity sort*.\n\nAlgorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.\n\nThis is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016-05\n\n**Translation of**: Haskell\n\n```\n# routine cribbed from List::Utils;\nsub transpose(@list is copy) {\n gather {\n while @list {\n my @heads;\n if @list[0] !~~ Positional { @heads = @list.shift; }\n else { @heads = @list.map({$_.shift unless $_ ~~ []}); }\n @list = @list.map({$_ unless $_ ~~ []});\n take [@heads];\n }\n }\n}\n\nsub beadsort(@l) {\n (transpose(transpose(map {[1 xx $_]}, @l))).map(*.elems);\n}\n\nmy @list = 2,1,3,5;\nsay beadsort(@list).perl;\n\n```\n\nOutput:\n\n```\n(5, 3, 2, 1)\n```\n\nHere we simulate the dropping beads by using the push method.\n\n```\nsub beadsort(*@list) {\n my @rods;\n for words ^«@list -> $x { @rods[$x].push(1) }\n gather for ^@rods[0] -> $y {\n take [+] @rods.map: { .[$y] // last }\n }\n}\n\nsay beadsort 2,1,3,5;\n\n```\n\nThe ^ is the \"upto\" operator that gives a range of 0 up to (but not including) its endpoint. We use it as a hyperoperator (^«) to generate all the ranges of rod numbers we should drop a bead on, with the result that $x tells us which rod to drop each bead on. Then we use ^ again on the first rod to see how deep the beads are stacked, since they are guaranteed to be the deepest there. The [+] adds up all the beads that are found at level $y. The last short circuits the map so we don't have to look for all the missing beads at a given level, since the missing beads are all guaranteed to come after the existing beads at that level (because we always dropped left to right starting at rod 0)."
}
]
|
[
{
"role": "user",
"content": "Task\n\nBogosort a list of numbers.\n\nBogosort simply shuffles a collection randomly until it is sorted.\n\n\"Bogosort\" is a perversely inefficient algorithm only used as an in-joke.\n\nIts average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in *n* factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.\n\nIts best case is O(n) since a single pass through the elements may suffice to order them.\n\nPseudocode:\n\n```\nwhile not InOrder(list) do\n Shuffle(list)\ndone\n\n```\n\nThe Knuth shuffle may be used to implement the shuffle part of this algorithm."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub bogosort (@list is copy) {\n @list .= pick(*) until [<=] @list;\n return @list;\n}\n\nmy @nums = (^5).map: { rand };\nsay @nums.sort.Str eq @nums.&bogosort.Str ?? 'ok' !! 'not ok';\n\n```"
}
]
|
[
{
"role": "user",
"content": "A **bubble** sort is generally considered to be the simplest sorting algorithm.\n\nA **bubble** sort is also known as a **sinking** sort.\n\nBecause of its simplicity and ease of visualization, it is often taught in introductory computer science courses.\n\nBecause of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.\n\nThe bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values \"bubble\" rapidly toward the end, pushing others down around them). \nBecause each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. \nA boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.\n\nThis can be expressed in pseudo-code as follows (assuming 1-based indexing):\n\n```\nrepeat\n if itemCount <= 1\n return\n hasChanged := false\n decrement itemCount\n repeat with index from 1 to itemCount\n if (item at index) > (item at (index + 1))\n swap (item at index) with (item at (index + 1))\n hasChanged := true\nuntil hasChanged = false\n\n```\n\nTask\n\nSort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.\n\nReferences\n\n* The article on Wikipedia.\n* Dance interpretation."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version #24 \"Seoul\"\n\n```\nsub bubble_sort (@a) {\n for ^@a -> $i {\n for $i ^..^ @a -> $j {\n @a[$j] < @a[$i] and @a[$i, $j] = @a[$j, $i];\n }\n }\n}\n```"
}
]
|
[
{
"role": "user",
"content": "Sort an array of integers (of any convenient size) into ascending order using Circlesort.\n\nIn short, compare the first element to the last element, then the second element to the second last element, etc.\n\nThen split the array in two and recurse until there is only one single element in the array, like this:\n\n```\nBefore:\n6 7 8 9 2 5 3 4 1\nAfter:\n1 4 3 5 2 9 8 7 6\n\n```\n\nRepeat this procedure until quiescence (i.e. until there are no swaps).\n\nShow both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.)\n\nOptimizations (like doing *0.5 log2(n)* iterations and then continue with an Insertion sort) are optional.\n\nPseudo code:\n\n```\n function circlesort (index lo, index hi, swaps)\n {\n if lo == hi return (swaps)\n high := hi\n low := lo\n mid := int((hi-lo)/2)\n while lo < hi {\n if (value at lo) > (value at hi) {\n swap.values (lo,hi)\n swaps++\n }\n lo++\n hi--\n }\n if lo == hi\n if (value at lo) > (value at hi+1) {\n swap.values (lo,hi+1)\n swaps++\n }\n swaps := circlesort(low,low+mid,swaps)\n swaps := circlesort(low+mid+1,high,swaps)\n return(swaps)\n }\n while circlesort (0, sizeof(array)-1, 0)\n\n```\n\nSee also\n\n* For more information on Circle sorting, see Sourceforge."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nThe given algorithm can be simplified in several ways. There's no need to compute the midpoint, since the hi/lo will end up there. The extra swap conditional can be eliminated by incrementing hi at the correct moment inside the loop. There's no need to\npass accumulated swaps down the call stack.\n\nThis does generic comparisons, so it works on any ordered type, including numbers or strings.\n\n```\nsub circlesort (@x, $beg, $end) {\n my $swaps = 0;\n if $beg < $end {\n my ($lo, $hi) = $beg, $end;\n repeat {\n if @x[$lo] after @x[$hi] {\n @x[$lo,$hi] .= reverse;\n ++$swaps;\n }\n ++$hi if --$hi == ++$lo\n } while $lo < $hi;\n $swaps += circlesort(@x, $beg, $hi);\n $swaps += circlesort(@x, $lo, $end);\n }\n $swaps;\n}\n\nsay my @x = (-100..100).roll(20);\nsay @x while circlesort(@x, 0, @x.end);\n\nsay @x = <The quick brown fox jumps over the lazy dog.>;\nsay @x while circlesort(@x, 0, @x.end);\n\n```\n\nOutput:\n\n```\n16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88\n-99 -78 16 20 36 -81 -29 46 25 59 -64 -7 39 26 88 -1 35 85 76 100\n-99 -78 -29 -81 16 -64 -7 20 -1 39 25 26 36 46 59 35 76 88 85 100\n-99 -81 -78 -64 -29 -7 -1 16 20 25 26 35 36 39 46 59 76 85 88 100\nThe quick brown fox jumps over the lazy dog.\nThe brown fox jumps lazy dog. quick over the\nThe brown dog. fox jumps lazy over quick the\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Cocktail sort. 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\nThe cocktail shaker sort is an improvement on the Bubble Sort.\n\nThe improvement is basically that values \"bubble\" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):\n\n```\nfunction cocktailSort( A : list of sortable items )\n do\n swapped := false\n for each i in 0 to length( A ) - 2 do\n if A[ i ] > A[ i+1 ] then // test whether the two \n // elements are in the wrong \n // order\n swap( A[ i ], A[ i+1 ] ) // let the two elements\n // change places\n swapped := true;\n if swapped = false then\n // we can exit the outer loop here if no swaps occurred.\n break do-while loop;\n swapped := false\n for each i in length( A ) - 2 down to 0 do\n if A[ i ] > A[ i+1 ] then\n swap( A[ i ], A[ i+1 ] )\n swapped := true;\n while swapped; // if no elements have been swapped, \n // then the list is sorted\n\n```\n\nRelated task\n: * cocktail sort with shifting bounds"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub cocktail_sort ( @a ) {\n my $range = 0 ..^ @a.end;\n loop {\n my $swapped_forward = 0;\n for $range.list -> $i {\n if @a[$i] > @a[$i+1] {\n @a[ $i, $i+1 ] .= reverse;\n $swapped_forward = 1;\n } \n }\n last if not $swapped_forward;\n\n my $swapped_backward = 0;\n for $range.reverse -> $i {\n if @a[$i] > @a[$i+1] {\n @a[ $i, $i+1 ] .= reverse;\n $swapped_backward = 1;\n }\n }\n last if not $swapped_backward;\n }\n return @a;\n}\n\nmy @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) };\nsay @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Cocktail sort. 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\nThe cocktail sort is an improvement on the Bubble Sort.\n\nA cocktail sort is also known as:\n\n: : : : * cocktail shaker sort\n * happy hour sort\n * bidirectional bubble sort\n * a bubble sort variation\n * a selection sort variation\n * ripple sort\n * shuffle sort\n * shuttle sort\n\nThe improvement is basically that values \"bubble\" (migrate) both directions through the\narray, because on each iteration the cocktail sort *bubble sorts* once\nforwards and once backwards.\n\nAfter *ii* passes, the first *ii* and the\nlast *ii* elements in the array are in their correct\npositions, and don't have to be checked (again).\n\nBy shortening the part of the array that is sorted each time, the number of\ncomparisons can be halved.\n\nPseudocode for the 2nd algorithm (from\nWikipedia) with an added comment and changed indentations:\n\n```\nfunction A = cocktailShakerSort(A)\n% `beginIdx` and `endIdx` marks the first and last index to check.\nbeginIdx = 1;\nendIdx = length(A) - 1;\n\n while beginIdx <= endIdx\n newBeginIdx = endIdx;\n newEndIdx = beginIdx;\n for ii = beginIdx:endIdx\n if A(ii) > A(ii + 1)\n [A(ii+1), A(ii)] = deal(A(ii), A(ii+1));\n newEndIdx = ii;\n end\n end\n\n % decreases `endIdx` because the elements after `newEndIdx` are in correct order\n endIdx = newEndIdx - 1;\n\n % (FOR (below) decrements the II index by -1.\n\n for ii = endIdx:-1:beginIdx\n if A(ii) > A(ii + 1)\n [A(ii+1), A(ii)] = deal(A(ii), A(ii+1));\n newBeginIdx = ii;\n end\n end\n\n % increases `beginIdx` because the elements before `newBeginIdx` are in correct order.\n beginIdx = newBeginIdx + 1;\n end\nend\n\n```\n\n**%** indicates a comment, and **deal** indicates a *swap*.\n\nTask\n\nImplement a *cocktail sort* and optionally show the sorted output here on this page.\n\nSee the *discussion* page for some timing comparisons.\n\nRelated task\n: * cocktail sort"
},
{
"role": "assistant",
"content": "**Works with**: Rakudo version 2020.05\n\n```\nsub cocktail_sort ( @a ) {\n my ($min, $max) = 0, +@a - 2;\n loop {\n my $swapped_forward = 0;\n for $min .. $max -> $i {\n given @a[$i] cmp @a[$i+1] {\n when More {\n @a[ $i, $i+1 ] .= reverse;\n $swapped_forward = 1\n }\n default {}\n }\n }\n last if not $swapped_forward;\n $max -= 1;\n\n my $swapped_backward = 0;\n for ($min .. $max).reverse -> $i {\n given @a[$i] cmp @a[$i+1] {\n when More {\n @a[ $i, $i+1 ] .= reverse;\n $swapped_backward = 1\n }\n default {}\n }\n }\n last if not $swapped_backward;\n $min += 1;\n }\n @a\n}\n\nmy @weights = (flat 0..9, 'A'..'F').roll(2 + ^4 .roll).join xx 100;\nsay @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';\n\n```"
}
]
|
[
{
"role": "user",
"content": "This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.\n\nTask\n\nImplement a *comb sort*.\n\nThe **Comb Sort** is a variant of the Bubble Sort.\n\nLike the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges.\n\nDividing the gap by \n\n(\n1\n−\n\ne\n\n−\nφ\n\n)\n\n−\n1\n≈\n1.247330950103979\n{\\displaystyle {\\displaystyle (1-e^{-\\varphi })^{-1}\\approx 1.247330950103979}}\n works best, but 1.3 may be more practical.\n\nSome implementations use the insertion sort once the gap is less than a certain amount.\n\nAlso see\n\n* the Wikipedia article: Comb sort.\n\nVariants:\n\n* Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings.\n* Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small). Comb sort with a low gap isn't much better than the Bubble Sort.\n\nPseudocode:\n\n```\nfunction combsort(array input)\n gap := input.size //initialize gap size\n loop until gap = 1 and swaps = 0\n //update the gap value for a next comb. Below is an example\n gap := int(gap / 1.25)\n if gap < 1\n //minimum gap is 1\n gap := 1\n end if\n i := 0\n swaps := 0 //see Bubble Sort for an explanation\n //a single \"comb\" over the input list\n loop until i + gap >= input.size //see Shell sort for similar idea\n if input[i] > input[i+gap]\n swap(input[i], input[i+gap])\n swaps := 1 // Flag a swap has occurred, so the\n // list is not guaranteed sorted\n end if\n i := i + 1\n end loop\n end loop\nend function\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub comb_sort ( @a is copy ) {\n my $gap = +@a;\n my $swaps = 1;\n while $gap > 1 or $swaps {\n $gap = ( ($gap * 4) div 5 ) || 1 if $gap > 1;\n\n $swaps = 0;\n for ^(+@a - $gap) -> $i {\n my $j = $i + $gap;\n if @a[$i] > @a[$j] {\n @a[$i, $j] .= reverse;\n $swaps = 1;\n }\n }\n }\n return @a;\n}\n\nmy @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) };\nsay @weights.sort.Str eq @weights.&comb_sort.Str ?? 'ok' !! 'not ok';\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Counting sort. 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\nImplement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.\n\nPseudocode\n\n```\nfunction countingSort(array, min, max):\n count: array of (max - min + 1) elements\n initialize count with 0\n for each number in array do\n count[number - min] := count[number - min] + 1\n done\n z := 0\n for i from min to max do\n while ( count[i - min] > 0 ) do\n array[z] := i\n z := z+1\n count[i - min] := count[i - min] - 1\n done\n done\n\n```\n\nThe *min* and *max* can be computed apart, or be known *a priori*.\n\n**Note**: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to **232** elements may be needed. I.E.: we need to hold a count value up to **232-1**, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known *a priori*. (However, as a counterexample, the use of *sparse arrays* minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values *a priori*.)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nsub counting-sort (@ints) {\n my $off = @ints.min;\n (my @counts)[$_ - $off]++ for @ints;\n flat @counts.kv.map: { ($^k + $off) xx ($^v // 0) }\n}\n\n# Testing:\nconstant @age-range = 2 .. 102;\nmy @ages = @age-range.roll(50);\nsay @ages.&counting-sort;\nsay @ages.sort;\n\nsay @ages.&counting-sort.join eq @ages.sort.join ?? 'ok' !! 'not ok';\n\n```\n\nOutput:\n\n```\n(5 5 5 7 9 17 19 19 20 21 25 27 28 30 32 34 38 40 41 45 48 49 50 51 53 54 55 56 59 62 65 66 67 69 70 73 74 81 83 85 87 91 91 93 94 96 99 99 100 101)\n(5 5 5 7 9 17 19 19 20 21 25 27 28 30 32 34 38 40 41 45 48 49 50 51 53 54 55 56 59 62 65 66 67 69 70 73 74 81 83 85 87 91 91 93 94 96 99 99 100 101)\nok\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Cycle\\_sort. 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\nFrom the the Wikipedia entry on cycle sorting:\n\n: **Cycle sort** is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm.\n: It is based on the idea that the permutation to be sorted can be factored into cycles, which can individually be rotated to give a sorted result.\n\n: Unlike nearly every other sort, items are never written elsewhere in the array simply to push them out of the way of the action.\n: Each value is either written zero times, if it's already in its correct position, or written one time to its correct position.\n: This matches the minimal number of overwrites required for a completed in-place sort.\n\n: Minimizing the number of writes is useful when making writes to some huge data set is very expensive, such as with EEPROMs like Flash memory where each write reduces the lifespan of the memory.\n\nSee also\n\n* Youtube Visualization and audibilization of Cycle Sort algorithm."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub cycle_sort ( @nums ) {\n my $writes = 0;\n\n # Loop through the array to find cycles to rotate.\n for @nums.kv -> $cycle_start, $item is copy {\n\n # Find where to put the item.\n my $pos = $cycle_start\n + @nums[ $cycle_start ^.. * ].grep: * < $item;\n\n # If the item is already there, this is not a cycle.\n next if $pos == $cycle_start;\n\n # Otherwise, put the item there or right after any duplicates.\n $pos++ while $item == @nums[$pos];\n ( @nums[$pos], $item ) .= reverse;\n $writes++;\n\n # Rotate the rest of the cycle.\n while $pos != $cycle_start {\n\n # Find where to put the item.\n $pos = $cycle_start\n + @nums[ $cycle_start ^.. * ].grep: * < $item;\n\n # Put the item there or right after any duplicates.\n $pos++ while $item == @nums[$pos];\n ( @nums[$pos], $item ) .= reverse;\n $writes++;\n }\n }\n\n return $writes;\n}\n\nmy @a = <0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6>;\n\nsay @a;\nsay 'writes ', cycle_sort(@a);\nsay @a;\n\n```\n\nOutput:\n\n```\n0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6\nwrites 10\n0 0 1 1 2 2 2 2 3.5 4 5 6 7 8 9\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Gnome sort. 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\nGnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.\n\nThe pseudocode for the algorithm is:\n\n```\nfunction gnomeSort(a[0..size-1])\n i := 1\n j := 2\n while i < size do\n if a[i-1] <= a[i] then\n // for descending sort, use >= for comparison\n i := j\n j := j + 1 \n else\n swap a[i-1] and a[i]\n i := i - 1\n if i = 0 then\n i := j\n j := j + 1\n endif\n endif\n done\n\n```\n\nTask\n\nImplement the Gnome sort in your language to sort an array (or list) of numbers."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.03\n\n```\nsub gnome_sort (@a) {\n my ($i, $j) = 1, 2;\n while $i < @a {\n if @a[$i - 1] <= @a[$i] {\n ($i, $j) = $j, $j + 1;\n }\n else {\n (@a[$i - 1], @a[$i]) = @a[$i], @a[$i - 1];\n $i--;\n ($i, $j) = $j, $j + 1 if $i == 0;\n }\n }\n}\n\nmy @n = (1..10).roll(20);\nsay @n.&gnome_sort ~~ @n.sort ?? 'ok' !! 'not ok';\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Heapsort. 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\nHeapsort is an in-place sorting algorithm with worst case and average complexity of O(*n* log*n*).\n\nThe basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element.\n\nWe repeatedly \"remove\" the maximal element from the heap, thus building the sorted list from back to front.\n\nA heap sort requires random access, so can only be used on an array-like data structure.\n\nPseudocode:\n\n```\nfunction heapSort(a, count) is\n input: an unordered array a of length count\n \n (first place a in max-heap order)\n heapify(a, count)\n \n end := count - 1\n while end > 0 do\n (swap the root(maximum value) of the heap with the\n last element of the heap)\n swap(a[end], a[0])\n (decrement the size of the heap so that the previous\n max value will stay in its proper place)\n end := end - 1\n (put the heap back in max-heap order)\n siftDown(a, 0, end)\n\n```\n\n```\nfunction heapify(a,count) is\n (start is assigned the index in a of the last parent node)\n start := (count - 2) / 2\n \n while start ≥ 0 do\n (sift down the node at index start to the proper place\n such that all nodes below the start index are in heap\n order)\n siftDown(a, start, count-1)\n start := start - 1\n (after sifting down the root all nodes/elements are in heap order)\n \nfunction siftDown(a, start, end) is\n (end represents the limit of how far down the heap to sift)\n root := start\n\n while root * 2 + 1 ≤ end do (While the root has at least one child)\n child := root * 2 + 1 (root*2+1 points to the left child)\n (If the child has a sibling and the child's value is less than its sibling's...)\n if child + 1 ≤ end and a[child] < a[child + 1] then\n child := child + 1 (... then point to the right child instead)\n if a[root] < a[child] then (out of max-heap order)\n swap(a[root], a[child])\n root := child (repeat to continue sifting down the child now)\n else\n return\n\n```\n\nWrite a function to sort a collection of integers using heapsort."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub heap_sort ( @list ) {\n for ( 0 ..^ +@list div 2 ).reverse -> $start {\n _sift_down $start, @list.end, @list;\n }\n\n for ( 1 ..^ +@list ).reverse -> $end {\n @list[ 0, $end ] .= reverse;\n _sift_down 0, $end-1, @list;\n }\n}\n\nsub _sift_down ( $start, $end, @list ) {\n my $root = $start;\n while ( my $child = $root * 2 + 1 ) <= $end {\n $child++ if $child + 1 <= $end and [<] @list[ $child, $child+1 ];\n return if @list[$root] >= @list[$child];\n @list[ $root, $child ] .= reverse;\n $root = $child;\n }\n}\n\nmy @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;\nsay 'Input = ' ~ @data;\n@data.&heap_sort;\nsay 'Output = ' ~ @data;\n\n```\n\nOutput:\n\n```\nInput = 6 7 2 1 8 9 5 3 4\nOutput = 1 2 3 4 5 6 7 8 9\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Insertion sort. 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 O(*n*2) sorting algorithm which moves elements one at a time into the correct position.\nThe algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary.\nTo start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part.\n\nAlthough insertion sort is an O(*n*2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:\n\n: 1. small *n*,\n 2. as the final finishing-off algorithm for O(*n* log*n*) algorithms such as mergesort and quicksort.\n\nThe algorithm is as follows (from wikipedia):\n\n```\nfunction insertionSort(array A)\n for i from 1 to length[A]-1 do\n value := A[i] \n j := i-1\n while j >= 0 and A[j] > value do\n A[j+1] := A[j]\n j := j-1\n done\n A[j+1] = value\n done\n\n```\n\nWriting the algorithm for integers will suffice."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub insertion_sort ( @a is copy ) {\n for 1 .. @a.end -> $i {\n my $value = @a[$i];\n my $j;\n loop ( $j = $i-1; $j >= 0 and @a[$j] > $value; $j-- ) {\n @a[$j+1] = @a[$j];\n }\n @a[$j+1] = $value;\n }\n return @a;\n}\n\nmy @data = 22, 7, 2, -5, 8, 4;\nsay 'input = ' ~ @data;\nsay 'output = ' ~ @data.&insertion_sort;\n```\n\nOutput:\n\n```\ninput = 22 7 2 -5 8 4\noutput = -5 2 4 7 8 22\n\n```"
}
]
|
[
{
"role": "user",
"content": "The **merge sort** is a recursive sort of order n\\*log(n).\n\nIt is notable for having a worst case and average complexity of *O(n\\*log(n))*, and a best case complexity of *O(n)* (for pre-sorted input).\n\nThe basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups).\n\nThen merge the groups back together so that their elements are in order.\n\nThis is how the algorithm gets its *divide and conquer* description.\n\nTask\n\nWrite a function to sort a collection of integers using the merge sort.\n\nThe merge sort algorithm comes in two parts:\n\n```\n a sort function and \n a merge function \n\n```\n\nThe functions in pseudocode look like this:\n\n```\nfunction mergesort(m)\n var list left, right, result\n if length(m) ≤ 1\n return m\n else\n var middle = length(m) / 2\n for each x in m up to middle - 1\n add x to left\n for each x in m at and after middle\n add x to right\n left = mergesort(left)\n right = mergesort(right)\n if last(left) ≤ first(right) \n append right to left\n return left\n result = merge(left, right)\n return result\n\nfunction merge(left,right)\n var list result\n while length(left) > 0 and length(right) > 0\n if first(left) ≤ first(right)\n append first(left) to result\n left = rest(left)\n else\n append first(right) to result\n right = rest(right)\n if length(left) > 0 \n append rest(left) to result\n if length(right) > 0 \n append rest(right) to result\n return result\n\n```\n\nSee also\n\n* the Wikipedia entry: merge sort\n\nNote: better performance can be expected if, rather than recursing until length(m) ≤ 1, an insertion sort is used for length(m) smaller than some threshold larger than **1**. However, this complicates the example code, so it is not shown here."
},
{
"role": "assistant",
"content": "```\n#| Recursive, single-thread, mergesort implementation\nsub mergesort ( @a ) {\n\treturn @a if @a <= 1;\n\n\t# recursion step\n\tmy $m = @a.elems div 2;\n\tmy @l = samewith @a[ 0 ..^ $m ];\n\tmy @r = samewith @a[ $m ..^ @a ];\n\n\t# short cut - in case of no overlapping in left and right parts\n\treturn flat @l, @r if @l[*-1] !after @r[0];\n\treturn flat @r, @l if @r[*-1] !after @l[0];\n\n\t# merge step\n\treturn flat gather {\n\t\ttake @l[0] before @r[0]\n\t\t\t\t?? @l.shift\n\t\t\t\t!! @r.shift\n\t\t while @l and @r;\n\n\t\ttake @l, @r;\n\t}\n}\n```\n\nSome intial testing\n\n```\nmy @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;\nsay 'input = ' ~ @data;\nsay 'output = ' ~ @data.&merge_sort;\n```\n\nOutput:\n\n```\ninput = 6 7 2 1 8 9 5 3 4\noutput = 1 2 3 4 5 6 7 8 9\n```\n\n### concurrent implementation\n\nLet's implement it using parallel sorting.\n\n```\n#| Recursive, naive multi-thread, mergesort implementation\nsub mergesort-parallel-naive ( @a ) {\n\treturn @a if @a <= 1;\n\n\tmy $m = @a.elems div 2;\n\n\t# recursion step launching new thread\n my @l = start { samewith @a[ 0 ..^ $m ] };\n\t\n # meanwhile recursively sort right side\n my @r = samewith @a[ $m ..^ @a ] ;\n\n\t# as we went parallel on left side, we need to await the result\n\tawait @l[0] andthen @l = @l[0].result;\n\n\t# short cut - in case of no overlapping left and right parts\n\treturn flat @l, @r if @l[*-1] !after @r[0];\n\treturn flat @r, @l if @r[*-1] !after @l[0];\n\n\t# merge step\n\treturn flat gather {\n\t\ttake @l[0] before @r[0]\n\t\t\t\t?? @l.shift\n\t\t\t\t!! @r.shift\n\t\t while @l and @r;\n\n\t\ttake @l, @r;\n\t}\n}\n```\n\nand tune the batch size required to launch a new thread.\n\n```\n#| Recursive, batch tuned multi-thread, mergesort implementation\nsub mergesort-parallel ( @a, $batch = 2**9 ) {\n\treturn @a if @a <= 1;\n\n\tmy $m = @a.elems div 2;\n\n\t# recursion step\n\tmy @l = $m >= $batch\n\t\t\t ?? start { samewith @a[ 0 ..^ $m ], $batch }\n\t\t\t !! samewith @a[ 0 ..^ $m ], $batch ;\n\n\t# meanwhile recursively sort right side\n\tmy @r = samewith @a[ $m ..^ @a ], $batch;\n\n\t# if we went parallel on left side, we need to await the result\n\tawait @l[0] andthen @l = @l[0].result if @l[0] ~~ Promise;\n\n\t# short cut - in case of no overlapping left and right parts\n\treturn flat @l, @r if @l[*-1] !after @r[0];\n\treturn flat @r, @l if @r[*-1] !after @l[0];\n\n\t# merge step\n\treturn flat gather {\n\t\ttake @l[0] before @r[0]\n\t\t\t\t?? @l.shift\n\t\t\t\t!! @r.shift\n\t\t while @l and @r;\n\n\t\ttake @l, @r;\n\t}\n}\n```\n\n### testing\n\nLet's run some tests ...\n\n```\nsay \"x\" x 10 ~ \" Testing \" ~ \"x\" x 10;\nuse Test;\nmy @functions-under-test = &mergesort, &mergesort-parallel-naive, &mergesort-parallel;\nmy @testcases =\n\t\t() => (),\n\t\t<a>.List => <a>.List,\n\t\t<a a> => <a a>,\n\t\t(\"b\", \"a\", 3) => (3, \"a\", \"b\"),\n\t\t<h b a c d f e g> => <a b c d e f g h>,\n\t\t<a 🎮 3 z 4 🐧> => <a 🎮 3 z 4 🐧>.sort\n\t\t;\n\nplan @testcases.elems * @functions-under-test.elems;\nfor @functions-under-test -> &fun {\n\tsay &fun.name;\n\tis-deeply &fun(.key), .value, .key ~ \" => \" ~ .value for @testcases;\n}\ndone-testing;\n```\n\nOutput:\n\n```\nxxxxxxxxxx Testing xxxxxxxxxx\n1..18\nmergesort\nok 1 - =>\nok 2 - a => a\nok 3 - a a => a a\nok 4 - b a 3 => 3 a b\nok 5 - h b a c d f e g => a b c d e f g h\nok 6 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\nmergesort-parallel-naive\nok 7 - =>\nok 8 - a => a\nok 9 - a a => a a\nok 10 - b a 3 => 3 a b\nok 11 - h b a c d f e g => a b c d e f g h\nok 12 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\nmergesort-parallel\nok 13 - =>\nok 14 - a => a\nok 15 - a a => a a\nok 16 - b a 3 => 3 a b\nok 17 - h b a c d f e g => a b c d e f g h\nok 18 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\n```\n\n### benchmarking\n\nand some Benchmarking.\n\n```\nuse Benchmark;\nmy $runs = 5;\nmy $elems = 10 * Kernel.cpu-cores * 2**10;\nmy @unsorted of Str = ('a'..'z').roll(8).join xx $elems;\nmy UInt $l-batch = 2**13;\nmy UInt $m-batch = 2**11;\nmy UInt $s-batch = 2**9;\nmy UInt $t-batch = 2**7;\n\nsay \"elements: $elems, runs: $runs, cpu-cores: {Kernel.cpu-cores}, large/medium/small/tiny-batch: $l-batch/$m-batch/$s-batch/$t-batch\";\n\nmy %results = timethese $runs, {\n\tsingle-thread => { mergesort(@unsorted) },\n\tparallel-naive => { mergesort-parallel-naive(@unsorted) },\n\tparallel-tiny-batch => { mergesort-parallel(@unsorted, $t-batch) },\n\tparallel-small-batch => { mergesort-parallel(@unsorted, $s-batch) },\n\tparallel-medium-batch => { mergesort-parallel(@unsorted, $m-batch) },\n\tparallel-large-batch => { mergesort-parallel(@unsorted, $l-batch) },\n}, :statistics;\n\nmy @metrics = <mean median sd>;\nmy $msg-row = \"%.4f\\t\" x @metrics.elems ~ '%s';\n\nsay @metrics.join(\"\\t\");\nfor %results.kv -> $name, %m {\n\tsay sprintf($msg-row, %m{@metrics}, $name);\n}\n```\n\n```\nelements: 40960, runs: 5, cpu-cores: 4, large/medium/small/tiny-batch: 8192/2048/512/128\nmean\tmedian\tsd\n7.7683\t8.0265\t0.5724\tparallel-naive\n3.1354\t3.1272\t0.0602\tparallel-tiny-batch\n2.6932\t2.6599\t0.1831\tparallel-medium-batch\n2.8139\t2.7832\t0.0641\tparallel-large-batch\n3.0908\t3.0593\t0.0675\tparallel-small-batch\n5.9989\t5.9450\t0.1518\tsingle-thread\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array of integers (of any convenient size) into ascending order using Pancake sorting.\n\nIn short, instead of individual elements being sorted, the only operation allowed is to \"flip\" one end of the list, like so:\n\n```\n Before: 6 7 8 9 2 5 3 4 1\n After: 9 8 7 6 2 5 3 4 1\n\n```\n\nOnly one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it **must** be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)\n\nShow both the initial, unsorted list and the final sorted list.\n\n(Intermediate steps during sorting are optional.)\n\nOptimizations are optional (but recommended).\n\nRelated tasks\n\n* Number reversal game\n* Topswops\n\nAlso see\n\n* Wikipedia article: pancake sorting."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub pancake_sort(@a is copy) {\n my $endpoint = @a.end;\n while $endpoint > 0 and not [<] @a {\n my $max_i = [0..$endpoint].max: { @a[$_] };\n my $max = @a[$max_i];\n if @a[$endpoint] == $max {\n $endpoint-- while $endpoint >= 0 and @a[$endpoint] == $max;\n next;\n }\n # @a[$endpoint] is not $max, so it needs flipping;\n # Flip twice if max is not already at the top.\n @a[0..$max_i] .= reverse if $max_i != 0;\n @a[0..$endpoint] .= reverse;\n $endpoint--;\n }\n return @a;\n}\n\nfor <6 7 2 1 8 9 5 3 4>,\n <4 5 7 1 46 78 2 2 1 9 10>,\n <0 -9 -8 2 -7 8 6 -2 -8 3> -> @data {\n say 'input = ' ~ @data;\n say 'output = ' ~ @data.&pancake_sort\n}\n\n```\n\nOutput:\n\n```\ninput = 6 7 2 1 8 9 5 3 4\noutput = 1 2 3 4 5 6 7 8 9\ninput = 4 5 7 1 46 78 2 2 1 9 10\noutput = 1 1 2 2 4 5 7 9 10 46 78\ninput = 0 -9 -8 2 -7 8 6 -2 -8 3\noutput = -9 -8 -8 -7 -2 0 2 3 6 8\n```\n\nThe following is an alternative adapted from the code by Andrew Shitov.\n\n```\n# 20240908 Updated Raku programming solution\n\nsub pancake-sort(@data is copy) { # imperative\n for @data.elems - 1 ... 1 {\n @data[0 .. @data[0..$_].maxpairs[*-1].key] .= reverse;\n @data[0 .. $_] .= reverse;\n }\n return @data\n}\n\nsub pancake_sort(@data is copy) { # recursive\n return @data if @data.elems <= 1;\n @data[0 .. @data.maxpairs[*-1].key] .= reverse;\n return pancake_sort(@data[1..*-1]).append: @data[0]\n}\n\nfor <6 7 2 1 8 9 5 3 4>,\n <4 5 7 1 46 78 2 2 1 9 10>,\n <0 -9 -8 2 -7 8 6 -2 -8 3> -> @data {\n say 'input = ' ~ @data;\n say 'output = ' ~ pancake-sort(@data);\n say 'output = ' ~ pancake_sort(@data) ~ \"\\n\"\n}\n\n```\n\nOutput:\n\n```\ninput = 6 7 2 1 8 9 5 3 4\noutput = 1 2 3 4 5 6 7 8 9\noutput = 1 2 3 4 5 6 7 8 9\n\ninput = 4 5 7 1 46 78 2 2 1 9 10\noutput = 1 1 2 2 4 5 7 9 10 46 78\noutput = 1 1 2 2 4 5 7 9 10 46 78\n\ninput = 0 -9 -8 2 -7 8 6 -2 -8 3\noutput = -9 -8 -8 -7 -2 0 2 3 6 8\noutput = -9 -8 -8 -7 -2 0 2 3 6 8\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Sort an array of numbers (of any convenient size) into ascending order using Patience sorting.\n\nRelated task\n: * Longest increasing subsequence"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2015-10-22\n\n```\nmulti patience(*@deck) {\n my @stacks;\n for @deck -> $card {\n with @stacks.first: $card before *[*-1] -> $stack {\n $stack.push: $card;\n }\n else {\n @stacks.push: [$card];\n }\n }\n gather while @stacks {\n take .pop given min :by(*[*-1]), @stacks;\n @stacks .= grep: +*;\n }\n}\n\nsay ~patience ^10 . pick(*);\n\n```\n\nOutput:\n\n```\n0 1 2 3 4 5 6 7 8 9\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement a permutation sort, which proceeds by generating the possible permutations\nof the input array/list until discovering the sorted one.\n\nPseudocode:\n\n```\nwhile not InOrder(list) do\n nextPermutation(list)\ndone\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n# Lexicographic permuter from \"Permutations\" task.\nsub next_perm ( @a ) {\n my $j = @a.end - 1;\n $j-- while $j >= 1 and [>] @a[ $j, $j+1 ];\n\n my $aj = @a[$j];\n my $k = @a.end;\n $k-- while [>] $aj, @a[$k];\n\n @a[ $j, $k ] .= reverse;\n\n my Int $r = @a.end;\n my Int $s = $j + 1;\n while $r > $s {\n @a[ $r, $s ] .= reverse;\n $r--;\n $s++;\n }\n}\n\nsub permutation_sort ( @a ) {\n my @n = @a.keys;\n my $perm_count = [*] 1 .. +@n; # Factorial\n for ^$perm_count {\n my @permuted_a = @a[ @n ];\n return @permuted_a if [le] @permuted_a;\n next_perm(@n);\n }\n}\n\nmy @data = < c b e d a >; # Halfway between abcde and edcba\nsay 'Input = ' ~ @data;\nsay 'Output = ' ~ @data.&permutation_sort;\n\n```\n\nOutput:\n\n```\nInput = c b e d a\nOutput = a b c d e\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Quicksort. 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\nSort an array (or list) elements using the quicksort algorithm.\n\nThe elements must have a strict weak order and the index of the array can be of any discrete type.\n\nFor languages where this is not possible, sort an array of integers.\n\nQuicksort, also known as *partition-exchange sort*, uses these steps.\n\n: : 1. Choose any element of the array to be the pivot.\n 2. Divide all other elements (except the pivot) into two partitions.\n * All elements less than the pivot must be in the first partition.\n * All elements greater than the pivot must be in the second partition.\n 3. Use recursion to sort both partitions.\n 4. Join the first sorted partition, the pivot, and the second sorted partition.\n\nThe best pivot creates partitions of equal length (or lengths differing by **1**).\n\nThe worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array).\n\nThe run-time of Quicksort ranges from *O(n* log *n)* with the best pivots, to *O(n2)* with the worst pivots, where *n* is the number of elements in the array.\n\nThis is a simple quicksort algorithm, adapted from Wikipedia.\n\n```\nfunction quicksort(array)\n less, equal, greater := three empty arrays\n if length(array) > 1 \n pivot := select any element of array\n for each x in array\n if x < pivot then add x to less\n if x = pivot then add x to equal\n if x > pivot then add x to greater\n quicksort(less)\n quicksort(greater)\n array := concatenate(less, equal, greater)\n\n```\n\nA better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays.\n\n```\nfunction quicksort(array)\n if length(array) > 1\n pivot := select any element of array\n left := first index of array\n right := last index of array\n while left ≤ right\n while array[left] < pivot\n left := left + 1\n while array[right] > pivot\n right := right - 1\n if left ≤ right\n swap array[left] with array[right]\n left := left + 1\n right := right - 1\n quicksort(array from first index to right)\n quicksort(array from left to last index)\n\n```\n\nQuicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with merge sort, because both sorts have an average time of *O(n* log *n)*.\n\n: *\"On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times.\"* — http://perldoc.perl.org/sort.html\n\nQuicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end.\n\n* Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort.\n* Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase.\n\nWith quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention!\n\nThis task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations."
},
{
"role": "assistant",
"content": "```\n#| Recursive, single-thread, random pivot, single-pass, quicksort implementation\nmulti quicksort(\\a where a.elems < 2) { a }\nmulti quicksort(\\a, \\pivot = a.pick) {\n\tmy %prt{Order} is default([]) = a.classify: * cmp pivot;\n\t|samewith(%prt{Less}), |%prt{Same}, |samewith(%prt{More})\n}\n```\n\n### concurrent implementation\n\nThe partitions can be sorted in parallel.\n\n```\n#| Recursive, parallel, random pivot, single-pass, quicksort implementation\nmulti quicksort-parallel-naive(\\a where a.elems < 2) { a }\nmulti quicksort-parallel-naive(\\a, \\pivot = a.pick) {\n\tmy %prt{Order} is default([]) = a.classify: * cmp pivot;\n\tmy Promise $less = start { samewith(%prt{Less}) }\n\tmy $more = samewith(%prt{More});\n\tawait $less andthen |$less.result, |%prt{Same}, |$more;\n}\n```\n\nLet's tune the parallel execution by applying a minimum batch size in order to spawn a new thread.\n\n```\n#| Recursive, parallel, batch tuned, single-pass, quicksort implementation\nsub quicksort-parallel(@a, $batch = 2**9) {\n\treturn @a if @a.elems < 2;\n\n\t# separate unsorted input into Order Less, Same and More compared to a random $pivot\n\tmy $pivot = @a.pick;\n\tmy %prt{Order} is default([]) = @a.classify( * cmp $pivot );\n\n\t# decide if we sort the Less partition on a new thread\n\tmy $less = %prt{Less}.elems >= $batch\n\t\t\t ?? start { samewith(%prt{Less}, $batch) }\n\t\t\t !! samewith(%prt{Less}, $batch);\n\n\t# meanwhile use current thread for sorting the More partition\n\tmy $more = samewith(%prt{More}, $batch);\n\n\t# if we went parallel, we need to await the result\n\tawait $less andthen $less = $less.result if $less ~~ Promise;\n\n\t# concat all sorted partitions into a list and return\n\t|$less, |%prt{Same}, |$more;\n}\n```\n\n### testing\n\nLet's run some tests.\n\n```\nsay \"x\" x 10 ~ \" Testing \" ~ \"x\" x 10;\nuse Test;\nmy @functions-under-test = &quicksort, &quicksort-parallel-naive, &quicksort-parallel;\nmy @testcases =\n\t\t() => (),\n\t\t<a>.List => <a>.List,\n\t\t<a a> => <a a>,\n\t\t(\"b\", \"a\", 3) => (3, \"a\", \"b\"),\n\t\t<h b a c d f e g> => <a b c d e f g h>,\n\t\t<a 🎮 3 z 4 🐧> => <a 🎮 3 z 4 🐧>.sort\n\t\t;\n\nplan @testcases.elems * @functions-under-test.elems;\nfor @functions-under-test -> &fun {\n\tsay &fun.name;\n\tis-deeply &fun(.key), .value, .key ~ \" => \" ~ .value for @testcases;\n}\ndone-testing;\n```\n\n```\nxxxxxxxxxx Testing xxxxxxxxxx\n1..18\nquicksort\nok 1 - =>\nok 2 - a => a\nok 3 - a a => a a\nok 4 - b a 3 => 3 a b\nok 5 - h b a c d f e g => a b c d e f g h\nok 6 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\nquicksort-parallel-naive\nok 7 - =>\nok 8 - a => a\nok 9 - a a => a a\nok 10 - b a 3 => 3 a b\nok 11 - h b a c d f e g => a b c d e f g h\nok 12 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\nquicksort-parallel\nok 13 - =>\nok 14 - a => a\nok 15 - a a => a a\nok 16 - b a 3 => 3 a b\nok 17 - h b a c d f e g => a b c d e f g h\nok 18 - a 🎮 3 z 4 🐧 => 3 4 a z 🎮 🐧\n```\n\n### benchmarking\n\nand some benchmarking\n\n```\nsay \"x\" x 11 ~ \" Benchmarking \" ~ \"x\" x 11;\nuse Benchmark;\nmy $runs = 5;\nmy $elems = 10 * Kernel.cpu-cores * 2**10;\nmy @unsorted of Str = ('a'..'z').roll(8).join xx $elems;\nmy UInt $l-batch = 2**13;\nmy UInt $m-batch = 2**11;\nmy UInt $s-batch = 2**9;\nmy UInt $t-batch = 2**7;\n\nsay \"elements: $elems, runs: $runs, cpu-cores: {Kernel.cpu-cores}, large/medium/small/tiny-batch: $l-batch/$m-batch/$s-batch/$t-batch\";\n\nmy %results = timethese $runs, {\n\tsingle-thread => { quicksort(@unsorted) },\n\tparallel-naive => { quicksort-parallel-naive(@unsorted) },\n\tparallel-tiny-batch => { quicksort-parallel(@unsorted, $t-batch) },\n\tparallel-small-batch => { quicksort-parallel(@unsorted, $s-batch) },\n\tparallel-medium-batch => { quicksort-parallel(@unsorted, $m-batch) },\n\tparallel-large-batch => { quicksort-parallel(@unsorted, $l-batch) },\n}, :statistics;\n\nmy @metrics = <mean median sd>;\nmy $msg-row = \"%.4f\\t\" x @metrics.elems ~ '%s';\n\nsay @metrics.join(\"\\t\");\nfor %results.kv -> $name, %m {\n\tsay sprintf($msg-row, %m{@metrics}, $name);\n}\n```\n\n```\nxxxxxxxxxxx Benchmarking xxxxxxxxxxx\nelements: 40960, runs: 5, cpu-cores: 4, large/medium/small/tiny-batch: 8192/2048/512/128\nmean\tmedian\tsd\n2.9503\t2.8907\t0.2071\tparallel-small-batch\n3.2054\t3.1727\t0.2078\tparallel-tiny-batch\n5.6524\t5.0980\t1.2628\tparallel-naive\n3.4717\t3.3353\t0.3622\tparallel-medium-batch\n4.6275\t4.7793\t0.4930\tparallel-large-batch\n6.5401\t6.2832\t0.5585\tsingle-thread\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an integer array with the radix sort algorithm.\n\nThe primary purpose is to complete the characterization of sort algorithms task."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nA base-10 radix sort, done on the string representation of the integers. Signs are handled by in-place reversal of the '-' bucket on the last iteration. (The sort in there is not cheating; it only makes sure we process the buckets in the right order, since classify might return the buckets in random order. It might be more efficient to create our own ordered buckets, but this is succinct.)\n\n```\nsub radsort (@ints) {\n my $maxlen = max @ints».chars;\n my @list = @ints».fmt(\"\\%0{$maxlen}d\");\n\n for reverse ^$maxlen -> $r {\n my @buckets = @list.classify( *.substr($r,1) ).sort: *.key;\n @buckets[0].value = @buckets[0].value.reverse.List\n if !$r and @buckets[0].key eq '-';\n @list = flat map *.value.values, @buckets;\n }\n @list».Int;\n}\n\n.say for radsort (-2_000 .. 2_000).roll(20);\n\n```\n\nOutput:\n\n```\n-1585\n-1427\n-1228\n-1067\n-945\n-657\n-643\n-232\n-179\n-28\n37\n411\n488\n509\n716\n724\n1504\n1801\n1864\n1939\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array (or list) of elements using the Selection sort algorithm.\n\nIt works as follows:\n\nFirst find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.\n\nIts asymptotic complexity is O(n2) making it inefficient on large arrays.\n\nIts primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.\n\nNo other sorting algorithm has less data movement.\n\nReferences\n\n* Rosetta Code: O (complexity).\n* Wikipedia: Selection sort.\n* Wikipedia: [Big O notation]."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nSolution 1:\n\n```\nsub selection_sort ( @a is copy ) {\n for 0 ..^ @a.end -> $i {\n my $min = [ $i+1 .. @a.end ].min: { @a[$_] };\n @a[$i, $min] = @a[$min, $i] if @a[$i] > @a[$min];\n }\n return @a;\n}\n\nmy @data = 22, 7, 2, -5, 8, 4;\nsay 'input = ' ~ @data;\nsay 'output = ' ~ @data.&selection_sort;\n\n```\n\nOutput:\n\n```\ninput = 22 7 2 -5 8 4\noutput = -5 2 4 7 8 22\n\n```\n\nSolution 2:\n\n```\nsub selectionSort(@tmp) {\n for ^@tmp -> $i {\n my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;\n }\n return @tmp;\n}\n\n```\n\nOutput:\n\n```\ninput = 22 7 2 -5 8 4\noutput = -5 2 4 7 8 22\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSort an array of elements using the Shell sort algorithm, a diminishing increment sort.\n\nThe Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.\n\nShell sort is a sequence of interleaved insertion sorts based on an increment sequence.\nThe increment size is reduced after each pass until the increment size is 1.\n\nWith an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's \"best case\".\n\nAny sequence will sort the data as long as it ends in 1, but some work better than others.\n\nEmpirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.\n[1]\n\nOther good sequences are found at the On-Line Encyclopedia of Integer Sequences."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub shell_sort ( @a is copy ) {\n loop ( my $gap = (@a/2).round; $gap > 0; $gap = ( $gap * 5 / 11 ).round ) {\n for $gap .. @a.end -> $i {\n my $temp = @a[$i];\n\n my $j;\n loop ( $j = $i; $j >= $gap; $j -= $gap ) {\n my $v = @a[$j - $gap];\n last if $v <= $temp;\n @a[$j] = $v;\n }\n\n @a[$j] = $temp;\n }\n }\n return @a;\n}\nmy @data = 22, 7, 2, -5, 8, 4;\nsay 'input = ' ~ @data;\nsay 'output = ' ~ @data.&shell_sort;\n\n```\n\nOutput:\n\n```\ninput = 22 7 2 -5 8 4\noutput = -5 2 4 7 8 22\n\n```"
}
]
|
[
{
"role": "user",
"content": "In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.\n\nTask: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.\n\nSleep sort was presented anonymously on 4chan and has been discussed on Hacker News."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nawait map -> $delay { start { sleep $delay ; say $delay } },\n <6 8 1 12 2 14 5 2 1 0>;\n\n```\n\nOutput:\n\n```\n0\n1\n1\n2\n2\n5\n6\n8\n12\n14\n```\n\nThis can also be written using reactive programming:\n\n```\n#!/usr/bin/env raku\nuse v6;\nreact whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }\n\n```\n\nOutput:\n\n```\n$ ./sleep-sort 1 3 5 6 2 4\n1\n2\n3\n4\n5\n6\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Stooge sort. 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\nShow the Stooge Sort for an array of integers.\n\nThe Stooge Sort algorithm is as follows:\n\n```\nalgorithm stoogesort(array L, i = 0, j = length(L)-1)\n if L[j] < L[i] then\n L[i] ↔ L[j]\n if j - i > 1 then\n t := (j - i + 1)/3\n stoogesort(L, i , j-t)\n stoogesort(L, i+t, j )\n stoogesort(L, i , j-t)\n return L\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub stoogesort( @L, $i = 0, $j = @L.end ) {\n @L[$j,$i] = @L[$i,$j] if @L[$i] > @L[$j];\n\n my $interval = $j - $i;\n \n if $interval > 1 {\n my $t = ( $interval + 1 ) div 3;\n stoogesort( @L, $i , $j-$t );\n stoogesort( @L, $i+$t, $j );\n stoogesort( @L, $i , $j-$t );\n }\n return @L;\n}\n\nmy @L = 1, 4, 5, 3, -6, 3, 7, 10, -2, -5;\n\nstoogesort(@L).Str.say;\n\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The original article was at Strand sort. 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\nImplement the Strand sort.\n\nThis is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.04.01\n\n```\nsub infix:<M> (@x-in, @y-in) {\n my @x = | @x-in;\n my @y = | @y-in;\n flat @x, @y,\n reverse gather while @x and @y {\n take do given @x[*-1] cmp @y[*-1] {\n when More { pop @x }\n when Less { pop @y }\n when Same { pop(@x), pop(@y) }\n }\n }\n}\n\nsub strand (@x) {\n my $i = 0;\n my $prev = -Inf;\n gather while $i < @x {\n @x[$i] before $prev ?? $i++ !! take $prev = splice(@x, $i, 1)[0];\n }\n}\n\nsub strand_sort (@x is copy) {\n my @out;\n @out M= strand(@x) while @x;\n @out;\n}\n\nmy @a = (^100).roll(10);\nsay \"Before {@a}\";\n@a = strand_sort(@a);\nsay \"After {@a}\";\n\n@a = <The quick brown fox jumps over the lazy dog>;\nsay \"Before {@a}\";\n@a = strand_sort(@a);\nsay \"After {@a}\";\n\n```\n\nOutput:\n\n```\nBefore 1 20 64 72 48 75 96 55 42 74\nAfter 1 20 42 48 55 64 72 74 75 96\nBefore The quick brown fox jumps over the lazy dog\nAfter The brown dog fox jumps lazy over quick the\n```"
}
]
|
[
{
"role": "user",
"content": "| |\n| --- |\n| This page uses content from **Wikipedia**. The current wikipedia article is at Tree\\_sort. The original RosettaCode article was extracted from the wikipedia article № 295989333 of 15:13, 12 June 2009 . The list of authors can be seen in the page history. As with Rosetta Code, the pre **5 June 2009** text of Wikipedia is available under the GNU FDL. (See links for details on variance) |\n\nA **tree sort** is a sort algorithm that builds a binary search tree from the keys to be sorted, and then traverses the tree (in-order) so that the keys come out in sorted order. Its typical use is when sorting the elements of a stream from a file. Several other sorts would have to load the elements to a temporary data structure, whereas in a tree sort the act of loading the input into a data structure is sorting it.\n\nThe tree sort is considered by some to be the faster method to sort a linked list, followed by Quicksort and Mergesort:\n\n* A Comparative Study of Linked List Sorting Algorithms by Ching-Kuang Shene\n\nSediment sort, bubble sort, selection sort perform very badly.\n\n* http://www.martinbroadhurst.com/sorting-a-linked-list-by-turning-it-into-a-binary-tree.html\n\n**Task:** \nFirst, construct a doubly linked list (unsorted). \nThen construct a tree in situ: use the prev and next of that list as left and right tree pointers. \nThen traverse the tree, in order, and recreate a doubly linked list, again in situ, but of course now in sorted order."
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n```\n# 20231201 Raku programming solution\n\nclass BinaryTree { has ($.node, $.leftSubTree, $.rightSubTree) is rw;\n\n method insert($item) {\n if not $.node.defined {\n $.node = $item;\n ($.leftSubTree, $.rightSubTree)>>.&{ $_ = BinaryTree.new }\n } elsif $item cmp $.node < 0 {\n $.leftSubTree.insert($item);\n } else {\n $.rightSubTree.insert($item);\n }\n }\n\n method inOrder(@ll) {\n return unless $.node.defined;\n $.leftSubTree.inOrder(@ll);\n @ll.push($.node);\n $.rightSubTree.inOrder(@ll);\n }\n}\n\nsub treeSort(@ll) {\n my $searchTree = BinaryTree.new;\n for @ll -> $i { $searchTree.insert($i) }\n $searchTree.inOrder(my @ll2);\n return @ll2\n}\n\nsub printLinkedList(@ll, Str $fmt, Bool $sorted) {\n for @ll -> $i { printf \"$fmt \", $i }\n $sorted ?? say() !! print \"-> \"\n}\n\nmy @ll = <5 3 7 9 1>;\n#my @ll = [37, 88, 13, 18, 72, 77, 29, 93, 21, 97, 37, 42, 67, 22, 29, 2];\nprintLinkedList(@ll, \"%d\", False);\nmy @lls = treeSort(@ll);\nprintLinkedList(@lls, \"%d\", True);\n\nmy @ll2 = <d c e b a>;\n#my @ll2 = <one two three four five six seven eight nine ten>;\nprintLinkedList(@ll2, \"%s\", False);\nmy @lls2 = treeSort(@ll2);\nprintLinkedList(@lls2, \"%s\", True);\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Soundex is an algorithm for creating indices for words based on their pronunciation.\n\nTask\n\nThe goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).\n\nCaution\n\nThere is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if **Ashcraft** is coded to **A-261**.\n\n* If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see \"Side-by-Side\" rule above), 2 for the K). Since the vowel \"A\" separates the Z and K, the K is coded.\n* If \"H\" or \"W\" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nUS census algorithm, so \"Ashcraft\" and \"Burroughs\" adjusted to match.\nWe fake up a first consonant in some cases to make up for the fact that we always trim the first numeric code (so that the 'l' of 'Lloyd' is properly deleted).\n\n```\nsub soundex ($name --> Str) {\n my $first = substr($name,0,1).uc;\n gather {\n take $first;\n my $fakefirst = '';\n $fakefirst = \"de \" if $first ~~ /^ <[AEIOUWH]> /;\n \"$fakefirst$name\".lc.trans('wh' => '') ~~ /\n ^\n [\n [\n | <[ bfpv ]>+ { take 1 }\n | <[ cgjkqsxz ]>+ { take 2 }\n | <[ dt ]>+ { take 3 }\n | <[ l ]>+ { take 4 }\n | <[ mn ]>+ { take 5 }\n | <[ r ]>+ { take 6 }\n ]\n || .\n ]+\n $ { take 0,0,0 }\n /;\n }.flat.[0,2,3,4].join;\n}\n\nfor < Soundex S532\n Example E251\n Sownteks S532\n Ekzampul E251\n Euler E460\n Gauss G200\n Hilbert H416\n Knuth K530\n Lloyd L300\n Lukasiewicz L222\n Ellery E460\n Ghosh G200\n Heilbronn H416\n Kant K530\n Ladd L300\n Lissajous L222\n Wheaton W350\n Ashcraft A261\n Burroughs B620\n Burrows B620\n O'Hara O600 >\n-> $n, $s {\n my $s2 = soundex($n);\n say $n.fmt(\"%16s \"), $s, $s eq $s2 ?? \" OK\" !! \" NOT OK $s2\";\n}\n\n```\n\nOutput:\n\n```\n Soundex S532 OK\n Example E251 OK\n Sownteks S532 OK\n Ekzampul E251 OK\n Euler E460 OK\n Gauss G200 OK\n Hilbert H416 OK\n Knuth K530 OK\n Lloyd L300 OK\n Lukasiewicz L222 OK\n Ellery E460 OK\n Ghosh G200 OK\n Heilbronn H416 OK\n Kant K530 OK\n Ladd L300 OK\n Lissajous L222 OK\n Wheaton W350 OK\n Ashcraft A261 OK\n Burroughs B620 OK\n Burrows B620 OK\n O'Hara O600 OK\n```"
}
]
|
[
{
"role": "user",
"content": "A sparkline is a graph of successive values laid out horizontally\nwhere the height of the line is proportional to the values in succession.\n\nTask\n\nUse the following series of Unicode characters to create a program\nthat takes a series of numbers separated by one or more whitespace or comma characters\nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: `'▁▂▃▄▅▆▇█'` \n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input,\nhere on this page:\n\n1. 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n2. 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\n\n: (note the mix of separators in this second case)!\n\nNotes\n\n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n: : `\"0, 1, 19, 20\" -> ▁▁██`\n : (Aiming to use just two spark levels)\n\n: : `\"0, 999, 4000, 4999, 7000, 7999\" -> ▁▁▅▅██`\n : (Aiming to use just three spark levels)\n\n: : It may be helpful to include these cases in output tests.\n\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nconstant @bars = '▁' ... '█';\nwhile prompt 'Numbers separated by anything: ' -> $_ {\n my @numbers = map +*, .comb(/ '-'? [[\\d+ ['.' \\d*]?] | ['.' \\d+]] /);\n my ($mn,$mx) = @numbers.minmax.bounds;\n say \"min: $mn.fmt('%5f'); max: $mx.fmt('%5f')\";\n say @bars[ @numbers.map: { @bars * ($_ - $mn) / ($mx - $mn) min @bars - 1 } ].join;\n}\n\n```\n\nOutput:\n\n```\nNumbers separated by anything: 9 18 27 36 45 54 63 72 63 54 45 36 27 18 9\n9 18 27 36 45 54 63 72 63 54 45 36 27 18 9\nmin: 9.000000; max: 72.000000\n▁▂▃▄▅▆▇█▇▆▅▄▃▂▁\nNumbers separated by anything: 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\n1.5 0.5 3.5 2.5 5.5 4.5 7.5 6.5\nmin: 0.500000; max: 7.500000\n▂▁▄▃▆▅█▇\nNumbers separated by anything: 3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3 \nmin: -4.000000; max: 3.000000\n█▇▆▅▄▃▂▁▂▃▄▅▆▇█\nNumbers separated by anything: ^D\n```"
}
]
|
[
{
"role": "user",
"content": "Special characters are symbols (single characters or sequences of characters) that have a \"special\" built-in meaning in the language and typically cannot be used in identifiers.\n\nEscape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.\n\nTask\n\nList the special characters and show escape sequences in the language.\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\nTechnically speaking, all characters are special in Raku, since\nthey're all just the result of particular mixes of parse rules.\nNevertheless, some characters may appear to be more special than\nothers. (However, we will not document any operators here, which\ncontain plenty of odd characters in Raku.)\n\nSigils:\n\n```\n $ Item\n @\tPositional\n %\tAssociative\n &\tCallable\n```\n\nTwigils may occur only after a sigil, and indicate special scoping:\n\n```\n *\tDynamically scoped\n ?\tCompile-time constant\n ^\tPositional placeholder\n :\tNamed placeholder\n !\tPrivate attribute\n .\tPublic attribute/accessor\n ~\tSlang\n =\tPod data\n <\tNamed match from $/\n```\n\nQuote characters:\n\n```\n ''\tSingle quotes\n \"\"\tDouble quotes\n //\tRegex\n 「」\tQuotes that allow no interpolation at all\n <>\tQuote words\n «»\tShell-style words\n```\n\nEscapes within single quotes:\n\n```\n \\\\\tBackslash\n \\'\tQuote char\n```\n\nEscapes within double quotes:\n\n```\n {}\tInterpolate results of block\n $\tInterpolate item\n @\tInterpolate list (requires postcircumfix)\n %\tInterpolate hash (requires postcircumfix)\n &\tInterpolate call (requires postcircumfix)\n \\\\\tBackslash\n \\\"\tQuote char\n \\a\tAlarm\n \\b\tBackspace\n \\c\tDecimal, control, or named char\n \\e\tEscape\n \\f\tFormfeed\n \\n\tNewline\n \\o\tOctal char\n \\r\tReturn\n \\t\tTab\n \\x\tHex char\n \\0\tNull\n```\n\nEscapes within character classes and translations include most of the double-quote backslashes, plus:\n\n```\n ..\trange\n```\n\nEscapes within regexes include most of the double-quote escapes, plus:\n\n```\n :\tSome kind of declaration\n <>\tSome kind of assertion\n []\tSimple grouping\n ()\tCapture grouping\n {}\tSide effect block\n .\tAny character\n \\d\tDigit\n \\w\tAlphanumeric\n \\s\tWhitespace\n \\h\tHorizontal whitespace\n \\v\tVertical whitespace\n ''\tSingle quoted string\n \"\"\tDouble quoted string\n «\tWord initial boundary\n »\tWord final boundary\n ^\tString start\n ^^\tLine start\n $\tString end\n $$\tLine end\n```\n\nNote that all non-alphanumeric characters are reserved for escapes and operators in Raku regexes.\n\nAny lowercase backslash escape in a regex may be uppercased to negate it, hence \\N matches anything that is not a newline."
}
]
|
[
{
"role": "user",
"content": "Task\n\nNumbers **n** such that reverse(**d**) divides reverse(**n**) for all divisors **d** of **n**, where **n < 200**"
},
{
"role": "assistant",
"content": "```\nuse Prime::Factor:ver<0.3.0+>;\n\nsay \"{+$_} matching numbers:\\n{.batch(10)».fmt('%3d').join: \"\\n\"}\"\n given (1..^200).grep: { all .flip «%%« .&divisors».flip };\n\n```\n\nOutput:\n\n```\n72 matching numbers:\n 1 2 3 4 5 6 7 8 9 11\n 13 17 19 22 23 26 27 29 31 33\n 37 39 41 43 44 46 47 53 55 59\n 61 62 66 67 69 71 73 77 79 82\n 83 86 88 89 93 97 99 101 103 107\n109 113 121 127 131 137 139 143 149 151\n157 163 167 169 173 179 181 187 191 193\n197 199\n```"
}
]
|
[
{
"role": "user",
"content": "This task is an aggregation of lesser-known factorials that nevertheless have some mathematical use.\n\nSpecial factorials\n\n| Name | Formula | Example calculation | Links |\n| --- | --- | --- | --- |\n| Superfactorial | n sf(n) = ∏ k! k=1 | sf(4) = 1! × 2! × 3! × 4! = 288 | * Wikipedia * OEIS:A000178 |\n| Hyperfactorial | n *H*(n) = ∏ kk k=1 | *H*(4) = 11 × 22 × 33 × 44 = 27,648 | * Wikipedia * OEIS:A002109 |\n| Alternating factorial | n af(n) = ∑ (-1)n-ii! i=1 | af(3) = -12×1! + -11×2! + -10×3! = 5 | * Wikipedia * OEIS:A005165 |\n| Exponential factorial | *n*$ = n(n-1)(n-2)... | 4$ = 4321 = 262,144 | * Wikipedia * OEIS:A049384 |\n\nTask\n\n* Write a function/procedure/routine for each of the factorials in the table above.\n* Show sf(*n*), *H*(*n*), and af(*n*) where 0 ≤ *n* ≤ 9. Only show as many numbers as the data types in your language can handle. Bignums are welcome, but not required.\n* Show 0$, 1$, 2$, 3$, and 4$.\n* Show the number of digits in 5$. (Optional)\n* Write a function/procedure/routine to find the inverse factorial (sometimes called reverse factorial). That is, if 5! = 120, then rf(120) = 5. This function is simply undefined for most inputs.\n* Use the inverse factorial function to show the inverse factorials of 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, and 3628800.\n* Show rf(119). The result should be undefined.\n\nNotes\n: Since the factorial inverse of **1** is both 0 and 1, your function should return **0** in this case since it is normal to use the first match found in a series.\n\nSee also\n\n* Factorial\n* Factorions\n* Left factorials\n* Multifactorial\n* Primorial numbers\n* Stirling numbers of the first kind"
},
{
"role": "assistant",
"content": "```\nsub postfix:<!> ($n) { [*] 1 .. $n }\nsub postfix:<$> ($n) { [R**] 1 .. $n }\n\nsub sf ($n) { [*] map { $_! }, 1 .. $n }\nsub H ($n) { [*] map { $_ ** $_ }, 1 .. $n }\nsub af ($n) { [+] map { (-1) ** ($n - $_) * $_! }, 1 .. $n }\nsub rf ($n) {\n state @f = 1, |[\\*] 1..*;\n $n == .value ?? .key !! Nil given @f.first: :p, * >= $n;\n}\n\nsay 'sf : ', map &sf , 0..9;\nsay 'H : ', map &H , 0..9;\nsay 'af : ', map &af , 0..9;\nsay '$ : ', map *$ , 1..4;\n\nsay '5$ has ', 5$.chars, ' digits';\n\nsay 'rf : ', map &rf, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800;\nsay 'rf(119) = ', rf(119).raku;\n\n```\n\nOutput:\n\n```\nsf : (1 1 2 12 288 34560 24883200 125411328000 5056584744960000 1834933472251084800000)\nH : (1 1 4 108 27648 86400000 4031078400000 3319766398771200000 55696437941726556979200000 21577941222941856209168026828800000)\naf : (0 1 1 5 19 101 619 4421 35899 326981)\n$ : (1 2 9 262144)\n5$ has 183231 digits\nrf : (0 2 3 4 5 6 7 8 9 10)\nrf(119) = Nil\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nLet (**p1**, **p2**) are neighbor primes.\n\nFind and show here in base ten if **p1+ p2 -1** is prime, where **p1, p2 < 100**."
},
{
"role": "assistant",
"content": "```\n# 20210809 Raku programming solution \n\nfor (grep {.is-prime}, 3..*).rotor(2 => -1) -> (\\P1,\\P2) {\n last if P2 ≥ Ⅽ;\n ($_ = P1+P2-1).is-prime and printf \"%2d, %2d => %3d\\n\", P1, P2, $_\n}\n\n```\n\nOutput:\n\n```\n 3, 5 => 7\n 5, 7 => 11\n 7, 11 => 17\n11, 13 => 23\n13, 17 => 29\n19, 23 => 41\n29, 31 => 59\n31, 37 => 67\n41, 43 => 83\n43, 47 => 89\n61, 67 => 127\n67, 71 => 137\n73, 79 => 151\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nFind the Pythagorean triplet for which a + b + c = 1000 and print the product of a, b, and c. The problem was taken from Project Euler problem 9\n\nRelated task\n\n* Pythagorean triples"
},
{
"role": "assistant",
"content": "```\nhyper for 1..998 -> $a {\n my $a2 = $a²;\n for $a + 1 .. 999 -> $b {\n my $c = 1000 - $a - $b;\n last if $c < $b;\n say \"$a² + $b² = $c²\\n$a + $b + $c = {$a+$b+$c}\\n$a × $b × $c = {$a×$b×$c}\"\n and exit if $a2 + $b² == $c²\n }\n}\n\n```\n\nOutput:\n\n```\n200² + 375² = 425²\n200 + 375 + 425 = 1000\n200 × 375 × 425 = 31875000\n```"
}
]
|
[
{
"role": "user",
"content": "Special variables have a predefined meaning within a computer programming language.\n\nTask\n\nList the special variables used within the language."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nIt is probably useful to briefly explain normal variables in Raku before tackling special variables.\n\nVariables in Raku have a prefix sigil to distinguish them from named subroutines, functions, classes, and so on. There is a system of sigils to mark the fundamental structural type of the variable:\n\n```\n $foo scalar (object)\n @foo ordered array\n %foo unordered hash (associative array)\n &foo code/rule/token/regex\n ::foo package/module/class/role/subset/enum/type/grammar\n\n```\n\nSigils indicate overall interface, not the exact type of the bound object. Different sigils imply different minimal abilities. Ordinary sigils indicate normally scoped variables, either lexical or package scoped. Oddly scoped variables include a secondary sigil (a twigil) that indicates what kind of strange scoping the variable is subject to:\n\n```\n $foo # ordinary scoping\n $.foo # object attribute public accessor\n $^foo # self-declared formal positional parameter\n $:foo # self-declared formal named parameter\n $*foo # dynamically overridable global variable\n $?foo # compiler hint variable\n $=foo # POD variable\n $<foo> # match variable, short for $/{'foo'}\n $!foo # object attribute private storage\n $~foo # the foo sublanguage seen by the parser at this lexical spot\n\n```\n\nA selection (not comprehensive) of Raku's automatically set and/or pre-defined compile-time and run-time variables.\n\n```\n# Lexical variables\n\n $_ # implicit variable lexically scoped to the current block\n $! # current Exception object\n $/ # last match\n $0, $1, $2... # captured values from match: $/[0], $/[1], $/[2] ...\n\n# Compile-time variables\n\n$?PACKAGE # current package\n$?CLASS # current class\n$?MODULE # current module\n$?ROLE # current role\n$?DISTRIBUTION # which OS distribution am I compiling under\n$?FILE # current filename of source file\n$?LINE # current line number in source file\n&?ROUTINE # current sub or method (itself)\n&?BLOCK # current block (itself)\n\n# Dynamic variables\n\n$*USAGE # value of the auto-generated USAGE message\n$*PROGRAM-NAME # path to the current executable\n$*PROGRAM # location (in the form of an IO::Path object) of the Raku program being executed\n@*ARGS # command-line arguments\n$*ARGFILES # the magic command-line input handle\n$*CWD # current working directory\n$*DISTRO # which OS distribution am I running under\n%*ENV # system environment variables\n$*ERR # standard error handle\n$*EXECUTABLE-NAME # name of the Raku executable that is currently running\n$*EXECUTABLE # IO::Path absolute path of the Raku executable that is currently running\n$*IN # standard input handle; is an IO object\n$*KERNEL # operating system running under\n$*OUT # standard output handle\n$*RAKU # Raku version running under\n$*PID # system process id\n$*TZ # local time zone\n$*USER # system user id\n\n# Run-time variables\n\n$*COLLATION # object that can be used to configure Unicode collation levels\n$*TOLERANCE # used by the =~= operator to decide if two values are approximately equal\n$*DEFAULT-READ-ELEMS # affects the number of bytes read by default by IO::Handle.read\n\n```\n\nAlso, not really a variable but...\n\n```\n * # A standalone term that has no fixed value, instead it captures the notion of \"Whatever\",\n # the meaning of which is decided lazily by whatever it is an argument to.\n # See the docs on Whatever: https://docs.raku.org/type/Whatever\n\n```"
}
]
|
[
{
"role": "user",
"content": "Render the text **This is an example of speech synthesis** as speech.\n\nRelated task\n: * using a speech engine to highlight words"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nrun 'espeak', 'This is an example of speech synthesis.';\n\n```"
}
]
|
[
{
"role": "user",
"content": "**Ordinal numbers** (as used in this Rosetta Code task), are numbers that describe the *position* of something in a list.\n\nIt is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.\n\nThe ordinal numbers are (at least, one form of them):\n\n```\n 1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ··· etc\n\n```\n\nsometimes expressed as:\n\n```\n 1st 2nd 3rd 4th 5th 6th 7th ··· 99th 100th ··· 1000000000th ···\n\n```\n\nFor this task, the following (English-spelled form) will be used:\n\n```\n first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth\n\n```\n\nFurthermore, the short scale numbering system (i.e. 2,000,000,000 is two billion) will be used here. wp:Long and short scales\n\n**2,000,000,000** is two billion, *not* two milliard.\n\nTask\n\nWrite a driver and a function (subroutine/routine ···) that returns the English-spelled ordinal version of a specified number (a positive integer).\n\nOptionally, try to support as many forms of an integer that can be expressed: **123** **00123.0** **1.23e2** all are forms of the same integer.\n\nShow all output here.\n\nTest cases\n\nUse (at least) the test cases of:\n\n```\n 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003\n\n```\n\nRelated tasks\n\n* Number names\n* N'th"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\nRakudo version 2019.07.1 is updated to Unicode version 12.1. Unicode version 12.0 introduced some new numeric digits, which changed the output here a bit. This will *work* with earlier versions of Rakudo, but will yield slightly different results.\n\nThis would be pretty simple to implement from scratch; it would be straightforward to do a minor modification of the Number names task code. Much simpler to just use the Lingua::EN::Numbers module from the Raku ecosystem though. It will easily handles ordinal number conversions.\n\nWe need to be slightly careful of terminology. In Raku, 123, 00123.0, & 1.23e2 are not all integers. They are respectively an Int (integer), a Rat (rational number) and a Num (floating point number). (The fourth numeric is a Complex) For this task it doesn't much matter as the ordinal routine coerces its argument to an Int, but to Raku they are different things. We can further abuse allomorphic and String types and role mixins for some somewhat non-intuitive results as well.\n\nNote that the different allomorphic integer forms of 123 are evaluated on *use*, not on *assignment*. They can be passed around in parameters, but until they are used numerically, they retain their stringy characteristics and are distinctive, determinable through introspection. The numerics are evaluated on assignment, hence the stringified output not exactly matching the input format. The mixin role returns different things depending on what context you evaluate it under. When evaluated as a string it is 17, numerically, it is 123.\n\nRaku uses Unicode natively. If a glyph has a Unicode 'Numeric Digit' (<:Nd>) property, it is treated as a numeric digit, and may be used as one.\n\nIt is not really clear what is meant by \"Write a driver and a function...\". Well, the function part is clear enough; driver not so much. Perhaps this will suffice.\n\n```\nuse Lingua::EN::Numbers;\n\n# The task\n+$_ ?? printf( \"Type: \\%-14s %16s : %s\\n\", .^name, $_, .&ordinal ) !! say \"\\n$_:\" for\n\n# Testing\n'Required tests',\n1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,\n\n'Optional tests - different forms of 123',\n'Numerics',\n123, 00123.0, 1.23e2, 123+0i,\n\n'Allomorphs',\n|<123 1_2_3 00123.0 1.23e2 123+0i 0b1111011 0o173 0x7B 861/7>,\n\n'Numeric Strings',\n|'1_2_3 00123.0 1.23e2 123+0i 0b1111011 0o173 0x7B 861/7'.words,\n\n'Unicode Numeric Strings',\n# (Only using groups of digits from the same Unicode block. Technically,\n# digits from any block could be combined with digits from any other block.)\n|(^0x1FFFF).grep( { .chr ~~ /<:Nd>/ and .unival == 1|2|3 }).rotor(3)».chr».join,\n\n'Role Mixin',\n'17' but 123;\n\n```\n\nOutput:\n\n```\nRequired tests:\nType: Int 1 : first\nType: Int 2 : second\nType: Int 3 : third\nType: Int 4 : fourth\nType: Int 5 : fifth\nType: Int 11 : eleventh\nType: Int 65 : sixty-fifth\nType: Int 100 : one hundredth\nType: Int 101 : one hundred first\nType: Int 272 : two hundred seventy-second\nType: Int 23456 : twenty-three thousand, four hundred fifty-sixth\nType: Int 8007006005004003 : eight quadrillion, seven trillion, six billion, five million, four thousand third\n\nOptional tests - different forms of 123:\n\nNumerics:\nType: Int 123 : one hundred twenty-third\nType: Rat 123 : one hundred twenty-third\nType: Num 123 : one hundred twenty-third\nType: Complex 123+0i : one hundred twenty-third\n\nAllomorphs:\nType: IntStr 123 : one hundred twenty-third\nType: IntStr 1_2_3 : one hundred twenty-third\nType: RatStr 00123.0 : one hundred twenty-third\nType: NumStr 1.23e2 : one hundred twenty-third\nType: ComplexStr 123+0i : one hundred twenty-third\nType: IntStr 0b1111011 : one hundred twenty-third\nType: IntStr 0o173 : one hundred twenty-third\nType: IntStr 0x7B : one hundred twenty-third\nType: RatStr 861/7 : one hundred twenty-third\n\nNumeric Strings:\nType: Str 1_2_3 : one hundred twenty-third\nType: Str 00123.0 : one hundred twenty-third\nType: Str 1.23e2 : one hundred twenty-third\nType: Str 123+0i : one hundred twenty-third\nType: Str 0b1111011 : one hundred twenty-third\nType: Str 0o173 : one hundred twenty-third\nType: Str 0x7B : one hundred twenty-third\nType: Str 861/7 : one hundred twenty-third\n\nUnicode Numeric Strings:\nType: Str 123 : one hundred twenty-third\nType: Str ١٢٣ : one hundred twenty-third\nType: Str ۱۲۳ : one hundred twenty-third\nType: Str ߁߂߃ : one hundred twenty-third\nType: Str १२३ : one hundred twenty-third\nType: Str ১২৩ : one hundred twenty-third\nType: Str ੧੨੩ : one hundred twenty-third\nType: Str ૧૨૩ : one hundred twenty-third\nType: Str ୧୨୩ : one hundred twenty-third\nType: Str ௧௨௩ : one hundred twenty-third\nType: Str ౧౨౩ : one hundred twenty-third\nType: Str ೧೨೩ : one hundred twenty-third\nType: Str ൧൨൩ : one hundred twenty-third\nType: Str ෧෨෩ : one hundred twenty-third\nType: Str ๑๒๓ : one hundred twenty-third\nType: Str ໑໒໓ : one hundred twenty-third\nType: Str ༡༢༣ : one hundred twenty-third\nType: Str ၁၂၃ : one hundred twenty-third\nType: Str ႑႒႓ : one hundred twenty-third\nType: Str ១២៣ : one hundred twenty-third\nType: Str ᠑᠒᠓ : one hundred twenty-third\nType: Str ᥇᥈᥉ : one hundred twenty-third\nType: Str ᧑᧒᧓ : one hundred twenty-third\nType: Str ᪁᪂᪃ : one hundred twenty-third\nType: Str ᪑᪒᪓ : one hundred twenty-third\nType: Str ᭑᭒᭓ : one hundred twenty-third\nType: Str ᮱᮲᮳ : one hundred twenty-third\nType: Str ᱁᱂᱃ : one hundred twenty-third\nType: Str ᱑᱒᱓ : one hundred twenty-third\nType: Str ꘡꘢꘣ : one hundred twenty-third\nType: Str ꣑꣒꣓ : one hundred twenty-third\nType: Str ꤁꤂꤃ : one hundred twenty-third\nType: Str ꧑꧒꧓ : one hundred twenty-third\nType: Str ꧱꧲꧳ : one hundred twenty-third\nType: Str ꩑꩒꩓ : one hundred twenty-third\nType: Str ꯱꯲꯳ : one hundred twenty-third\nType: Str 123 : one hundred twenty-third\nType: Str 𐒡𐒢𐒣 : one hundred twenty-third\nType: Str 𐴱𐴲𐴳 : one hundred twenty-third\nType: Str 𑁧𑁨𑁩 : one hundred twenty-third\nType: Str 𑃱𑃲𑃳 : one hundred twenty-third\nType: Str 𑄷𑄸𑄹 : one hundred twenty-third\nType: Str 𑇑𑇒𑇓 : one hundred twenty-third\nType: Str 𑋱𑋲𑋳 : one hundred twenty-third\nType: Str 𑑑𑑒𑑓 : one hundred twenty-third\nType: Str 𑓑𑓒𑓓 : one hundred twenty-third\nType: Str 𑙑𑙒𑙓 : one hundred twenty-third\nType: Str 𑛁𑛂𑛃 : one hundred twenty-third\nType: Str 𑜱𑜲𑜳 : one hundred twenty-third\nType: Str 𑣡𑣢𑣣 : one hundred twenty-third\nType: Str 𑱑𑱒𑱓 : one hundred twenty-third\nType: Str 𑵑𑵒𑵓 : one hundred twenty-third\nType: Str 𑶡𑶢𑶣 : one hundred twenty-third\nType: Str 𖩡𖩢𖩣 : one hundred twenty-third\nType: Str 𖭑𖭒𖭓 : one hundred twenty-third\nType: Str 𝟏𝟐𝟑 : one hundred twenty-third\nType: Str 𝟙𝟚𝟛 : one hundred twenty-third\nType: Str 𝟣𝟤𝟥 : one hundred twenty-third\nType: Str 𝟭𝟮𝟯 : one hundred twenty-third\nType: Str 𝟷𝟸𝟹 : one hundred twenty-third\nType: Str 𞥑𞥒𞥓 : one hundred twenty-third\n\nRole Mixin:\nType: Str+{<anon|1>} 17 : one hundred twenty-third\n```"
}
]
|
[
{
"role": "user",
"content": "Definitions\n\nA **sphenic number** is a positive integer that is the product of three distinct prime numbers. More technically it's a square-free 3-almost prime (see Related tasks below).\n\nFor the purposes of this task, a **sphenic triplet** is a group of three sphenic numbers which are consecutive.\n\nNote that sphenic quadruplets are not possible because every fourth consecutive positive integer is divisible by 4 (= 2 x 2) and its prime factors would not therefore be distinct.\n\nExamples\n\n30 (= 2 x 3 x 5) is a sphenic number and is also clearly the first one.\n\n[1309, 1310, 1311] is a sphenic triplet because 1309 (= 7 x 11 x 17), 1310 (= 2 x 5 x 31) and 1311 (= 3 x 19 x 23) are 3 consecutive sphenic numbers.\n\nTask\n\nCalculate and show here:\n\n1. All sphenic numbers less than 1,000.\n\n2. All sphenic triplets less than 10,000.\n\nStretch\n\n3. How many sphenic numbers are there less than 1 million?\n\n4. How many sphenic triplets are there less than 1 million?\n\n5. What is the 200,000th sphenic number and its 3 prime factors?\n\n6. What is the 5,000th sphenic triplet?\n\nHint: you only need to consider sphenic numbers less than 1 million to answer 5. and 6.\n\nReferences\n\n* Wikipedia: Sphenic number\n* OEIS:A007304 - Sphenic numbers\n* OEIS:A165936 - Sphenic triplets (in effect)\n\nRelated tasks\n\n* Almost prime\n* Square-free integers"
},
{
"role": "assistant",
"content": "Not the most efficient algorithm, but **massively** parallelizable, so finishes pretty quickly.\n\n```\nuse Prime::Factor;\nuse List::Divvy;\nuse Lingua::EN::Numbers;\n\nmy @sphenic = lazy (^Inf).hyper(:200batch).grep: { my @pf = .&prime-factors; +@pf == 3 and [email protected] == 3 };\nmy @triplets = lazy (^Inf).grep( { @sphenic[$_]+2 == @sphenic[$_+2] } ).map: {(@sphenic[$_,$_+1,$_+2])}\n\nsay \"Sphenic numbers less than 1,000:\\n\" ~\n @sphenic.&upto(1e3).batch(15)».fmt(\"%3d\").join: \"\\n\";\n\nsay \"\\nSphenic triplets less than 10,000:\";\n.say for @triplets.&before(*.[2] > 1e4);\n\nsay \"\\nThere are {(+@sphenic.&upto(1e6)).&comma} sphenic numbers less than {1e6.Int.&comma}\";\nsay \"There are {(+@triplets.&before(*.[2] > 1e6)).&comma} sphenic triplets less than {1e6.Int.&comma}\";\nsay \"The 200,000th sphenic number is {@sphenic[2e5-1].&comma} ({@sphenic[2e5-1].&prime-factors.join(' × ')}).\";\nsay \"The 5,000th sphenic triplet is ({@triplets[5e3-1].join(', ')}).\"\n\n```\n\nOutput:\n\n```\nSphenic numbers less than 1,000:\n 30 42 66 70 78 102 105 110 114 130 138 154 165 170 174\n182 186 190 195 222 230 231 238 246 255 258 266 273 282 285\n286 290 310 318 322 345 354 357 366 370 374 385 399 402 406\n410 418 426 429 430 434 435 438 442 455 465 470 474 483 494\n498 506 518 530 534 555 561 574 582 590 595 598 602 606 609\n610 615 618 627 638 642 645 646 651 654 658 663 665 670 678\n682 705 710 715 730 741 742 754 759 762 777 782 786 790 795\n805 806 814 822 826 830 834 854 861 874 885 890 894 897 902\n903 906 915 935 938 942 946 957 962 969 970 978 986 987 994\n\nSphenic triplets less than 10,000:\n(1309 1310 1311)\n(1885 1886 1887)\n(2013 2014 2015)\n(2665 2666 2667)\n(3729 3730 3731)\n(5133 5134 5135)\n(6061 6062 6063)\n(6213 6214 6215)\n(6305 6306 6307)\n(6477 6478 6479)\n(6853 6854 6855)\n(6985 6986 6987)\n(7257 7258 7259)\n(7953 7954 7955)\n(8393 8394 8395)\n(8533 8534 8535)\n(8785 8786 8787)\n(9213 9214 9215)\n(9453 9454 9455)\n(9821 9822 9823)\n(9877 9878 9879)\n\nThere are 206,964 sphenic numbers less than 1,000,000\nThere are 5,457 sphenic triplets less than 1,000,000\nThe 200,000th sphenic number is 966,467 (17 × 139 × 409).\nThe 5,000th sphenic triplet is (918005, 918006, 918007).\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nAn animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:\n\n: * |\n * /\n * - or ─\n * \\\n\nA stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ). \n \nThere are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18. \n \nWe don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..\n\n: * Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.\n + '.', '..', '...'\n + '.', '..', '...', '..'\n * Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.\n + '|', '/', '─', '\\'\n * Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.\n + '⁎', '⁑', '⁂'\n + '⁎', '⁑', '⁂', '⁑'\n * Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..\n + '🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'\n * Arrows:\n + '⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'\n * Bird - This looks decent but may be missing something.\n + '︷', '︵', '︹', '︺', '︶', '︸'\n + '︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'\n * Plants - This isn't quite complete\n + '☘', '❀', '❁'\n + '☘', '❀', '❁', '❀'\n * Eclipse - From Raku Throbber post author\n + '🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.05\n\nTraditionally these are know as throbbers or progress indicators.\n\nThis implementation will accept an array of elements to use as its throbber frames, or as a scrolling marquee and optionally a delay before it returns the next element.\n\n```\nclass throbber {\n has @.frames;\n has $.delay is rw = 0;\n has $!index = 0;\n has Bool $.marquee = False;\n method next {\n $!index = ($!index + 1) % [email protected];\n sleep $.delay if $.delay;\n if $!marquee {\n (\"\\b\" x @.frames) ~ @.frames.rotate($!index).join;\n }\n else {\n \"\\b\" ~ @.frames[$!index];\n }\n }\n}\n\nmy $rod = throbber.new( :frames(< | / - \\ >), :delay(.25) );\nprint \"\\e[?25lLong running process... \";\nprint $rod.next for ^20;\n\nmy $clock = throbber.new( :frames(\"🕐\" .. \"🕛\") );\nprint \"\\r\\nSomething else with a delay... \";\nuntil my $done {\n # do something in a loop;\n sleep 1/12;\n print \"\\b\", $clock.next;\n $done = True if $++ >= 60;\n}\n\nmy $moon = throbber.new( :frames('🌑🌒🌓🌔🌕🌖🌗🌘'.comb) );\nprint \"\\r\\nGonna be a long night... \";\nuntil my $end {\n # do something in a loop;\n sleep 1/8;\n print \"\\b\", $moon.next;\n $end = True if $++ >= 60;\n}\n\nmy $scroll = throbber.new( :frames('PLEASE STAND BY... '.comb), :delay(.1), :marquee );\nprint \"\\r\\nEXPERIENCING TECHNICAL DIFFICULTIES: { $scroll.frames.join }\";\nprint $scroll.next for ^95;\n\nEND { print \"\\e[?25h\\n\" } # clean up on exit\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nProduce a spiral array.\n\nA *spiral array* is a square arrangement of the first N2 natural numbers, where the\n \nnumbers increase sequentially as you go around the edges of the array spiraling inwards.\n\nFor example, given **5**, produce this array:\n\n```\n 0 1 2 3 4\n15 16 17 18 5\n14 23 24 19 6\n13 22 21 20 7\n12 11 10 9 8\n\n```\n\nRelated tasks\n\n* Zig-zag matrix\n* Identity\\_matrix\n* Ulam\\_spiral\\_(for\\_primes)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n### Object-oriented Solution\n\nSuppose we set up a Turtle class like this:\n\n```\nclass Turtle {\n my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1];\n my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc.\n\n has @.loc = 0,0;\n has $.dir = 0;\n has %.world;\n has $.maxegg;\n has $.range-x;\n has $.range-y;\n\n method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; }\n method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; }\n\n method lay-egg($egg) {\n %!world{~@!loc} = $egg;\n $!maxegg max= $egg;\n $!range-x minmax= @!loc[0];\n $!range-y minmax= @!loc[1];\n }\n\n method look($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n %!world{~$there};\n }\n\n method forward($ahead = 1) {\n my $there = @!loc »+« @dv[$!dir] »*» $ahead;\n @!loc = @($there);\n }\n\n method showmap() {\n my $form = \"%{$!maxegg.chars}s\";\n my $endx = $!range-x.max;\n for $!range-y.list X $!range-x.list -> ($y, $x) {\n print (%!world{\"$x $y\"} // '').fmt($form);\n print $x == $endx ?? \"\\n\" !! ' ';\n }\n }\n}\n\n# Now we can build the spiral in the normal way from outside-in like this:\n\nsub MAIN(Int $size = 5) {\nmy $t = Turtle.new(dir => 2);\nmy $counter = 0;\n$t.forward(-1);\nfor 0..^ $size -> $ {\n $t.forward;\n $t.lay-egg($counter++);\n}\nfor $size-1 ... 1 -> $run {\n $t.turn-right;\n $t.forward, $t.lay-egg($counter++) for 0..^$run;\n $t.turn-right;\n $t.forward, $t.lay-egg($counter++) for 0..^$run;\n}\n$t.showmap;\n}\n\n```\n\nOr we can build the spiral from inside-out like this:\n\n```\nsub MAIN(Int $size = 5) {\nmy $t = Turtle.new(dir => ($size %% 2 ?? 4 !! 0));\nmy $counter = $size * $size;\nwhile $counter {\n $t.lay-egg(--$counter);\n $t.turn-left;\n $t.turn-right if $t.look;\n $t.forward;\n}\n$t.showmap;\n}\n\n```\n\nNote that with these \"turtle graphics\" we don't actually have to care about the coordinate system, since the `showmap` method can show whatever rectangle was modified by the turtle. So unlike the standard inside-out algorithm, we don't have to find the center of the matrix first.\n\n### Procedural Solution\n\n```\nsub spiral_matrix ( $n ) {\n my @sm;\n my $len = $n;\n my $pos = 0;\n\n for ^($n/2).ceiling -> $i {\n my $j = $i + 1;\n my $e = $n - $j;\n\n @sm[$i ][$i + $_] = $pos++ for ^( $len); # Top\n @sm[$j + $_][$e ] = $pos++ for ^(--$len); # Right\n @sm[$e ][$i + $_] = $pos++ for reverse ^( $len); # Bottom\n @sm[$j + $_][$i ] = $pos++ for reverse ^(--$len); # Left\n }\n\n return @sm;\n}\n\nsay .fmt('%3d') for spiral_matrix(5);\n\n```\n\nOutput:\n\n```\n 0 1 2 3 4\n15 16 17 18 5\n14 23 24 19 6\n13 22 21 20 7\n12 11 10 9 8\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nSplit a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\nFor instance, the string:\n\n```\n gHHH5YY++///\\ \n\n```\n\nshould be split and show:\n\n```\n g, HHH, 5, YY, ++, ///, \\ \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.05\n\n```\nsub group-chars ($str) { $str.comb: / (.) $0* / }\n\n# Testing:\n\nfor Q[gHHH5YY++///\\], Q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂️👨👩👧👦] -> $string {\n put 'Original: ', $string;\n put ' Split: ', group-chars($string).join(', ');\n}\n\n```\n\nOutput:\n\n```\nOriginal: gHHH5YY++///\\\n Split: g, HHH, 5, YY, ++, ///, \\\nOriginal: fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃🤔🇺🇸🤦♂️👨👩👧👦\n Split: fff, , n⃗n⃗n⃗, »»», , ℵℵ, ☄☄, ☃, ☃̂, ☃, 🤔, 🇺🇸, 🤦♂️, 👨👩👧👦\n\n```\n\nThe second test-case is to show that Raku works with strings on the Unicode grapheme level, handles whitespace, combiners, and zero width characters up to Unicode Version 13.0 correctly. (Raku generally tracks updates to the Unicode spec and typically lags no more than a month behind.) For those of you with browsers unable to display the second string, it consists of:\n\n* {LATIN SMALL LETTER F} x 3\n* {ZERO WIDTH NO-BREAK SPACE} x 3\n* {LATIN SMALL LETTER N, COMBINING RIGHT ARROW ABOVE} x 3\n* {RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK} x 3\n* {SPACE} x 2,\n* {ALEF SYMBOL} x 2,\n* {COMET} x 2,\n* {SNOWMAN} x 1,\n* {SNOWMAN, COMBINING CIRCUMFLEX ACCENT} x 1\n* {SNOWMAN} x 1,\n* {THINKING FACE} x 1\n* {REGIONAL INDICATOR SYMBOL LETTER U, REGIONAL INDICATOR SYMBOL LETTER S} x 1\n* {FACE PALM, ZERO WIDTH JOINER, MALE SIGN, VARIATION SELECTOR-16} x 1\n* {MAN, ZERO WIDTH JOINER, WOMAN, ZERO WIDTH JOINER, GIRL, ZERO WIDTH JOINER, BOY} x 1"
}
]
|
[
{
"role": "user",
"content": "Create Spoof game. See details: Spoof game"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nsub query_for_integer ($prompt) { loop { ($_ = prompt \"$prompt \") ~~ /^ \\d+ $/ ?? return $_ !! say '(need an integer)'; } }\n\nsub spoof_for_2 {\n my ($mypot, $myguess, $yourpot, $yourguess) = 0, 0, 0, 0;\n my $ngames = query_for_integer('How many games do you want?');\n\n for 1 .. $ngames {\n\n repeat {\n $mypot = 1 + 3.rand.Int;\n $myguess = 1 + 6.rand.Int;\n } until $mypot+3 < $myguess;\n say 'I have set my pot and guess.';\n\n repeat {\n $yourpot = query_for_integer('Your pot?' );\n $yourguess = query_for_integer('Your guess?');\n } until 0 <= $yourpot & $yourguess <= 6 and $yourpot+4 > $yourguess;\n\n say \"My pot is: $mypot\\nMy guess is: $myguess\";\n\n given $mypot + $yourpot {\n when $myguess & $yourguess { say 'Draw!' }\n when $myguess { say 'I won!' }\n when $yourguess { say 'You won!' }\n default { say 'No winner!' }\n }\n }\n}\n\nspoof_for_2();\n\n```\n\nOutput:\n\n```\nHow many games do you want? 1\nYour pot? 2\nYour guess? 3\nI have set my pot and guess.\nMy pot is: 1\nMy guess is: 5\nYou won!\n```"
}
]
|
[
{
"role": "user",
"content": "This task has three parts:\n\n* Connect to a MySQL database (connect\\_db)\n* Create user/password records in the following table (create\\_user)\n* Authenticate login requests against the table (authenticate\\_user)\n\nThis is the table definition:\n\n```\ncreate table users (\n userid int primary key auto_increment,\n username varchar(32) unique key not null,\n pass_salt tinyblob not null,\n -- a string of 16 random bytes\n pass_md5 tinyblob not null\n -- binary MD5 hash of pass_salt concatenated with the password\n);\n\n```\n\n(pass\\_salt and pass\\_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\n```\nuse v6;\nuse DBIish;\n\nmulti connect_db(:$dbname, :$host, :$user, :$pass) {\n my $db = DBIish.connect(\"mysql\",host => $host, database =>$dbname, user =>$user, password =>$pass, :RaiseError) \n or die \"ERROR: {DBIish.errstr}.\";\n $db;\n}\n\nmulti create_user(:$db, :$user, :$pass) {\n #https://stackoverflow.com/questions/53365101/converting-pack-to-perl6\n my $salt = Buf.new((^256).roll(16));\n my $sth = $db.prepare(q:to/STATEMENT/);\n INSERT IGNORE INTO users (username, pass_salt, pass_md5)\n VALUES (?, ?, unhex(md5(concat(pass_salt, ?))))\n STATEMENT\n $sth.execute($user,$salt,$pass);\n $sth.insert-id or Any;\n}\n\nmulti authenticate_user (:$db, :$user, :$pass) {\n my $sth = $db.prepare(q:to/STATEMENT/);\n SELECT userid FROM users WHERE\n username=? AND pass_md5=unhex(md5(concat(pass_salt, ?)))\n STATEMENT\n $sth.execute($user,$pass);\n my $userid = $sth.fetch;\n $userid[0] or Any;\n}\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nShow the first **30** positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first **3** positive integers which are both squares and cubes, and mark them as such."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy @square-and-cube = map { .⁶ }, 1..Inf;\n\nmy @square-but-not-cube = (1..Inf).map({ .² }).grep({ $_ ∉ @square-and-cube[^@square-and-cube.first: * > $_, :k]});\n\nput \"First 30 positive integers that are a square but not a cube: \\n\", @square-but-not-cube[^30];\n\nput \"\\nFirst 15 positive integers that are both a square and a cube: \\n\", @square-and-cube[^15];\n\n```\n\nOutput:\n\n```\nFirst 30 positive integers that are a square but not a cube: \n4 9 16 25 36 49 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 784 841 900 961 1024 1089\n\nFirst 15 positive integers that are both a square and a cube: \n1 64 729 4096 15625 46656 117649 262144 531441 1000000 1771561 2985984 4826809 7529536 11390625\n```"
}
]
|
[
{
"role": "user",
"content": "Task.\n\nDaniel Shanks's Square Form Factorization (SquFoF).\n\nInvented around 1975, *‘On a 32-bit computer, SquFoF is the clear champion factoring algorithm*\n*for numbers between 1010 and 1018, and will likely remain so.’*\n\nAn integral binary quadratic form is a polynomial\n*f*(*x,y*) = *ax2* + *bxy* + *cy2*\nwith integer coefficients and discriminant *D* = *b2* – *4ac*.\nFor each positive discriminant there are multiple forms (*a, b, c*).\n\nThe next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator\n*rho*, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.\nUsing floor(*√N*), rho constructs a *principal form*\n(*1, b, c*) with *D* = *4N*.\n\nSquFoF is based on the existence of cycles containing *ambiguous forms*, with the property that *a* divides *b*.\nThey come in pairs of associated forms (*a, b, c*) and (*c, b, a*) called symmetry points.\nIf an ambiguous form is found (there is one for each divisor of D), write the discriminant as\n(*ak*)*2* – *4ac* = *a*(*a·k2* – *4c*) = *4N*\nand (if a is not equal to 1 or 2) N is split.\n\nShanks used *square forms* to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle\nis squared, that square form will always land in the principal cycle. Conversely, the square root of any\nform in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).\n\nA square form is easy to find: the last coefficient *c* is a perfect square. This happens about once\nevery ∜N-th cycle step and for even indices only. Let rho compute the inverse square root form and track\nthe ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).\nThen *a* or *a/2* divides D and therefore N.\n\nTo avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing\nearly in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,\nno roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.\n\nSometimes the cycle length is too short to find a proper square form. This is fixed by running five instances\nof SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.\nIf N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.\n\nReference.\n\n[1] A detailed analysis of SquFoF (2007)"
},
{
"role": "assistant",
"content": "### A just for fun snail ..\n\nReferences: Algorithm, C program example from the WP page and also the pseudocode from here.\n\n```\n# 20210325 Raku programming solution\n\nmy @multiplier = ( 1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11 );\n\nsub circumfix:<⌊ ⌋>{ $^n.floor }; sub prefix:<√>{ $^n.sqrt }; # just for fun\n\nsub SQUFOF ( \\𝑁 ) { \n\n return 1 if 𝑁.is-prime; # if n is prime return 1\n return √𝑁 if √𝑁 == Int(√𝑁); # if n is a perfect square return √𝑁\n\n for @multiplier -> \\𝑘 { \n my \\Pₒ = $ = ⌊ √(𝑘*𝑁) ⌋; # P[0]=floor(√N)\n my \\Qₒ = $ = 1 ; # Q[0]=1\n my \\Q = $ = 𝑘*𝑁 - Pₒ²; # Q[1]=N-P[0]^2 & Q[i]\n my \\Pₚᵣₑᵥ = $ = Pₒ; # P[i-1] = P[0]\n my \\Qₚᵣₑᵥ = $ = Qₒ; # Q[i-1] = Q[0] \n my \\P = $ = 0; # P[i]\n my \\Qₙₑₓₜ = $ = 0; # P[i+1]\n my \\b = $ = 0; # b[i]\n # i = 1\n repeat until √Q == Int(√Q) { # until Q[i] is a perfect square\n b = ⌊⌊ √(𝑘*𝑁) + Pₚᵣₑᵥ ⌋ / Q ⌋; # floor(floor(√N+P[i-1])/Q[i])\n P = b*Q - Pₚᵣₑᵥ; # P[i]=b*Q[i]-P[i-1] \n Qₙₑₓₜ = Qₚᵣₑᵥ + b*(Pₚᵣₑᵥ - P); # Q[i+1]=Q[i-1]+b(P[i-1]-P[i]) \n ( Qₚᵣₑᵥ, Q, Pₚᵣₑᵥ ) = Q, Qₙₑₓₜ, P; # i++\n } \n\n b = ⌊ ⌊ √(𝑘*𝑁)+P ⌋ / Q ⌋; # b=floor((floor(√N)+P[i])/Q[0])\n Pₚᵣₑᵥ = b*Qₒ - P; # P[i-1]=b*Q[0]-P[i]\n Q = ( 𝑘*𝑁 - Pₚᵣₑᵥ² )/Qₒ; # Q[1]=(N-P[0]^2)/Q[0] & Q[i]\n Qₚᵣₑᵥ = Qₒ; # Q[i-1] = Q[0]\n # i = 1\n loop { # repeat\n b = ⌊ ⌊ √(𝑘*𝑁)+Pₚᵣₑᵥ ⌋ / Q ⌋; # b=floor(floor(√N)+P[i-1])/Q[i])\n P = b*Q - Pₚᵣₑᵥ; # P[i]=b*Q[i]-P[i-1]\n Qₙₑₓₜ = Qₚᵣₑᵥ + b*(Pₚᵣₑᵥ - P); # Q[i+1]=Q[i-1]+b(P[i-1]-P[i])\n last if (P == Pₚᵣₑᵥ); # until P[i+1]=P[i]\n ( Qₚᵣₑᵥ, Q, Pₚᵣₑᵥ ) = Q, Qₙₑₓₜ, P; # i++ \n } \n given 𝑁 gcd P { return $_ if $_ != 1|𝑁 } \n } # gcd(N,P[i]) (if != 1 or N) is a factor of N, otherwise try next k\n return 0 # give up\n}\n\nrace for ( \n 11111, # wikipedia.org/wiki/Shanks%27s_square_forms_factorization#Example\n 4558849, # example from talk page\n # all of the rest are taken from the FreeBASIC entry\n 2501,12851,13289,75301,120787,967009,997417,7091569,13290059,\n 42854447,223553581,2027651281,11111111111,100895598169,1002742628021,\n # time hoarders \n 60012462237239, # = 6862753 * 8744663 15s \n 287129523414791, # = 6059887 * 47381993 80s\n 11111111111111111, # = 2071723 * 5363222357 2m\n 384307168202281507, # = 415718707 * 924440401 5m\n 1000000000000000127, # = 111756107 * 8948056861 12m\n 9007199254740931, # = 10624181 * 847801751 17m\n 922337203685477563, # = 110075821 * 8379108103 41m\n 314159265358979323, # = 317213509 * 990371647 61m\n 1152921505680588799, # = 139001459 * 8294312261 93m\n 658812288346769681, # = 62222119 * 10588072199 112m\n 419244183493398773, # = 48009977 * 8732438749 135m\n 1537228672809128917, # = 26675843 * 57626245319 254m\n # don't know how to handle this one\n # for 1e-323, 1e-324 { my $*TOLERANCE = $_ ; \n # say 4611686018427387877.sqrt ≅ 4611686018427387877.sqrt.Int }\n # skip the perfect square check and start k with 3 to get the following \n # 4611686018427387877, # = 343242169 * 13435662733 217m\n) -> \\data {\n given data.&SQUFOF {\n when 0 { say \"The number \", data, \" is not factored.\" }\n when 1 { say \"The number \", data, \" is a prime.\" }\n default { say data, \" = \", $_, \" * \", data div $_.Int }\n }\n}\n\n```\n\nOutput:\n\n```\n11111 = 41 * 271 \n4558849 = 383 * 11903 \n2501 = 61 * 41 \n12851 = 71 * 181 \n13289 = 97 * 137 \n75301 = 293 * 257 \n120787 = 43 * 2809 \n967009 = 601 * 1609 \n997417 = 257 * 3881 \n7091569 = 2663 * 2663 \n13290059 = 3119 * 4261 \n42854447 = 4423 * 9689 \n223553581 = 11213 * 19937 \n2027651281 = 44021 * 46061 \n11111111111 = 21649 * 513239\n100895598169 = 112303 * 898423 \nThe number 1002742628021 is a prime.\n60012462237239 = 6862753 * 8744663 \n287129523414791 = 6059887 * 47381993 \n11111111111111111 = 2071723 * 5363222357\n384307168202281507 = 415718707 * 924440401 \n1000000000000000127 = 111756107 * 8948056861 \n9007199254740931 = 10624181 * 847801751 \n922337203685477563 = 110075821 * 8379108103 \n314159265358979323 = 317213509 * 990371647\n1152921505680588799 = 139001459 * 8294312261 \n658812288346769681 = 62222119 * 10588072199 \n419244183493398773 = 48009977 * 8732438749 \n1537228672809128917 = 26675843 * 57626245319 \n\n```\n\n### Use NativeCall\n\nUse idea similar to the second approach from here, by compiling the C (Classical heuristic) entry to a shared library and then make use of the squfof routine.\n\nsqufof.raku\n\n```\n# 20210326 Raku programming solution\n\nuse NativeCall;\n\nconstant LIBSQUFOF = '/home/user/LibSQUFOF.so';\n\nsub squfof(uint64 $n) returns uint64 is native(LIBSQUFOF) { * };\n\nrace for (\n 11111, # wikipedia.org/wiki/Shanks%27s_square_forms_factorization#Example\n 4558849, # example from talk page\n # all of the rest are taken from the FreeBASIC entry\n 2501,12851,13289,75301,120787,967009,997417,7091569,13290059,\n 42854447,223553581,2027651281,11111111111,100895598169,1002742628021,\n 60012462237239, # = 6862753 * 8744663\n 287129523414791, # = 6059887 * 47381993\n 11111111111111111, # = 2071723 * 5363222357\n 384307168202281507, # = 415718707 * 924440401\n 1000000000000000127, # = 111756107 * 8948056861\n 9007199254740931, # = 10624181 * 847801751\n 922337203685477563, # = 110075821 * 8379108103\n 314159265358979323, # = 317213509 * 990371647\n 1152921505680588799, # = 139001459 * 8294312261\n 658812288346769681, # = 62222119 * 10588072199\n 419244183493398773, # = 48009977 * 8732438749\n 1537228672809128917, # = 26675843 * 57626245319\n 4611686018427387877, # = 343242169 * 13435662733\n) -> \\data {\n given squfof(data) { say data, \" = \", $_, \" * \", data div $_ }\n}\n\n```\n\nOutput:\n\n```\ngcc -Wall -fPIC -shared -o LibSQUFOF.so squfof.c\n\nfile LibSQUFOF.so\nLibSQUFOF.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=f7f9864e5508ba1de80cbc6e2f4d789f4ec448e9, not stripped\nraku -c squfof.raku && time ./squfof.raku\nSyntax OK\n11111 = 41 * 271\n4558849 = 383 * 11903\n2501 = 61 * 41\n12851 = 71 * 181\n13289 = 97 * 137\n75301 = 293 * 257\n120787 = 43 * 2809\n967009 = 1609 * 601\n997417 = 257 * 3881\n7091569 = 2663 * 2663\n13290059 = 3119 * 4261\n42854447 = 4423 * 9689\n223553581 = 11213 * 19937\n2027651281 = 44021 * 46061\n11111111111 = 21649 * 513239\n100895598169 = 112303 * 898423\n1002742628021 = 1 * 1002742628021\n60012462237239 = 6862753 * 8744663\n287129523414791 = 6059887 * 47381993\n11111111111111111 = 2071723 * 5363222357\n384307168202281507 = 415718707 * 924440401\n1000000000000000127 = 111756107 * 8948056861\n9007199254740931 = 10624181 * 847801751\n922337203685477563 = 110075821 * 8379108103\n314159265358979323 = 317213509 * 990371647\n1152921505680588799 = 139001459 * 8294312261\n658812288346769681 = 62222119 * 10588072199\n419244183493398773 = 48009977 * 8732438749\n1537228672809128917 = 26675843 * 57626245319\n4611686018427387877 = 343242169 * 13435662733\n\nreal 0m0.784s\nuser 0m0.716s\nsys 0m0.056s\n\n\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nCreate a program that will calculate **n** decimal digits of the square root of a non─negative number.\n\nThe program should continue forever (or until the number of digits is specified) calculating and outputting each decimal digit in succession.\n\nThe program should be a \"spigot algorithm\" generating the digits of the number sequentially from left to right providing increasing precision as the algorithm proceeds."
},
{
"role": "assistant",
"content": "Implemented a long division algorithm..\n\n```\n# 20201023 Raku programming solution\n\nsub integral (Str $in) { # prepend '0' if length is odd\n given $in { .chars mod 2 ?? ('0'~$_).comb(2) !! .comb(2) }\n}\n\nsub fractional (Str $in) { # append '0' if length is odd\n given $in { .chars mod 2 ?? ($_~'0').comb(2) !! .comb(2) }\n}\n\nsub SpigotSqrt ($in) {\n\n my @dividends, my @fractional; # holds digital duos\n my $d = 9; # unit digit part of divisors & running answer\n my $D = ''; # tens+ digit part of divisors\n my $dot_printed = False;\n my $dividend; my $quotient = ''; my $remainder;\n\n return \"Sorry, minimum charge is $0⁺\" if $in ≤ 0;\n\n if $in.narrow ~~ Int { # integer\n @dividends = integral($in.Str)\n } else {\n given split(/\\./, $in.Str) { # floating point\n @dividends = integral(@_[0]);\n @fractional = fractional(@_[1]);\n }\n }\n\n $dividend = shift @dividends;\n\n loop {\n until ( $remainder = $dividend - ($D~$d) * $d ) ≥ 0 {\n $d-- # keep trying till the max divisor is found\n }\n print $d; # running answer\n $quotient ~= $d;\n unless @dividends.Bool {\n last if ( $remainder == 0 and $quotient != 0 and [email protected] );\n unless $dot_printed { print '.' and $dot_printed = True }\n if @fractional.Bool { # happen only once\n @dividends.append: @fractional;\n @fractional = (); # retired\n } else {\n @dividends.append: '00';\n }\n }\n $dividend = $remainder.Str ~ shift @dividends;\n $D = 2*$quotient;\n $d = 9\n }\n}\n\n#`[ matches result from https://stackoverflow.com/a/28152047/3386748\nfor <99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067> { # ]\nfor < 25 0.0625 152.2756 13579.02468 > {\n say \"The square root of $_ is\";\n SpigotSqrt $_ ; print \"\\n\";\n}\n\n```\n\nOutput:\n\n```\nThe square root of 25 is\n5\nThe square root of 0.0625 is\n0.25\nThe square root of 152.2756 is\n12.34\nThe square root of 13579.02468 is\n116.5290722523782903561833846788464631805119729204989141878325473726703822155976113726101636833624692173783050112427274490403132495026916228339453686341013613481116569793281525666303293666139135373395664751766204609166006753350008676787108560810713189340122619853015331030735400702976991920098868235804433621649473896395145322270105611438518020713137788187701241059921153133101219142225340975562189465283743880315403123043908068827985609461380033349440281928044661628680849458194668644072518779930532625670101046028192429778354952392572052578927533919600336446165970115867463651405291843435779882540897283554569528134419570259054368204716277521872340583781499813500950876849873104131526244245476070417915^C\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nWrite a function to test if a number is *square-free*.\n\nA *square-free* is an integer which is divisible by no perfect square other\nthan **1** (unity).\n\nFor this task, only positive square-free numbers will be used.\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n\n: : * **1** ───► **145** (inclusive)\n * **1** trillion ───► **1** trillion + **145** (inclusive)\n\n(One trillion = 1,000,000,000,000)\n\nShow here (on this page) the count of square-free integers from:\n\n: : * **1** ───► one hundred (inclusive)\n * **1** ───► one thousand (inclusive)\n * **1** ───► ten thousand (inclusive)\n * **1** ───► one hundred thousand (inclusive)\n * **1** ───► one million (inclusive)\n\nSee also\n: * the Wikipedia entry: square-free integer"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.06\n\nThe prime factoring algorithm is not really the best option for finding long runs of sequential square-free numbers. It works, but is probably better suited for testing arbitrary numbers rather than testing every sequential number from 1 to some limit. If you know that that is going to be your use case, there are faster algorithms.\n\n```\n# Prime factorization routines\nsub prime-factors ( Int $n where * > 0 ) {\n return $n if $n.is-prime;\n return [] if $n == 1;\n my $factor = find-factor( $n );\n flat prime-factors( $factor ), prime-factors( $n div $factor );\n}\n\nsub find-factor ( Int $n, $constant = 1 ) {\n return 2 unless $n +& 1;\n if (my $gcd = $n gcd 6541380665835015) > 1 {\n return $gcd if $gcd != $n\n }\n my $x = 2;\n my $rho = 1;\n my $factor = 1;\n while $factor == 1 {\n $rho *= 2;\n my $fixed = $x;\n for ^$rho {\n $x = ( $x * $x + $constant ) % $n;\n $factor = ( $x - $fixed ) gcd $n;\n last if 1 < $factor;\n }\n }\n $factor = find-factor( $n, $constant + 1 ) if $n == $factor;\n $factor;\n}\n\n# Task routine\nsub is-square-free (Int $n) { my @v = $n.&prime-factors.Bag.values; @v.sum/@v <= 1 }\n\n# The Task\n# Parts 1 & 2\nfor 1, 145, 1e12.Int, 145+1e12.Int -> $start, $end {\n say \"\\nSquare─free numbers between $start and $end:\\n\",\n ($start .. $end).hyper(:4batch).grep( &is-square-free ).list.fmt(\"%3d\").comb(84).join(\"\\n\");\n}\n\n# Part 3\nfor 1e2, 1e3, 1e4, 1e5, 1e6 {\n say \"\\nThe number of square─free numbers between 1 and {$_} (inclusive) is: \",\n +(1 .. .Int).race.grep: &is-square-free;\n}\n\n```\n\nOutput:\n\n```\nSquare─free numbers between 1 and 145:\n 1 2 3 5 6 7 10 11 13 14 15 17 19 21 22 23 26 29 30 31 33 \n 34 35 37 38 39 41 42 43 46 47 51 53 55 57 58 59 61 62 65 66 67 \n 69 70 71 73 74 77 78 79 82 83 85 86 87 89 91 93 94 95 97 101 102 \n103 105 106 107 109 110 111 113 114 115 118 119 122 123 127 129 130 131 133 134 137 \n138 139 141 142 143 145\n\nSquare─free numbers between 1000000000000 and 1000000000145:\n1000000000001 1000000000002 1000000000003 1000000000005 1000000000006 1000000000007 \n1000000000009 1000000000011 1000000000013 1000000000014 1000000000015 1000000000018 \n1000000000019 1000000000021 1000000000022 1000000000023 1000000000027 1000000000029 \n1000000000030 1000000000031 1000000000033 1000000000037 1000000000038 1000000000039 \n1000000000041 1000000000042 1000000000043 1000000000045 1000000000046 1000000000047 \n1000000000049 1000000000051 1000000000054 1000000000055 1000000000057 1000000000058 \n1000000000059 1000000000061 1000000000063 1000000000065 1000000000066 1000000000067 \n1000000000069 1000000000070 1000000000073 1000000000074 1000000000077 1000000000078 \n1000000000079 1000000000081 1000000000082 1000000000085 1000000000086 1000000000087 \n1000000000090 1000000000091 1000000000093 1000000000094 1000000000095 1000000000097 \n1000000000099 1000000000101 1000000000102 1000000000103 1000000000105 1000000000106 \n1000000000109 1000000000111 1000000000113 1000000000114 1000000000115 1000000000117 \n1000000000118 1000000000119 1000000000121 1000000000122 1000000000123 1000000000126 \n1000000000127 1000000000129 1000000000130 1000000000133 1000000000135 1000000000137 \n1000000000138 1000000000139 1000000000141 1000000000142 1000000000145\n\nThe number of square─free numbers between 1 and 100 (inclusive) is: 61\n\nThe number of square─free numbers between 1 and 1000 (inclusive) is: 608\n\nThe number of square─free numbers between 1 and 10000 (inclusive) is: 6083\n\nThe number of square─free numbers between 1 and 100000 (inclusive) is: 60794\n\nThe number of square─free numbers between 1 and 1000000 (inclusive) is: 607926\n```"
}
]
|
[
{
"role": "user",
"content": "Solve the Stable marriage problem using the Gale/Shapley algorithm.\n\n**Problem description** \nGiven an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.\n\nA stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman *also* prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.\n\nGale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.\n\n**Task Specifics** \nGiven ten males:\n\n```\n abe, bob, col, dan, ed, fred, gav, hal, ian, jon\n\n```\n\nAnd ten females:\n\n```\n abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan\n\n```\n\nAnd a complete list of ranked preferences, where the most liked is to the left:\n\n```\n abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay\n bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay\n col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan\n dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi\n ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay\n fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay\n gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay\n hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee\n ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve\n jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope\n \n abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal\n bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal\n cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon\n dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed\n eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob\n fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal\n gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian\n hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred\n ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan\n jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan\n\n```\n\n1. Use the Gale Shapley algorithm to find a stable set of engagements\n2. Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.\n\n**References**\n\n1. The Stable Marriage Problem. (Eloquent description and background information).\n2. Gale-Shapley Algorithm Demonstration.\n3. Another Gale-Shapley Algorithm Demonstration.\n4. Stable Marriage Problem - Numberphile (Video).\n5. Stable Marriage Problem (the math bit) (Video).\n6. The Stable Marriage Problem and School Choice. (Excellent exposition)"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2016.10\n\n**Translation of**: Perl\n\n```\nmy %he-likes =\n abe => < abi eve cath ivy jan dee fay bea hope gay >,\n bob => < cath hope abi dee eve fay bea jan ivy gay >,\n col => < hope eve abi dee bea fay ivy gay cath jan >,\n dan => < ivy fay dee gay hope eve jan bea cath abi >,\n ed => < jan dee bea cath fay eve abi ivy hope gay >,\n fred => < bea abi dee gay eve ivy cath jan hope fay >,\n gav => < gay eve ivy bea cath abi dee hope jan fay >,\n hal => < abi eve hope fay ivy cath jan bea gay dee >,\n ian => < hope cath dee gay bea abi fay ivy jan eve >,\n jon => < abi fay jan gay eve bea dee cath ivy hope >,\n;\n \nmy %she-likes =\n abi => < bob fred jon gav ian abe dan ed col hal >,\n bea => < bob abe col fred gav dan ian ed jon hal >,\n cath => < fred bob ed gav hal col ian abe dan jon >,\n dee => < fred jon col abe ian hal gav dan bob ed >,\n eve => < jon hal fred dan abe gav col ed ian bob >,\n fay => < bob abe ed ian jon dan fred gav col hal >,\n gay => < jon gav hal fred bob abe col ed dan ian >,\n hope => < gav jon bob abe ian dan hal ed col fred >,\n ivy => < ian col hal gav fred bob abe ed jon dan >,\n jan => < ed hal gav abe bob jon col ian fred dan >,\n;\n\nmy %fiancé;\nmy %fiancée;\nmy %proposed;\n \nsub she-prefers ($her, $hottie) { .index($hottie) < .index(%fiancé{$her}) given ~%she-likes{$her} }\nsub he-prefers ($him, $hottie) { .index($hottie) < .index(%fiancée{$him}) given ~%he-likes{$him} }\n \nmatch'em;\ncheck-stability;\n\nperturb'em;\ncheck-stability;\n \nsub match'em { #'\n say 'Matchmaking:';\n while unmatched-guy() -> $guy {\n my $gal = preferred-choice($guy);\n %proposed{\"$guy $gal\"} = '❤';\n if not %fiancé{$gal} {\n engage($guy, $gal);\n say \"\\t$gal and $guy\";\n }\n elsif she-prefers($gal, $guy) {\n\t my $engaged-guy = %fiancé{$gal};\n\t engage($guy, $gal);\n\t %fiancée{$engaged-guy} = '';\n\t say \"\\t$gal dumped $engaged-guy for $guy\";\n\t}\n }\n}\n \nsub check-stability {\n my @instabilities = gather for flat %he-likes.keys X %she-likes.keys -> $m, $w {\n\tif he-prefers($m, $w) and she-prefers($w, $m) {\n\t take \"\\t$w prefers $m to %fiancé{$w} and $m prefers $w to %fiancée{$m}\";\n\t}\n }\n\n say 'Stablility:';\n if @instabilities {\n\t.say for @instabilities;\n }\n else {\n say \"\\t(all marriages stable)\";\n }\n}\n \nsub unmatched-guy { %he-likes.keys.first: { not %fiancée{$_} } }\n \nsub preferred-choice($guy) { %he-likes{$guy}.first: { not %proposed{\"$guy $_\" } } }\n \nsub engage($guy, $gal) {\n %fiancé{$gal} = $guy;\n %fiancée{$guy} = $gal;\n}\n \nsub perturb'em { #'\n say 'Perturb:';\n say \"\\tengage abi with fred and bea with jon\";\n engage('fred', 'abi');\n engage('jon', 'bea');\n}\n\n```\n\nOutput:\n\n```\nMatchmaking:\n cath and bob\n ivy and dan\n abi and jon\n hope and ian\n jan and ed\n eve and abe\n eve dumped abe for hal\n ivy dumped dan for abe\n fay and dan\n gay and gav\n bea and fred\n dee and col\nStablility:\n (all marriages stable)\nPerturb:\n engage abi with fred and bea with jon\nStablility:\n fay prefers jon to dan and jon prefers fay to bea\n eve prefers jon to hal and jon prefers eve to bea\n gay prefers jon to gav and jon prefers gay to bea\n bea prefers fred to jon and fred prefers bea to abi\n```"
}
]
|
[
{
"role": "user",
"content": "A **stack** is a container of elements with last in, first out access policy. Sometimes it also called **LIFO**.\n\nThe stack is accessed through its **top**.\n\nThe basic stack operations are:\n\n* *push* stores a new element onto the stack top;\n* *pop* returns the last pushed stack element, while removing it from the stack;\n* *empty* tests if the stack contains no elements.\n\nSometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):\n\n* *top* (sometimes called *peek* to keep with the *p* theme) returns the topmost element without modifying the stack.\n\nStacks allow a very simple hardware implementation.\n\nThey are common in almost all processors.\n\nIn programming, stacks are also very popular for their way (**LIFO**) of resource management, usually memory.\n\nNested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).\n\nThis is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.\n\nSee stack machine.\n\nMany algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.\n\nTask\n\nCreate a stack supporting the basic operations: push, pop, empty.\n\nSee also\n\n* Array\n* Associative array: Creation, Iteration\n* Collections\n* Compound data type\n* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal\n* Linked list\n* Queue: Definition, Usage\n* Set\n* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal\n* Stack"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku still has the stack functions from Perl 5, but now they also can be accessed by object notation:\n\n```\nmy @stack; # just a array\[email protected]($elem); # add $elem to the end of @stack\n$elem = @stack.pop; # get the last element back\[email protected] == 0 # true, because the stack is empty\nnot @stack # also true because @stack is false\n```"
}
]
|
[
{
"role": "user",
"content": "Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.\n\nTask\n\nPrint out (in a manner considered suitable for the platform) the current call stack.\n\nThe amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.\n\nYou may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.\n\nThe task should allow the program to continue after generating the stack trace.\n\nThe task report here must include the trace from a sample program."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2013-03-03\n\n```\nsub g { say Backtrace.new.concise }\nsub f { g }\nsub MAIN { f }\n\n```\n\nOutput:\n\n```\n in sub g at bt:1\n in sub f at bt:2\n in sub MAIN at bt:3\n```"
}
]
|
[
{
"role": "user",
"content": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure.\n\nWrite a function \"step\\_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step\\_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\n```\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\n```\n\nInductive proof that step\\_up() steps up one step, if it terminates:\n\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step\\_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step\\_up() calls. QED\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\n```\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n```"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nsub step_up { step_up until step; }\n\n```"
}
]
|
[
{
"role": "user",
"content": "Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.\n\nTask\n\nDemonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.\n\nLanguages that always run from main() can be omitted from this task."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\nWhen executed with the standard setting, Raku code always runs the mainline code automatically, followed by the MAIN function if you have one. However, it's possible to start up with an alternate setting that might want to create its own event loop or MAIN. In such cases you can\nalways capture control at various phases with blocks that we call \"phasers\":\n\n```\nBEGIN {...} # as soon as parsed\nCHECK {...} # end of compile time\nINIT {...} # beginning of run time\nEND {...} # end of run time\n\n```"
}
]
|
[
{
"role": "user",
"content": "Build and show a web page displaying the data from the task separate the house number from the street name in a formatted and colored table.\n\nTask\n\nWrite the code which automatically opens a web page in a browser showing the addresses.\n*No static data must be shown, only processed data.*"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2017.09\n\nUses the code from the Separate the house number from the street name task almost verbatim. Included here to make a complete, runnable example.\n\n```\nuse File::Temp;\n\nmy $addresses = qq :to /END/;\n Plataanstraat 5\n Straat 12\n Straat 12 II\n Dr. J. Straat 12\n Dr. J. Straat 12 a\n Dr. J. Straat 12-14\n Laan 1940 – 1945 37\n Plein 1940 2\n 1213-laan 11\n 16 april 1944 Pad 1\n 1e Kruisweg 36\n Laan 1940-’45 66\n Laan ’40-’45\n Langeloërduinen 3 46\n Marienwaerdt 2e Dreef 2\n Provincialeweg N205 1\n Rivium 2e Straat 59.\n Nieuwe gracht 20rd\n Nieuwe gracht 20rd 2\n Nieuwe gracht 20zw /2\n Nieuwe gracht 20zw/3\n Nieuwe gracht 20 zw/4\n Bahnhofstr. 4\n Wertstr. 10\n Lindenhof 1\n Nordesch 20\n Weilstr. 6\n Harthauer Weg 2\n Mainaustr. 49\n August-Horch-Str. 3\n Marktplatz 31\n Schmidener Weg 3\n Karl-Weysser-Str. 6\n END\n\nmy @row-color = '#d7fffe', '#9dbcd4';\n\n# build the table\nsub genTable () {\n my $table = '<table border=\"2\"> <tr bgcolor=\"#02ccfe\">' ~\n qq|<th>Address</th><th>Street</th><th>House Number</th>\\n|;\n my $i = 0;\n for $addresses.lines -> $addr {\n $table ~= qq|<tr bgcolor=\"{@row-color[$i++ % 2]}\"><td>{$addr}</td>|;\n $addr ~~ m[\n ( .*? )\n [\n \\s+\n (\n | \\d+ [ \\- | \\/ ] \\d+\n | <!before 1940 | 1945> \\d+ <[ a..z I . / \\x20 ]>* \\d*\n )\n ]?\n $\n ];\n quietly $table ~= qq|<td>{$0.Str}</td><td>{$1.Str||''}</td></tr>\\n|;\n }\n $table ~ '</table>';\n}\n\n# generate the page content\nsub content {\n qq :to /END/;\n <html>\n <head>\n <title>Rosetta Code - Start a Web Browser</title>\n <meta charset=\"UTF-8\">\n </head>\n <body bgcolor=\"#d8dcd6\">\n <p align=\"center\">\n <font face=\"Arial, sans-serif\" size=\"5\">Split the house number from the street name</font>\n </p>\n <p align=\"center\">\n { genTable }\n </p>\n </body>\n </html>\n END\n}\n\n# Use a temporary file name and file handle\nmy ($fn, $fh) = tempfile :suffix('.html');\n\n# dump the content to the file\n$fh.spurt: content;\n\n# use appropriate command for Windows or X11\n# other OSs/WMs may need different invocation\nmy $command = $*DISTRO.is-win ?? \"start $fn\" !! \"xdg-open $fn\";\n\n# start the browser\nshell $command;\n\n# wait for a bit to give browser time to load before destroying temp file\nsleep 5;\n\n```\n\nOutput:\n\nWill start the default browser (or open a new tab/window in a running one) and display this table.\n\n| Address | Street | House Number |\n| --- | --- | --- |\n| Plataanstraat 5 | Plataanstraat | 5 |\n| Straat 12 | Straat | 12 |\n| Straat 12 II | Straat | 12 II |\n| Dr. J. Straat 12 | Dr. J. Straat | 12 |\n| Dr. J. Straat 12 a | Dr. J. Straat | 12 a |\n| Dr. J. Straat 12-14 | Dr. J. Straat | 12-14 |\n| Laan 1940 – 1945 37 | Laan 1940 – 1945 | 37 |\n| Plein 1940 2 | Plein 1940 | 2 |\n| 1213-laan 11 | 1213-laan | 11 |\n| 16 april 1944 Pad 1 | 16 april 1944 Pad | 1 |\n| 1e Kruisweg 36 | 1e Kruisweg | 36 |\n| Laan 1940-’45 66 | Laan 1940-’45 | 66 |\n| Laan ’40-’45 | Laan ’40-’45 | |\n| Langeloërduinen 3 46 | Langeloërduinen | 3 46 |\n| Marienwaerdt 2e Dreef 2 | Marienwaerdt 2e Dreef | 2 |\n| Provincialeweg N205 1 | Provincialeweg N205 | 1 |\n| Rivium 2e Straat 59. | Rivium 2e Straat | 59. |\n| Nieuwe gracht 20rd | Nieuwe gracht | 20rd |\n| Nieuwe gracht 20rd 2 | Nieuwe gracht | 20rd 2 |\n| Nieuwe gracht 20zw /2 | Nieuwe gracht | 20zw /2 |\n| Nieuwe gracht 20zw/3 | Nieuwe gracht | 20zw/3 |\n| Nieuwe gracht 20 zw/4 | Nieuwe gracht | 20 zw/4 |\n| Bahnhofstr. 4 | Bahnhofstr. | 4 |\n| Wertstr. 10 | Wertstr. | 10 |\n| Lindenhof 1 | Lindenhof | 1 |\n| Nordesch 20 | Nordesch | 20 |\n| Weilstr. 6 | Weilstr. | 6 |\n| Harthauer Weg 2 | Harthauer Weg | 2 |\n| Mainaustr. 49 | Mainaustr. | 49 |\n| August-Horch-Str. 3 | August-Horch-Str. | 3 |\n| Marktplatz 31 | Marktplatz | 31 |\n| Schmidener Weg 3 | Schmidener Weg | 3 |\n| Karl-Weysser-Str. 6 | Karl-Weysser-Str. | 6 |"
}
]
|
[
{
"role": "user",
"content": "**Background**\n\nThis task is inspired by Mark Nelson's DDJ Column \"Wordplay\" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.\n\nThe challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two *different* U.S. States (so that all four state names differ from one another).\n\nWhat states are these?\n\nThe problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to Gödel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.\n\nA second challenge in the form of a set of fictitious new states was also presented.\n\nTask\n\nWrite a program to solve the challenge using both the original list of states and the fictitious list.\n\nCaveats\n\n* case and spacing aren't significant - just letters (harmonize case)\n* don't expect the names to be in any order - such as being sorted\n* don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)\n\nComma separated list of state names used in the original puzzle:\n\n```\n \"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\",\n \"California\", \"Colorado\", \"Connecticut\", \"Delaware\", \n \"Florida\", \"Georgia\", \"Hawaii\", \"Idaho\", \"Illinois\", \n \"Indiana\", \"Iowa\", \"Kansas\", \"Kentucky\", \"Louisiana\",\n \"Maine\", \"Maryland\", \"Massachusetts\", \"Michigan\",\n \"Minnesota\", \"Mississippi\", \"Missouri\", \"Montana\",\n \"Nebraska\", \"Nevada\", \"New Hampshire\", \"New Jersey\",\n \"New Mexico\", \"New York\", \"North Carolina\", \"North Dakota\",\n \"Ohio\", \"Oklahoma\", \"Oregon\", \"Pennsylvania\", \"Rhode Island\",\n \"South Carolina\", \"South Dakota\", \"Tennessee\", \"Texas\",\n \"Utah\", \"Vermont\", \"Virginia\",\n \"Washington\", \"West Virginia\", \"Wisconsin\", \"Wyoming\"\n\n```\n\nComma separated list of additional fictitious state names to be added to the original (Includes a duplicate):\n\n```\n\"New Kory\", \"Wen Kory\", \"York New\", \"Kory New\", \"New Kory\"\n\n```\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2018.03\n\n```\nmy @states = <\n Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware\n Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky\n Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi\n Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico\n New_York North_Carolina North_Dakota Ohio Oklahoma Oregon Pennsylvania\n Rhode_Island South_Carolina South_Dakota Tennessee Texas Utah Vermont\n Virginia Washington West_Virginia Wisconsin Wyoming\n>;\n\nsay \"50 states:\";\n.say for anastates @states;\n \nsay \"\\n54 states:\";\n.say for sort anastates @states, < New_Kory Wen_Kory York_New Kory_New New_Kory >;\n\nsub anastates (*@states) {\n my @s = @states.unique».subst('_', ' ');\n \n my @pairs = gather for ^@s -> $i {\n\tfor $i ^..^ @s -> $j {\n\t take [ @s[$i], @s[$j] ];\n\t}\n }\n \n my $equivs = hash @pairs.classify: *.lc.comb.sort.join;\n\n gather for $equivs.values -> @c {\n\tfor ^@c -> $i {\n\t for $i ^..^ @c -> $j {\n\t\tmy $set = set @c[$i].list, @c[$j].list;\n\t\ttake @c[$i].list.join(', ') ~ ' = ' ~ @c[$j].list.join(', ') if $set == 4;\n\t }\n\t}\n }\n}\n\n```\n\nOutput:\n\n```\n50 states:\nNorth Carolina, South Dakota = North Dakota, South Carolina\n\n54 states:\nNew Kory, Kory New = Wen Kory, York New\nNew Kory, Wen Kory = York New, Kory New\nNew Kory, York New = Wen Kory, Kory New\nNew York, Kory New = New Kory, Wen Kory\nNew York, Kory New = New Kory, York New\nNew York, Kory New = Wen Kory, York New\nNew York, New Kory = Wen Kory, Kory New\nNew York, New Kory = Wen Kory, York New\nNew York, New Kory = York New, Kory New\nNew York, Wen Kory = New Kory, Kory New\nNew York, Wen Kory = New Kory, York New\nNew York, Wen Kory = York New, Kory New\nNew York, York New = New Kory, Kory New\nNew York, York New = New Kory, Wen Kory\nNew York, York New = Wen Kory, Kory New\nNorth Carolina, South Dakota = North Dakota, South Carolina\n```"
}
]
|
[
{
"role": "user",
"content": "Statistics is all about large groups of numbers.\nWhen talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).\nIf you have set of data \n\nx\n\ni\n{\\displaystyle {\\displaystyle x\\_{i}}}\n where \n\ni\n=\n1\n,\n2\n,\n…\n,\nn\n\n{\\displaystyle {\\displaystyle i=1,2,\\ldots ,n\\,\\!}}\n, the mean is \n\nx\n¯\n≡\n\n\n1\nn\n\n∑\n\ni\n\nx\n\ni\n{\\displaystyle {\\displaystyle {\\bar {x}}\\equiv {1 \\over n}\\sum \\_{i}x\\_{i}}}\n, while the stddev is \n\nσ\n≡\n\n1\nn\n\n∑\n\ni\n\n\n(\n\n\nx\n\ni\n−\n\nx\n¯\n)\n\n2\n{\\displaystyle {\\displaystyle \\sigma \\equiv {\\sqrt {{1 \\over n}\\sum \\_{i}\\left(x\\_{i}-{\\bar {x}}\\right)^{2}}}}}\n.\n\nWhen examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).\nWhen plotted, often as bar graphs, it visually indicates how often each data value occurs.\n\n**Task** Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.\nCreate 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.\nDo so for sample size of 1,000 and 10,000, maybe even higher if you feel like.\nShow a histogram of any of these sets.\nDo you notice some patterns about the standard deviation?\n\n**Extra** Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)\n\nHint\n\nFor a finite population with equal probabilities at all points, one can derive:\n\n: (\n x\n −\n\n\n x\n ¯\n\n )\n\n 2\n ¯\n =\n\n x\n\n 2\n ¯\n −\n\n x\n ¯\n\n 2\n {\\displaystyle {\\displaystyle {\\overline {(x-{\\overline {x}})^{2}}}={\\overline {x^{2}}}-{\\overline {x}}^{2}}}\n\nOr, more verbosely:\n\n: 1\n N\n\n ∑\n\n i\n =\n 1\n\n N\n (\n\n x\n\n i\n −\n\n\n x\n ¯\n\n )\n\n 2\n =\n\n\n 1\n N\n\n (\n\n\n ∑\n\n i\n =\n 1\n\n N\n\n x\n\n i\n\n 2\n )\n −\n\n x\n ¯\n\n 2\n .\n {\\displaystyle {\\displaystyle {\\frac {1}{N}}\\sum \\_{i=1}^{N}(x\\_{i}-{\\overline {x}})^{2}={\\frac {1}{N}}\\left(\\sum \\_{i=1}^{N}x\\_{i}^{2}\\right)-{\\overline {x}}^{2}.}}\n\nSee also\n\n* Statistics/Normal distribution\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 2018.03\n\n```\nfor 100, 1_000, 10_000 -> $N {\n say \"size: $N\";\n my @data = rand xx $N;\n printf \"mean: %f\\n\", my $mean = $N R/ [+] @data;\n printf \"stddev: %f\\n\", sqrt\n $mean**2 R- $N R/ [+] @data »**» 2;\n printf \"%.1f %s\\n\", .key, '=' x (500 * .value.elems / $N)\n for sort @data.classify: (10 * *).Int / 10;\n say '';\n}\n\n```\n\nOutput:\n\n```\nsize: 100\nmean: 0.52518699464629726\nstddev: 0.28484207464779548\n0.0\t==============================\n0.1\t======================================================================\n0.2\t===================================\n0.3\t==================================================\n0.4\t============================================================\n0.5\t=============================================\n0.6\t====================\n0.7\t===========================================================================\n0.8\t======================================================================\n0.9\t=============================================\n\nsize: 1000\nmean: 0.51043974182914975\nstddev: 0.29146336553431618\n0.0\t==============================================\n0.1\t==================================================\n0.2\t===========================================\n0.3\t========================================================\n0.4\t===================================================\n0.5\t=======================================\n0.6\t===========================================================\n0.7\t====================================================\n0.8\t==============================================\n0.9\t========================================================\n\nsize: 10000\nmean: 0.50371817503544458\nstddev: 0.2900716333092252\n0.0\t===================================================\n0.1\t=================================================\n0.2\t=============================================\n0.3\t====================================================\n0.4\t==============================================\n0.5\t====================================================\n0.6\t================================================\n0.7\t===================================================\n0.8\t====================================================\n0.9\t==================================================\n```"
}
]
|
[
{
"role": "user",
"content": "The probability density function (pdf) of the chi-squared (or χ2) distribution as used in statistics is\n\n: f\n (\n x\n ;\n\n k\n )\n =\n\n x\n\n k\n 2\n −\n 1\n\n e\n\n −\n\n\n x\n 2\n\n\n 2\n\n\n k\n 2\n Γ\n\n (\n\n\n k\n 2\n )\n {\\displaystyle {\\displaystyle f(x;\\,k)={\\dfrac {x^{{\\frac {k}{2}}-1}e^{-{\\frac {x}{2}}}}{2^{\\frac {k}{2}}\\Gamma \\left({\\frac {k}{2}}\\right)}}}}\n , where \n\n x\n >\n 0\n {\\textstyle x>0}\n\nHere, \n\nΓ\n(\nk\n\n/\n2\n)\n{\\textstyle \\Gamma (k/2)}\n denotes the Gamma\\_function.\n\nThe use of the gamma function in the equation below reflects the chi-squared distribution's origin as a special case of the gamma\ndistribution.\n\nIn probability theory and statistics, the gamma distribution is a two-parameter family of continuous probability distributions.\nThe exponential distribution, Erlang distribution, and chi-square distribution are special cases of the gamma distribution.\n\nThe probability density function (pdf) of the gamma distribution is given by the formula\n\n: f\n (\n x\n ;\n k\n ,\n θ\n )\n =\n\n x\n\n k\n −\n 1\n\n e\n\n −\n x\n\n /\n θ\n\n\n θ\n\n k\n Γ\n (\n k\n )\n\n\n for \n x\n >\n 0\n\n and \n k\n ,\n θ\n >\n 0.\n {\\displaystyle {\\displaystyle f(x;k,\\theta )={\\frac {x^{k-1}e^{-x/\\theta }}{\\theta ^{k}\\Gamma (k)}}\\quad {\\text{ for }}x>0{\\text{ and }}k,\\theta >0.}}\n\nwhere Γ(*k*) is the Gamma\\_function, with shape parameter k and a scale parameter θ.\n\nThe cumulative probability distribution of the gamma distribution is the area under the curve of the distribution, which indicates\nthe increasing probability of the x value of a single random point within the gamma distribution being less than or equal to the x value\nof the cumulative probability distribution. The gamma cumulative probability distribution function can be calculated as\n\n: F\n (\n x\n ;\n k\n ,\n θ\n )\n =\n\n ∫\n\n 0\n\n x\n f\n (\n u\n ;\n k\n ,\n θ\n )\n\n d\n u\n =\n\n γ\n\n (\n\n k\n ,\n\n\n x\n θ\n )\n\n Γ\n (\n k\n )\n ,\n {\\displaystyle {\\displaystyle F(x;k,\\theta )=\\int \\_{0}^{x}f(u;k,\\theta )\\,du={\\frac {\\gamma \\left(k,{\\frac {x}{\\theta }}\\right)}{\\Gamma (k)}},}}\n\nwhere \n\nγ\n\n(\n\nk\n,\n\n\nx\nθ\n)\n{\\displaystyle {\\displaystyle \\gamma \\left(k,{\\frac {x}{\\theta }}\\right)}}\n is the lower incomplete gamma function.\n\nThe lower incomplete gamma function can be calculated as\n\nx\n\ns\n\n\ne\n\n−\nx\n\n∑\n\nm\n=\n0\n\n∞\n\nx\n\nm\n\nΓ\n(\ns\n+\nm\n+\n1\n)\n{\\displaystyle x^{s}\\,e^{-x}\\sum \\_{m=0}^{\\infty }{\\frac {x^{m}}{\\Gamma (s+m+1)}}}\n\nand so, for the chi-squared cumulative probability distribution and substituting chi-square k into s as k/2 and chi-squared x into x as x / 2,\n\n: F\n (\n x\n ;\n\n k\n )\n =\n (\n x\n\n /\n 2\n\n )\n\n (\n k\n\n /\n 2\n )\n\n\n e\n\n −\n x\n\n /\n 2\n\n ∑\n\n m\n =\n 0\n\n ∞\n\n (\n x\n\n /\n 2\n\n )\n\n m\n\n Γ\n (\n\n\n k\n 2\n +\n m\n +\n 1\n )\n .\n {\\displaystyle F(x;\\,k)=(x/2)^{(k/2)}\\,e^{-x/2}\\sum \\_{m=0}^{\\infty }{\\frac {(x/2)^{m}}{\\Gamma ({\\frac {k}{2}}+m+1)}}.}\n\nBecause series formulas may be subject to accumulated errors from rounding in the frequently used region where x and k are under 10 and near one another, you may instead use a mathematics function library, if available for your programming task, to calculate gamma and incomplete gamma.\n\nTask\n\n* Calculate and show the values of the χ2(x; k) for k = 1 through 5 inclusive and x integer from 0 and through 10 inclusive.\n\n* Create a function to calculate the cumulative probability function for the χ2 distribution. This will need to be reasonably accurate (at least 6 digit accuracy) for k = 3.\n\n* Calculate and show the p values of statistical samples which result in a χ2(k = 3) value of 1, 2, 4, 8, 16, and 32. (Statistical *p values* can be calculated for the purpose of this task as approximately 1 - P(x), with P(x) the cumulative probability function at x for χ2.)\n\n: : The following is a chart for 4 airports:\n\nFlight Delays\n\n| Airport | On Time | Delayed | Totals |\n| --- | --- | --- | --- |\n| Dallas/Fort Worth | 77 | 23 | 100 |\n| Honolulu | 88 | 12 | 100 |\n| LaGuardia | 79 | 21 | 100 |\n| Orlando | 81 | 19 | 100 |\n| All Totals | 325 | 75 | 400 |\n| Expected per 100 | 81.25 | 18.75 | 100 |\n\n: : χ2 on a 2D table is calculated as the sum of the squares of the differences from expected divided by the expected numbers for each entry on the table. The k for the chi-squared distribution is to be calculated as df, the degrees of freedom for the table, which is a 2D parameter, (count of airports - 1) \\* (count of measures per airport - 1), which here is (4 - 1 )(2 - 1) = 3.\n\n* Calculate the Chi-squared statistic for the above table and find its p value using your function for the cumulative probability for χ2 with k = 3 from the previous task.\n\nStretch task\n\n* Show how you could make a plot of the curves for the probability distribution function χ2(x; k) for k = 0, 1, 2, and 3.\n\nRelated Tasks\n\n* Statistics/Basic\n* Statistics/Normal\\_distribution\n\nSee also\n\n[Chi Squared Test]\n[NIST page on the Chi-Square Distribution]"
},
{
"role": "assistant",
"content": "**Translation of**: Julia\n\n```\n# 20221101 Raku programming solution\n\nuse Graphics::PLplot;\n\nsub Γ(\\z) { # https://rosettacode.org/wiki/Gamma_function#Raku\n constant g = 9;\n z < .5 ?? π/ sin(π * z) / Γ(1 - z) \n !! sqrt(2*π) * (z + g - 1/2)**(z - 1/2) * exp(-(z + g - 1/2)) *\n [+] < 1.000000000000000174663 5716.400188274341379136\n -14815.30426768413909044 14291.49277657478554025\n -6348.160217641458813289 1301.608286058321874105\n -108.1767053514369634679 2.605696505611755827729\n -0.7423452510201416151527e-2 0.5384136432509564062961e-7\n -0.4023533141268236372067e-8 > Z* 1, |map 1/(z + *), 0..*\n}\n\nsub χ2(\\x,\\k) {x>0 && k>0 ?? (x**(k/2 - 1)*exp(-x/2)/(2**(k/2)*Γ(k / 2))) !! 0}\n \nsub Γ_cdf(\\k,\\x) { x**k * exp(-x) * sum( ^101 .map: { x** $_ / Γ(k+$_+1) } ) }\n\nsub cdf_χ2(\\x,\\k) { (x <= 0 or k <= 0) ?? 0.0 !! Γ_cdf(k / 2, x / 2) }\n\nsay ' 𝒙 χ² ', [~] (1..5)».&{ \"𝒌 = $_\" ~ ' ' x 13 };\nsay '-' x my \\width = 93;\nfor 0..10 -> \\x {\n say x.fmt('%2d'), [~] (1…5)».&{χ2(x, $_).fmt: \" %-.{((width-2) div 5)-4}f\"}\n}\n\nsay \"\\nχ² 𝒙 cdf for χ² P value (df=3)\\n\", '-' x 36;\nfor 2 «**« ^6 -> \\p {\n my $cdf = cdf_χ2(p, 3).fmt: '%-.10f';\n say p.fmt('%2d'), \" $cdf \", (1-$cdf).fmt: '%-.10f'\n}\n\nmy \\airport = [ <77 23>, <88 12>, <79 21>, <81 19> ];\nmy \\expected = [ <81.25 18.75> xx 4 ];\nmy \\dtotal = ( (airport »-« expected)»² »/» expected )».List.flat.sum;\n\nsay \"\\nFor the airport data, diff total is \",dtotal,\", χ² is \", χ2(dtotal, 3), \", p value \", cdf_χ2(dtotal, 3);\n\ngiven Graphics::PLplot.new( device => 'png', file-name => 'output.png' ) {\n .begin;\n .pen-width: 3 ;\n .environment: x-range => [-1.0, 10.0], y-range => [-0.1, 0.5], just => 0 ;\n .label: x-axis => '', y-axis => '', title => 'Chi-squared distribution' ;\n for 0..3 -> \\𝒌 { \n .color-index0: 1+2*𝒌;\n .line: (0, .1 … 10).map: -> \\𝒙 { ( 𝒙, χ2( 𝒙, 𝒌 ) )».Num };\n .text-viewport: side=>'t', disp=>-𝒌-2, pos=>.5, just=>.5, text=>'k = '~𝒌 \n } # plplot.sourceforge.net/docbook-manual/plplot-html-5.15.0/plmtex.html\n .end \n}\n\n```\n\nOutput:\n\n```\n 𝒙 χ² 𝒌 = 1 𝒌 = 2 𝒌 = 3 𝒌 = 4 𝒌 = 5 \n---------------------------------------------------------------------------------------------\n 0 0.00000000000000 0.00000000000000 0.00000000000000 0.00000000000000 0.00000000000000\n 1 0.24197072451914 0.30326532985632 0.24197072451914 0.15163266492816 0.08065690817305\n 2 0.10377687435515 0.18393972058572 0.20755374871030 0.18393972058572 0.13836916580686\n 3 0.05139344326792 0.11156508007421 0.15418032980377 0.16734762011132 0.15418032980377\n 4 0.02699548325659 0.06766764161831 0.10798193302638 0.13533528323661 0.14397591070183\n 5 0.01464498256193 0.04104249931195 0.07322491280963 0.10260624827987 0.12204152134939\n 6 0.00810869555494 0.02489353418393 0.04865217332964 0.07468060255180 0.09730434665928\n 7 0.00455334292164 0.01509869171116 0.03187340045148 0.05284542098906 0.07437126772012\n 8 0.00258337316926 0.00915781944437 0.02066698535409 0.03663127777747 0.05511196094425\n 9 0.00147728280398 0.00555449826912 0.01329554523581 0.02499524221105 0.03988663570744\n10 0.00085003666025 0.00336897349954 0.00850036660252 0.01684486749771 0.02833455534173\n\nχ² 𝒙 cdf for χ² P value (df=3)\n------------------------------------\n 1 0.1987480431 0.8012519569\n 2 0.4275932955 0.5724067045\n 4 0.7385358701 0.2614641299\n 8 0.9539882943 0.0460117057\n16 0.9988660157 0.0011339843\n32 0.9999994767 0.0000005233\n\nFor the airport data, diff total is 4.512821, χ² is 0.08875392598443506, p value 0.7888504263193072\n```"
}
]
|
[
{
"role": "user",
"content": "The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.\n\nThe task\n\n1. Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n2. Mention any native language support for the generation of normally distributed random numbers.\n\nReference\n\n* You may refer to code in Statistics/Basic if available."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\n```\nsub normdist ($m, $σ) {\n my $r = sqrt -2 * log rand;\n my $Θ = τ * rand;\n $r * cos($Θ) * $σ + $m;\n}\n\nsub MAIN ($size = 100000, $mean = 50, $stddev = 4) {\n my @dataset = normdist($mean,$stddev) xx $size;\n\n my $m = [+](@dataset) / $size;\n say (:$m);\n\n my $σ = sqrt [+](@dataset X** 2) / $size - $m**2;\n say (:$σ);\n\n (my %hash){.round}++ for @dataset;\n my $scale = 180 * $stddev / $size;\n constant @subbar = < ⎸ ▏ ▎ ▍ ▌ ▋ ▊ ▉ █ >;\n for %hash.keys».Int.minmax(+*) -> $i {\n my $x = (%hash{$i} // 0) * $scale;\n my $full = floor $x;\n my $part = 8 * ($x - $full);\n say $i, \"\\t\", '█' x $full, @subbar[$part];\n }\n}\n\n```\n\nOutput:\n\n```\n\"m\" => 50.006107405837142e0\n\"σ\" => 4.0814435639885254e0\n33\t⎸\n34\t⎸\n35\t⎸\n36\t▏\n37\t▎\n38\t▊\n39\t█▋\n40\t███⎸\n41\t█████▊\n42\t██████████⎸\n43\t███████████████▋\n44\t███████████████████████▏\n45\t████████████████████████████████▌\n46\t███████████████████████████████████████████▍\n47\t██████████████████████████████████████████████████████▏\n48\t███████████████████████████████████████████████████████████████▏\n49\t█████████████████████████████████████████████████████████████████████▋\n50\t███████████████████████████████████████████████████████████████████████▊\n51\t█████████████████████████████████████████████████████████████████████▌\n52\t███████████████████████████████████████████████████████████████⎸\n53\t██████████████████████████████████████████████████████▎\n54\t███████████████████████████████████████████⎸\n55\t████████████████████████████████▌\n56\t███████████████████████▍\n57\t███████████████▉\n58\t█████████▉\n59\t█████▍\n60\t███▍\n61\t█▋\n62\t▊\n63\t▍\n64\t▏\n65\t⎸\n66\t⎸\n67\t⎸\n```"
}
]
|
[
{
"role": "user",
"content": "Euler Project #284\n\n\nTask\n\nThe 3-digit number 376 in the decimal numbering system is an example of numbers with the special property that its square ends with the same digits: **376\\*376 = 141376**. Let's call a number with this property a steady square. Find steady squares under **10.000**"
},
{
"role": "assistant",
"content": "```\n.say for ({$++²}…*).kv.grep( {$^v.ends-with: $^k} )[1..10]\n\n```\n\nOutput:\n\n```\n(1 1)\n(5 25)\n(6 36)\n(25 625)\n(76 5776)\n(376 141376)\n(625 390625)\n(9376 87909376)\n(90625 8212890625)\n(109376 11963109376)\n```"
}
]
|
[
{
"role": "user",
"content": "Steffensen's method is a numerical method to find the roots of functions. It is similar to Newton's method, but, unlike Newton's, does not require derivatives. Like Newton's, however, it is prone towards not finding a solution at all.\n\nIn this task we will do a root-finding problem that illustrates both the advantage—that no derivatives are required—and the disadvantage—that the method often gives no answer. We will try to find intersection points of two Bézier curves.\n\n### Steffensen's method\n\nWe will be using the variant of Steffensen's method that employs Aitken's extrapolation. Aitken's extrapolation is illustrated by the following ATS function:\n\n```\nfun aitken\n (f : double -> double, (* function double to double *)\n p0 : double) (* initial fixed point estimate *)\n : double =\n let\n val p1 = f(p0)\n val p2 = f(p1)\n val p1m0 = p1 - p0\n in\n p0 - (p1m0 * p1m0) / (p2 - (2.0 * p1) + p0)\n end\n\n```\n\nThe return value is a function of \n\np\n0\n{\\displaystyle {\\displaystyle p0}}\n, \n\np\n1\n=\nf\n(\np\n0\n)\n{\\displaystyle {\\displaystyle p1=f(p0)}}\n, and \n\np\n2\n=\nf\n(\nf\n(\np\n0\n)\n)\n{\\displaystyle {\\displaystyle p2=f(f(p0))}}\n. What one is trying to find is a so-called fixed point of \n\nf\n{\\displaystyle {\\displaystyle f}}\n: a value of \n\np\n{\\displaystyle {\\displaystyle p}}\n such that \n\nf\n(\np\n)\n=\np\n{\\displaystyle {\\displaystyle f(p)=p}}\n. Our implementation of Steffensen's method will be to repeat Aitken's extrapolation until either a tolerance is satisfied or too many iterations have been executed:\n\n```\nfun steffensen_aitken (* finds fixed point p such that f(p) = p *)\n (f : double -> double, (* function double to double *)\n pinit : double, (* initial estimate *)\n tol : double, (* tolerance *)\n maxiter : int) (* maximum number of iterations *)\n : Option (double) = (* return a double, IF tolerance is met *)\n let\n var p0 : double = pinit\n var p : double = aitken (f, p0)\n var iter : int = 1 (* iteration counter *)\n in\n while (abs (p - p0) > tol andalso iter < maxiter)\n begin\n p0 := p;\n p := aitken (f, p0);\n iter := iter + 1\n end;\n if abs (p - p0) > tol then None () else Some (p)\n end\n\n```\n\nThe function `steffensen_aitken` will find a fixed point for us, but how can we use that to find a root? In particular, suppose one wants to find \n\nt\n{\\displaystyle {\\displaystyle t}}\n such that \n\ng\n(\nt\n)\n=\n0\n{\\displaystyle {\\displaystyle g(t)=0}}\n. Then what one can do (and what we will try to do) is find a fixed point \n\np\n{\\displaystyle {\\displaystyle p}}\n of \n\nf\n(\nt\n)\n=\ng\n(\nt\n)\n+\nt\n{\\displaystyle {\\displaystyle f(t)=g(t)+t}}\n. In that case, \n\np\n=\nf\n(\np\n)\n=\ng\n(\np\n)\n+\np\n{\\displaystyle {\\displaystyle p=f(p)=g(p)+p}}\n, and therefore \n\ng\n(\np\n)\n=\n0\n{\\displaystyle {\\displaystyle g(p)=0}}\n.\n\n### The problem we wish to solve\n\nSuppose we have two quadratic planar Bézier curves, with control points \n\n(\n−\n1\n,\n0\n)\n,\n(\n0\n,\n10\n)\n,\n(\n1\n,\n0\n)\n{\\displaystyle {\\displaystyle (-1,0),(0,10),(1,0)}}\n and \n\n(\n2\n,\n1\n)\n,\n(\n−\n8\n,\n2\n)\n,\n(\n2\n,\n3\n)\n{\\displaystyle {\\displaystyle (2,1),(-8,2),(2,3)}}\n, respectively. These two parabolas are shown in the following figure. As you can see, they intersect at four points.\n\nWe want to try to find the points of intersection.\n\nThe method we will use is *implicitization*. In this method, one first rewrites one of the curves as an implicit equation in \n\nx\n{\\displaystyle {\\displaystyle x}}\n and \n\ny\n{\\displaystyle {\\displaystyle y}}\n. For this we will use the parabola that is convex upwards: it has implicit equation \n\n5\n\nx\n\n2\n+\ny\n−\n5\n=\n0\n{\\displaystyle {\\displaystyle 5x^{2}+y-5=0}}\n. Then what one does is plug the parametric equations of the *other* curve into the implicit equation. The resulting equation is \n\n5\n(\nx\n(\nt\n)\n\n)\n\n2\n+\ny\n(\nt\n)\n−\n5\n=\n0\n{\\displaystyle {\\displaystyle 5(x(t))^{2}+y(t)-5=0}}\n, where \n\nt\n{\\displaystyle {\\displaystyle t}}\n is the independent parameter for the curve that is convex *leftwards*. After expansion, this will be a degree-4 equation in \n\nt\n{\\displaystyle {\\displaystyle t}}\n. Find its four roots and you have found the points of intersection of the two curves.\n\nThat is easier said than done.\n\nThere are excellent ways to solve this problem, but we will not be using those. Our purpose, after all, is to illustrate Steffensen's method: both its advantages and its drawbacks. Let us look at an advantage: to use Steffensen's method (which requires only function values, not derivatives), we do not actually have to expand that polynomial in \n\nt\n{\\displaystyle {\\displaystyle t}}\n. Instead, we can evaluate \n\nx\n(\nt\n)\n{\\displaystyle {\\displaystyle x(t)}}\n and \n\ny\n(\nt\n)\n{\\displaystyle {\\displaystyle y(t)}}\n and plug the resulting numbers into the implicit equation. What is more, we do not even need to write \n\nx\n(\nt\n)\n{\\displaystyle {\\displaystyle x(t)}}\n and \n\ny\n(\nt\n)\n{\\displaystyle {\\displaystyle y(t)}}\n as polynomials, but instead can evaluate them directly from their control points, using de Casteljau's algorithm:\n\n```\nfun de_casteljau\n (c0 : double, (* control point coordinates (one axis) *)\n c1 : double,\n c2 : double,\n t : double) (* the independent parameter *)\n : double = (* value of x(t) or y(t) *)\n let\n val s = 1.0 - t\n val c01 = (s * c0) + (t * c1)\n val c12 = (s * c1) + (t * c2)\n val c012 = (s * c01) + (t * c12)\n in\n c012\n end\n\nfun x_convex_left_parabola (t : double) : double =\n de_casteljau (2.0, ~8.0, 2.0, t)\n\nfun y_convex_left_parabola (t : double) : double =\n de_casteljau (1.0, 2.0, 3.0, t)\n\n```\n\nPlugging \n\nx\n(\nt\n)\n{\\displaystyle {\\displaystyle x(t)}}\n and \n\ny\n(\nt\n)\n{\\displaystyle {\\displaystyle y(t)}}\n into the implicit equation, and writing \n\nf\n(\nt\n)\n{\\displaystyle {\\displaystyle f(t)}}\n as the function whose fixed points are to be found:\n\n```\nfun implicit_equation (x : double, y : double) : double =\n (5.0 * x * x) + y - 5.0\n\nfun f (t : double) : double = (* find fixed points of this function *)\n let\n val x = x_convex_left_parabola (t)\n val y = y_convex_left_parabola (t)\n in\n implicit_equation (x, y) + t\n end\n\n```\n\nWhat is left to be done is simple, but tricky: use the `steffensen_aitken` function to find those fixed points. This is where a huge disadvantage of Steffensen's method (shared with Newton's method) will be illustrated. What is likely to happen is that only some of the intersection points will be found. Furthermore, for most of our initial estimates, Steffensen's method will not give us an answer at all.\n\n### The task\n\nUse the methods described above to try to find intersection points of the two parabolas. For initial estimates, use \n\np\ni\nn\ni\nt\n=\n\nt\n\n0\n=\n0.0\n,\n0.1\n,\n0.2\n,\n⋯\n,\n0.9\n,\n1.0\n{\\displaystyle {\\displaystyle {\\it {pinit}}=t\\_{0}=0.0,0.1,0.2,\\cdots ,0.9,1.0}}\n. Choose reasonable settings for tolerance and maximum iterations. (The ATS example has 0.00000001 and 1000, respectively.) For each initial estimate, if tolerance was not met before maximum iterations was reached, print that there was no answer. On the other hand, if there was an answer, plug the resulting value of \n\nt\n{\\displaystyle {\\displaystyle t}}\n into \n\nx\n(\nt\n)\n{\\displaystyle {\\displaystyle x(t)}}\n and \n\ny\n(\nt\n)\n{\\displaystyle {\\displaystyle y(t)}}\n to find the intersection point \n\n(\nx\n,\ny\n)\n{\\displaystyle {\\displaystyle (x,y)}}\n. Check that that this answer is correct, by plugging \n\n(\nx\n,\ny\n)\n{\\displaystyle {\\displaystyle (x,y)}}\n into the implicit equation. If it is not correct, print that Steffensen's method gave a spurious answer. Otherwise print the value of \n\n(\nx\n,\ny\n)\n{\\displaystyle {\\displaystyle (x,y)}}\n.\n\n(*The ATS example has purposely been written in a fashion to be readable as if it were pseudocode. You may use it as a reference implementation.*)\n\n### See also\n\n* Bézier curves/Intersections"
},
{
"role": "assistant",
"content": "**Translation of**: Go\n\n```\n# 20230928 Raku programming solution\n\nsub aitken($f, $p0) {\n my $p2 = $f( my $p1 = $f($p0) ); \n my $p1m0 = $p1 - $p0;\n return $p0 - $p1m0*$p1m0/($p2-2.0*$p1+$p0);\n}\n\nsub steffensenAitken($f, $pinit, $tol, $maxiter) {\n my ($iter, $p) = 1, aitken($f, my $p0 = $pinit);\n while abs($p-$p0) > $tol and $iter < $maxiter {\n $p = aitken($f, $p0 = $p);\n $iter++\n }\n return abs($p-$p0) > $tol ?? NaN !! $p\n}\n\nsub deCasteljau($c0, $c1, $c2, $t) {\n my $s = 1.0 - $t;\n return $s*($s*$c0 + $t*$c1) + $t*($s*$c1 + $t*$c2)\n}\n\nsub xConvexLeftParabola($t) { return deCasteljau(2.0, -8.0, 2.0, $t) }\n\nsub yConvexRightParabola($t) { return deCasteljau(1.0, 2.0, 3.0, $t) }\n\nsub implicitEquation($x, $y) { return 5.0*$x*$x + $y - 5.0 }\n\nsub f($t) {\n implicitEquation(xConvexLeftParabola($t), yConvexRightParabola($t)) + $t\n}\n\nmy $t0 = 0.0;\nfor ^11 {\n print \"t0 = {$t0.fmt: '%0.1f'} : \";\n my $t = steffensenAitken(&f, $t0, 0.00000001, 1000);\n if $t.isNaN {\n say \"no answer\";\n } else {\n my ($x, $y) = xConvexLeftParabola($t), yConvexRightParabola($t);\n if abs(implicitEquation($x, $y)) <= 0.000001 {\n printf \"intersection at (%f, %f)\\n\", $x, $y;\n } else {\n say \"spurious solution\";\n }\n }\n $t0 += 0.1;\n}\n\n```\n\nYou may Attempt This Online!"
}
]
|
[
{
"role": "user",
"content": "Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:\n\n> 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146\n\nThe primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.\n\nIf possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.\n\n**Note:** If you wish to try multiple data sets, you might try this generator."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Translation of**: Perl\n\nHandles negative stems properly.\n\n```\nmy @data = <\n 12 127 28 42 39 113 42 18 44 118 44\n 37 113 124 37 48 127 36 29 31 125 139\n 131 115 105 132 104 123 35 113 122 42 117\n 119 58 109 23 105 63 27 44 105 99 41\n 128 121 116 125 32 61 37 127 29 113 121\n 58 114 126 53 114 96 25 109 7 31 141\n 46 13 27 43 117 116 27 7 68 40 31\n 115 124 42 128 52 71 118 117 38 27 106\n 33 117 116 111 40 119 47 105 57 122 109\n 124 115 43 120 43 27 27 18 28 48 125\n 107 114 34 133 45 120 30 127 31 116 146\n>».Int.sort;\n \nmy Int $stem_unit = 10;\nmy %h = @data.classify: * div $stem_unit;\n \nmy $range = [minmax] %h.keys».Int;\nmy $stem_format = \"%{$range.min.chars max $range.max.chars}d\";\n \nfor $range.list -> $stem {\n my $leafs = %h{$stem} // [];\n say $stem.fmt($stem_format), ' | ', ~$leafs.map: * % $stem_unit;\n}\n\n```\n\nOutput:\n\n```\n 0 | 7 7\n 1 | 2 3 8 8\n 2 | 3 5 7 7 7 7 7 7 8 8 9 9\n 3 | 0 1 1 1 1 2 3 4 5 6 7 7 7 8 9\n 4 | 0 0 1 2 2 2 2 3 3 3 4 4 4 5 6 7 8 8\n 5 | 2 3 7 8 8\n 6 | 1 3 8\n 7 | 1\n 8 | \n 9 | 6 9\n10 | 4 5 5 5 5 6 7 9 9 9\n11 | 1 3 3 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 8 9 9\n12 | 0 0 1 1 2 2 3 4 4 4 5 5 5 6 7 7 7 7 8 8\n13 | 1 2 3 9\n14 | 1 6\n```"
}
]
|
[
{
"role": "user",
"content": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.\n\n1. The first and second members of the sequence are both 1:\n * 1, 1\n2. Start by considering the second member of the sequence\n3. Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n * 1, 1, 2\n4. Append the considered member of the sequence to the end of the sequence:\n * 1, 1, 2, 1\n5. Consider the next member of the series, (the third member i.e. 2)\n6. GOTO 3\n\n * ─── Expanding another loop we get: ───\n7. Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n * 1, 1, 2, 1, 3\n8. Append the considered member of the sequence to the end of the sequence:\n * 1, 1, 2, 1, 3, 2\n9. Consider the next member of the series, (the fourth member i.e. 1)\n\nThe task is to\n\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\nRelated tasks\n: * Fusc sequence.\n * Continued fraction/Arithmetic\n\nRef\n\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: rakudo version 2017-03\n\n```\nconstant @Stern-Brocot = 1, 1, { |(@_[$_ - 1] + @_[$_], @_[$_]) given ++$ } ... *;\n \nput @Stern-Brocot[^15];\n \nfor flat 1..10, 100 -> $ix {\n say \"First occurrence of {$ix.fmt('%3d')} is at index: {([email protected]($ix, :k)).fmt('%4d')}\";\n}\n \nsay so 1 == all map ^1000: { [gcd] @Stern-Brocot[$_, $_ + 1] }\n\n```\n\nOutput:\n\n```\n1 1 2 1 3 2 3 1 4 3 5 2 5 3 4\nFirst occurrence of 1 is at index: 1\nFirst occurrence of 2 is at index: 3\nFirst occurrence of 3 is at index: 5\nFirst occurrence of 4 is at index: 9\nFirst occurrence of 5 is at index: 11\nFirst occurrence of 6 is at index: 33\nFirst occurrence of 7 is at index: 19\nFirst occurrence of 8 is at index: 21\nFirst occurrence of 9 is at index: 35\nFirst occurrence of 10 is at index: 39\nFirst occurrence of 100 is at index: 1179\nTrue\n```"
}
]
|
[
{
"role": "user",
"content": "Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number\nof cycles (counting fixed points as cycles of length one).\n\nThey may be defined directly to be the number of permutations of **n**\nelements with **k** disjoint cycles.\n\nStirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.\n\nDepending on the application, Stirling numbers of the first kind may be \"signed\"\nor \"unsigned\". Signed Stirling numbers of the first kind arise when the\npolynomial expansion is expressed in terms of falling factorials; unsigned when\nexpressed in terms of rising factorials. The only substantial difference is that,\nfor signed Stirling numbers of the first kind, values of S1(n, k) are negative\nwhen n + k is odd.\n\nStirling numbers of the first kind follow the simple identities:\n\n```\n S1(0, 0) = 1\n S1(n, 0) = 0 if n > 0\n S1(n, k) = 0 if k > n\n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned\n or\n S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed\n\n```\n\nTask\n\n: * Write a routine (function, procedure, whatever) to find **Stirling numbers of the first kind**. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n: * Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, **S1(n, k)**, up to **S1(12, 12)**. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.\n\n: * If your language supports large integers, find and show here, on this page, the maximum value of **S1(n, k)** where **n == 100**.\n\nSee also\n\n: * **Wikipedia - Stirling numbers of the first kind**\n * **OEIS:A008275 - Signed Stirling numbers of the first kind**\n * **OEIS:A130534 - Unsigned Stirling numbers of the first kind**\n\nRelated Tasks\n\n: * **Stirling numbers of the second kind**\n * **Lah numbers**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n```\nsub Stirling1 (Int \\n, Int \\k) {\n return 1 unless n || k;\n return 0 unless n && k;\n state %seen;\n (%seen{\"{n - 1}|{k - 1}\"} //= Stirling1(n - 1, k - 1)) +\n (n - 1) * (%seen{\"{n - 1}|{k}\"} //= Stirling1(n - 1, k))\n}\n\nmy $upto = 12;\n\nmy $mx = (1..^$upto).map( { Stirling1($upto, $_) } ).max.chars;\n\nput 'Unsigned Stirling numbers of the first kind: S1(n, k):';\nput 'n\\k', (0..$upto)».fmt: \"%{$mx}d\";\n\nfor 0..$upto -> $row {\n $row.fmt('%-3d').print;\n put (0..$row).map( { Stirling1($row, $_) } )».fmt: \"%{$mx}d\";\n}\n\nsay \"\\nMaximum value from the S1(100, *) row:\";\nsay (^100).map( { Stirling1 100, $_ } ).max;\n\n```\n\nOutput:\n\n```\nUnsigned Stirling numbers of the first kind: S1(n, k):\nn\\k 0 1 2 3 4 5 6 7 8 9 10 11 12\n0 1\n1 0 1\n2 0 1 1\n3 0 2 3 1\n4 0 6 11 6 1\n5 0 24 50 35 10 1\n6 0 120 274 225 85 15 1\n7 0 720 1764 1624 735 175 21 1\n8 0 5040 13068 13132 6769 1960 322 28 1\n9 0 40320 109584 118124 67284 22449 4536 546 36 1\n10 0 362880 1026576 1172700 723680 269325 63273 9450 870 45 1\n11 0 3628800 10628640 12753576 8409500 3416930 902055 157773 18150 1320 55 1\n12 0 39916800 120543840 150917976 105258076 45995730 13339535 2637558 357423 32670 1925 66 1\n\nMaximum value from the S1(100, *) row:\n19710908747055261109287881673376044669240511161402863823515728791076863288440277983854056472903481625299174865860036734731122707870406148096000000000000000000\n```"
}
]
|
[
{
"role": "user",
"content": "Stirling numbers of the second kind, or Stirling partition numbers, are the\nnumber of ways to partition a set of n objects into k non-empty subsets. They are\nclosely related to Bell numbers, and may be derived from them.\n\nStirling numbers of the second kind obey the recurrence relation:\n\n```\n S2(n, 0) and S2(0, k) = 0 # for n, k > 0\n S2(n, n) = 1\n S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)\n\n```\n\nTask\n\n: * Write a routine (function, procedure, whatever) to find **Stirling numbers of the second kind**. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n: * Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, **S2(n, k)**, up to **S2(12, 12)**. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).\n\n: * If your language supports large integers, find and show here, on this page, the maximum value of **S2(n, k)** where **n == 100**.\n\nSee also\n\n: * **Wikipedia - Stirling numbers of the second kind**\n * **OEIS:A008277 - Stirling numbers of the second kind**\n\nRelated Tasks\n\n: * **Stirling numbers of the first kind**\n * **Bell numbers**\n * **Lah numbers**"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2019.07.1\n\n```\nsub Stirling2 (Int \\n, Int \\k) {\n ((1,), { (0, |@^last) »+« (|(@^last »*« @^last.keys), 0) } … *)[n;k]\n}\n\nmy $upto = 12;\n\nmy $mx = (1..^$upto).map( { Stirling2($upto, $_) } ).max.chars;\n\nput 'Stirling numbers of the second kind: S2(n, k):';\nput 'n\\k', (0..$upto)».fmt: \"%{$mx}d\";\n\nfor 0..$upto -> $row {\n $row.fmt('%-3d').print;\n put (0..$row).map( { Stirling2($row, $_) } )».fmt: \"%{$mx}d\";\n}\n\nsay \"\\nMaximum value from the S2(100, *) row:\";\nsay (^100).map( { Stirling2 100, $_ } ).max;\n\n```\n\nOutput:\n\n```\nStirling numbers of the second kind: S2(n, k):\nn\\k 0 1 2 3 4 5 6 7 8 9 10 11 12\n0 1\n1 0 1\n2 0 1 1\n3 0 1 3 1\n4 0 1 7 6 1\n5 0 1 15 25 10 1\n6 0 1 31 90 65 15 1\n7 0 1 63 301 350 140 21 1\n8 0 1 127 966 1701 1050 266 28 1\n9 0 1 255 3025 7770 6951 2646 462 36 1\n10 0 1 511 9330 34105 42525 22827 5880 750 45 1\n11 0 1 1023 28501 145750 246730 179487 63987 11880 1155 55 1\n12 0 1 2047 86526 611501 1379400 1323652 627396 159027 22275 1705 66 1\n\nMaximum value from the S2(100, *) row:\n7769730053598745155212806612787584787397878128370115840974992570102386086289805848025074822404843545178960761551674\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nImplement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.\n\nNumbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.03\n\nThe .trans method in Raku improves on Perl 5's tr/// by allowing multi-character translation tables.\n\nWe build the full table during .new, which simplifies .encode and .decode.\n\n```\nclass Straddling_Checkerboard {\n has @!flat_board; # 10x3 stored as 30x1\n has $!plain2code; # full translation table, invertable\n has @!table; # Printable layout, like Wikipedia entry\n \n my $numeric_escape = '/';\n my $exclude = /<-[A..Z0..9.]>/; # Omit the escape character\n\n method display_table { gather { take ~ .list for @!table } };\n\n method decode ( Str $s --> Str ) {\n $s.trans($!plain2code.antipairs);\n }\n\n method encode ( Str $s, :$collapse? --> Str ) {\n my $replace = $collapse ?? '' !! '.';\n $s.uc.subst( $exclude, $replace, :g ).trans($!plain2code);\n }\n\n submethod BUILD ( :$alphabet, :$u where 0..9, :$v where 0..9 ) {\n die if $u == $v;\n die if $alphabet.comb.sort.join ne [~] flat './', 'A'..'Z';\n\n @!flat_board = $alphabet.uc.comb;\n @!flat_board.splice( $u min $v, 0, Any );\n @!flat_board.splice( $u max $v, 0, Any );\n\n @!table = [ ' ',| [ 0 .. 9] ],\n [ ' ',|@!flat_board[ 0 .. 9].map: {.defined ?? $_ !! ' '} ],\n [ $u, |@!flat_board[10 .. 19] ],\n [ $v, |@!flat_board[20 .. 29] ];\n\n my @order = 0..9; # This may be passed as a param in the future\n\n my @nums = flat @order,\n @order.map({ +\"$u$_\" }),\n @order.map({ +\"$v$_\" });\n\n my %c2p = @nums Z=> @!flat_board;\n %c2p{$_}:delete if %c2p{$_} eqv Any for keys %c2p;\n my %p2c = %c2p.invert;\n %p2c{$_} = %p2c{$numeric_escape} ~ $_ for 0..9;\n $!plain2code = [%p2c.keys] => [%p2c.values];\n }\n}\n\nsub MAIN ( :$u = 3, :$v = 7, :$alphabet = 'HOLMESRTABCDFGIJKNPQUVWXYZ./' ) {\n my Straddling_Checkerboard $sc .= new: :$u, :$v, :$alphabet;\n $sc.display_table;\n\n for 0..1 -> $collapse {\n my $original = 'One night-it was on the twentieth of March, 1888-I was returning';\n my $en = $sc.encode($original, :$collapse);\n my $de = $sc.decode($en);\n say '';\n say \"Original: $original\";\n say \"Encoded: $en\";\n say \"Decoded: $de\";\n }\n}\n\n```\n\nOutput:\n\n```\n 0 1 2 3 4 5 6 7 8 9\n H O L M E S R T\n3 A B C D F G I J K N\n7 P Q U V W X Y Z . /\n\nOriginal: One night-it was on the twentieth of March, 1888-I was returning\nEncoded: 13957839363509783697874306781397890578974539936590781347843083207878791798798798783678743067885972839363935\nDecoded: ONE.NIGHT.IT.WAS.ON.THE.TWENTIETH.OF.MARCH..1888.I.WAS.RETURNING\n\nOriginal: One night-it was on the twentieth of March, 1888-I was returning\nEncoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935\nDecoded: ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING\n```"
}
]
|
[
{
"role": "user",
"content": "Definition\n\n**n** is a **strange number** (expressed in base ten) if every adjacent decimal digit differs from its neighbour by a prime number.\n\nTask\n\nShow all strange numbers for 100 < **n** < 500\n\nStretch goal\n\nShow the number of 10-digit strange numbers that begin with 1"
},
{
"role": "assistant",
"content": "```\nsub infix:<′>(\\x,\\y) { abs(x - y) ∈ (2, 3, 5, 7) }\n\nmy ($low,$high) = 100, 500;\nmy @strange.push: $_ if so all .comb.rotor(2 => -1).map: { .[0] ′ .[1] } for $low ^..^ $high;\n\nsay \"Between $low and $high there are {+@strange} strange numbers:\\n\";\nprint @strange.batch(20)».fmt(\"%4d\").join: \"\\n\";\n\n```\n\nOutput:\n\n```\nBetween 100 and 500 there are 87 strange numbers:\n\n 130 131 135 136 138 141 142 146 147 149 161 163 164 168 169 181 183 185 186 202\n 203 205 207 241 242 246 247 249 250 252 253 257 258 270 272 274 275 279 292 294\n 296 297 302 303 305 307 313 314 316 318 350 352 353 357 358 361 363 364 368 369\n 381 383 385 386 413 414 416 418 420 424 425 427 429 461 463 464 468 469 470 472\n 474 475 479 492 494 496 497\n```"
}
]
|
[
{
"role": "user",
"content": "**n** is a **strange plus number** if the sum of the first two digits is prime and the sum of the second two digits is also prime.\n\nWhere 100 < **n** < 500\n\nRelated task\n\n* Strange\\_numbers"
},
{
"role": "assistant",
"content": "```\nunit sub MAIN ($start = 100, $end = 500);\nput +$_, \" matching numbers from $start to $end:\\n\", $_ given\n ($start .. $end).hyper(:256batch,:8degree).grep: { all .comb.rotor(2 => -1).map: { .sum.is-prime } };\n\n```\n\nOutput:\n\n```\n65 matching numbers from 100 to 500:\n111 112 114 116 120 121 123 125 129 141 143 147 149 161 165 167 202 203 205 207 211 212 214 216 230 232 234 238 250 252 256 258 292 294 298 302 303 305 307 320 321 323 325 329 341 343 347 349 383 385 389 411 412 414 416 430 432 434 438 470 474 476 492 494 498\n```"
}
]
|
[
{
"role": "user",
"content": "Primes **n, m,** and **p** are *strange unique primes* if **n, m,** and **p** are unique and their sum **n + m + p** is also prime. Assume **n** < **m** < **p**.\n\nTask\n: * Find all triplets of strange unique primes in which **n, m,** and **p** are all less than **30**.\n * (stretch goal) Show the count (only) of all the triplets of strange unique primes in which **n, m,** and **p** are all less than **1,000**."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\n# 20210312 Raku programming solution\n\nfor 30, 1000 -> \\k {\n given (2..k).grep(*.is-prime).combinations(3).grep(*.sum.is-prime) {\n say \"Found \", +$_, \" strange unique prime triplets up to \", k\n }\n}\n\n```\n\nOutput:\n\n```\nFound 42 strange unique prime triplets up to 30\nFound 241580 strange unique prime triplets up to 1000\n\n```"
}
]
|
[
{
"role": "user",
"content": "Description\n\nIn linear algebra, the Strassen algorithm (named after Volker Strassen), is an algorithm for matrix multiplication.\n\nIt is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices, but would be slower than the fastest known algorithms for extremely large matrices.\n\nTask\n\nWrite a routine, function, procedure etc. in your language to implement the Strassen algorithm for matrix multiplication.\n\nWhile practical implementations of Strassen's algorithm usually switch to standard methods of matrix multiplication for small enough sub-matrices (currently anything less than 512×512 according to Wikipedia), for the purposes of this task you should not switch until reaching a size of 1 or 2.\n\nRelated task\n: * Matrix multiplication\n\nSee also\n: * Wikipedia article"
},
{
"role": "assistant",
"content": "Special thanks go to the module author, Fernando Santagata, on showing how to deal with a pass-by-value case.\n\n**Translation of**: Julia\n\n```\n# 20210126 Raku programming solution\n\nuse Math::Libgsl::Constants;\nuse Math::Libgsl::Matrix;\nuse Math::Libgsl::BLAS;\n \nmy @M;\n \nsub SQM (\\in) { # create custom sq matrix from CSV \n die \"Not a ■\" if (my \\L = in.split(/\\,/)).sqrt != (my \\size = L.sqrt.Int);\n my Math::Libgsl::Matrix \\M .= new: size, size;\n for ^size Z L.rotor(size) -> ($i, @row) { M.set-row: $i, @row } \n M\n}\n \nsub infix:<⊗>(\\x,\\y) { # custom multiplication \n my Math::Libgsl::Matrix \\z .= new: x.size1, x.size2;\n dgemm(CblasNoTrans, CblasNoTrans, 1, x, y, 1, z);\n z\n}\n \nsub infix:<⊕>(\\x,\\y) { # custom addition\n my Math::Libgsl::Matrix \\z .= new: x.size1, x.size2;\n z.copy(x).add(y) \n}\n \nsub infix:<⊖>(\\x,\\y) { # custom subtraction\n my Math::Libgsl::Matrix \\z .= new: x.size1, x.size2;\n z.copy(x).sub(y)\n}\n \nsub Strassen($A, $B) {\n \n { return $A ⊗ $B } if (my \\n = $A.size1) == 1;\n \n my Math::Libgsl::Matrix ($A11,$A12,$A21,$A22,$B11,$B12,$B21,$B22); \n my Math::Libgsl::Matrix ($P1,$P2,$P3,$P4,$P5,$P6,$P7);\n my Math::Libgsl::Matrix::View ($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8);\n ($mv1,$mv2,$mv3,$mv4,$mv5,$mv6,$mv7,$mv8)».=new ;\n\n my \\half = n div 2; # dimension of quarter submatrices \n\n $A11 = $mv1.submatrix($A, 0,0, half,half); # \n $A12 = $mv2.submatrix($A, 0,half, half,half); # create quarter views \n $A21 = $mv3.submatrix($A, half,0, half,half); # of operand matrices \n $A22 = $mv4.submatrix($A, half,half, half,half); # \n $B11 = $mv5.submatrix($B, 0,0, half,half); # 11 12 \n $B12 = $mv6.submatrix($B, 0,half, half,half); # \n $B21 = $mv7.submatrix($B, half,0, half,half); # 21 22 \n $B22 = $mv8.submatrix($B, half,half, half,half); # \n \n $P1 = Strassen($A12 ⊖ $A22, $B21 ⊕ $B22);\n $P2 = Strassen($A11 ⊕ $A22, $B11 ⊕ $B22);\n $P3 = Strassen($A11 ⊖ $A21, $B11 ⊕ $B12);\n $P4 = Strassen($A11 ⊕ $A12, $B22 );\n $P5 = Strassen($A11, $B12 ⊖ $B22);\n $P6 = Strassen($A22, $B21 ⊖ $B11);\n $P7 = Strassen($A21 ⊕ $A22, $B11 );\n \n my Math::Libgsl::Matrix $C .= new: n, n; # Build C from\n my Math::Libgsl::Matrix::View ($mvC11,$mvC12,$mvC21,$mvC22); # C11 C12\n ($mvC11,$mvC12,$mvC21,$mvC22)».=new ; # C21 C22\n\n given $mvC11.submatrix($C, 0,0, half,half) { .add: (($P1 ⊕ $P2) ⊖ $P4) ⊕ $P6 }; \n given $mvC12.submatrix($C, 0,half, half,half) { .add: $P4 ⊕ $P5 };\n given $mvC21.submatrix($C, half,0, half,half) { .add: $P6 ⊕ $P7 };\n given $mvC22.submatrix($C, half,half, half,half) { .add: (($P2 ⊖ $P3) ⊕ $P5) ⊖ $P7 };\n\n $C \n}\n \nfor $=pod[0].contents { next if /^\\n$/ ; @M.append: SQM $_ }\n \nfor @M.rotor(2) { \n my $product = @_[0] ⊗ @_[1];\n# $product.get-row($_)».round(1).fmt('%2d').put for ^$product.size1;\n \n say \"Regular multiply:\";\n $product.get-row($_)».fmt('%.10g').put for ^$product.size1;\n \n $product = Strassen @_[0], @_[1];\n \n say \"Strassen multiply:\";\n $product.get-row($_)».fmt('%.10g').put for ^$product.size1;\n} \n \n=begin code \n1,2,3,4\n5,6,7,8\n1,1,1,1,2,4,8,16,3,9,27,81,4,16,64,256\n4,-3,4/3,-1/4,-13/3,19/4,-7/3,11/24,3/2,-2,7/6,-1/4,-1/6,1/4,-1/6,1/24\n1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16\n1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1\n=end code\n\n```\n\nOutput:\n\n```\nRegular multiply:\n19 22\n43 50\nStrassen multiply:\n19 22\n43 50\nRegular multiply:\n1 0 -1.387778781e-16 -2.081668171e-17\n1.33226763e-15 1 -4.440892099e-16 -1.110223025e-16\n0 0 1 0\n7.105427358e-15 0 7.105427358e-15 1\nStrassen multiply:\n1 5.684341886e-14 -2.664535259e-15 -1.110223025e-16\n-1.136868377e-13 1 -7.105427358e-15 2.220446049e-15\n0 0 1 5.684341886e-14\n0 0 -2.273736754e-13 1\nRegular multiply:\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\nStrassen multiply:\n1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n```"
}
]
|
[
{
"role": "user",
"content": "2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n*N*-stream merge\n: The same as above, but reading from ***N*** sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n**Works with**: Rakudo version 2018.02\n\n```\nsub merge_streams ( @streams ) {\n my @s = @streams.map({ hash( STREAM => $_, HEAD => .get ) })\\\n .grep({ .<HEAD>.defined });\n\n return gather while @s {\n my $h = @s.min: *.<HEAD>;\n take $h<HEAD>;\n $h<HEAD> := $h<STREAM>.get\n orelse @s .= grep( { $_ !=== $h } );\n }\n}\n\nsay merge_streams([ @*ARGS».&open ]);\n\n```"
}
]
|
[
{
"role": "user",
"content": "Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.\n\nTask\n\nCreate a string variable equal to any text value.\n\nAppend the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.\n\nShow the contents of the variable after the append operation."
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\n```\nmy $str = \"foo\";\n$str ~= \"bar\";\nsay $str;\n\n```\n\nOutput:\n\n```\nfoobar\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nTake the string **alphaBETA** and demonstrate how to convert it to:\n\n: : : * upper-case and\n * lower-case\n\nUse the default encoding of a string literal or plain ASCII if there is no string literal in your language.\n\nNote: In some languages alphabets toLower and toUpper is not reversable.\n\nShow any additional case conversion functions (e.g. swapping case, capitalizing the first letter, etc.) that may be included in the library of your language.\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)\nIn Raku, case modification is implemented as builtin subroutine or method:\n\n```\nmy $word = \"alpha BETA\" ;\nsay uc $word; # all uppercase (subroutine call)\nsay $word.uc; # all uppercase (method call)\n# from now on we use only method calls as examples\nsay $word.lc; # all lowercase\nsay $word.tc; # first letter titlecase\nsay $word.tclc; # first letter titlecase, rest lowercase\nsay $word.wordcase; # capitalize each word\n```\n\nOutput:\n\n```\nALPHA BETA\nalpha beta\nAlpha BETA\nAlpha beta\nAlpha Beta\n```"
}
]
|
[
{
"role": "user",
"content": "Task\n\nDemonstrate how to compare two strings from within the language and how to achieve a lexical comparison.\n\nThe task should demonstrate:\n\n* Comparing two strings for exact equality\n* Comparing two strings for inequality (i.e., the inverse of exact equality)\n* Comparing two strings to see if one is lexically ordered before than the other\n* Comparing two strings to see if one is lexically ordered after than the other\n* How to achieve both case sensitive comparisons and case insensitive comparisons within the language\n* How the language handles comparison of numeric strings if these are not treated lexically\n* Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system.\n\nFor example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction.\n\nHere \"generic/polymorphic\" comparison means that the function or operator you're using doesn't always do string comparison, but bends the actual semantics of the comparison depending on the types one or both arguments; with such an operator, you achieve string comparison only if the arguments are sufficiently string-like in type or appearance.\n\nIn contrast, a \"coercive/allomorphic\" comparison function or operator has fixed string-comparison semantics regardless of the argument type; instead of the operator bending, it's the arguments that are forced to bend instead and behave like strings if they can, and the operator simply fails if the arguments cannot be viewed somehow as strings. A language may have one or both of these kinds of operators; see the Raku entry for an example of a language with both kinds of operators.\n\nOther tasks related to string operations:\n\nMetrics\n\n* Array length\n* String length\n* Copy a string\n* Empty string (assignment)\n\nCounting\n\n* Word frequency\n* Letter frequency\n* Jewels and stones\n* I before E except after C\n* Bioinformatics/base count\n* Count occurrences of a substring\n* Count how many vowels and consonants occur in a string\n\nRemove/replace\n\n* XXXX redacted\n* Conjugate a Latin verb\n* Remove vowels from a string\n* String interpolation (included)\n* Strip block comments\n* Strip comments from a string\n* Strip a set of characters from a string\n* Strip whitespace from a string -- top and tail\n* Strip control codes and extended characters from a string\n\nAnagrams/Derangements/shuffling\n\n* Word wheel\n* ABC problem\n* Sattolo cycle\n* Knuth shuffle\n* Ordered words\n* Superpermutation minimisation\n* Textonyms (using a phone text pad)\n* Anagrams\n* Anagrams/Deranged anagrams\n* Permutations/Derangements\n\nFind/Search/Determine\n\n* ABC words\n* Odd words\n* Word ladder\n* Semordnilap\n* Word search\n* Wordiff (game)\n* String matching\n* Tea cup rim text\n* Alternade words\n* Changeable words\n* State name puzzle\n* String comparison\n* Unique characters\n* Unique characters in each string\n* Extract file extension\n* Levenshtein distance\n* Palindrome detection\n* Common list elements\n* Longest common suffix\n* Longest common prefix\n* Compare a list of strings\n* Longest common substring\n* Find common directory path\n* Words from neighbour ones\n* Change e letters to i in words\n* Non-continuous subsequences\n* Longest common subsequence\n* Longest palindromic substrings\n* Longest increasing subsequence\n* Words containing \"the\" substring\n* Sum of the digits of n is substring of n\n* Determine if a string is numeric\n* Determine if a string is collapsible\n* Determine if a string is squeezable\n* Determine if a string has all unique characters\n* Determine if a string has all the same characters\n* Longest substrings without repeating characters\n* Find words which contains all the vowels\n* Find words which contain the most consonants\n* Find words which contains more than 3 vowels\n* Find words whose first and last three letters are equal\n* Find words with alternating vowels and consonants\n\nFormatting\n\n* Substring\n* Rep-string\n* Word wrap\n* String case\n* Align columns\n* Literals/String\n* Repeat a string\n* Brace expansion\n* Brace expansion using ranges\n* Reverse a string\n* Phrase reversals\n* Comma quibbling\n* Special characters\n* String concatenation\n* Substring/Top and tail\n* Commatizing numbers\n* Reverse words in a string\n* Suffixation of decimal numbers\n* Long literals, with continuations\n* Numerical and alphabetical suffixes\n* Abbreviations, easy\n* Abbreviations, simple\n* Abbreviations, automatic\n\nSong lyrics/poems/Mad Libs/phrases\n\n* Mad Libs\n* Magic 8-ball\n* 99 bottles of beer\n* The Name Game (a song)\n* The Old lady swallowed a fly\n* The Twelve Days of Christmas\n\nTokenize\n\n* Text between\n* Tokenize a string\n* Word break problem\n* Tokenize a string with escaping\n* Split a character string based on change of character\n\nSequences\n\n* Show ASCII table\n* De Bruijn sequences\n* Summarize and say sequence\n* Generate lower case ASCII alphabet"
},
{
"role": "assistant",
"content": "(formerly Perl 6)\n\nRaku uses strong typing dynamically (and gradual typing statically), but normal string and numeric comparisons are coercive. (You may use generic comparison operators if you want polymorphic comparison—but usually you don't. :)\n\nString comparisons never do case folding because that's a very complicated subject in the modern world of Unicode. (You can explicitly apply an appropriate case-folding function to the arguments before doing the comparison, or for \"equality\" testing you can do matching with a case-insensitive regex, assuming Unicode's language-neutral case-folding rules are okay.)\n\n```\nsub compare($a,$b) {\n my $A = \"{$a.WHAT.^name} '$a'\";\n my $B = \"{$b.WHAT.^name} '$b'\";\n\n if $a eq $b { say \"$A and $B are lexically equal\" }\n if $a ne $b { say \"$A and $B are not lexically equal\" }\n\n if $a gt $b { say \"$A is lexically after $B\" }\n if $a lt $b { say \"$A is lexically before than $B\" }\n\n if $a ge $b { say \"$A is not lexically before $B\" }\n if $a le $b { say \"$A is not lexically after $B\" }\n\n if $a === $b { say \"$A and $B are identical objects\" }\n if $a !=== $b { say \"$A and $B are not identical objects\" }\n\n if $a eqv $b { say \"$A and $B are generically equal\" }\n if $a !eqv $b { say \"$A and $B are not generically equal\" }\n\n if $a before $b { say \"$A is generically after $B\" }\n if $a after $b { say \"$A is generically before $B\" }\n\n if $a !after $b { say \"$A is not generically before $B\" }\n if $a !before $b { say \"$A is not generically after $B\" }\n\n say \"The lexical relationship of $A and $B is { $a leg $b }\" if $a ~~ Stringy;\n say \"The generic relationship of $A and $B is { $a cmp $b }\";\n say \"The numeric relationship of $A and $B is { $a <=> $b }\" if $a ~~ Numeric;\n say '';\n}\n\ncompare 'YUP', 'YUP';\ncompare 'BALL', 'BELL';\ncompare 24, 123;\ncompare 5.1, 5;\ncompare 5.1e0, 5 + 1/10;\n\n```\n\nOutput:\n\n```\nStr 'YUP' and Str 'YUP' are lexically equal\nStr 'YUP' is not lexically before Str 'YUP'\nStr 'YUP' is not lexically after Str 'YUP'\nStr 'YUP' and Str 'YUP' are identical objects\nStr 'YUP' and Str 'YUP' are generically equal\nStr 'YUP' is not generically before Str 'YUP'\nStr 'YUP' is not generically after Str 'YUP'\nThe lexical relationship of Str 'YUP' and Str 'YUP' is Same\nThe generic relationship of Str 'YUP' and Str 'YUP' is Same\n\nStr 'BALL' and Str 'BELL' are not lexically equal\nStr 'BALL' is lexically before than Str 'BELL'\nStr 'BALL' is not lexically after Str 'BELL'\nStr 'BALL' and Str 'BELL' are not identical objects\nStr 'BALL' and Str 'BELL' are not generically equal\nStr 'BALL' is generically after Str 'BELL'\nStr 'BALL' is not generically before Str 'BELL'\nThe lexical relationship of Str 'BALL' and Str 'BELL' is Increase\nThe generic relationship of Str 'BALL' and Str 'BELL' is Increase\n\nInt '24' and Int '123' are not lexically equal\nInt '24' is lexically after Int '123'\nInt '24' is not lexically before Int '123'\nInt '24' and Int '123' are not identical objects\nInt '24' and Int '123' are not generically equal\nInt '24' is generically after Int '123'\nInt '24' is not generically before Int '123'\nThe generic relationship of Int '24' and Int '123' is Increase\nThe numeric relationship of Int '24' and Int '123' is Increase\n\nRat '5.1' and Int '5' are not lexically equal\nRat '5.1' is lexically after Int '5'\nRat '5.1' is not lexically before Int '5'\nRat '5.1' and Int '5' are not identical objects\nRat '5.1' and Int '5' are not generically equal\nRat '5.1' is generically before Int '5'\nRat '5.1' is not generically after Int '5'\nThe generic relationship of Rat '5.1' and Int '5' is Decrease\nThe numeric relationship of Rat '5.1' and Int '5' is Decrease\n\nNum '5.1' and Rat '5.1' are lexically equal\nNum '5.1' is not lexically before Rat '5.1'\nNum '5.1' is not lexically after Rat '5.1'\nNum '5.1' and Rat '5.1' are not identical objects\nNum '5.1' and Rat '5.1' are not generically equal\nNum '5.1' is not generically before Rat '5.1'\nNum '5.1' is not generically after Rat '5.1'\nThe generic relationship of Num '5.1' and Rat '5.1' is Same\nThe numeric relationship of Num '5.1' and Rat '5.1' is Same\n```\n\n### Unicode normalization by default\n\nBe aware that Raku applies normalization (Unicode NFC form (Normalization Form Canonical)) by default to all input and output except for file names See docs. Raku follows the Unicode spec. Raku follows **all** of the Unicode spec, including parts that some people don't like. There are some graphemes for which the Unicode consortium has specified that the NFC form is a different (though usually visually identical) grapheme. Referred to in Unicode standard annex #15 as **Canonical Equivalence**. Raku adheres to that spec.\n\nOne that people seem to get hung up on is the Kelvin symbol \"K\" getting automatically converted to ASCII uppercase \"K\".\n\n```\nsay \"\\c[KELVIN SIGN]\".uniname;\n# => LATIN CAPITAL LETTER K\n\nmy $kelvin = \"\\c[KELVIN SIGN]\";\nmy $k = \"\\c[LATIN CAPITAL LETTER K]\";\nsay ($kelvin eq $k); # True, lexically equal\nsay ($kelvin eqv $k); # True, generically equal\nsay ($kelvin === $k); # True, identical objects\n\n```\n\nIn most programming language the previous two objects wouldn't be equivalent, but since Raku follows the Unicode specification, and normalization is applied automatically, they show up as equivalent.\n\nIt's officially identified as a possible trap for string handling. See docs."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.