[User]
Task

Sort the most popular computer programming languages based in number of members in Rosetta Code categories.

Sample output on 02 August 2022 at 09:50 +02

```
Rank:  1 (1,565 entries) Phix
Rank:  2 (1,558 entries) Wren
Rank:  3 (1,531 entries) Julia
Rank:  4 (1,507 entries) Raku
Rank:  5 (1,500 entries) Go
Rank:  6 (1,466 entries) Perl
Rank:  7 (1,409 entries) Python
Rank:  8 (1,402 entries) Nim
Rank:  9 (1,254 entries) J
Rank: 10 (1,211 entries) C
...
```

Notes

* Each language typically demonstrates one or two methods of accessing the data:

:   :   :   * with web scraping   (via http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000)
            * with the API method   (examples below for Awk, Perl, Ruby, Tcl, etc).

* The scraping and API solutions can be separate subsections, see the Tcl example.
* Filtering wrong results is optional.   You can check against Special:MostLinkedCategories (if using web scraping)

:   :   If you use the API, and do elect to filter, you may check your results against this complete, accurate, sortable, wikitable listing of all **971** programming languages, updated periodically, *typically weekly*.

* A complete ranked listing of all   **813**   languages (from the REXX example) is included here   ──►   output from the REXX program.

[Assistant]
(formerly Perl 6)

### Raku: Using the API

Note that this counts **only** the tasks. It does not include other non-task categories in the counts yielding more realistic, non-inflated numbers. Raku is Unicode aware and handles non-ASCII names natively. This does not attempt to 'unify' different language names that are the same behind the scenes as a result of Rosettacodes' capitalization peculiarities. (E.G. μC++, UC++ & ΜC++)

```
use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Sort::Naturally;

my $client = HTTP::UserAgent.new;

my $url = 'https://rosettacode.org/w';

my $tablefile = './RC_Popularity.txt';

my %cat = (
    'Programming_Tasks' => 'Task',
    'Draft_Programming_Tasks' => 'Draft'
);
my %tasks;

for %cat.keys.sort -> $cat {
    mediawiki-query(
        $url, 'pages',
        :generator<categorymembers>,
        :gcmtitle("Category:$cat"),
        :gcmlimit<350>,
        :rawcontinue(),
        :prop<title>
    ).map({ %tasks{%cat{$cat}}++ });
}

my %counts =
    mediawiki-query(
        $url, 'pages',
        :generator<categorymembers>,
        :gcmtitle<Category:Programming Languages>,
        :gcmlimit<350>,
        :rawcontinue(),
        :prop<categoryinfo>
    )
    .map({
        my $title = .<title>.subst(/^'Category:'/, '');
        my $tasks = (.<categoryinfo><pages> || 0);
        my $categories = (.<categoryinfo><subcats> || 0);
        my $total = (.<categoryinfo><size> || 0);
       $title  => [$tasks ,$categories, $total]
   });

my $out = open($tablefile, :w)  or die "$!\n";

# Add table boilerplate and header
$out.say:
    "\{|class=\"wikitable sortable\"\n",
    "|+ As of { Date.today } :: {+%counts} Languages\n",
    '!Rank!!Language!!Task<br>Entries!!Tasks<br>done %!!Non-task<br>Subcate-<br>gories!!Total<br>Categories'
;

my @bg = <#fff; #ccc;>;
my $ff = 0;
my $rank = 1;
my $ties = 0;

# Get sorted unique task counts
for %counts.values»[0].unique.sort: -* -> $count {
    $ff++;
    # Get list of tasks with this count
    my @these = %counts.grep( *.value[0] == $count )».keys.sort: *.&naturally;

    for @these {
        $ties++;
        $out.say:
          "|- style=\"background-color: { @bg[$ff % 2] }\"\n"~
          "|$rank\n"~
          "|[[:Category:$_|]]\n"~
          "|$count\n"~
          "|{(100 * $count/%tasks<Draft Task>.sum).round(.01)} %\n"~
          "|{%counts{$_}[1]}\n"~
          "|{%counts{$_}[2]}"
    }
    $rank += $ties;
    $ties = 0;
}
$out.say( "|}" );
$out.say('=' x 5, " query, download & processing: {(now - INIT now).round(.01)} seconds ", '=' x 5);
$out.close;

sub mediawiki-query ($site, $type, *%query) {
    my $url = "$site/api.php?" ~ uri-query-string(
        :action<query>, :format<json>, :formatversion<2>, |%query);
    my $continue = '';

    gather loop {
        my $response = $client.get("$url&$continue");
        my $data = from-json($response.content);
        take $_ for $data.<query>.{$type}.values;
        $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);
    }
}

sub uri-query-string (*%fields) {
    join '&', %fields.map: { "{.key}={uri-escape .value}" }
}

```

Abridged output:

See full output here.

As of 2019-02-10 :: 715 Languages

| Rank | Language | Task Entries | Tasks done % | Non-task Subcate- gories | Total Categories |
| --- | --- | --- | --- | --- | --- |
| 1 | Go | 1100 | 96.15 % | 4 | 1104 |
| 2 | Perl 6 | 1046 | 91.43 % | 4 | 1050 |
| 3 | Kotlin | 1029 | 89.95 % | 1 | 1030 |
| 4 | Python | 1017 | 88.9 % | 17 | 1034 |
| 5 | Phix | 991 | 86.63 % | 3 | 994 |
| 6 | Racket | 986 | 86.19 % | 3 | 989 |
| 7 | Perl | 963 | 84.18 % | 5 | 968 |
| 8 | Julia | 958 | 83.74 % | 3 | 961 |
| 9 | C | 940 | 82.17 % | 3 | 943 |
| 10 | Tcl | 925 | 80.86 % | 4 | 929 |
| 11 | Zkl | 918 | 80.24 % | 1 | 919 |
| 12 | J | 901 | 78.76 % | 3 | 904 |
| 13 | Java | 897 | 78.41 % | 3 | 900 |
| 14 | REXX | 886 | 77.45 % | 4 | 890 |
| 15 | D | 871 | 76.14 % | 3 | 874 |
| 16 | Ruby | 866 | 75.7 % | 3 | 869 |
| 17 | Haskell | 849 | 74.21 % | 3 | 852 |
| 18 | Scala | 789 | 68.97 % | 3 | 792 |
| 19 | Sidef | 787 | 68.79 % | 1 | 788 |
| 20 | PicoLisp | 772 | 67.48 % | 3 | 775 |

### Raku: Using web scraping

Scraping the languages and categories pages. Raku automatically handles Unicode names correctly.

```
my $languages =  qx{wget -O - 'http://rosettacode.org/wiki/Category:Programming_Languages'};
my $categories = qx{wget -O - 'http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000'};

my @lines = $languages.lines;
shift @lines until @lines[0] ~~ / '<h2>Subcategories</h2>' /;
my \languages = set gather for @lines {
    last if / '/bodycontent' /;
    take ~$0 if
        / '<li><a href="/wiki/Category:' .*? '" title="Category:' .*? '">' (.*?) '</a></li>' /;
}

@lines = $categories.lines;
my @results = sort -*.[0], gather for @lines {
    take [+$1.subst(',', ''), ~$0] if
        / '<li><a href="/wiki/Category:' .*? '" title="Category:' .*? '">'
        (.*?) <?{ ~$0 ∈ languages }>
        '</a>' .*? '(' (<[, 0..9]>+) ' member' /;
}

for @results.kv -> $i, @l {
    printf "%d:\t%4d - %s\n", $i+1, |@l;
}

```

Output:

(As of 2018-10-28) Here we show only the top 10.

```
1:	1036 - Go
2:	1029 - Kotlin
3:	1014 - Python
4:	 998 - Perl 6
5:	 980 - Racket
6:	 929 - Tcl
7:	 926 - C
8:	 910 - Perl
9:	 904 - Zkl
10:	 901 - J
```


[User]
This task is based on an idea hatched from this C1R Implementation.

Write a program that will accept as input the name of a task from Rosetta Code and the name of a language. The program should then download the solution for the specified task in the specified language, present the source to the user and prompt the user to confirm running the example.

The program should verify that the tools needed to compile or run the solution are present before running it.
If the solution can not be run, a graceful exit should happen. (i.e. the program should not crash)

Besides its own language, the program should support at least two other languages. (Ideally it would support most of the languages available, but that is too much to ask. Though some languages are simple, e.g. python, pike, perl, bash and several more only need the solution saved in a file and given to the language as argument to run, so it should be easy to support many languages like that).

If you know what is needed to support a particular language, please help to add support for that language to implementations in other languages.

Extra credit: add a function to get a list of all solutions of a given language and run them to create a report on which solutions failed to run.

More credit: also test if the output of a solution compares to a given result. The expected output should be loaded from a file with the name of the task. (This way all implementations can share the same set of files, and anyone can add more files. In the future the content of these files could be stored directly in a section of the task on Rosetta Code itself.)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

This is a fairly comprehensive task code runner. It is set up to work for Raku by default, but has basic configurations to run Perl, Python, Tcl and Go tasks as well. It can be easily tweaked to work with other languages by adding a load-lang('whatever'){} routine similar to the Raku, Perl, Python, Tcl and Go ones. (And ensuring that the appropriate compiler is installed and accessible.) There is so much variation to the task requirements and calling conventions that it would be problematic to make a general purpose, language agnostic code runner so some configuration is necessary to make it work with other languages.

(Note that there is no dependency download code nor resource hash for Python and Go, though they can run a remarkable number of tasks without.)

By default, this will download the Raku section of any (every) task that has a Raku example, extract the code blocks and attempt to run them. Many tasks require files or user interaction to proceed, others are not complete runnable code blocks (example code fragments), some tasks run forever. To try to deal with and compensate for this, this implementation can load a %resource hash that will: supply input files where necessary, skip unrunnable code fragments, limit long and/or infinite running blocks, supply user interaction code where possible, and skip blocks where user interaction is unavoidable.

There are several command line options to control its actions. See the README in the repository for details.

The complete implementation is too large and cumbersome to post in it's entirety here, only the main task retrieval and execution code is included.

For the whole ball of wax see the rc-run github repository.

Run with no parameters to run every implemented task on Rosetta Code. Feed it a task name to only download / run that task. Give it command line switches to adjust its behaviour.

Note: This is set up to run under Linux. It could be adapted for Windows (or OSX I suppose) fairly easily but I don't have access to those OSs, nor do I care to seek it.

```
use HTTP::UserAgent;
use URI::Escape;
use JSON::Fast;
use Text::Levenshtein::Damerau;
use MONKEY-SEE-NO-EVAL;

#####################################
say "Version = 2020-03-15T12:15:31";
#####################################

sleep 1;

my %*SUB-MAIN-OPTS = :named-anywhere;

unit sub MAIN(
    Str $run = '',        #= Task or file name
    Str :$lang = 'raku',  #= Language, default raku - used to load configuration settings
    Int :$skip = 0,       #= Skip # to continue partially into a list
    Bool :f(:$force),     #= Override any task skip parameter in %resource hash
    Bool :l(:$local),     #= Only use code from local cache
    Bool :r(:$remote),    #= Only use code from remote server (refresh local cache)
    Bool :q(:$quiet),     #= Less verbose, don't display source code
    Bool :d(:$deps),      #= Load dependencies
    Bool :p(:$pause),     #= pause after each task
    Bool :b(:$broken),    #= pause after each task which is broken or fails in some way
    Int  :$sleep = 0,     #= sleep for $sleep after each task
    Bool :t(:$timer),     #= save timing data for each task
);

die 'You can select local or remote, but not both...' if $local && $remote;

## INITIALIZATION

my $client   = HTTP::UserAgent.new;
my $url      = 'https://rosettacode.org/w';

my %c = ( # text colors
    code  => "\e[0;92m", # green
    delim => "\e[0;93m", # yellow
    cmd   => "\e[1;96m", # cyan
    bad   => "\e[0;91m", # red
    warn  => "\e[38;2;255;155;0m", # orange
    dep   => "\e[38;2;248;24;148m", # pink
    clr   => "\e[0m",    # clear formatting
);

my $view      = 'xdg-open';       # image viewer, this will open default under Linux
my %l         = load-lang($lang); # load language parameters
my %resource  = load-resources($lang);
my $get-tasks = True;

my @tasks;

run('clear');

## FIGURE OUT WHICH TASKS TO RUN

if $run {
    if $run.IO.e and $run.IO.f {# is it a file?
        @tasks = $run.IO.lines; # yep, treat each line as a task name
    } else {                    # must be a single task name
        @tasks = ($run);        # treat it so
    }
    $get-tasks = False;         # don't need to retrieve task names from web
}

if $get-tasks { # load tasks from web if cache is not found, older than one day or forced
    if !"%l<dir>.tasks".IO.e or (now - "%l<dir>.tasks".IO.modified) > 86400 or $remote {
        note 'Retrieving task list from site.';
        @tasks = mediawiki-query( # get tasks from web
        $url, 'pages',
        :generator<categorymembers>,
        :gcmtitle("Category:%l<language>"),
        :gcmlimit<350>,
        :rawcontinue(),
        :prop<title>
        )»<title>.grep( * !~~ /^'Category:'/ ).sort;
        "%l<dir>.tasks".IO.spurt: @tasks.sort.join("\n");
    } else {
        note 'Using cached task list.';
        @tasks = "%l<dir>.tasks".IO.slurp.lines; # load tasks from file
    }
}

my $tfile;
if $timer {
    $tfile = open :w, "{$lang}-time.txt";
    $tfile.close;
}

note "Skipping first $skip tasks..." if $skip;
my $redo;

## MAIN LOOP

for @tasks -> $title {
    $redo = False;
    next if $++ < $skip;
    next unless $title ~~ /\S/; # filter blank lines (from files)
    say my $tasknum = $skip + ++$, ")  $title";

    my $name = $title.subst(/<-[-0..9A..Za..z]>/, '_', :g);
    my $taskdir = "./rc/%l<dir>/$name";

    my $modified = "$taskdir/$name.txt".IO.e ?? "$taskdir/$name.txt".IO.modified !! 0;

    my $entry;
    if $remote or !"$taskdir/$name.txt".IO.e or ((now - $modified) > 86400 * 7) {
        my $page = $client.get("{ $url }/index.php?title={ uri-escape $title }&action=raw").content;

        uh-oh("Whoops, can't find page: $url/$title :check spelling.\n\n{fuzzy-search($title)}", 'warn')
            and next if $page.elems == 0;
        say "Getting code from: https://rosettacode.org/wiki/{ $title.subst(' ', '_', :g) }#%l<language>";

        $entry = $page.comb(rx:i/'=={{header|' $(%l<header>) '}}==' .+? [<?before \n'=='<-[={]>*'{{header'> || $] /).Str //
          uh-oh("No code found\nMay be bad markup", 'warn');

        if $entry ~~ /^^ 'See [[' (.+?) '/' $(%l<language>) / { # no code on main page, check sub page
            $entry = $client.get("{ $url }/index.php?title={ uri-escape $/[0].Str ~ '/' ~ %l<language> }&action=raw").content;
        }
        mkdir $taskdir unless $taskdir.IO.d;
        spurt( "$taskdir/$name.txt", $entry );
    } else {
        if "$taskdir/$name.txt".IO.e {
            $entry = "$taskdir/$name.txt".IO.slurp;
            say "Loading code from: $taskdir/$name.txt";
        } else {
            uh-oh("Task code $taskdir/$name.txt not found, check spelling or run remote.", 'warn');
            next;
        }
    }

    my @blocks = $entry.comb: %l<tag>;

    unless @blocks {
        uh-oh("No code found\nMay be bad markup", 'warn') unless %resource{"$name"}<skip> ~~ /'ok to skip'/;
        say "Skipping $name: ", %resource{"$name"}<skip>, "\n" if %resource{"$name"}<skip>
    }

    for @blocks.kv -> $k, $v {
        my $n = +@blocks == 1 ?? '' !! $k;
        spurt( "$taskdir/$name$n%l<ext>", $v );
        if %resource{"$name$n"}<skip> && !$force {
            dump-code ("$taskdir/$name$n%l<ext>");
            if %resource{"$name$n"}<skip> ~~ /'broken'/ {
                uh-oh(%resource{"$name$n"}<skip>, 'bad');
                pause if $broken;
            } else {
                say "{%c<warn>}Skipping $name$n: ", %resource{"$name$n"}<skip>, "{%c<clr>}\n";
            }
            next;
        }
        say "\nTesting $name$n";
        run-it($taskdir, "$name$n", $tasknum);
    }
    say  %c<delim>, '=' x 79, %c<clr>;
    redo if $redo;
    sleep $sleep if $sleep;
    pause if $pause;
}

## SUBROUTINES

sub mediawiki-query ($site, $type, *%query) {
    my $url = "$site/api.php?" ~ uri-query-string(
        :action<query>, :format<json>, :formatversion<2>, |%query);
    my $continue = '';

    gather loop {
        my $response = $client.get("$url&$continue");
        my $data = from-json($response.content);
        take $_ for $data.<query>.{$type}.values;
        $continue = uri-query-string |($data.<query-continue>{*}».hash.hash or last);
    }
}

sub run-it ($dir, $code, $tasknum) {
    my $current = $*CWD;
    chdir $dir;
    if %resource{$code}<file> -> $fn {
        copy "$current/rc/resources/{$_}", "./{$_}" for $fn[]
    }
    dump-code ("$code%l<ext>") unless $quiet;
    check-dependencies("$code%l<ext>", $lang) if $deps;
    my @cmd = %resource{$code}<cmd> ?? |%resource{$code}<cmd> !! "%l<exe> $code%l<ext>\n";
    if $timer {
        $tfile = open :a, "{$current}/{$lang}-time.txt";
    }
    my $time = 'NA: not run or killed before completion';
    for @cmd -> $cmd {
        say "\nCommand line: {%c<cmd>}$cmd",%c<clr>;
        if $timer { $tfile.say: "Command line: $cmd".chomp }
        my $start = now;
        try shell $cmd;
        $time = (now - $start).round(.001);
        CATCH {
            when /'exit code: 137'/ { }
            default {
                .resume unless $broken;
                uh-oh($_, 'bad');
                if %resource{$code}<fail-by-design> {
                    say %c<warn>, 'Fails by design, (or at least, it\'s not unexpected).', %c<clr>;
                } else {
                    if pause.lc eq 'r' {
                       unlink "$code.txt";
                       $redo = True;
                    }
                }
             }
        }
    if $timer { $tfile.say("#$tasknum - Wallclock seconds: $time\n") }
    }
    chdir $current;
    say "\nDone task #$tasknum: $code - wallclock seconds: $time\e[?25h";
    $tfile.close if $timer;
}

sub pause {
    prompt "Press enter to procede:> ";
    # or
    # sleep 5;
}

sub dump-code ($fn) {
    say "\n", %c<delim>, ('vvvvvvvv' xx 7).join(' CODE '), %c<clr>, "\n", %c<code>;
    print $fn.IO.slurp;
    say %c<clr>,"\n\n",%c<delim>,('^^^^^^^^' xx 7).join(' CODE '),%c<clr>;
}

sub uri-query-string (*%fields) { %fields.map({ "{.key}={uri-escape .value}" }).join('&') }

sub clear { "\r" ~ ' ' x 100 ~ "\r" }

sub uh-oh ($err, $class='warn') { put %c{$class}, "{'#' x 79}\n\n $err \n\n{'#' x 79}", %c<clr> }

sub fuzzy-search ($title) {
    my @tasknames;
    if "%l<dir>.tasks".IO.e {
        @tasknames = "%l<dir>.tasks".IO.slurp.lines;
    }
    return '' unless @tasknames.elems;
    " Did you perhaps mean:\n\n\t" ~
    @tasknames.grep( {.lc.contains($title.lc) or dld($_, $title) < (5 min $title.chars)} ).join("\n\t");
}                # Damerau Levenshtein distance  ^^^

multi check-dependencies ($fn, 'raku') {
    my @use = $fn.IO.slurp.comb(/<?after ^^ \h* 'use '> \N+? <?before \h* ';'>/);
    if +@use {
        say %c<dep>, 'Checking dependencies...', %c<clr>;
        for @use -> $module {
            if $module eq any('v6', 'v6.c', 'v6.d', 'nqp', 'NativeCall', 'Test') or $module.contains('MONKEY')
              or $module.contains('experimental') or $module.starts-with('lib') or $module.contains('from<Perl5>') {
                print %c<dep>;
                say 'ok, no installation necessary: ', $module;
                print %c<clr>;
                next;
            }
            my $installed = $*REPO.resolve(CompUnit::DependencySpecification.new(:short-name($module)));
            my @mods = $module;
            if './../../../raku-modules.txt'.IO.e {
                my $fh = open( './../../../perl6-modules.txt', :r ) or die $fh;
                @mods.append: $fh.lines;
                $fh.close;
            }
            my $fh = open( './../../../raku-modules.txt', :w ) or die $fh;
            $fh.spurt: @mods.Bag.keys.sort.join: "\n";
            $fh.close;
            print %c<dep>;
            if $installed {
                say 'ok, installed: ', $module
            } else {
                say 'not installed: ', $module;
                shell("zef install $module");
            }
            print %c<clr>;
        }
    }
}

multi check-dependencies ($fn, 'perl') {
    my @use = $fn.IO.slurp.comb(/<?after ^^ \h* 'use '> \N+? <?before \h* ';'>/);
    if +@use {
        for @use -> $module {
            next if $module eq $module.lc;
            next if $module.starts-with(any('constant','bignum'));
            my $installed = shell( "%l<exe> -e 'eval \"use {$module}\"; exit 1 if \$@'" );
            print %c<dep>;
            if $installed {
                say 'ok:            ', $module
            } else {
                say 'not installed: ', $module;
                try shell("sudo cpan $module");
            }
            print %c<clr>;
        }
    }
}

multi check-dependencies  ($fn, $unknown) {
    note "Sorry, don't know how to handle dependencies for $unknown language."
};

multi load-lang ('raku') { ( # Language specific variables. Adjust to suit.
    language => 'Raku',  # language category name
    exe      => 'raku',  # executable name to run perl6 in a shell
    ext      => '.raku', # file extension for perl6 code (optional, but nice to have)
    dir      => 'raku',  # directory to save tasks to
    header   => 'Raku',  # header text (=={{header|Raku}}==)
    # tags marking blocks of code - spaced out to placate wiki formatter
    # and to avoid getting tripped up when trying to run _this_ task.
    # note that this tag only selects the syntax highlighting, continue to
    # leave 'perl6' as an option, 'raku' is now live on the site.
    tag => rx/:i <?after '<syntaxhighlight lang="' ['perl6'|'raku'] '"' ' line'? '>' > .*? <?before '</' 'syntaxhighlight>'>/,
) }

multi load-lang ('perl') { (
    language => 'Perl',
    exe      => 'perl',
    ext      => '.pl',
    dir      => 'perl',
    header   => 'Perl',
    tag => rx/:i <?after '<syntaxhighlight lang="' 'perl' '"' ' line'? '>' > .*? <?before '</' 'lang>'>/,
) }

multi load-lang ('python') { (
    language => 'Python',
    exe      => 'python',
    ext      => '.py',
    dir      => 'python',
    header   => 'Python',
    tag => rx/:i <?after '<syntaxhighlight lang="' 'python' '"' ' line'? '>' > .*? <?before '</' 'lang>'>/,
) }

multi load-lang ('go') { (
    language => 'Go',
    exe      => 'go run',
    ext      => '.go',
    dir      => 'go',
    header   => 'Go',
    tag => rx/:i <?after '<syntaxhighlight lang="' 'go'  '"' ' line'? '>' > .*? <?before '</' 'lang>'>/,
) }

multi load-lang ('tcl') { (
    language => 'Tcl',
    exe      => 'tclsh',
    ext      => '.tcl',
    dir      => 'tcl',
    header   => 'Tcl',
    tag => rx/:i <?after '<syntaxhighlight lang="' 'tcl'  '"' ' line'? '>' > .*? <?before '</' 'lang>'>/,
) }

multi load-lang ($unknown) { die "Sorry, don't know how to handle $unknown language." };

multi load-resources ($unknown) { () };

```

Output:

with command line

:   **raku RC-run.p6 -q "Determine if a string is numeric"**

```
Retrieving tasks
1)  Determine if a string is numeric
Getting code from: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Raku

Testing Determine_if_a_string_is_numeric

Command line: raku Determine_if_a_string_is_numeric.p6

               Coerce     Don't coerce
    String   whitespace    whitespace
       <1>      True         True
     <1.2>      True         True
   <1.2.3>     False        False
      <-6>      True         True
     <1/2>      True         True
     <12e>     False        False
     <B17>     False        False
 <1.3e+12>      True         True
  <1.3e12>      True         True
 <-2.6e-3>      True         True
    <zero>     False        False
      <0x>     False        False
   <0xA10>      True         True
  <0b1001>      True         True
    <0o16>      True         True
    <0o18>     False        False
    <2+5i>      True         True
    <True>     False        False
   <False>     False        False
     <Inf>      True         True
     <NaN>      True         True
 <0x10.50>      True         True
   <0b102>     False        False
  <0o_5_3>      True         True
      <௫௯>      True         True
  <  12  >      True         True
   <1 1 1>     False        False
        <>      True        False
       < >      True        False

Done task #1: Determine_if_a_string_is_numeric - wallclock seconds: 0.171
===============================================================================
```

Or, if the full %resource hash is loaded it will automatically feed input parameters to tasks that require them:
**raku RC-run.p6 Lucky\_and\_even\_lucky\_numbers** -q

```
Retrieving tasks
1 Lucky_and_even_lucky_numbers
Getting code from: http://rosettacode.org/wiki/Lucky_and_even_lucky_numbers#Raku

Testing Lucky_and_even_lucky_numbers

Command line: raku Lucky_and_even_lucky_numbers.p6 20 , lucky

79

Command line: raku Lucky_and_even_lucky_numbers.p6 1 20

(1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79)

Command line: raku Lucky_and_even_lucky_numbers.p6 1 20 evenlucky

(2 4 6 10 12 18 20 22 26 34 36 42 44 50 52 54 58 68 70 76)

Command line: raku Lucky_and_even_lucky_numbers.p6 6000 -6100

(6009 6019 6031 6049 6055 6061 6079 6093)

Command line: raku Lucky_and_even_lucky_numbers.p6 6000 -6100 evenlucky

(6018 6020 6022 6026 6036 6038 6050 6058 6074 6090 6092)

Done Lucky_and_even_lucky_numbers
===============================================================================
```

Try running a Go task - Command line: **raku RC-run.p6 -q --lang=go "Determine if a string is numeric"**

Finds two task entries, downloads both and runs each:

```
1)  Determine if a string is numeric
Getting code from: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Go

Testing Determine_if_a_string_is_numeric0

Command line: go run Determine_if_a_string_is_numeric0.go

Are these strings numeric?
     1 -> true
  3.14 -> true
  -100 -> true
   1e2 -> true
   NaN -> true
  rose -> false

Done task #1: Determine_if_a_string_is_numeric0 - wallclock seconds: 0.16

Testing Determine_if_a_string_is_numeric1

Command line: go run Determine_if_a_string_is_numeric1.go

Are these strings integers?
    1 -> true
  one -> false

Done task #1: Determine_if_a_string_is_numeric1 - wallclock seconds: 0.147
===============================================================================
```


[User]
A RosettaCode contributor is going on a long journey.

To ease the boredom of a long flight he takes his favourite programming language manual and a list of RosettaCode tasks,   but there's a catch:   the tasks have to be description only and not include all the solutions already supplied by other programmers.

Task
:   * Scrape   http://rosettacode.org/wiki/Category:Programming\_Tasks   for all the tasks.
    * Traverse the links.
    * Extract the text or HTML between a tag with a class of   "infobox"   and the beginning of the table with the id of   "toc".

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.10

```
use HTTP::UserAgent;
use Gumbo;

my $ua = HTTP::UserAgent.new;
my $taskfile = './RC_tasks.html';

# Get list of Tasks
say "Updating Programming_Tasks list...";
my $page   = "https://rosettacode.org/wiki/Category:Programming_Tasks";
my $html   = $ua.get($page).content;
my $xmldoc = parse-html($html, :TAG<div>, :id<mw-pages>);
my @tasks  = parse-html($xmldoc[0].Str, :TAG<li>).Str.comb( /'/wiki/' <-["]>+ / )».substr(6); #"
my $f      = open("./RC_Programming_Tasks.txt", :w)  or die "$!\n";
note "Writing Programming_Tasks file...";
$f.print( @tasks.join("\n") );
$f.close;

sleep .5;

for 'Programming_Tasks' -> $category
{ # Scrape info from each page.

    note "Loading $category file...";
    note "Retreiving tasks...";
    my @entries = "./RC_{$category}.txt".IO.slurp.lines;

    for @entries -> $title {
        note $title;

        # Get the raw page
        my $html = $ua.get: "https://rosettacode.org/wiki/{$title}";

        # Filter out the actual task description
        $html.content ~~ m|'<div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><div'
                            .+? 'using any language you may know.</div>' (.+?) '<div id="toc"'|;

        my $task = cleanup $0.Str;

        # save to a file
        my $fh = $taskfile.IO.open :a;

        $fh.put: "<hr>\n     $title\n<hr>\n$task";

        $fh.close;

        sleep 3; # Don't pound the server
    }
}

sub cleanup ( $string ) {
    $string.subst( /^.+ '</div>'/, '' )
}

```

Abridged sample output:

---

```
    100_doors

```

---

There are 100 doors in a row that are all initially closed.

You make 100 passes by the doors.

The first time through, visit every door and  *toggle*  the door  (if the door is closed,  open it;   if it is open,  close it).

The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it.

The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door.

Task

Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed?

**Alternate:**
As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares.

Opening only those doors is an   optimization   that may also be expressed;

however, as should be obvious, this defeats the intent of comparing implementations across programming languages.

---

```
    15_Puzzle_Game

```

---

Task

Implement the Fifteen Puzzle Game.

Related Task

* 15 Puzzle Solver

---

```
    15_puzzle_solver

```

---

Your task is to write a program that finds a solution in the fewest single moves (no multimoves) possible to a random Fifteen Puzzle Game.
For this task you will be using the following puzzle:

```
15 14  1  6
 9 11  4 12
 0 10  7  3
13  8  5  2
```

Solution:

```
 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15  0

```

The output must show the moves' directions, like so: left, left, left, down, right... and so on.
There are 2 solutions with 52 moves:
rrrulddluuuldrurdddrullulurrrddldluurddlulurruldrdrd
rrruldluuldrurdddluulurrrdlddruldluurddlulurruldrrdd
finding either one, or both is an acceptable result.
see: Pretty Print of Optimal Solution

Extra credit.

Solve the following problem:

```
  0 12  9 13
 15 11 10 14
  3  7  2  5
  4  8  6  1

```

Related Task

* 15 puzzle game

**...and so on...**


[User]
Task

Implement a   **rot-13**   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).

Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line,   or (if no filenames are passed thereon) acting as a filter on its   "standard input."

(A number of UNIX scripting languages and utilities, such as   *awk*   and   *sed*   either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g.,   Perl   and   Python).

The   **rot-13**   encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of   spoiler   or potentially offensive material.

Many news reader and mail user agent programs have built-in **rot-13** encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.

The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   **z**   to   **a**   as necessary).

Thus the letters   **abc**   become   **nop**   and so on.

Technically **rot-13** is a   "mono-alphabetic substitution cipher"   with a trivial   "key".

A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.

Related tasks

* Caesar cipher
* Substitution Cipher
* Vigenère Cipher/Cryptanalysis

Other tasks related to string operations:

Metrics

* Array length
* String length
* Copy a string
* Empty string  (assignment)

Counting

* Word frequency
* Letter frequency
* Jewels and stones
* I before E except after C
* Bioinformatics/base count
* Count occurrences of a substring
* Count how many vowels and consonants occur in a string

Remove/replace

* XXXX redacted
* Conjugate a Latin verb
* Remove vowels from a string
* String interpolation (included)
* Strip block comments
* Strip comments from a string
* Strip a set of characters from a string
* Strip whitespace from a string -- top and tail
* Strip control codes and extended characters from a string

Anagrams/Derangements/shuffling

* Word wheel
* ABC problem
* Sattolo cycle
* Knuth shuffle
* Ordered words
* Superpermutation minimisation
* Textonyms (using a phone text pad)
* Anagrams
* Anagrams/Deranged anagrams
* Permutations/Derangements

Find/Search/Determine

* ABC words
* Odd words
* Word ladder
* Semordnilap
* Word search
* Wordiff  (game)
* String matching
* Tea cup rim text
* Alternade words
* Changeable words
* State name puzzle
* String comparison
* Unique characters
* Unique characters in each string
* Extract file extension
* Levenshtein distance
* Palindrome detection
* Common list elements
* Longest common suffix
* Longest common prefix
* Compare a list of strings
* Longest common substring
* Find common directory path
* Words from neighbour ones
* Change e letters to i in words
* Non-continuous subsequences
* Longest common subsequence
* Longest palindromic substrings
* Longest increasing subsequence
* Words containing "the" substring
* Sum of the digits of n is substring of n
* Determine if a string is numeric
* Determine if a string is collapsible
* Determine if a string is squeezable
* Determine if a string has all unique characters
* Determine if a string has all the same characters
* Longest substrings without repeating characters
* Find words which contains all the vowels
* Find words which contain the most consonants
* Find words which contains more than 3 vowels
* Find words whose first and last three letters are equal
* Find words with alternating vowels and consonants

Formatting

* Substring
* Rep-string
* Word wrap
* String case
* Align columns
* Literals/String
* Repeat a string
* Brace expansion
* Brace expansion using ranges
* Reverse a string
* Phrase reversals
* Comma quibbling
* Special characters
* String concatenation
* Substring/Top and tail
* Commatizing numbers
* Reverse words in a string
* Suffixation of decimal numbers
* Long literals, with continuations
* Numerical and alphabetical suffixes
* Abbreviations, easy
* Abbreviations, simple
* Abbreviations, automatic

Song lyrics/poems/Mad Libs/phrases

* Mad Libs
* Magic 8-ball
* 99 bottles of beer
* The Name Game (a song)
* The Old lady swallowed a fly
* The Twelve Days of Christmas

Tokenize

* Text between
* Tokenize a string
* Word break problem
* Tokenize a string with escaping
* Split a character string based on change of character

Sequences

* Show ASCII table
* De Bruijn sequences
* Summarize and say sequence
* Generate lower case ASCII alphabet

[Assistant]
(formerly Perl 6)

```
my @abc = 'a'..'z';
my $abc = [@abc».uc, @abc];
put .trans: $abc => $abc».rotate(13) for lines
```

Input:

```
Rosetta Code
```

Output:

```
Ebfrggn Pbqr
```

As a one-liner:

```
$ raku -pe '.=trans: {$_ => $_».rotate(13)}({[$_».uc, @$_]}("a".."z"))'
```


[User]
A round-robin tournament is also known as an all-play-all-tournament; each participant plays every other participant once.

For N participants the number of rounds is N-1 if N is an even number. When there are an odd number of participants then each round one contestor has no opponent (AKA as a "bye"). The number of rounds is N in that case.

Task

Write a program that prints out a tournament schedule for 12 participants (represented by numbers 1 to 12).

See also
:   * **Wikipedia - Round-robin tournament**

[Assistant]
```
my @players = (1,0)[$_%2] .. $_ given 12;
my $half = +@players div 2;
my $round = 0;

loop {
    printf "Round %2d: %s\n", ++$round, "{ zip( @players[^$half], @players[$half..*].reverse ).map: { sprintf "(%2d vs %-2d)", |$_ } }";
    @players[1..*].=rotate(-1);
    last if [<] @players;
}

```

Output:

```
Round  1: ( 1 vs 12) ( 2 vs 11) ( 3 vs 10) ( 4 vs 9 ) ( 5 vs 8 ) ( 6 vs 7 )
Round  2: ( 1 vs 11) (12 vs 10) ( 2 vs 9 ) ( 3 vs 8 ) ( 4 vs 7 ) ( 5 vs 6 )
Round  3: ( 1 vs 10) (11 vs 9 ) (12 vs 8 ) ( 2 vs 7 ) ( 3 vs 6 ) ( 4 vs 5 )
Round  4: ( 1 vs 9 ) (10 vs 8 ) (11 vs 7 ) (12 vs 6 ) ( 2 vs 5 ) ( 3 vs 4 )
Round  5: ( 1 vs 8 ) ( 9 vs 7 ) (10 vs 6 ) (11 vs 5 ) (12 vs 4 ) ( 2 vs 3 )
Round  6: ( 1 vs 7 ) ( 8 vs 6 ) ( 9 vs 5 ) (10 vs 4 ) (11 vs 3 ) (12 vs 2 )
Round  7: ( 1 vs 6 ) ( 7 vs 5 ) ( 8 vs 4 ) ( 9 vs 3 ) (10 vs 2 ) (11 vs 12)
Round  8: ( 1 vs 5 ) ( 6 vs 4 ) ( 7 vs 3 ) ( 8 vs 2 ) ( 9 vs 12) (10 vs 11)
Round  9: ( 1 vs 4 ) ( 5 vs 3 ) ( 6 vs 2 ) ( 7 vs 12) ( 8 vs 11) ( 9 vs 10)
Round 10: ( 1 vs 3 ) ( 4 vs 2 ) ( 5 vs 12) ( 6 vs 11) ( 7 vs 10) ( 8 vs 9 )
Round 11: ( 1 vs 2 ) ( 3 vs 12) ( 4 vs 11) ( 5 vs 10) ( 6 vs 9 ) ( 7 vs 8 )
```


[User]
**RPG**   =   Role Playing Game.

You're running a tabletop RPG, and your players are creating characters.

Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.

One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.

Some players like to assign values to their attributes in the order they're rolled.

To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:

* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.

However, this can require a lot of manual dice rolling. A programatic solution would be much faster.

Task

Write a program that:

1. Generates 4 random, whole values between 1 and 6.
2. Saves the sum of the 3 largest values.
3. Generates a total of 6 values this way.
4. Displays the total, and all 6 values once finished.

* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2018.04.1

```
my ( $min_sum, $hero_attr_min, $hero_count_min ) = 75, 15, 2;
my @attr-names = <Str Int Wis Dex Con Cha>;

sub heroic { + @^a.grep: * >= $hero_attr_min }

my @attr;
repeat until @attr.sum     >= $min_sum
         and heroic(@attr) >= $hero_count_min {

    @attr = @attr-names.map: { (1..6).roll(4).sort(+*).skip(1).sum };
}

say @attr-names Z=> @attr;
say "Sum: {@attr.sum}, with {heroic(@attr)} attributes >= $hero_attr_min";

```

Output:

```
(Str => 15 Int => 16 Wis => 13 Dex => 11 Con => 15 Cha => 6)
Sum: 76, with 3 attributes >= 15

```


[User]
A daemon is a service that runs in the background independent of a users login session.

Demonstrate how a program disconnects from the terminal to run as a daemon in the background.

Write a small program that writes a message roughly once a second to its stdout which should be redirected to a file.

Note that in some language implementations it may not be possible to disconnect from the terminal, and instead the process needs to be started with stdout (and stdin) redirected to files before program start. If that is the case then a helper program to set up this redirection should be written in the language itself. A shell wrapper, as would be the usual solution on Unix systems, is not appropriate.

[Assistant]
(formerly Perl 6)

```
# Reference:
# https://github.com/hipek8/p6-UNIX-Daemonize/

use v6;
use UNIX::Daemonize;
use File::Temp;

my ($output, $filehandle) = tempfile(:tempdir("/tmp"),:!unlink) or die;

say "Output now goes to ",$output;

daemonize();

loop {
   sleep(1);
   spurt $output, DateTime.now.Str~"\n", :append;
}

```

Output:

```
root@ubuntu:~# su - david

david@ubuntu:~$ ./dumper.p6
Output now goes to /tmp/x2ovx9JG8b
david@ubuntu:~$ tail -f /tmp/x2ovx9JG8b
2018-12-11T20:20:01.510484+08:00
2018-12-11T20:20:02.513732+08:00
2018-12-11T20:20:03.517063+08:00
2018-12-11T20:20:04.520394+08:00
2018-12-11T20:20:05.524871+08:00
2018-12-11T20:20:06.528244+08:00
2018-12-11T20:20:07.531985+08:00
2018-12-11T20:20:08.537776+08:00
2018-12-11T20:20:09.541606+08:00
2018-12-11T20:20:10.545796+08:00
2018-12-11T20:20:11.549047+08:00
2018-12-11T20:20:12.552704+08:00
^C
david@ubuntu:~$ exit
logout
root@ubuntu:~# tail -f /tmp/x2ovx9JG8b
2018-12-11T20:20:28.623690+08:00
2018-12-11T20:20:29.626978+08:00
2018-12-11T20:20:30.634309+08:00
2018-12-11T20:20:31.637481+08:00
2018-12-11T20:20:32.640794+08:00
2018-12-11T20:20:33.643947+08:00
2018-12-11T20:20:34.647146+08:00
2018-12-11T20:20:35.651008+08:00
^C
root@ubuntu:~# su - david
david@ubuntu:~$ tail -f /tmp/x2ovx9JG8b
2018-12-11T20:20:51.711357+08:00
2018-12-11T20:20:52.715044+08:00
2018-12-11T20:20:53.718921+08:00
2018-12-11T20:20:54.722134+08:00
2018-12-11T20:20:55.725970+08:00
2018-12-11T20:20:56.729160+08:00
2018-12-11T20:20:57.732376+08:00
2018-12-11T20:20:58.735409+08:00
2018-12-11T20:20:59.738886+08:00
2018-12-11T20:21:00.743045+08:00
2018-12-11T20:21:01.748113+08:00
2018-12-11T20:21:02.753204+08:00
2018-12-11T20:21:03.756665+08:00
2018-12-11T20:21:04.759902+08:00
^C
david@ubuntu:~$ pkill -c moar
1

```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Run-length\_encoding. 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) |

Task

Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.

The output can be anything, as long as you can recreate the input with it.

Example
:   Input: `WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW`
:   Output: `12W1B12W3B24W1B14W`

Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.

[Assistant]
(formerly Perl 6)
Note that Raku regexes don't care about unquoted whitespace, and that backrefs
count from 0, not from 1.

```
sub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) }

sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) }

my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW');
say $e;
say decode($e);
```

Output:

```
12W1B12W3B24W1B14W
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
```


[User]
Given the example Differential equation:

:   y
    ′
    (
    t
    )
    =
    t
    ⋅

    y
    (
    t
    )
    {\displaystyle {\displaystyle y'(t)=t\cdot {\sqrt {y(t)}}}}

With initial condition:

:   t

    0
    =
    0
    {\displaystyle {\displaystyle t\_{0}=0}}
     and

    y

    0
    =
    y
    (

    t

    0
    )
    =
    y
    (
    0
    )
    =
    1
    {\displaystyle {\displaystyle y\_{0}=y(t\_{0})=y(0)=1}}

This equation has an exact solution:

:   y
    (
    t
    )
    =

    1
    16
    (

    t

    2
    +
    4

    )

    2
    {\displaystyle {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}}}

Task

Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation.

* Solve the given differential equation over the range

  t
  =
  0
  …
  10
  {\displaystyle {\displaystyle t=0\ldots 10}}
   with a step value of

  δ
  t
  =
  0.1
  {\displaystyle {\displaystyle \delta t=0.1}}
   (101 total points, the first being given)
* Print the calculated values of

  y
  {\displaystyle {\displaystyle y}}
   at whole numbered

  t
  {\displaystyle {\displaystyle t}}
  's (

  0.0
  ,
  1.0
  ,
  …
  10.0
  {\displaystyle {\displaystyle 0.0,1.0,\ldots 10.0}}
  ) along with error as compared to the exact solution.

Method summary

Starting with a given

y

n
{\displaystyle {\displaystyle y\_{n}}}
 and

t

n
{\displaystyle {\displaystyle t\_{n}}}
 calculate:

:   δ

    y

    1
    =
    δ
    t
    ⋅

    y
    ′
    (

    t

    n
    ,

    y

    n
    )

    {\displaystyle {\displaystyle \delta y\_{1}=\delta t\cdot y'(t\_{n},y\_{n})\quad }}
:   δ

    y

    2
    =
    δ
    t
    ⋅

    y
    ′
    (

    t

    n
    +

    1
    2
    δ
    t
    ,

    y

    n
    +

    1
    2
    δ

    y

    1
    )
    {\displaystyle {\displaystyle \delta y\_{2}=\delta t\cdot y'(t\_{n}+{\tfrac {1}{2}}\delta t,y\_{n}+{\tfrac {1}{2}}\delta y\_{1})}}
:   δ

    y

    3
    =
    δ
    t
    ⋅

    y
    ′
    (

    t

    n
    +

    1
    2
    δ
    t
    ,

    y

    n
    +

    1
    2
    δ

    y

    2
    )
    {\displaystyle {\displaystyle \delta y\_{3}=\delta t\cdot y'(t\_{n}+{\tfrac {1}{2}}\delta t,y\_{n}+{\tfrac {1}{2}}\delta y\_{2})}}
:   δ

    y

    4
    =
    δ
    t
    ⋅

    y
    ′
    (

    t

    n
    +
    δ
    t
    ,

    y

    n
    +
    δ

    y

    3
    )

    {\displaystyle {\displaystyle \delta y\_{4}=\delta t\cdot y'(t\_{n}+\delta t,y\_{n}+\delta y\_{3})\quad }}

then:

:   y

    n
    +
    1
    =

    y

    n
    +

    1
    6
    (
    δ

    y

    1
    +
    2
    δ

    y

    2
    +
    2
    δ

    y

    3
    +
    δ

    y

    4
    )
    {\displaystyle {\displaystyle y\_{n+1}=y\_{n}+{\tfrac {1}{6}}(\delta y\_{1}+2\delta y\_{2}+2\delta y\_{3}+\delta y\_{4})}}
:   t

    n
    +
    1
    =

    t

    n
    +
    δ
    t

    {\displaystyle {\displaystyle t\_{n+1}=t\_{n}+\delta t\quad }}

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.03

```
sub runge-kutta(&yp) {
    return -> \t, \y, \δt {
        my $a = δt * yp( t, y );
        my $b = δt * yp( t + δt/2, y + $a/2 );
        my $c = δt * yp( t + δt/2, y + $b/2 );
        my $d = δt * yp( t + δt, y + $c );
        ($a + 2*($b + $c) + $d) / 6;
    }
}

constant δt = .1;
my &δy = runge-kutta { $^t * sqrt($^y) };

loop (
    my ($t, $y) = (0, 1);
    $t <= 10;
    ($t, $y) »+=« (δt, δy($t, $y, δt))
) {
    printf "y(%2d) = %12f ± %e\n", $t, $y, abs($y - ($t**2 + 4)**2 / 16)
    if $t %% 1;
}

```

Output:

```
y( 0) =     1.000000 ± 0.000000e+00
y( 1) =     1.562500 ± 1.457219e-07
y( 2) =     3.999999 ± 9.194792e-07
y( 3) =    10.562497 ± 2.909562e-06
y( 4) =    24.999994 ± 6.234909e-06
y( 5) =    52.562489 ± 1.081970e-05
y( 6) =    99.999983 ± 1.659460e-05
y( 7) =   175.562476 ± 2.351773e-05
y( 8) =   288.999968 ± 3.156520e-05
y( 9) =   451.562459 ± 4.072316e-05
y(10) =   675.999949 ± 5.098329e-05
```


[User]
Task

Demonstrate a language's ability for programs to execute code written in the language provided at runtime.

Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.

You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.

For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.

[Assistant]
(formerly Perl 6)
Any syntactically valid sequence of statements may be run, and the snippet to be run can see its outer lexical scope at the point of the eval:

```
use MONKEY-SEE-NO-EVAL;

my ($a, $b) = (-5, 7);
my $ans = EVAL 'abs($a * $b)';  # => 35

```

Unlike in Perl 5, eval in Raku only compiles and executes the string, but does not trap exceptions. You must say try eval to get that behavior (or supply a CATCH block within the text to be evaluated).


[User]
Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.

Do so in a way which:

* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a *global* variable

or note that these are impossible.

See also

* For more general examples and language-specific details, see Eval.
* Dynamic variable names is a similar task.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-12-22

For security, you must explicitly allow use of 'EVAL'.

```
use MONKEY-SEE-NO-EVAL;
sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { EVAL $code } }

say eval_with_x('3 * x', 5, 10);      # Says "15".
say eval_with_x('3 * x', 5, 10, 50);  # Says "105".

```


[User]
A **Ruth–Aaron** pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum.

A **Ruth–Aaron** triple consists of ***three*** consecutive integers with the same properties.

There is a second variant of **Ruth–Aaron** numbers, one which uses prime *factors* rather than prime *divisors*. The difference; divisors are unique, factors may be repeated. The 714, 715 pair appears in both, so the name still fits.

It is common to refer to each **Ruth–Aaron** group by the first number in it.

Task

* Find and show, here on this page, the first **30** **Ruth-Aaron numbers** (factors).

* Find and show, here on this page, the first **30** **Ruth-Aaron numbers** (divisors).

Stretch

* Find and show the first **Ruth-Aaron triple** (factors).

* Find and show the first **Ruth-Aaron triple** (divisors).

See also

* Wikipedia: Ruth–Aaron pair * OEIS:A006145 - Ruth-Aaron numbers (1): sum of prime divisors of n = sum of prime divisors of n+1 * OEIS:A039752 - Ruth-Aaron numbers (2): sum of prime divisors of n = sum of prime divisors of n+1 (both taken with multiplicity)

[Assistant]
```
use Prime::Factor;

my @pf  = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.sum;
my @upf = lazy (^∞).hyper(:1000batch).map: *.&prime-factors.unique.sum;

# Task: < 1 second
put "First 30 Ruth-Aaron numbers (Factors):\n" ~
(1..∞).grep( { @pf[$_] == @pf[$_ + 1] } )[^30];

put "\nFirst 30 Ruth-Aaron numbers (Divisors):\n" ~
(1..∞).grep( { @upf[$_] == @upf[$_ + 1] } )[^30];

# Stretch: ~ 5 seconds
put "\nFirst Ruth-Aaron triple (Factors):\n" ~
(1..∞).first: { @pf[$_] == @pf[$_ + 1] == @pf[$_ + 2] }

# Really, really, _really_ slow. 186(!) minutes... but with no cheating or "leg up".
put "\nFirst Ruth-Aaron triple (Divisors):\n" ~
(1..∞).first: { @upf[$_] == @upf[$_ + 1] == @upf[$_ + 2] }

```

Output:

```
First 30 Ruth-Aaron numbers (Factors):
5 8 15 77 125 714 948 1330 1520 1862 2491 3248 4185 4191 5405 5560 5959 6867 8280 8463 10647 12351 14587 16932 17080 18490 20450 24895 26642 26649

First 30 Ruth-Aaron numbers (Divisors):
5 24 49 77 104 153 369 492 714 1682 2107 2299 2600 2783 5405 6556 6811 8855 9800 12726 13775 18655 21183 24024 24432 24880 25839 26642 35456 40081

First Ruth-Aaron triple (Factors):
417162

First Ruth-Aaron triple (Divisors):
89460294
```


[User]
S-Expressions   are one convenient way to parse and store data.

Task

Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats.

The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc).

Newlines and other whitespace may be ignored unless contained within a quoted string.

“()”   inside quoted strings are not interpreted, but treated as part of the string.

Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error.

For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes.

Languages that support it may treat unquoted strings as symbols.

Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes.

The reader should be able to read the following input

```
((data "quoted data" 123 4.5)
 (data (!@# (4.5) "(more" "data)")))

```

and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.)

The writer should be able to take the produced list and turn it into a new S-Expression.
Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted.

Extra Credit

Let the writer produce pretty printed output with indenting and line-breaks.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.02

This parses the task, but it isn't really a good lisp parser, because it always wants whitespace between lists, so `(()())` will fail ( `(() ())` wont)

```
grammar S-Exp {
  rule TOP    {^ <s-list> $};

  token s-list { '(' ~ ')' [ <in_list>+ % [\s+] | '' ] }
  token in_list { <s-token> | <s-list> }

  proto token s-token {*}
  token s-token:sym<Num>    {\d*\.?\d+}
  token s-token:sym<String> {'"' ['\"' |<-[\\"]>]*? '"'} #'
  token s-token:sym<Atom>   {<-[()\s]>+}

}

# The Actions class, for each syntactic rule there is a method
# that stores some data in the abstract syntax tree with make
class S-Exp::ACTIONS {
  method TOP ($/) {make $<s-list>.ast}
  method s-list ($/) {make [$<in_list>».ast]}
  method in_list ($/) {make $/.values[0].ast}

  method s-token:sym<Num> ($/){make +$/}
  method s-token:sym<String> ($/){make ~$/.substr(1,*-1)}
  method s-token:sym<Atom> ($/){make ~$/}
}

multi s-exp_writer (Positional $ary) {'(' ~ $ary.map(&s-exp_writer).join(' ') ~ ')'}
multi s-exp_writer (Numeric    $num) {~$num}
multi s-exp_writer (Str        $str) {
  return $str unless $str ~~ /<[(")]>|\s/;
  return '()' if $str eq '()';
  '"' ~ $str.subst('"', '\"' ) ~ '"';
}

my $s-exp = '((data "quoted data" 123 4.5)
 (data (!@# (4.5) "(more" "data)")))';

my $actions = S-Exp::ACTIONS.new();
my $raku_array = (S-Exp.parse($s-exp, :$actions)).ast;

say "the expression:\n$s-exp\n";
say "the Raku expression:\n{$raku_array.raku}\n";
say "and back:\n{s-exp_writer($raku_array)}";

```

Output:

```
the expression:
((data "quoted data" 123 4.5)
 (data (!@# (4.5) "(more" "data)")))

the Raku expression:
[["data", "quoted data", "123", 9/2], ["data", ["!\@#", [9/2], "(more", "data)"]]]

and back:
((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))
```


[User]
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result.

For example, for an addition, it is the operations    +↑    and    +↓    defined as:    *a* +↓ *b* ≤ *a* + *b* ≤ *a* +↑ *b*.

Additionally it is desired that the width of the interval    (*a* +↑ *b*) - (*a* +↓ *b*)    would be about the machine epsilon after removing the exponent part.

Differently to the standard floating-point arithmetic, safe interval arithmetic is **accurate** (but still imprecise).

I.E.:   the result of each defined operation contains (though does not identify) the exact mathematical outcome.

Usually a   FPU's   have machine    +,-,\*,/    operations accurate within the machine precision.

To illustrate it, let us consider a machine with decimal floating-point arithmetic that has the precision is **3** decimal points.

If the result of the machine addition is    1.23,    then the exact mathematical result is within the interval    ]1.22, 1.24[.

When the machine rounds towards zero, then the exact result is within    [1.23,1.24[.    This is the basis for an implementation of safe addition.

Task;

Show how    +↓    and    +↑    can be implemented in your language using the standard floating-point type.

Define an interval type based on the standard floating-point one,   and implement an interval-valued addition of two floating-point numbers considering them exact, in short an operation that yields the interval    [*a* +↓ *b*, *a* +↑ *b*].

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

Raku uses 64 bit IEEE floating points numbers which provide 53 binary digits
of accuracy. If you insist on using floats your answer will be accurate in the range
± 1.1102230246251565e-16. Raku actually makes it somewhat difficult to output
an exact stringified float with more than 15 digits of accuracy. It automatically
rounds since it doesn't try to pretend that it is more accurate than that.

If you really DO need very high precision and accuracy, Raku has native
built-in Rational number support. Rationals are the ratio of two integers, and
are always exact. Standard Rats are limited to 64 bits of precision in the
denominator. On overflow, they will downgrade to a float (Num).
FatRats have unlimited denominators.

There is no need to load any external libraries or force the use of Rats. Unless
you force it otherwise, decimal number are always stored as Rats as long as they
will fit within the denominator limit.

You can see the two integers making up the ratio of a Rat (or FatRat) using the
.nude method (**nu**merator, **de**nominator).

Rats and FatRats by default stringify to a fixed number of places for
non-terminating fractions and the same number of digits as the denominator for
terminating fractions. If you need more control over stringification, load the
module Rat::Precise for configurable stringification. Rat::Precise *only* affects
stringification, not calculation. Calculations are always done at full (exact) precision.

```
say "Floating points: (Nums)";
say "Error: " ~ (2**-53).Num;

sub infix:<±+> (Num $a, Num $b) {
    my \ε = (2**-53).Num;
    $a - ε + $b, $a + ε + $b,
}

printf "%4.16f .. %4.16f\n", (1.14e0 ±+ 2e3);

say "\nRationals:";

say ".1 + .2 is exactly equal to .3: ", .1 + .2 === .3;

say "\nLarge denominators require explicit coercion to FatRats:";
say "Sum of inverses of the first 500 natural numbers:";
my $sum = sum (1..500).map: { FatRat.new(1,$_) };
say $sum;
say $sum.nude;

{
    say "\nRat stringification may not show full precision for terminating fractions by default.";
    say "Use a module to get full precision.";
    use Rat::Precise; # module loading is scoped to the enclosing block
    my $rat = 1.5**63;
    say "\nRaku default stringification for 1.5**63:\n" ~ $rat; # standard stringification
    say "\nRat::Precise stringification for 1.5**63:\n" ~$rat.precise; # full precision
}

```

Output:

```
Floating points: (Nums)
Error: 1.1102230246251565e-16
2001.1400000000000000 .. 2001.1400000000000000

Rationals:
.1 + .2 is exactly equal to .3: True

Large denominators require explicit coercion to FatRats:
Sum of inverses of the first 500 natural numbers:
6.79282342999052460298928714536797369481981381439677911664308889685435662379055049245764940373586560391756598584375065928223134688479711715030249848314807266844371012370203147722209400570479644295921001097190193214586271
(6633384299891198065461433023874214660151383488987829406868700907802279376986364154005690172480537248349310365871218591743641116766728139494727637850449054802989613344274500453825922847052235859615378238909694581687099 976528297586037954584851660253897317730151176683856787284655867127950765610716178591036797598551026470244168088645451676177520177514977827924165875515464044694152207479405310883385229609852607806002629415184926954240)

Rat stringification may not show full precision for terminating fractions by default.
Use a module to get full precision.

Raku default stringification for 1.5**63:
124093581919.64894769782737365038

Rat::Precise stringification for 1.5**63:
124093581919.648947697827373650380188008224280338254175148904323577880859375

```


[User]
A prime number *p* is a Sophie Germain prime if 2*p* + 1 is also prime.
The number 2*p* + 1 associated with a Sophie Germain prime is called a **safe prime**.

Task

Generate the first   **50**   Sophie Germain prime numbers.

See also

* Wikipedia: Sophie Germain primes * OEIS:A005384 - Sophie Germain primes * Related Task: Safe\_primes\_and\_unsafe\_primes

[Assistant]
```
put join "\n", (^∞ .grep: { .is-prime && ($_*2+1).is-prime } )[^50].batch(10)».fmt: "%4d";

```

Output:

```
   2    3    5   11   23   29   41   53   83   89
 113  131  173  179  191  233  239  251  281  293
 359  419  431  443  491  509  593  641  653  659
 683  719  743  761  809  911  953 1013 1019 1031
1049 1103 1223 1229 1289 1409 1439 1451 1481 1499
```


[User]
Does the language implementation allow for a "safer mode" of execution? Usually termed **Safe mode**, a more realistic view is probably **Safer mode** or **restricted mode**. It is one thing to place restrictions on execution, and another thing entirely to allow execution of scripts from untrusted sources and assume nothing untoward will happen.

Along with a simple yes/no answer, describe what features are restricted when running in safe mode.

[Assistant]
(formerly Perl 6)

*Mostly a cut-n-paste from the Untrusted environment task.*

Raku doesn't really provide a high security mode for untrusted environments. By default, Raku is sort of a walled garden. It is difficult to access memory directly, especially in locations not controlled by the Raku interpreter, so unauthorized memory access is unlikely to be a threat with default Raku commands and capabilities.

It is possible (and quite easy) to run Raku with a restricted setting which will disable many IO commands that can be used to access or modify things outside of the Raku interpreter. However, a determined bad actor could theoretically work around the restrictions, especially if the nativecall interface is available. The nativecall interface allows directly calling in to and executing code from C libraries so anything possible in C is now possible in Raku. This is great for all of the power it provides, but along with that comes the responsibility and inherent security risk. The same issue arises with unrestricted loading of modules. If modules can be loaded, especially from arbitrary locations, then any and all restriction imposed by the setting can be worked around.

The restricted setting is modifiable, but by default places restrictions on or completely disables the following things:

User Subroutines (disabled)

:   * sub chmod() *modify filesystem permissions*
    * sub copy() *copy a file*
    * sub link() *create a link to a file*
    * sub mkdir() *make a filesystem directory*
    * sub open() *open a filesystem location / file*
    * sub pipe() *open a pipe*
    * sub QX() *execute arbitrary code*
    * sub rename() *rename a file*
    * sub rmdir() *remove a directory*
    * sub run() *run arbitrary code*
    * sub shell() *execute code in a shell*
    * sub socket() *open a socket*
    * sub spurt() *write a file*
    * sub symlink() *create a symbolic link to a location*
    * sub unlink() *delete a file*

Internal Subroutines (disabled)

:   * sub CHANGE-DIRECTORY *change directory*
    * sub CHMOD-PATH *change permissions*
    * sub COPY-FILE *copy a file*
    * sub MAKE-DIR *make a directory*
    * sub REMOVE-DIR *remove a directory*
    * sub RENAME-PATH *rename a directory*
    * sub SYMLINK-PATH *create a symbolic link*
    * sub UNLINK-PATH *delete a file*

Classes (disabled)

:   * class IO::CatHandle *streaming file handle*
    * class IO::Handle *file handle*
    * class IO::Path *filesystem path*
    * class IO::Pipe *OS pipe*
    * class IO::Socket *OS socket*
    * class IO::Socket::INET *Network socket*
    * class NativeCall *Nativecall interface to foreign code (C mostly)*
    * class Proc *OS Process*
    * class Proc::Async *Asynchronous OS Process*

Method Mixins / Roles (locked down so can't be overridden)

:   * method FALLBACK() *handle unknown method calls*
    * method new() *create a new instance*
    * method gist() *display method*

Really, if you want to lock down a Raku instance so it is "safe" for unauthenticated, untrusted, general access, you are better off running it in some kind of locked down virtual machine or sandbox managed by the operating system rather than trying to build an ad hoc "safe" environment.


[User]
Definitions
:   :   * A   **safe prime**   is a prime   **p**   and where   **(p-1)/2**   is also prime.
        * The corresponding prime  **(p-1)/2**   is known as a   **Sophie Germain**   prime.
        * An   **unsafe prime**   is a prime   **p**   and where   **(p-1)/2**   *isn't*   a prime.
        * An   **unsafe prime**   is a prime that   *isn't*   a   **safe**   prime.

Task
:   :   * Find and display (on one line) the first   **35**   safe primes.
        * Find and display the   *count*   of the safe primes below   1,000,000.
        * Find and display the   *count*   of the safe primes below 10,000,000.
        * Find and display (on one line) the first   **40**   unsafe primes.
        * Find and display the   *count*   of the unsafe primes below   1,000,000.
        * Find and display the   *count*   of the unsafe primes below 10,000,000.
        * (Optional)   display the   *counts*   and   "below numbers"   with commas.

Show all output here.

Related Task
:   :   * strong and weak primes.

Also see
:   :   * The OEIS article:     safe   primes.
        * The OEIS article:   unsafe primes.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.08

Raku has a built-in method .is-prime to test for prime numbers. It's great for testing individual numbers or to find/filter a few thousand numbers, but when you are looking for millions, it becomes a drag. No fear, the Raku ecosystem has a fast prime sieve module available which can produce 10 million primes in a few seconds. Once we have the primes, it is just a small matter of filtering and formatting them appropriately.

```
sub comma { $^i.flip.comb(3).join(',').flip }

use Math::Primesieve;

my $sieve = Math::Primesieve.new;

my @primes = $sieve.primes(10_000_000);

my %filter = @primes.Set;

my $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };

for 'safe', 35, 'unsafe', 40 -> $type, $quantity {
    say "The first $quantity $type primes are:";

    say $primes{$type}[^$quantity]».,

    say "The number of $type primes up to {comma $_}: ",
    comma $primes{$type}.first(* > $_, :k) // +$primes{$type} for 1e6, 1e7;

    say '';
}

```

Output:

```
The first 35 safe primes are:
(5 7 11 23 47 59 83 107 167 179 227 263 347 359 383 467 479 503 563 587 719 839 863 887 983 1,019 1,187 1,283 1,307 1,319 1,367 1,439 1,487 1,523 1,619)
The number of safe primes up to 1,000,000: 4,324
The number of safe primes up to 10,000,000: 30,657

The first 40 unsafe primes are:
(2 3 13 17 19 29 31 37 41 43 53 61 67 71 73 79 89 97 101 103 109 113 127 131 137 139 149 151 157 163 173 181 191 193 197 199 211 223 229 233)
The number of unsafe primes up to 1,000,000: 74,174
The number of unsafe primes up to 10,000,000: 633,922
```


[User]
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.

That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.

To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.

In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)

The task

1. Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
2. Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers *are* allowed.)
3. Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).
4. Show your answers here.

Extra credit (optional)

* Give some indication of the number of coconuts each sailor hides during the night.

Note

* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is *not* that tale!

C.f

* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015.09

There is nowhere in the spec where it explicitly states that the sailors cannot equally share zero coconuts in the morning. Actually, The On-Line Encyclopedia of Integer Sequences A002021 considers the cases for 1 and 2 sailors equally sharing zero coconuts in the morning to be the correct answer.

This will test combinations of sailors and coconuts to see if they form a valid pairing. The first 6 are done using brute force, testing every combination until a valid one is found. For cases of 7 to 15 sailors, it uses a carefully crafted filter to drastically reduce the number of trials needed to find a valid case (to one, as it happens... :-) )

```
my @ones = flat 'th', 'st', 'nd', 'rd', 'th' xx 6;
my @teens = 'th' xx 10;
my @suffix = lazy flat (@ones, @teens, @ones xx 8) xx *;

# brute force the first six
for 1 .. 6 -> $sailors { for $sailors .. * -> $coconuts { last if check( $sailors, $coconuts ) } }

# finesse 7 through 15
for 7 .. 15 -> $sailors { next if check( $sailors, coconuts( $sailors ) ) }

sub is_valid ( $sailors is copy, $nuts is copy ) {
    return 0, 0 if $sailors == $nuts == 1;
    my @shares;
    for ^$sailors {
        return () unless $nuts % $sailors == 1;
        push @shares, ($nuts - 1) div $sailors;
        $nuts -= (1 + $nuts div $sailors);
    }
    push @shares, $nuts div $sailors;
    return @shares if !?($nuts % $sailors);
}

sub check ($sailors, $coconuts) {
    if my @piles = is_valid($sailors, $coconuts) {
        say "\nSailors $sailors: Coconuts $coconuts:";
        for ^(@piles - 1) -> $k {
             say "{$k+1}@suffix[$k+1] takes @piles[$k], gives 1 to the monkey."
        }
        say "The next morning, each sailor takes @piles[*-1]\nwith none left over for the monkey.";
        return True;
    }
    False;
}

multi sub coconuts ( $sailors where { $sailors % 2 == 0 } ) { ($sailors - 1) * ($sailors ** $sailors - 1) }
multi sub coconuts ( $sailors where { $sailors % 2 == 1 } ) { $sailors ** $sailors - $sailors + 1 }

```

Output:

```
Sailors 1: Coconuts 1:
1st takes 0, gives 1 to the monkey.
The next morning, each sailor takes 0
with none left over for the monkey.

Sailors 2: Coconuts 3:
...

Sailors 5: Coconuts 3121:
1st takes 624, gives 1 to the monkey.
2nd takes 499, gives 1 to the monkey.
3rd takes 399, gives 1 to the monkey.
4th takes 319, gives 1 to the monkey.
5th takes 255, gives 1 to the monkey.
The next morning, each sailor takes 204
with none left over for the monkey.

Sailors 6: Coconuts 233275:
1st takes 38879, gives 1 to the monkey.
2nd takes 32399, gives 1 to the monkey.
3rd takes 26999, gives 1 to the monkey.
4th takes 22499, gives 1 to the monkey.
5th takes 18749, gives 1 to the monkey.
6th takes 15624, gives 1 to the monkey.
The next morning, each sailor takes 13020
with none left over for the monkey.

Sailors 7: Coconuts 823537:
...

Sailors 15: Coconuts 437893890380859361:
...

```


[User]
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important.

Any solution is allowed here, but many computer scientists will consider it inelegant to collect either fringe in its entirety before starting to collect the other one. In fact, this problem is usually proposed in various forums as a way to show off various forms of concurrency (tree-rotation algorithms have also been used to get around the need to collect one tree first). Thinking of it a slightly different way, an elegant solution is one that can perform the minimum amount of work to falsify the equivalence of the fringes when they differ somewhere in the middle, short-circuiting the unnecessary additional traversals and comparisons.

Any representation of a binary tree is allowed, as long as the nodes are orderable, and only downward links are used (for example, you may not use parent or sibling pointers to avoid recursion).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Unlike in Perl 5, where => is just a synonym for comma, in Raku it creates a true Pair object. So here we use Pair objects for our "cons" cells, just as if we were doing this in Lisp. We use the gather/take construct to harvest the leaves lazily as the elements are visited with a standard recursive algorithm, using multiple dispatch to differentiate nodes from leaves. The eqv value equivalence is applied to the two lists in parallel.

```
sub fringe ($tree) {
    multi sub fringey (Pair $node) { fringey $_ for $node.kv; }
    multi sub fringey ( Any $leaf) { take $leaf; }

    gather fringey $tree;
}

sub samefringe ($a, $b) { fringe($a) eqv fringe($b) }

# Testing:

my $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8;
my $b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8))));
my $c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8;

my $x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9;
my $y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8;
my $z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8;

say  so samefringe $a, $a;
say  so samefringe $a, $b;
say  so samefringe $a, $c;

say not samefringe $a, $x;
say not samefringe $a, $y;
say not samefringe $a, $z;

```

Output:

```
True
True
True
True
True
True
```


[User]
"Never trust user input." If the Super Mario Bros. 3 Wrong Warp or [Bobby Tables] have taught programmers anything, it's that user input can be dangerous in unexpected ways.

In general, the task of preventing errors such as the above are best left to the built-in security features of the language rather than a filter of your own creation. This exercise is to test your ability to think about all the possible ways user input could break your program.

Task

Create a function that takes a list of 20 first and last names, and copies them to a record or struct. Ten of them must be typical input, (i.e. consist of only letters of the alphabet and punctuation), but the other ten must be deliberately chosen to cause problems with a program that expects only letters and punctuation. A few examples:

* ASCII control codes such as NUL, CR, LF
* Code for the language you are using that can result in damage (e.g. -rm -rf, delete System32, DROP TABLE, etc.)
* Numbers, symbols, foreign languages, emojis, etc.

(There were already solutions provided before the requirement that ten names are "normal" and ten are potentially harmful was added. Those answers satisfied the task requirements at the time they were submitted.)

Related tasks

* Parametrized SQL statement

[Assistant]
It would be helpful if the task author would be a little more specific about what he is after. How user inputs must be "sanitized" entirely depends on how the data is going to be used.

For internal usage, in Raku, where you are simply storing data into an internal data structure, it is pretty much a non issue. Variables in Raku aren't executed without specific instructions to do so. Full stop.

Your name is a string of 2.6 million null bytes? Ok. Good luck typing that in.

You're called 'rm -rf /'? Wow. sucks to be you.

Now, it may be a good idea to check for a maximum permitted length; (2.6e6 null bytes) but Raku would handle it with no problem.

The problem mostly comes in when you need to interchange data with some 3rd party library / system; but every different system is going to have it's own quirks and caveats. There is no "one size fits all" solution.

In general, when it comes to sanitizing user input, the best way to go about it is: **don't**. It's a losing game.

Instead either validate input to make sure it follows a certain format, whitelist input so only a know few commands are permitted, or if those aren't possible, use 3rd party tools the 3rd party system provides to make arbitrary input "safe" to run. Which one of these is used depends on what system you need to interact with.

For the case given, (Bobby Tables), where you are presumably putting names into some 3rd party data storage (nominally a database of some kind), you would use bound parameters to automatically "make safe" any user input. See the Raku entry under the Parametrized SQL statement task.

Validating is making sure the the input matches some predetermined format, usually with some sort of regular expression. For names, you probably want to allow a fixed maximum (and minimum!) number of: any word or digit character, space and period characters and possibly some small selection of non-word characters. It is a careful balance between too restrictive and too permissive. You need to avoid falling into pre-conceived assumptions about:
names, time, gender, addresses, phone numbers... the list goes on.

When passing a user command to the operating system, you probably want to use whitelisting. Only a very few commands from a predetermined list are allowed to be used.

```
   if $command ∈ <ls time cd df> then { execute $command }

```

or some such. What the whitelist contains and how to determine if the input matches is a whole article in itself.

Unfortunately, this is very vague and hand-wavey due to the vagueness of the task description. Really, any language could copy/paste 95% or better of the above, change the language name, and be done with it. But until the task description is made a little more focused, it will have to do.


[User]
Most programming languages offer support for subroutines.
When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program.
Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping").
These sets may also be defined by special modifiers to the variable and function declarations.

Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function.
If your language has no scope modifiers, note it.

[Assistant]
(formerly Perl 6)
Raku has a system of declarators that introduce new names into various scopes.

```
my $lexical-variable;
our $package-variable;
state $persistent-lexical;
has $.public-attribute;

```

Lexically scoped variables, declared with my, are the norm.
Function definitions are intrinsically lexical by default, but allow for forward references, unlike any other declaration.

Package variables, declared with our, are de-emphasized. Unlike in Perl 5, almost no built-ins use package declarations for anything other than type names, and most of Perl 5's global punctuational variables become dynamic variables instead, with the final recourse in the GLOBAL and PROCESS packages. The per-interpreter GLOBAL package is mainly for users; all predefined process-wide information is stored in the PROCESS symbol table instead. The our declarator actually just declares an alias to a variable of the same name in the current package, and is in a sense just permission to use that global variable in the current scope as if it were a lexical. Type and constant declarations, including enums, are intrinsically considered "our" declarations, since Raku considers constants to be degenerate types.

State variables, declared with state, are persistent lexicals that are not re-initialized on each function entry, but retain their previous value. An initializer is run only the first time through. State variables are similar but not identical to C static variables; in Raku each closure clone gets its own state variable, since such closures are really a form of generic code.

The has declarator is for declaring items in object scope.
Method declarations are implicitly in "has" scope.

In Perl 5, dynamic scoping is done via "local" to temporarily change the value of a global variable. This mechanism is still specced for Raku, albeit with a different keyword, temp, that better reflects what it's doing. None of the implementations yet implement temp, since Raku does dynamic scoping via a more robust system of scanning up the call stack for the innermost dynamic declaration, which actually lives in the lexical scope of the function declaring it. We distinguish dynamic variables syntactically by introducing a "twigil" after the sigil. The twigil for dynamic variables is \* to represent that we don't know how to qualify the location of the variable.

```
sub a {
    my $*dyn = 'a';
    c();
}
sub b {
    my $*dyn = 'b';
    c();
}
sub c {
    say $*dyn;
}
a();  # says a
b();  # says b

```

The standard IO filehandles are dynamic variables $\*IN, $\*OUT, and $\*ERR, which allows a program to easily redirect the input or output from any subroutine and all its children. More generally, since most process-wide variables are accessed via this mechanism, and only look in the PROCESS package as a last resort, any chunk of code can pretend to be in a different kind of process environment merely by redefining one or more of the dynamic variables in question, such as %\*ENV.

This mechanism automatically produces thread-local storage if you declare your dynamic variable inside the lexical scope of the thread.


[User]
Task

Explain or demonstrate the levels of visibility of function names and labels within the language.

See also

* Variables for levels of scope relating to visibility of program variables
* Scope modifiers for general scope modification facilities

[Assistant]
(formerly Perl 6)

First a little hand-wavey exposition. The lines are rather blurry in Raku between subroutines, methods, operators and functions. Methods are associated with an object and are inheritable. Subroutines and operators are not. Other than that though there is a lot of overlap. "A function" doesn't really have a specific definition, but is more of a generic term used when talking about code reference type of things.

Methods don't have a separate scope from the object they are attached to. If the object is in scope, the method will be.

A subroutine is really just another type of object. It has a code reference and has ROUTINE semantics attached to it. The same holds for operators. Operators are really just subroutines with a funny calling convention. That being the case, scoping for subroutines very closely follows scoping rules for any other Raku variable type.

In general, subroutines are "my" variables by default (if you don't specify, the "my" is implicit), meaning scoping is lexical to the enclosing block and flows inward. A subroutine defined within a block will be visible to everything inside that block, even other blocks within that block. However, any inner block can define its own subroutine with the same name and that will be used in preference to the routine from an outer block. That implies you can easily override / redefine core functions from the Raku setting. The setting is the collection of built in functions supplied by Raku, typically and somewhat incongruously referred to as "CORE" even though technically it is the outermost scope. ( SKIN? BARK? CRUST? ... oooo! EXOSKELETON! :-) )

Alternately, subroutines may be declared as an "our" variable making it a package global, visible anywhere in the packages' namespace. That is somewhat discouraged though as it pollutes the namespace and reduces the granularity of control.

There are several ways to modify the relative scope of a subroutine (any item in the symbol table really) by adding modifiers to the name.

```
CALLER    # Contextual symbols in the immediate caller's lexical scope
OUTER     # Symbols in the next outer lexical scope
UNIT      # Symbols in the outermost lexical scope of compilation unit
SETTING   # Lexical symbols in the unit's DSL (usually CORE)
PARENT    # Symbols in this package's parent package (or lexical scope)

```

```
# call a routine before it has been defined
say log();              # prints: outer

# define a subroutine that overrides a CORE function
sub log { 'outer' };
{
    # redefine the subroutine in this block
    sub log { 'inner' };
    {
        # redefine the subroutine yet again
        sub log { 'way down inside' };

        # call it within this block
        say log();                 # prints: way down inside

        # call it from the block one level out
        say &OUTER::log();         # prints: inner

        # call it from the block two levels out
        say &OUTER::OUTER::log();  # prints: outer

        # call it from the outermost block
        say &UNIT::log();          # prints: outer

        # call a subroutine that is post declared in outermost scope
        outersub()
    }

    {
        # subroutine in an inner block that doesn't redefine it
        # uses definition from nearest enclosing block
        say log();      # prints: inner
    }
    # call it within this block
    say log();          # prints: inner

    # call it from the block one level out
    say &OUTER::log();  # prints: outer
}

sub outersub{
    # call subroutine within this block - gets outer sub
    say log();          # prints: outer

    # call subroutine from the scope of the callers block
    say &CALLER::log(); # prints: way down inside

    # call subroutine from the outer scope of the callers block
    say &CALLER::OUTER::log(); # prints: inner

    # call the original overridden CORE routine
    say &CORE::log(e);  # prints: 1 ( natural log of e )
}

```

Labels are less interesting and are typically useful only for control flow in looping constructs. They generally follow the same scoping rules as "my" variables. There is nearly always easier ways to do control flow though, so they aren't heavily used.


[User]
Definition

In object-oriented programming, a **sealed** or **final class** is one which cannot be inherited from.

Classes are sometimes made non-subclassable in this way if the author feels that it would not be useful or even undesirable for subclasses to be created from them. Moreover, in a compiled language, knowing that a class cannot be subclassed, may enable optimizations to be made.

Rather than sealing the entire class, it may be possible to just seal certain methods for the same reasons and with the same potential benefits.

Task

If your language supports the object oriented paradigm, explain what support it has for sealed classes and/or methods and, if there is no support, what if anything can be done to simulate them. If possible illustrate your answer with an example.

If your language does not support the object oriented paradigm (or its inheritance aspect), you may either simply say so, omit the task altogether or describe any equivalent structure(s) and restrictions on use which the language does have.

Reference

* Inheritance Non-subclassable classes

Related task

* Classes
* Inheritance/Single
* Inheritance/Multiple

[Assistant]
Raku doesn't have final class but Roles is normally used to mimic the goal.

```
# 20240626 Raku programming solution

role MovieWatcherRole { has Str $.name;
   method WatchMovie() { say "$.name is watching the movie."   }
   method EatPopcorn() { say "$.name is enjoying the popcorn." }
}

class MovieWatcher does MovieWatcherRole {
   method new(Str $name) { self.bless(:$name) }
}

class ParentMovieWatcher is MovieWatcher { }

role ChildMovieWatcherRole {
   method EatPopcorn() { say "$.name is eating too much popcorn." }
}

class ChildMovieWatcher is MovieWatcher does ChildMovieWatcherRole { }

role YoungChildMovieWatcherRole {
   method WatchMovie() {
      say "Sorry, $.name, you are too young to watch the movie."
   }
}

class YoungChildMovieWatcher is ChildMovieWatcher does YoungChildMovieWatcherRole { }

for ParentMovieWatcher.new('Donald'),
    ChildMovieWatcher.new('Lisa'),
    YoungChildMovieWatcher.new('Fred')
{ .WatchMovie and .EatPopcorn }

```

You may Attempt This Online!


[User]
Task[edit]

Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).

Raise an exception if the needle is missing.

If there is more than one occurrence then return the smallest index to the needle.

Extra credit

Return the largest index to a needle that has multiple occurrences in the haystack.

See also

* Search a list of records

---

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo Star version 2016.07

```
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;

for <Washington Bush> -> $needle {
    say "$needle -- { @haystack.first($needle, :k) // 'not in haystack' }";
}
```

Output:

```
Washington -- not in haystack
Bush -- 4

```

Or, including the "extra credit" task:

**Works with**: Rakudo Star version 2016.07

```
my Str @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;

for <Washingston Bush> -> $needle {
    my $first = @haystack.first($needle, :k);

    if defined $first {
        my $last = @haystack.first($needle, :k, :end);
        say "$needle -- first at $first, last at $last";
    }
    else {
        say "$needle -- not in haystack";
    }
}
```

Output:

```
Washingston -- not in haystack
Bush -- first at 4, last at 7

```

The built-in method `.first` takes a smart-matcher, and returns the first matching list element.
The `:k` adverb tells it to return the key (a.k.a. list index) instead of the value of the matching element.
The `:end` adverb tells it to start searching from the end of the list.

If you plan to do many searches on the same large list, you might want to build a search hash first for efficient look-up:

```
my @haystack = <Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo>;

my %index;
%index{.value} //= .key for @haystack.pairs;

for <Washington Bush> -> $needle {
    say "$needle -- { %index{$needle} // 'not in haystack' }";
}
```


[User]
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers.
But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test?

Task[edit]

Write a function/method/etc. that can find the first element in a given list matching a given condition.
It should be as generic and reusable as possible.
(Of course if your programming language already provides such a feature, you can use that instead of recreating it.)

Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases.

Data set

The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON:

```
[
  { "name": "Lagos",                "population": 21.0  },
  { "name": "Cairo",                "population": 15.2  },
  { "name": "Kinshasa-Brazzaville", "population": 11.3  },
  { "name": "Greater Johannesburg", "population":  7.55 },
  { "name": "Mogadishu",            "population":  5.85 },
  { "name": "Khartoum-Omdurman",    "population":  4.98 },
  { "name": "Dar Es Salaam",        "population":  4.7  },
  { "name": "Alexandria",           "population":  4.58 },
  { "name": "Abidjan",              "population":  4.4  },
  { "name": "Casablanca",           "population":  3.98 }
]

```

However, you shouldn't parse it from JSON, but rather represent it natively in your programming language.

* The top-level data structure should be an **ordered** collection *(i.e. a list, array, vector, or similar)*.
* Each element in this list should be an **associative** collection that maps from keys to values *(i.e. a struct, object, hash map, dictionary, or similar)*.
* Each of them has two entries: One string value with key "name", and one numeric value with key "population".
* You may rely on the list being sorted by population count, as long as you explain this to readers.

If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution.

Test cases

| Search | Expected result |
| --- | --- |
| Find the (zero-based) **index** of the first city in the list whose **name is "Dar Es Salaam"** | 6 |
| Find the **name** of the first city in this list whose **population is less than 5 million** | Khartoum-Omdurman |
| Find the **population** of the first city in this list whose **name starts with the letter "A"** | 4.58 |

Guidance

If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find\_index" or similar), that takes two arguments:

1. The list to search through.
2. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement.

If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is.

Related tasks

* Search a list

---

[Assistant]
(formerly Perl 6)

The built-in method .first fulfills the requirements of this task.
It takes any smart-matcher as a predicate. The :k adverb makes it return the key (i.e. numerical index) instead of the value of the element.

**Works with**: Rakudo version 2016.08

```
my @cities =
  { name => 'Lagos',                population => 21.0  },
  { name => 'Cairo',                population => 15.2  },
  { name => 'Kinshasa-Brazzaville', population => 11.3  },
  { name => 'Greater Johannesburg', population =>  7.55 },
  { name => 'Mogadishu',            population =>  5.85 },
  { name => 'Khartoum-Omdurman',    population =>  4.98 },
  { name => 'Dar Es Salaam',        population =>  4.7  },
  { name => 'Alexandria',           population =>  4.58 },
  { name => 'Abidjan',              population =>  4.4  },
  { name => 'Casablanca',           population =>  3.98 },
;

say @cities.first(*<name> eq 'Dar Es Salaam', :k);
say @cities.first(*<population> < 5).<name>;
say @cities.first(*<name>.match: /^A/).<population>;

```

Output:

```
6
Khartoum-Omdurman
4.58

```