[User]
Suppose you're on a game show and you're given the choice of three doors.

Behind one door is a car; behind the others, goats.

The car and the goats were placed randomly behind the doors before the show.

Rules of the game

After you have chosen a door, the door remains closed for the time being.

The game show host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.

If both remaining doors have goats behind them, he chooses one randomly.

After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.

Imagine that you chose Door 1 and the host opens Door 3, which has a goat.

He then asks you "Do you want to switch to Door Number 2?"

The question

Is it to your advantage to change your choice?

Note

The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.

Task

Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.

Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.

References
:   * Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
    * A YouTube video:   Monty Hall Problem - Numberphile.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

This implementation is parametric over the number of doors. Increasing the number of doors in play makes the superiority of the switch strategy even more obvious.

```
enum Prize <Car Goat>;
enum Strategy <Stay Switch>;

sub play (Strategy $strategy, Int :$doors = 3) returns Prize {

    # Call the door with a car behind it door 0. Number the
    # remaining doors starting from 1.
    my Prize @doors = flat Car, Goat xx $doors - 1;

    # The player chooses a door.
    my Prize $initial_pick = @doors.splice(@doors.keys.pick,1)[0];

    # Of the n doors remaining, the host chooses n - 1 that have
    # goats behind them and opens them, removing them from play.
    while @doors > 1 {
	@doors.splice($_,1)
	    when Goat
		given @doors.keys.pick;
    }

    # If the player stays, they get their initial pick. Otherwise,
    # they get whatever's behind the remaining door.
    return $strategy === Stay ?? $initial_pick !! @doors[0];
}

constant TRIALS = 10_000;

for 3, 10 -> $doors {
    my atomicint @wins[2];
    say "With $doors doors: ";
    for Stay, 'Staying', Switch, 'Switching' -> $s, $name {
        (^TRIALS).race.map: {
            @wins[$s]⚛++ if play($s, doors => $doors) == Car;
        }
        say "  $name wins ",
            round(100*@wins[$s] / TRIALS),
            '% of the time.'
    }
}

```

Output:

```
With 3 doors:
  Staying wins 34% of the time.
  Switching wins 66% of the time.
With 10 doors:
  Staying wins 10% of the time.
  Switching wins 90% of the time.
```


[User]
Morse code is one of the simplest and most versatile methods of telecommunication in existence.
It has been in use for more than 175 years — longer than any other electronic encoding system.

Task

Send a string as audible Morse code to an audio device   (e.g., the PC speaker).

As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file,
or indicate them somehow   (e.g. with a different pitch).

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-09-24

Here we use the user as the audio device.
Just read the output, leaving extra pauses where indicated
by either whitespace or underscore.

```
my %m = ' ', '_ _ ',
|<
    !	---.
    "	.-..-.
    $	...-..-
    '	.----.
    (	-.--.
    )	-.--.-
    +	.-.-.
    ,	--..--
    -	-....-
    .	.-.-.-
    /	-..-.
    :	---...
    ;	-.-.-.
    =	-...-
    ?	..--..
    @	.--.-.
    [	-.--.
    ]	-.--.-
    _	..--.-
    0	-----
    1	.----
    2	..---
    3	...--
    4	....-
    5	.....
    6	-....
    7	--...
    8	---..
    9	----.
    A	.-
    B	-...
    C	-.-.
    D	-..
    E	.
    F	..-.
    G	--.
    H	....
    I	..
    J	.---
    K	-.-
    L	.-..
    M	--
    N	-.
    O	---
    P	.--.
    Q	--.-
    R	.-.
    S	...
    T	-
    U	..-
    V	...-
    W	.--
    X	-..-
    Y	-.--
    Z	--..
>.map: -> $c, $m is copy {
    $m.=subst(rx/'-'/, 'BGAAACK!!! ', :g);
    $m.=subst(rx/'.'/, 'buck ', :g);
    $c => $m ~ '_';
}

say prompt("Gimme a string: ").uc.comb.map: { %m{$_} // "<scratch> " }

```

Sample run:

Gimme a string: **Howdy, World!**

buck buck buck buck \_ BGAAACK!!! BGAAACK!!! BGAAACK!!! \_ buck BGAAACK!!! BGAAACK!!! \_ BGAAACK!!! buck buck \_ BGAAACK!!! buck BGAAACK!!! BGAAACK!!! \_ BGAAACK!!! BGAAACK!!! buck buck BGAAACK!!! BGAAACK!!! \_ \_ \_ buck BGAAACK!!! BGAAACK!!! \_ BGAAACK!!! BGAAACK!!! BGAAACK!!! \_ buck BGAAACK!!! buck \_ buck BGAAACK!!! buck buck \_ BGAAACK!!! buck buck \_ BGAAACK!!! BGAAACK!!! BGAAACK!!! buck \_


[User]
Task

Draw a 'mosaic' matrix which, for the purposes of this task, is a square matrix which has 1's in alternate cells (both horizontally and vertically) starting with a 1 in the top-left hand cell.

Other cells can either be left blank or filled with some other character.

If you can please use GUI

Mosaic Matrix - image

### See also

* Four sides of square
* Matrix with two diagonals

[Assistant]
This isn't a matrix, especially if it is supposed to be graphical; it's a very small (or extremely low resolution) bitmap.

```
sub checker ($n) { (^$n).map: { 1 xx $n Z× (flat ($_ %% 2, $_ % 2) xx *) } }

.put for checker 7;
put '';
.put for checker 8;

```

Output:

```
1 0 1 0 1 0 1
0 1 0 1 0 1 0
1 0 1 0 1 0 1
0 1 0 1 0 1 0
1 0 1 0 1 0 1
0 1 0 1 0 1 0
1 0 1 0 1 0 1

1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
```


[User]
The string distance function (SDF) that is the subject of this entry
was proposed in a paper published in 2014 as a method for quickly
estimating how similar two
ordered sets or
strings are.
This SDF has also been proposed as being suitable in bioinformatics, e.g. for comparing sequences in the wp:fasta format.

Unfortunately, the original paper
by Sadi Evren Seker et al.
(arXiv:1401.6596 [cs.DS])
[1]
has a number of internal inconsistencies and for this and other
reasons is not entirely clear in several key respects, but the paper
does give some worked examples and several of these (notably the two
given under the "Worked Examples" heading below) agree with the
interpretation used by the authors of the Python entry herein, so that
interpretation is used in the present task description.

The Task

(a) Show a time-efficient implementation of the SDF as if by a
function mostFreqKSDF(s1, s2, k, n), where s1 and s2 are arbitrary
strings, and k and n are non-negative integers as explained below;

(b) Show the values produced by the SDF for the following values of s1 and s2,
with k = 2 and n = 10:

| String Inputs | "Top Two" | SDF Output (k=2, n=10) |
| --- | --- | --- |
| 'night' 'nacht' | n:1 i:1 n:1 a:1 | 8 |
| 'my' 'a' | m:1 y:1 a:1 | 10 |
| ‘research’ ‘research’ | r:2 e:2 r:2 e:2 | 2 |
| ‘significant’ ‘capabilities’ | i:3 n:2 i:3 a:2 | 4 |

(c) Show the value produced by the SDF for k = 2, n = 100,
and the two strings:

"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"

Reference Algorithm

The original paper employs an unusual scheme for encoding the
frequencies of single letters as a string of letters and numbers. This
scheme has several disadvantages, and so in the following we take a
more abstract view and simply assume, solely for the purposes
of this description, that two functions are available:

1) MostFreqK(s, k) returns (in decreasing order of their frequency of occurrence)
the k most frequently occurring letters in s, with
any ties broken by the position of the first occurrence in s;

2) For any letter c in MostFreqK(s, k), Freq(s,c) returns the frequency
of c in s.

MFKsimilarity

Next define MFKsimilarlity(s1, s2, k) as if by the following pseudo-code:

```
int function MFKsimilarity(string s1, string s2, int k):
    let similarity = 0
    let mfk1 = MostFreqK(s1, k)
    let mfk2 = MostFreqK(s2, k)
    for each c in mfk1
        if (c occurs in mfk2)
        then similarity += Freq(s1, c) + Freq(s2, c)
	end
    return similarity

```

String Distance Wrapper Function

Now define MostFreqKSDF as if by:

```
int function MostFreqKSDF(string s1, string s2, int k, int n)
    return n - MFKsimilarity(s1, s2, k)

```

Worked Examples

The original paper gives several worked examples, including
these two:

(i) MostFreqKSDF("night", "nacht", 2, 10)

For "night", the "top two" letters with their frequencies are: n:1 and i:1.

For "nacht", the "top two" letters with their frequencies are: n:1 and a:1.

Since "n" is the only shared letter amongst these candidates, the
SDF is 10 - 1 - 1 = 8, as per the original paper.

(2)
MostFreqKSDF(
"LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV",
"EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG",
2, 100)

For the first string, the "top two" letters with their frequencies are: L:9 and T:8;
and for the second, the "top two" are F:9 and L:8.

Since "L" is the only shared letter amongst these top-k characters, and since the sum of the corresponding frequencies is 9+8 = 17, the SDF is 83.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.09

My initial impressions of this task are registered on the discussion page under "Prank Page?".

The "most frequent k characters" hashing function is straightforward enough to implement. The distance function is incomprehensible though. The description doesn't match the pseudo-code and neither of them match the examples. I'm not going to bother trying to figure it out unless there is some possible value.

Maybe I am too hasty though. Lets give it a try. Implement a MFKC routine and run an assortment of words through it to get a feel for how it hashes different words.

```
# Fairly straightforward implementation, actually returns a list of pairs
# which can be joined to make a string or manipulated further.

sub mfkh ($string, \K = 2) {
    my %h;
    $string.comb.kv.map: { %h{$^v}[1] //= $^k; %h{$^v}[0]++ };
    %h.sort( { -$_.value[0], $_.value[1] } ).head(K).map( { $_.key => $_.value[0] } );
}

# lets try running 150 or so words from unixdic.txt through it to see
# how many unique hash values it comes up with.

my @test-words = <
    aminobenzoic arginine asinine biennial biennium brigantine brinkmanship
    britannic chinquapin clinging corinthian declination dickinson dimension
    dinnertime dionysian diophantine dominican financial financier finessing
    fingernail fingerprint finnish giovanni hopkinsian inaction inalienable
    inanimate incaution incendiary incentive inception incident incidental
    incinerate incline inclusion incommunicable incompletion inconceivable
    inconclusive incongruity inconsiderable inconsiderate inconspicuous
    incontrovertible inconvertible incurring incursion indefinable indemnify
    indemnity indeterminacy indian indiana indicant indifferent indigene
    indigenous indigent indispensable indochina indochinese indoctrinate
    indonesia inequivalent inexplainable infantile inferential inferring
    infestation inflammation inflationary influential information infringe
    infusion ingenious ingenuity ingestion ingredient inhabitant inhalation
    inharmonious inheritance inholding inhomogeneity inkling inoffensive
    inordinate inorganic inputting inseminate insensible insincere insinuate
    insistent insomnia insomniac insouciant installation instinct instinctual
    insubordinate insubstantial insulin insurrection intangible intelligent
    intensify intensive interception interruption intestinal intestine
    intoxicant introduction introversion intrusion invariant invasion inventive
    inversion involution justinian kidnapping kingpin lineprinter liniment
    livingston mainline mcginnis minion minneapolis minnie pigmentation
    pincushion pinion quinine quintessential resignation ruination seminarian
    triennial wilkinson wilmington wilsonian wineskin winnie winnipeg
>;

say @test-words.map( { join '', mfkh($_)».kv } ).Bag;

```

Output:

```
Bag(i2n2(151))
```

One... Nope, I was right, it *is* pretty much worthless.


[User]
Definition

The **n**th Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between **n** points on a circle (not necessarily touching every point by a chord).

By convention M[0] = 1.

Task

Compute and show on this page the first **42** Motzkin numbers or, if your language does not support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.

See also

* oeis:A001006 Motzkin numbers

[Assistant]
### Using binomial coefficients and Catalan numbers

```
use Lingua::EN::Numbers;

constant \C = 1, |[\×] (2, 6 … ∞) Z/ 2 .. *;

sub binomial { [×] ($^n … 0) Z/ 1 .. $^p }

my \𝐌 = 1, |(1..∞).map: -> \𝐧 { sum ^𝐧 .map( -> \𝐤 { C[𝐤] × binomial 𝐧, 2×𝐤 } ) };

say " 𝐧          𝐌[𝐧]            Prime?";
𝐌[^42].kv.map: { printf "%2d %24s  %s\n", $^k, $^v.&comma, $v.is-prime };

```

Output:

```
 𝐧          𝐌[𝐧]            Prime?
 0                        1  False
 1                        1  False
 2                        2  True
 3                        4  False
 4                        9  False
 5                       21  False
 6                       51  False
 7                      127  True
 8                      323  False
 9                      835  False
10                    2,188  False
11                    5,798  False
12                   15,511  True
13                   41,835  False
14                  113,634  False
15                  310,572  False
16                  853,467  False
17                2,356,779  False
18                6,536,382  False
19               18,199,284  False
20               50,852,019  False
21              142,547,559  False
22              400,763,223  False
23            1,129,760,415  False
24            3,192,727,797  False
25            9,043,402,501  False
26           25,669,818,476  False
27           73,007,772,802  False
28          208,023,278,209  False
29          593,742,784,829  False
30        1,697,385,471,211  False
31        4,859,761,676,391  False
32       13,933,569,346,707  False
33       40,002,464,776,083  False
34      114,988,706,524,270  False
35      330,931,069,469,828  False
36      953,467,954,114,363  True
37    2,750,016,719,520,991  False
38    7,939,655,757,745,265  False
39   22,944,749,046,030,949  False
40   66,368,199,913,921,497  False
41  192,137,918,101,841,817  False
```

### Using recurrence relationship

```
use Lingua::EN::Numbers;

my \𝐌 = 1, 1, { state $i = 2; ++$i; ($^b × (2 × $i - 1) + $^a × (3 × $i - 6)) ÷ ($i + 1) } … *;

say " 𝐧          𝐌[𝐧]            Prime?";
𝐌[^42].kv.map: { printf "%2d %24s  %s\n", $^k, $^v.&comma, $v.is-prime };

```

Same output


[User]
Task

Get the current location of the mouse cursor relative to the active window.

Please specify if the window may be externally created.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo/jvm version 2013-12-03

```
use java::awt::MouseInfo:from<java>;

given MouseInfo.getPointerInfo.getLocation {
    say .getX, 'x', .getY;
}

```

An implementation that will work on any X11 windowing system. Reports mouse position, window ID# and window name for whichever window the mouse pointer is over. Automatically moves mouse for hands-off testing purposes.

**Works with**: Rakudo version 2018.11

```
use X11::libxdo;
my $xdo = Xdo.new;

my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );

sleep .25;

for ^$dw -> $mx {
    my $my = (($mx / $dh * τ).sin * 500).abs.Int + 200;
    $xdo.move-mouse( $mx, $my, 0 );
    my ($x, $y, $window-id, $screen) = $xdo.get-mouse-info;
    my $name = (try $xdo.get-window-name($window-id) if $window-id)
       // 'No name set';

    my $line = "Mouse location: x=$x : y=$y\nWindow under mouse:\nWindow ID: " ~
       $window-id ~ "\nWindow name: " ~ $name ~ "\nScreen #: $screen";

    print "\e[H\e[J", $line;
    sleep .001;
}

say '';

```


[User]
Given a symbol table of a *zero-indexed* array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).

The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms.

Encoding algorithm

```
    for each symbol of the input sequence:
        output the index of the symbol in the symbol table
        move that symbol to the front of the symbol table

```

Decoding algorithm

```
    # Using the same starting symbol table
    for each index of the input sequence:
        output the symbol at that index of the symbol table
        move that symbol to the front of the symbol table

```

Example

Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters   **a**-to-**z**

:   :   :   :   :   | Input | Output | SymbolTable |
                    | --- | --- | --- |
                    | **b**roood | 1 | 'abcdefghijklmnopqrstuvwxyz' |
                    | b**r**oood | 1 17 | 'bacdefghijklmnopqrstuvwxyz' |
                    | br**o**ood | 1 17 15 | 'rbacdefghijklmnopqstuvwxyz' |
                    | bro**o**od | 1 17 15 0 | 'orbacdefghijklmnpqstuvwxyz' |
                    | broo**o**d | 1 17 15 0 0 | 'orbacdefghijklmnpqstuvwxyz' |
                    | brooo**d** | 1 17 15 0 0 5 | 'orbacdefghijklmnpqstuvwxyz' |

Decoding the indices back to the original symbol order:

:   :   :   :   :   | Input | Output | SymbolTable |
                    | --- | --- | --- |
                    | **1** 17 15 0 0 5 | b | 'abcdefghijklmnopqrstuvwxyz' |
                    | 1 **17** 15 0 0 5 | br | 'bacdefghijklmnopqrstuvwxyz' |
                    | 1 17 **15** 0 0 5 | bro | 'rbacdefghijklmnopqstuvwxyz' |
                    | 1 17 15 **0** 0 5 | broo | 'orbacdefghijklmnpqstuvwxyz' |
                    | 1 17 15 0 **0** 5 | brooo | 'orbacdefghijklmnpqstuvwxyz' |
                    | 1 17 15 0 0 **5** | broood | 'orbacdefghijklmnpqstuvwxyz' |

Task
:   * Encode and decode the following three strings of characters using the symbol table of the lowercase characters   **a**-to-**z**   as above.
    * Show the strings and their encoding here.
    * Add a check to ensure that the decoded string is the same as the original.

The strings are:

```
   broood
   bananaaa
   hiphophiphop

```

(Note the misspellings in the above strings.)

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-09-24

```
sub encode ( Str $word ) {
    my @sym = 'a' .. 'z';
    gather for $word.comb -> $c {
	die "Symbol '$c' not found in @sym" if $c eq @sym.none;
        @sym[0 .. take (@sym ... $c).end] .= rotate(-1);
    }
}

sub decode ( @enc ) {
    my @sym = 'a' .. 'z';
    [~] gather for @enc -> $pos {
        take @sym[$pos];
        @sym[0..$pos] .= rotate(-1);
    }
}

use Test;
plan 3;
for <broood bananaaa hiphophiphop> -> $word {
    my $enc = encode($word);
    my $dec = decode($enc);
    is $word, $dec, "$word.fmt('%-12s') ($enc[])";
}

```

Output:

```
1..3
ok 1 - broood       (1 17 15 0 0 5)
ok 2 - bananaaa     (1 1 13 1 1 1 0 0)
ok 3 - hiphophiphop (7 8 15 2 15 2 2 3 2 2 3 2)
```


[User]
Prime numbers are prime no matter what base they are represented in.

A prime number in a base other than 10 may not *look* prime at first glance.

For instance: **19** base 10 is **25** in base 7.

Several different prime numbers may be expressed as the "same" string when converted to a different base.

* **107** base **10** converted to base **6** == **255**

* **173** base **10** converted to base **8** == **255**

* **353** base **10** converted to base **12** == **255**

* **467** base **10** converted to base **14** == **255**

* **743** base **10** converted to base **18** == **255**

* **1277** base **10** converted to base **24** == **255**

* **1487** base **10** converted to base **26** == **255**

* **2213** base **10** converted to base **32** == **255**

Task

Restricted to bases **2** through **36**; find the strings that have the most different bases that evaluate to that string when converting prime numbers to a base.

Find the conversion string, the amount of bases that evaluate a prime to that string and the enumeration of bases that evaluate a prime to that string.

Display here, on this page, the string, the count and the list for all of the: **1** character, **2** character, **3** character, and **4** character strings that have the **maximum** base count that evaluate to that string.

*Should be no surprise, the string '2' has the largest base count for single character strings.*

Stretch goal

Do the same for the maximum **5** character string.

[Assistant]
Up to 4 character strings finish fairly quickly. 5 character strings take a while.

*All your base are belong to us. You have no chance to survive make your prime.*

```
use Math::Primesieve;
my $sieve = Math::Primesieve.new;

my %prime-base;

my $chars = 4; # for demonstration purposes. Change to 5 for the whole shmegegge.

my $threshold = ('1' ~ 'Z' x $chars).parse-base(36);

my @primes = $sieve.primes($threshold);

%prime-base.push: $_ for (2..36).map: -> $base {
    $threshold = (($base - 1).base($base) x $chars).parse-base($base);
    @primes[^(@primes.first: * > $threshold, :k)].race.map: { .base($base) => $base }
}

%prime-base.=grep: +*.value.elems > 10;

for 1 .. $chars -> $m {
    say "$m character strings that are prime in maximum bases: " ~ (my $e = ((%prime-base.grep( *.key.chars == $m )).max: +*.value.elems).value.elems);
    .say for %prime-base.grep( +*.value.elems == $e ).grep(*.key.chars == $m).sort: *.key;
    say '';
}

```

Output:

```
1 character strings that are prime in maximum bases: 34
2 => [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36]

2 character strings that are prime in maximum bases: 18
21 => [3 5 6 8 9 11 14 15 18 20 21 23 26 29 30 33 35 36]

3 character strings that are prime in maximum bases: 18
131 => [4 5 7 8 9 10 12 14 15 18 19 20 23 25 27 29 30 34]
551 => [6 7 11 13 14 15 16 17 19 21 22 24 25 26 30 32 35 36]
737 => [8 9 11 12 13 15 16 17 19 22 23 24 25 26 29 30 31 36]

4 character strings that are prime in maximum bases: 19
1727 => [8 9 11 12 13 15 16 17 19 20 22 23 24 26 27 29 31 33 36]
5347 => [8 9 10 11 12 13 16 18 19 22 24 25 26 30 31 32 33 34 36]

5 character strings that are prime in maximum bases: 18
30271 => [8 10 12 13 16 17 18 20 21 23 24 25 31 32 33 34 35 36]
```

You can't really assume that the maximum string will be all numeric digits. It is just an accident that they happen to work out that way with a upper limit of base 36. If we do the same filtering using a maximum of base 62, we end up with several that contain alphabetics.

```
use Math::Primesieve;
use Base::Any;

my $chars = 4;
my $check-base = 62;
my $threshold = $check-base ** $chars + 20;

my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes($threshold);

my %prime-base;

%prime-base.push: $_ for (2..$check-base).map: -> $base {
    $threshold = (($base - 1).&to-base($base) x $chars).&from-base($base);
    @primes[^(@primes.first: * > $threshold, :k)].race.map: { .&to-base($base) => $base }
}

%prime-base.=grep: +*.value.elems > 10;

for 1 .. $chars -> $m {
    say "$m character strings that are prime in maximum bases: " ~ (my $e = ((%prime-base.grep( *.key.chars == $m )).max: +*.value.elems).value.elems);
    .say for %prime-base.grep( +*.value.elems == $e ).grep(*.key.chars == $m).sort: *.key;
    say '';
}

```

Yields:

```
1 character strings that are prime in maximum bases: 60
2 => [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62]

2 character strings that are prime in maximum bases: 31
65 => [7 8 9 11 13 14 16 17 18 21 22 24 27 28 29 31 32 37 38 39 41 42 43 44 46 48 51 52 57 58 59]

3 character strings that are prime in maximum bases: 33
1L1 => [22 23 25 26 27 28 29 30 31 32 33 34 36 38 39 40 41 42 43 44 45 46 48 51 52 53 54 57 58 59 60 61 62]
B9B => [13 14 15 16 17 19 20 21 23 24 26 27 28 30 31 34 36 39 40 42 45 47 49 50 52 53 54 57 58 59 60 61 62]

4 character strings that are prime in maximum bases: 32
1727 => [8 9 11 12 13 15 16 17 19 20 22 23 24 26 27 29 31 33 36 37 38 39 41 45 46 48 50 51 57 58 60 61]
417B => [12 13 15 16 17 18 19 21 23 25 28 30 32 34 35 37 38 39 41 45 48 49 50 51 52 54 56 57 58 59 61 62]
```


[User]
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.

It is enough to:

1. State the number and extent of each index to the array.
2. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
3. Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.

Task

* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array.
   The idiomatic method for the language is preferred.

:   * The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, *if* indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).

* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.

Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).

[Assistant]
(formerly Perl 6)

```
# Raku supports multi dimension arrays natively. There are no arbitrary limits on the number of dimensions or maximum indices. Theoretically, you could have an infinite number of dimensions of infinite length, though in practice more than a few dozen dimensions gets unwieldy. An infinite maximum index is a fairly common idiom though. You can assign an infinite lazy list to an array and it will only produce the values when they are accessed.

my @integers = 1 .. Inf; # an infinite array containing all positive integers

say @integers[100000]; #100001 (arrays are zero indexed.)

# Multi dimension arrays may be predeclared which constrains the indices to the declared size:

my @dim5[3,3,3,3,3];

#Creates a preallocated 5 dimensional array where each branch has 3 storage slots and constrains the size to the declared size.
#It can then be accessed like so:

@dim5[0;1;2;1;0] = 'Raku';

say @dim5[0;1;2;1;0]; # prints 'Raku'

#@dim5[0;1;2;1;4] = 'error'; # runtime error: Index 4 for dimension 5 out of range (must be 0..2)

# Note that the dimensions do not _need_ to be predeclared / allocated. Raku will auto-vivify the necessary storage slots on first access.

my @a2;

@a2[0;1;2;1;0] = 'Raku';

@a2[0;1;2;1;4] = 'not an error';

# It is easy to access array "slices" in Raku.

my @b = map { [$_ X~ 1..5] }, <a b c d>;

.say for @b;
# [a1 a2 a3 a4 a5]
# [b1 b2 b3 b4 b5]
# [c1 c2 c3 c4 c5]
# [d1 d2 d3 d4 d5]

say @b[*;2]; # Get the all of the values in the third "column"
# (a3 b3 c3 d3)

# By default, Raku can store any object in an array, and it is not very compact. You can constrain the type of values that may be stored which can allow the optimizer to store them much more efficiently.

my @c = 1 .. 10; # Stores integers, but not very compactly since there are no constraints on what the values _may_ be

my uint16 @d = 1 .. 10 # Since there are and only can be unsigned 16 bit integers, the optimizer will use a much more compact memory layout.

# Indices must be a positive integer. Negative indices are not permitted, fractional indices will be truncated to an integer.

```


[User]
Task

Create a program that finds and outputs the root of a system of nonlinear equations
using Newton-Raphson method.

[Assistant]
(formerly Perl 6)

```
# Reference:
# https://github.com/pierre-vigier/Perl6-Math-Matrix
# Mastering Algorithms with Perl
# By Jarkko Hietaniemi, John Macdonald, Jon Orwant
# Publisher: O'Reilly Media, ISBN-10: 1565923987
# https://resources.oreilly.com/examples/9781565923980/blob/master/ch16/solve

use v6;

sub solve_funcs ($funcs, @guesses, $iterations, $epsilon) {
   my ($error_value, @values, @delta, @jacobian); my \ε = $epsilon;
   for 1 .. $iterations {
      for ^+$funcs { @values[$^i] = $funcs[$^i](|@guesses); }
      $error_value = 0;
      for ^+$funcs { $error_value += @values[$^i].abs }
      return @guesses if $error_value ≤ ε;
      for ^+$funcs { @delta[$^i] = -@values[$^i] }
      @jacobian = jacobian $funcs, @guesses, ε;
      @delta = solve_matrix @jacobian, @delta;
      loop (my $j = 0, $error_value = 0; $j < +$funcs; $j++) {
         $error_value += @delta[$j].abs ;
         @guesses[$j] += @delta[$j];
      }
      return @guesses if $error_value ≤ ε;
   }
   return @guesses;
}

sub jacobian ($funcs is copy, @points is copy, $epsilon is copy) {
   my ($Δ, @P, @M, @plusΔ, @minusΔ);
   my Array @jacobian; my \ε = $epsilon;
   for ^+@points -> $i {
      @plusΔ = @minusΔ = @points;
      $Δ = (ε * @points[$i].abs) || ε;
      @plusΔ[$i] = @points[$i] + $Δ;
      @minusΔ[$i] = @points[$i] - $Δ;
      for ^+$funcs { @P[$^k] = $funcs[$^k](|@plusΔ); }
      for ^+$funcs { @M[$^k] = $funcs[$^k](|@minusΔ); }
      for ^+$funcs -> $j {
         @jacobian[$j][$i] = (@P[$j] - @M[$j]) / (2 * $Δ);
      }
   }
   return @jacobian;
}

sub solve_matrix (@matrix_array is copy, @delta is copy) {
   # https://github.com/pierre-vigier/Perl6-Math-Matrix/issues/56
   { use Math::Matrix;
      my $matrix = Math::Matrix.new(@matrix_array);
      my $vector = Math::Matrix.new(@delta.map({.list}));
      die "Matrix is not invertible" unless $matrix.is-invertible;
      my @result = ( $matrix.inverted dot $vector ).transposed;
      return @result.split(" ");
   }
}

my $funcs = [
   { 9*$^x² + 36*$^y² + 4*$^z² - 36 }
   { $^x² - 2*$^y² - 20*$^z }
   { $^x² - $^y² + $^z² }
];

my @guesses = (1,1,0);

my @solution = solve_funcs $funcs, @guesses, 20, 1e-8;

say "Solution: ", @solution;

```

Output:

```
Solution: [0.8936282344764825 0.8945270103905782 -0.04008928615915281]

```


[User]
The factorial of a number, written as

n
!
{\displaystyle {\displaystyle n!}}
, is defined as

n
!
=
n
(
n
−
1
)
(
n
−
2
)
.
.
.
(
2
)
(
1
)
{\displaystyle {\displaystyle n!=n(n-1)(n-2)...(2)(1)}}
.

Multifactorials generalize factorials as follows:

:   n
    !
    =
    n
    (
    n
    −
    1
    )
    (
    n
    −
    2
    )
    .
    .
    .
    (
    2
    )
    (
    1
    )
    {\displaystyle {\displaystyle n!=n(n-1)(n-2)...(2)(1)}}
:   n
    !
    !
    =
    n
    (
    n
    −
    2
    )
    (
    n
    −
    4
    )
    .
    .
    .
    {\displaystyle {\displaystyle n!!=n(n-2)(n-4)...}}
:   n
    !
    !
    !
    =
    n
    (
    n
    −
    3
    )
    (
    n
    −
    6
    )
    .
    .
    .
    {\displaystyle {\displaystyle n!!!=n(n-3)(n-6)...}}
:   n
    !
    !
    !
    !
    =
    n
    (
    n
    −
    4
    )
    (
    n
    −
    8
    )
    .
    .
    .
    {\displaystyle {\displaystyle n!!!!=n(n-4)(n-8)...}}
:   n
    !
    !
    !
    !
    !
    =
    n
    (
    n
    −
    5
    )
    (
    n
    −
    10
    )
    .
    .
    .
    {\displaystyle {\displaystyle n!!!!!=n(n-5)(n-10)...}}

In all cases, the terms in the products are positive integers.

If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:

1. Write a function that given n and the degree, calculates the multifactorial.
2. Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.

**Note:** The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.

[Assistant]
(formerly Perl 6)

```
for 1 .. 5 -> $degree {
    sub mfact($n) { [*] $n, *-$degree ...^ * <= 0 };
    say "$degree: ", map &mfact, 1..10
}

```

Output:

```
1: 1 2 6 24 120 720 5040 40320 362880 3628800
2: 1 2 3 8 15 48 105 384 945 3840
3: 1 2 3 4 10 18 28 80 162 280
4: 1 2 3 4 5 12 21 32 45 120
5: 1 2 3 4 5 6 14 24 36 50
```


[User]
Simple shebangs can help with scripting, e.g., `#!/usr/bin/env python` at the top of a Python script will allow it to be run in a terminal as "`./script.py`".

Occasionally, a more complex shebang line is needed. For example, some languages do not include the program name in ARGV; a multiline shebang can reorder the arguments so that the program name is included in ARGV.

The syntax for a multiline shebang is complicated. The shebang lines must be simultaneously commented away from the main language and revealed to some shell (perhaps Bash) so that they can be executed. In other words, Polyglots.

Warning: Using a multiline shebang of the form `#!/bin/sh ... exec ... !#` will set the code's mimetype to `text/x-shellscript`, which creates problems such as Emacs treating the file as a shell script, no matter which language and file extension it really uses.

See also

* Native shebang - where the "program loaded" is *of* the actual native task language.

[Assistant]
(formerly Perl 6)

```
#!/usr/local/bin/raku
use MONKEY; EVAL '(exit $?0)' && EVAL 'exec rake $0 ${1+"$@"}'
& EVAL 'exec raku $0 $argv:q'
        if 0;

```


[User]
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.

By *distinct* we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.

By *initialized* we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.

This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the *same* mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.

This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).

See also: Closures/Value capture

[Assistant]
(formerly Perl 6)

Unlike in Perl 5, the list repetition operator evaluates the left argument thunk each time, so

```
my @a = Foo.new xx $n;

```

produces `$n` distinct objects.


[User]
Task

Given a set of data vectors in the following format:

```

            y
            =
            {

              y

                1

            ,

              y

                2

            ,
            .
            .
            .
            ,

              y

                n

            }

    {\displaystyle {\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}}

```

```

              X

                i

            =
            {

              x

                i
                1

            ,

              x

                i
                2

            ,
            .
            .
            .
            ,

              x

                i
                n

            }
            ,
            i
            ∈
            1..
            k

    {\displaystyle {\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}}

```

Compute the vector

β
=
{

β

1
,

β

2
,
.
.
.
,

β

k
}
{\displaystyle {\displaystyle \beta =\{\beta \_{1},\beta \_{2},...,\beta \_{k}\}}}
 using ordinary least squares regression using the following equation:

```

              y

                j

            =

              Σ

                i

              β

                i

            ⋅

              x

                i
                j

            ,
            j
            ∈
            1..
            n

    {\displaystyle {\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}}

```

You can assume  *y*  is given to you as a vector (a one-dimensional array), and  *X*  is given to you as a two-dimensional array (i.e. matrix).

[Assistant]
|  |
| --- |
| This example is **broken**. It fails to compile or causes a runtime error. Please fix the code and remove this message. |

(formerly Perl 6)
We're going to solve the example on the Wikipedia article using Clifford, a geometric algebra module. Optimization for large vector space does not quite work yet, so it's going to take (a lof of) time and a fair amount of memory, but it should work.

Let's create four vectors containing our input data:

w

=

w

k

e

k

h

0

=
(

h

k

)

0

e

k

h

1

=
(

h

k

)

1

e

k

h

2

=
(

h

k

)

2

e

k
{\displaystyle {\displaystyle {\begin{aligned}\mathbf {w} &=w^{k}\mathbf {e} \_{k}\\\mathbf {h\_{0}} &=(h^{k})^{0}\mathbf {e} \_{k}\\\mathbf {h\_{1}} &=(h^{k})^{1}\mathbf {e} \_{k}\\\mathbf {h\_{2}} &=(h^{k})^{2}\mathbf {e} \_{k}\end{aligned}}}}

Then what we're looking for are three scalars

α
{\displaystyle {\displaystyle \alpha }}
,

β
{\displaystyle {\displaystyle \beta }}
 and

γ
{\displaystyle {\displaystyle \gamma }}
 such that:

α

h
0
+
β

h
1
+
γ

h
2
=

w
{\displaystyle {\displaystyle \alpha \mathbf {h0} +\beta \mathbf {h1} +\gamma \mathbf {h2} =\mathbf {w} }}

To get for instance

α
{\displaystyle {\displaystyle \alpha }}
 we can first make the

β
{\displaystyle {\displaystyle \beta }}
 and

γ
{\displaystyle {\displaystyle \gamma }}
 terms disappear:

α

h
0
∧

h
1
∧

h
2
=

w
∧

h
1
∧

h
2
{\displaystyle {\displaystyle \alpha \mathbf {h0} \wedge \mathbf {h1} \wedge \mathbf {h2} =\mathbf {w} \wedge \mathbf {h1} \wedge \mathbf {h2} }}

Noting

I
=

h
0
∧

h
1
∧

h
2
{\displaystyle {\displaystyle I=\mathbf {h0} \wedge \mathbf {h1} \wedge \mathbf {h2} }}
, we then get:

α
=
(

w
∧

h
1
∧

h
2
)
⋅

I
~

/
I
⋅

I
~
{\displaystyle {\displaystyle \alpha =(\mathbf {w} \wedge \mathbf {h1} \wedge \mathbf {h2} )\cdot {\tilde {I}}/I\cdot {\tilde {I}}}}

**Note:** a number of the formulae above are invisible to the majority of browsers, including Chrome, IE/Edge, Safari and Opera. They may (subject to the installation of necessary fronts) be visible to Firefox.

```
use Clifford;
my @height = <1.47 1.50 1.52 1.55 1.57 1.60 1.63 1.65 1.68 1.70 1.73 1.75 1.78 1.80 1.83>;
my @weight = <52.21 53.12 54.48 55.84 57.20 58.57 59.93 61.29 63.11 64.47 66.28 68.10 69.92 72.19 74.46>;

my $w = [+] @weight Z* @e;

my $h0 = [+] @e[^@weight];
my $h1 = [+] @height Z* @e;
my $h2 = [+] (@height X** 2) Z* @e;

my $I = $h0∧$h1∧$h2;
my $I2 = ($I·$I.reversion).Real;

say "α = ", ($w∧$h1∧$h2)·$I.reversion/$I2;
say "β = ", ($w∧$h2∧$h0)·$I.reversion/$I2;
say "γ = ", ($w∧$h0∧$h1)·$I.reversion/$I2;

```

Output:

```
α = 128.81280357844
β = -143.1620228648
γ = 61.960325442
```

April 2016: This computation took over an hour with MoarVM, running in a VirtualBox linux system guest hosted by a windows laptop with a i7 intel processor.
March 2020: With various improvements to the language, 6.d releases of Raku now run the code 2x to 3x as fast, depending on the hardware used, but even so it is generous to describe it as 'slow'.


[User]
Task

Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school.

Only print the top half triangle of products.

[Assistant]
(formerly Perl 6)

```
(my $f = "%{$_}s" given my $width = ($_**2).chars ) given my $max = 12;

say '×'.fmt($f)  ~ ' ┃ ' ~ (1..$max).fmt($f);
say '━' x $width ~ '━╋'  ~ '━' x $max × (1+$width);

for 1..$max -> $i {
    say $i.fmt($f) ~ ' ┃ ' ~ ( $i ≤ $_ ?? $i×$_ !! '' for 1..$max ).fmt($f);
}
```

Output:

```
  x│   1   2   3   4   5   6   7   8   9  10  11  12
───┼────────────────────────────────────────────────
  1│   1   2   3   4   5   6   7   8   9  10  11  12
  2│       4   6   8  10  12  14  16  18  20  22  24
  3│           9  12  15  18  21  24  27  30  33  36
  4│              16  20  24  28  32  36  40  44  48
  5│                  25  30  35  40  45  50  55  60
  6│                      36  42  48  54  60  66  72
  7│                          49  56  63  70  77  84
  8│                              64  72  80  88  96
  9│                                  81  90  99 108
 10│                                     100 110 120
 11│                                         121 132
 12│                                             144

```


[User]
The **multiplicative order** of *a* relative to *m* is the least positive integer *n* such that *a^n* is 1 (modulo *m*).

Example

The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.

One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent *p^k* of *m*, and
combine the results with the *least common multiple* operation.

Now the order of *a* with regard to *p^k* must divide *Φ(p^k)*. Call this number *t*, and determine it's factors *q^e*. Since each multiple of the order will also yield 1 when used as exponent for *a*, it's enough to find the least d such that *(q^d)\*(t/(q^e))* yields 1 when used as exponent.

Task

Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.

---

An algorithm for the multiplicative order can be found in Bach & Shallit, *Algorithmic Number Theory, Volume I: Efficient Algorithms*, The MIT Press, 1996:

Exercise 5.8, page 115:

Suppose you are given a prime p and a complete factorization
of p-1.   Show how to compute the order of an
element a in (Z/(p))\* using O((lg p)4/(lg lg p)) bit
operations.

Solution, page 337:

Let the prime factorization of p-1  be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x.   (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi  such that the condition above holds.

This can be done as follows: first compute q1e1, q2e2, ... ,
qkek .  This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1  times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).

[Assistant]
(formerly Perl 6)

```
use Prime::Factor;

sub mo-prime($a, $p, $e) {
    my $m = $p ** $e;
    my $t = ($p - 1) * ($p ** ($e - 1)); #  = Phi($p**$e) where $p prime
    my @qs = 1;
    for prime-factors($t).Bag -> $f {
        @qs = flat @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) });
    }

    @qs.sort.first: -> $q { expmod( $a, $q, $m ) == 1 };
}

sub mo($a, $m) {
    $a gcd $m == 1 or die "$a and $m are not relatively prime";
    [lcm] flat 1, prime-factors($m).Bag.map: { mo-prime($a, .key, .value) };
}

multi MAIN('test') {
    use Test;

    for (10, 21, 25, 150, 1231, 123141, 34131) -> $n {
        is ([*] prime-factors($n).Bag.map( { .key ** .value } )), $n, "$n factors correctly";
    }

    is mo(37, 1000), 100, 'mo(37,1000) == 100';
    my $b = 10**20-1;
    is mo(2, $b), 3748806900, 'mo(2,10**20-1) == 3748806900';
    is mo(17, $b), 1499522760, 'mo(17,10**20-1) == 1499522760';
    $b = 100001;
    is mo(54, $b), 9090, 'mo(54,100001) == 9090';
}

```

Output:

```
ok 1 - 10 factors correctly
ok 2 - 21 factors correctly
ok 3 - 25 factors correctly
ok 4 - 150 factors correctly
ok 5 - 1231 factors correctly
ok 6 - 123141 factors correctly
ok 7 - 34131 factors correctly
ok 8 - mo(37,1000) == 100
ok 9 - mo(2,10**20-1) == 3748806900
ok 10 - mo(17,10**20-1) == 1499522760
ok 11 - mo(54,100001) == 9090
```


[User]
If the product of the divisors of an integer n (including n itself) is equal to n^2, then n is a *multiplicatively perfect number*.
Alternatively: the product of the proper divisors of n (i.e. excluding n) is equal to n.

Note that the integer '1' qualifies under the first definition (1 = 1 x 1), but not under the second since '1' has no proper divisors. Given this ambiguity, it is optional whether '1' is included or not in solutions to this task.

Task

Find and show on this page the multiplicatively perfect numbers below **500**.

Stretch

Find and show the number of multiplicatively perfect numbers under **500**, **5,000**, **50,000** and **500,000** and for each of these limits deduce (avoid counting separately) and show the number of *semi-primes* (numbers which are the product of exactly two primes) under that limit.

Related (and near duplicate) task

* Semiprime

See also

* The OEIS sequence:  A007422: Multiplicatively perfect numbers

[Assistant]
```
use List::Divvy;
use Lingua::EN::Numbers;

constant @primes = (^∞).grep: &is-prime;
constant @cubes  = @primes.map: *³;

state $cube = 0;
sub is-mpn(Int $n ) {
    return False if $n.is-prime;
    if $n == @cubes[$cube] {
        ++$cube;
        return True
    }
    my $factor = find-factor($n);
    return True if ($factor.is-prime && ( my $div = $n div $factor ).is-prime && ($div != $factor));
    False;
}

sub find-factor ( Int $n, $constant = 1 ) {
    my $x      = 2;
    my $rho    = 1;
    my $factor = 1;
    while $factor == 1 {
        $rho *= 2;
        my $fixed = $x;
        for ^$rho {
            $x = ( $x * $x + $constant ) % $n;
            $factor = ( $x - $fixed ) gcd $n;
            last if 1 < $factor;
        }
    }
    $factor = find-factor( $n, $constant + 1 ) if $n == $factor;
    $factor;
}

constant @mpn = lazy 1, |(2..*).grep: &is-mpn;

say 'Multiplicatively perfect numbers less than 500:';
put @mpn.&upto(500).batch(10)».fmt("%3d").join: "\n";

put "\nThere are:";
for 5e2, 5e3, 5e4, 5e5, 5e6 {
   printf  "%8s MPNs less than %9s, %7s semiprimes.\n",
     comma(my $count = +@mpn.&upto($_)), .Int.&comma,
     comma $count + @primes.map(*²).&upto($_) - @cubes.&upto($_) - 1;
}

```

Output:

```
Multiplicatively perfect numbers less than 500:
  1   6   8  10  14  15  21  22  26  27
 33  34  35  38  39  46  51  55  57  58
 62  65  69  74  77  82  85  86  87  91
 93  94  95 106 111 115 118 119 122 123
125 129 133 134 141 142 143 145 146 155
158 159 161 166 177 178 183 185 187 194
201 202 203 205 206 209 213 214 215 217
218 219 221 226 235 237 247 249 253 254
259 262 265 267 274 278 287 291 295 298
299 301 302 303 305 309 314 319 321 323
326 327 329 334 335 339 341 343 346 355
358 362 365 371 377 381 382 386 391 393
394 395 398 403 407 411 413 415 417 422
427 437 445 446 447 451 453 454 458 466
469 471 473 478 481 482 485 489 493 497

There are:
     150 MPNs less than       500,     153 semiprimes.
   1,354 MPNs less than     5,000,   1,365 semiprimes.
  12,074 MPNs less than    50,000,  12,110 semiprimes.
 108,223 MPNs less than   500,000, 108,326 semiprimes.
 978,983 MPNs less than 5,000,000, 979,274 semiprimes.
```


[User]
It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.

This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.

The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.

The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.

Test your code using the input string “`a!===b=!=c`” and the separators “`==`”, “`!=`” and “`=`”.

For these inputs the string should be parsed as `"a" (!=) "" (==) "b" (=) "" (!=) "c"`, where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is `"a", empty string, "b", empty string, "c"`.
Note that the quotation marks are shown for clarity and do not form part of the output.

**Extra Credit:** provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.

[Assistant]
(formerly Perl 6)

```
sub multisplit($str, @seps) { $str.split: / ||@seps /, :v }

my @chunks = multisplit 'a!===b=!=c==d', < == != = >;

# Print the strings.
say @chunks».Str.raku;

# Print the positions of the separators.
for grep Match, @chunks -> $s {
    say "{$s.fmt: '%2s'} from {$s.from.fmt: '%2d'} to {$s.to.fmt: '%2d'}";
}

```

Output:

```
("a", "!=", "", "==", "b", "=", "", "!=", "c", "==", "d")
!= from  1 to  3
== from  3 to  5
 = from  6 to  7
!= from  7 to  9
== from 10 to 12
```

Using the array @seps in a pattern automatically does alternation.
By default this would do longest-term matching (that is, | semantics), but we can force it to do left-to-right matching by embedding the array in a short-circuit alternation (that is, || semantics).
As it happens, with the task's specified list of separators, it doesn't make any difference.

Raku automatically returns Match objects that will stringify to the matched pattern, but can also be interrogated for their match positions, as illustrated above by post-processing the results two different ways.


[User]
Description

The multiton pattern is a design pattern which generalizes the singleton pattern. Whereas the singleton allows only one instance of a class to be created, the multiton pattern allows for the controlled creation of multiple instances, which it manages through the use of a map.

Task

Implement a basic Multiton class or other structure and test that it works as intended. If your language does not support the *object oriented* paradigm, then try to emulate a multiton as best you can with the tools available.

If your language supports multithreading, then you may optionally implement a thread safe variant as well.

Related task

* Singleton

[Assistant]
Tried to translate the C# example at WP but not sure if my interpretation/implementation is correct

```
# 20211001 Raku programming solution

enum MultitonType < Gold Silver Bronze >;

class Multiton {

   my %instances = MultitonType.keys Z=> $ ⚛= 1 xx * ;

   has $.type is rw;

   method TWEAK { $.type = 'Nothing' unless cas(%instances{$.type}, 1, 0) }
}

race for ^10 -> $i {
   Thread.start(
      sub {
#         sleep roll(^2);
         my $obj = Multiton.new: type => MultitonType.roll;
         say "Thread ", $i, " has got ", $obj.type;
      }
   );
}

```

Output:

```
Thread 5 has got Bronze
Thread 9 has got Gold
Thread 7 has got Nothing
Thread 8 has got Nothing
Thread 3 has got Nothing
Thread 2 has got Nothing
Thread 1 has got Nothing
Thread 0 has got Silver
Thread 4 has got Nothing
Thread 6 has got Nothing

```


[User]
A Munchausen number is a natural number *n* the sum of whose digits (in base 10), each raised to the power of itself, equals *n*.

(**Munchausen** is also spelled: **Münchhausen**.)

For instance:    3435 = 33 + 44 + 33 + 55

Task

Find all Munchausen numbers between   **1**   and   **5000**.

Also see
:   * The OEIS entry: A046253
    * The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number

[Assistant]
(formerly Perl 6)

```
sub is_munchausen ( Int $n ) {
    constant @powers = 0, |map { $_ ** $_ }, 1..9;
    $n == @powers[$n.comb].sum;
}
.say if .&is_munchausen for 1..5000;

```

Output:

```
1
3435
```


[User] Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.

[Assistant]
(formerly Perl 6)

Here's one simple way:

```
my $ppm = open("munching0.ppm", :w) orelse .die;

$ppm.print(q :to 'EOT');
P3
256 256
255
EOT

for 0 .. 255 -> $row {
    for 0 .. 255 -> $col {
        my $color = $row +^ $col;
        $ppm.print("0 $color 0 ");
    }
    $ppm.say();
}

$ppm.close();

```

Another way:

```
my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b },
		map -> $x { floor ($x/256) ** 3 * 256 },
		    (flat (0...255) Z
		     (255...0) Z
		     flat (0,2...254),(254,252...0));

my $PPM = open "munching1.ppm", :w orelse .die;

$PPM.print: qq:to/EOH/;
    P6
    # munching.pgm
    256 256
    255
    EOH

$PPM.write: @colors[$_] for ^256 X+^ ^256;

$PPM.close;

```


[User]
Task

Output the 8 notes of the **C major** diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.

These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on *Fixed do Solfège*.

For the purpose of this task, **Middle C** (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.

For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.

[Assistant]
(formerly Perl 6)

```
for 0,2,4,5,7,9,11,12 {
    shell "play -n -c1 synth 0.2 sin %{$_ - 9}"
}

```


[User]
A **mutex** (from "**mut**ual **ex**clusion") is a synchronization object, a variant of semaphore with *k*=1.
A mutex is said to be seized by a task decreasing *k*.
It is released when the task restores *k*. Mutexes are typically used to protect a shared resource from concurrent access.
A task seizes (or acquires) the mutex, then accesses the resource, and after that releases the mutex.

A mutex is a low-level synchronization primitive exposed to deadlocking. A deadlock can occur with just two tasks and two mutexes (if each task attempts to acquire both mutexes, but in the opposite order).
Entering the deadlock is usually aggravated by a race condition state, which leads to sporadic hangups, which are very difficult to track down.

# Variants of mutexes

## Global and local mutexes

Usually the OS provides various implementations of mutexes corresponding to the variants of tasks available in the OS. For example, system-wide mutexes can be used by processes. Local mutexes can be used only by threads etc. This distinction is maintained because, depending on the hardware, seizing a global mutex might be a thousand times slower than seizing a local one.

## Reentrant mutex

A reentrant mutex can be seized by the same task multiple times. Each seizing of the mutex is matched by releasing it, in order to allow another task to seize it.

## Read write mutex

A read write mutex can be seized at two levels for *read* and for *write*. The mutex can be seized for *read* by any number of tasks. Only one task may seize it for '*write*. Read write mutexes are usually used to protect resources which can be accessed in mutable and immutable ways. Immutable (read) access is granted concurrently for many tasks because they do not change the resource state. Read write mutexes can be reentrant, global or local. Further, promotion operations may be provided. That's when a task that has seized the mutex for *write* releases it while keeping seized for *read*. Note that the reverse operation is potentially deadlocking and requires some additional access policy control.

# Deadlock prevention

There exists a simple technique of deadlock prevention when mutexes are seized in some fixed order. This is discussed in depth in the Dining philosophers problem.

# Sample implementations / APIs

[Assistant]
(formerly Perl 6)

```
my $lock = Lock.new;

$lock.protect: { your-ad-here() }

```

Locks are reentrant. You may explicitly lock and unlock them, but the syntax above guarantees the lock will be unlocked on scope exit, even if by thrown exception or other exotic control flow. That being said, direct use of locks is discouraged in Raku in favor of promises, channels, and supplies, which offer better composable semantics.


[User]
Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.

Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:

:   F
    (
    0
    )

    =
    1

    ;

    M
    (
    0
    )
    =
    0

    F
    (
    n
    )

    =
    n
    −
    M
    (
    F
    (
    n
    −
    1
    )
    )
    ,

    n
    >
    0

    M
    (
    n
    )

    =
    n
    −
    F
    (
    M
    (
    n
    −
    1
    )
    )
    ,

    n
    >
    0.
    {\displaystyle {\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}}

(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).

[Assistant]
(formerly Perl 6)
A direct translation of the definitions of

F
{\displaystyle {\displaystyle F}}
 and

M
{\displaystyle {\displaystyle M}}
:

```
multi F(0) { 1 }; multi M(0) { 0 }
multi F(\𝑛) { 𝑛 - M(F(𝑛 - 1)) }
multi M(\𝑛) { 𝑛 - F(M(𝑛 - 1)) }

say map &F, ^20;
say map &M, ^20;

```

Output:

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

```


[User]
The classical **Möbius function: μ(n)** is an important multiplicative function in number theory and combinatorics.

There are several ways to implement a Möbius function.

A fairly straightforward method is to find the prime factors of a positive integer **n**, then define **μ(n)** based on the sum of the primitive factors. It has the values **{−1, 0, 1}** depending on the factorization of **n**:

:   * **μ(1)** is defined to be **1**.

:   * **μ(n) = 1** if **n** is a square-free positive integer with an **even** number of prime factors.

:   * **μ(n) = −1** if **n** is a square-free positive integer with an **odd** number of prime factors.

:   * **μ(n) = 0** if **n** has a **squared** prime factor.

Task
:   * Write a routine (function, procedure, whatever) **μ(n)** to find the Möbius number for a positive integer **n**.

:   * Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)

See also
:   * Wikipedia: Möbius function

Related Tasks
:   * Mertens function

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2022.12

Möbius number is not defined for n == 0. Raku arrays are indexed from 0 so store a blank value at position zero to keep n and μ(n) aligned.

```
use Prime::Factor;

sub μ (Int \n) {
    return 0 if n %% (4|9|25|49|121);
    my @p = prime-factors(n);
    +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0
}

my @möbius = lazy flat '', 1, (2..*).hyper.map: &μ;

# The Task
put "Möbius sequence - First 199 terms:\n",
    @möbius[^200]».fmt('%3s').batch(20).join: "\n";

```

Output:

```
Möbius sequence - First 199 terms:
      1  -1  -1   0  -1   1  -1   0   0   1  -1   0  -1   1   1   0  -1   0  -1
  0   1   1  -1   0   0   1   0   0  -1  -1  -1   0   1   1   1   0  -1   1   1
  0  -1  -1  -1   0   0   1  -1   0   0   0   1   0  -1   0   1   0   1   1  -1
  0  -1   1   0   0   1  -1  -1   0   1  -1  -1   0  -1   1   0   0   1  -1  -1
  0   0   1  -1   0   1   1   1   0  -1   0   1   0   1   1   1   0  -1   0   0
  0  -1  -1  -1   0  -1   1  -1   0  -1  -1   1   0  -1  -1   1   0   0   1   1
  0   0   1   1   0   0   0  -1   0   1  -1  -1   0   1   1   0   0  -1  -1  -1
  0   1   1   1   0   1   1   0   0  -1   0  -1   0   0  -1   1   0  -1   1   1
  0   1   0  -1   0  -1   1  -1   0   0  -1   0   0  -1  -1   0   0   1   1  -1
  0  -1  -1   1   0   1  -1   1   0   0  -1  -1   0  -1   1  -1   0  -1   0  -1
```


[User]
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.

Example

Returns would include `1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th`

Task

Use your routine to show here the output for *at least* the following (inclusive) ranges of integer inputs:
`0..25, 250..265, 1000..1025`

**Note:** apostrophes are now *optional* to allow correct apostrophe-less English.

[Assistant]
(formerly Perl 6)
(Spurious apostrophes intentionally omitted.)

```
my %irregulars = <1 st 2 nd 3 rd>, (11..13 X=> 'th');

sub nth ($n) { $n ~ ( %irregulars{$n % 100} // %irregulars{$n % 10} // 'th' ) }

say .list».&nth for [^26], [250..265], [1000..1025];

```

Output:

```
0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th
250th 251st 252nd 253rd 254th 255th 256th 257th 258th 259th 260th 261st 262nd 263rd 264th 265th
1000th 1001st 1002nd 1003rd 1004th 1005th 1006th 1007th 1008th 1009th 1010th 1011th 1012th 1013th 1014th 1015th 1016th 1017th 1018th 1019th 1020th 1021st 1022nd 1023rd 1024th 1025th
```

If you want to get Unicodally fancy, use this version instead:

```
my %irregulars = <1 ˢᵗ 2 ⁿᵈ 3 ʳᵈ>, (11..13 X=> 'ᵗʰ');

sub nth ($n) { $n ~ ( %irregulars{$n % 100} // %irregulars{$n % 10} // 'ᵗʰ' ) }

say .list».&nth for [^26], [250..265], [1000..1025];

```

Output:

> 0ᵗʰ 1ˢᵗ 2ⁿᵈ 3ʳᵈ 4ᵗʰ 5ᵗʰ 6ᵗʰ 7ᵗʰ 8ᵗʰ 9ᵗʰ 10ᵗʰ 11ᵗʰ 12ᵗʰ 13ᵗʰ 14ᵗʰ 15ᵗʰ 16ᵗʰ 17ᵗʰ 18ᵗʰ 19ᵗʰ 20ᵗʰ 21ˢᵗ 22ⁿᵈ 23ʳᵈ 24ᵗʰ 25ᵗʰ
>
> 250ᵗʰ 251ˢᵗ 252ⁿᵈ 253ʳᵈ 254ᵗʰ 255ᵗʰ 256ᵗʰ 257ᵗʰ 258ᵗʰ 259ᵗʰ 260ᵗʰ 261ˢᵗ 262ⁿᵈ 263ʳᵈ 264ᵗʰ 265ᵗʰ
>
> 1000ᵗʰ 1001ˢᵗ 1002ⁿᵈ 1003ʳᵈ 1004ᵗʰ 1005ᵗʰ 1006ᵗʰ 1007ᵗʰ 1008ᵗʰ 1009ᵗʰ 1010ᵗʰ 1011ᵗʰ 1012ᵗʰ 1013ᵗʰ 1014ᵗʰ 1015ᵗʰ 1016ᵗʰ 1017ᵗʰ 1018ᵗʰ 1019ᵗʰ 1020ᵗʰ 1021ˢᵗ 1022ⁿᵈ 1023ʳᵈ 1024ᵗʰ 1025ᵗʰ


[User]
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.

The
N
{\displaystyle {\displaystyle N}}
-body problem is an inherent feature of a physical description of mechanical system of

N
{\displaystyle {\displaystyle N}}
 interacting objects.
The system is described by Newton's Law

:   F
    →
    =

    m

    i

    d

    2

    r
    →

    i

    d

    t

    2
    ,
    i
    =
    1..
    N
    {\displaystyle {\displaystyle {\vec {F}}=m\_{i}{\frac {d^{2}{\vec {r}}\_{i}}{dt^{2}}},i=1..N}}

with continuous combined force from other bodies

:   F

    i
    =

    ∑

    j
    ≠
    i

    F

    i
    j
    ,
    i
    =
    1..
    N
    {\displaystyle {\displaystyle F\_{i}=\sum \_{j\neq i}^{}F\_{ij},i=1..N}}

Exact formulation of first mechanical problem is, given initial coordinates and velocities

t
=
0
{\displaystyle {\displaystyle t=0}}
, to find coordinates and velocities at

t
=

t

0
{\displaystyle {\displaystyle t=t\_{0}}}
 with accuracy more then given relative value

ϵ
=

r
→
−

r
→
′

|

r
→

|
{\displaystyle {\displaystyle \epsilon ={\frac {{\vec {r}}-{\vec {r}}'}{|{\vec {r}}|}}}}

As well known from physical background, only the choice of

N
=
2
{\displaystyle {\displaystyle N=2}}
 can be analytically solved.

Task

Write a simulation of three masses interacting under gravitation and show their evolution over a number of time-steps (at least 20).

[Assistant]
(formerly Perl 6)

We'll try to simulate the Sun+Earth+Moon system, with plausible astrometric values.

We use a 18-dimension vector

A
B
C
{\displaystyle {\displaystyle ABC}}
. The first nine dimensions are the positions of the three bodies. The other nine are the velocities. This allows us to write the dynamics as a first-temporal derivative equation, since

d

p
o
s
i
t
i
o
n

d
t
=

s
p
e
e
d
{\displaystyle {\displaystyle {\frac {d\mathrm {position} }{dt}}=\mathrm {speed} }}

and thus

d
A
B

C

1..9

d
t
=
A
B

C

10..18
{\displaystyle {\displaystyle {\frac {dABC\_{1..9}}{dt}}=ABC\_{10..18}}}

To keep things compact, we'll only display the first 20 lines of output.

```
# Simple Vector implementation
multi infix:<+>(@a, @b) { @a Z+ @b }
multi infix:<->(@a, @b) { @a Z- @b }
multi infix:<*>($r, @a) { $r X* @a }
multi infix:</>(@a, $r) { @a X/ $r }
sub norm { sqrt [+] @_ X** 2 }

# Runge-Kutta stuff
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;
    }
}

# gravitational constant
constant G = 6.674e-11;
# astronomical unit
constant au = 150e9;

# time constants in seconds
constant year = 365.25*24*60*60;
constant month = 21*24*60*60;

# masses in kg
constant $ma = 2e30;     # Sun
constant $mb = 6e24;     # Earth
constant $mc = 7.34e22;  # Moon

my &dABC = runge-kutta my &f = sub ( $t, @ABC ) {
    my @a = @ABC[0..2];
    my @b = @ABC[3..5];
    my @c = @ABC[6..8];

    my $ab = norm(@a - @b);
    my $ac = norm(@a - @c);
    my $bc = norm(@b - @c);

    return [
        flat
        @ABC[@(9..17)],
        map G * *,
        $mb/$ab**3 * (@b - @a) + $mc/$ac**3 * (@c - @a),
        $ma/$ab**3 * (@a - @b) + $mc/$bc**3 * (@c - @b),
        $ma/$ac**3 * (@a - @c) + $mb/$bc**3 * (@b - @c);
    ];
}

loop (
    my ($t, @ABC) = 0,
        0, 0, 0,                                 # Sun position
        au, 0, 0,                                # Earth position
        0.998*au, 0, 0,                          # Moon position
        0, 0, 0,                                 # Sun speed
        0, 2*pi*au/year, 0,                      # Earth speed
        0, 2*pi*(au/year + 0.002*au/month), 0    # Moon speed
    ;
    $t < .2;
    ($t, @ABC) »+=« (.01, dABC($t, @ABC, .01))
) {
    printf "t = %.02f : %s\n", $t, @ABC.fmt("%+.3e");
}

```

Output:

```
t = 0.00 : +0.000e+00 +0.000e+00 +0.000e+00 +1.500e+11 +0.000e+00 +0.000e+00 +1.497e+11 +0.000e+00 +0.000e+00 +0.000e+00 +0.000e+00 +0.000e+00 +0.000e+00 +2.987e+04 +0.000e+00 +0.000e+00 +3.090e+04 +0.000e+00
t = 0.01 : +9.008e-13 +5.981e-22 +0.000e+00 +1.500e+11 +2.987e+02 +0.000e+00 +1.497e+11 +3.090e+02 +0.000e+00 +1.802e-10 +1.794e-19 +0.000e+00 -5.987e-05 +2.987e+04 +0.000e+00 -1.507e-05 +3.090e+04 +0.000e+00
t = 0.02 : +3.603e-12 +4.785e-21 +0.000e+00 +1.500e+11 +5.973e+02 +0.000e+00 +1.497e+11 +6.181e+02 +0.000e+00 +3.603e-10 +7.177e-19 +0.000e+00 -1.197e-04 +2.987e+04 +0.000e+00 -3.014e-05 +3.090e+04 +0.000e+00
t = 0.03 : +8.107e-12 +1.615e-20 +0.000e+00 +1.500e+11 +8.960e+02 +0.000e+00 +1.497e+11 +9.271e+02 +0.000e+00 +5.405e-10 +1.615e-18 +0.000e+00 -1.796e-04 +2.987e+04 +0.000e+00 -4.521e-05 +3.090e+04 +0.000e+00
t = 0.04 : +1.441e-11 +3.828e-20 +0.000e+00 +1.500e+11 +1.195e+03 +0.000e+00 +1.497e+11 +1.236e+03 +0.000e+00 +7.206e-10 +2.871e-18 +0.000e+00 -2.395e-04 +2.987e+04 +0.000e+00 -6.028e-05 +3.090e+04 +0.000e+00
t = 0.05 : +2.252e-11 +7.476e-20 +0.000e+00 +1.500e+11 +1.493e+03 +0.000e+00 +1.497e+11 +1.545e+03 +0.000e+00 +9.008e-10 +4.486e-18 +0.000e+00 -2.993e-04 +2.987e+04 +0.000e+00 -7.535e-05 +3.090e+04 +0.000e+00
t = 0.06 : +3.243e-11 +1.292e-19 +0.000e+00 +1.500e+11 +1.792e+03 +0.000e+00 +1.497e+11 +1.854e+03 +0.000e+00 +1.081e-09 +6.460e-18 +0.000e+00 -3.592e-04 +2.987e+04 +0.000e+00 -9.041e-05 +3.090e+04 +0.000e+00
t = 0.07 : +4.414e-11 +2.051e-19 +0.000e+00 +1.500e+11 +2.091e+03 +0.000e+00 +1.497e+11 +2.163e+03 +0.000e+00 +1.261e-09 +8.792e-18 +0.000e+00 -4.191e-04 +2.987e+04 +0.000e+00 -1.055e-04 +3.090e+04 +0.000e+00
t = 0.08 : +5.765e-11 +3.062e-19 +0.000e+00 +1.500e+11 +2.389e+03 +0.000e+00 +1.497e+11 +2.472e+03 +0.000e+00 +1.441e-09 +1.148e-17 +0.000e+00 -4.789e-04 +2.987e+04 +0.000e+00 -1.206e-04 +3.090e+04 +0.000e+00
t = 0.09 : +7.296e-11 +4.360e-19 +0.000e+00 +1.500e+11 +2.688e+03 +0.000e+00 +1.497e+11 +2.781e+03 +0.000e+00 +1.621e-09 +1.453e-17 +0.000e+00 -5.388e-04 +2.987e+04 +0.000e+00 -1.356e-04 +3.090e+04 +0.000e+00
t = 0.10 : +9.008e-11 +5.981e-19 +0.000e+00 +1.500e+11 +2.987e+03 +0.000e+00 +1.497e+11 +3.090e+03 +0.000e+00 +1.802e-09 +1.794e-17 +0.000e+00 -5.987e-04 +2.987e+04 +0.000e+00 -1.507e-04 +3.090e+04 +0.000e+00
t = 0.11 : +1.090e-10 +7.961e-19 +0.000e+00 +1.500e+11 +3.285e+03 +0.000e+00 +1.497e+11 +3.399e+03 +0.000e+00 +1.982e-09 +2.171e-17 +0.000e+00 -6.586e-04 +2.987e+04 +0.000e+00 -1.658e-04 +3.090e+04 +0.000e+00
t = 0.12 : +1.297e-10 +1.034e-18 +0.000e+00 +1.500e+11 +3.584e+03 +0.000e+00 +1.497e+11 +3.709e+03 +0.000e+00 +2.162e-09 +2.584e-17 +0.000e+00 -7.184e-04 +2.987e+04 +0.000e+00 -1.808e-04 +3.090e+04 +0.000e+00
t = 0.13 : +1.522e-10 +1.314e-18 +0.000e+00 +1.500e+11 +3.882e+03 +0.000e+00 +1.497e+11 +4.018e+03 +0.000e+00 +2.342e-09 +3.032e-17 +0.000e+00 -7.783e-04 +2.987e+04 +0.000e+00 -1.959e-04 +3.090e+04 +0.000e+00
t = 0.14 : +1.766e-10 +1.641e-18 +0.000e+00 +1.500e+11 +4.181e+03 +0.000e+00 +1.497e+11 +4.327e+03 +0.000e+00 +2.522e-09 +3.517e-17 +0.000e+00 -8.382e-04 +2.987e+04 +0.000e+00 -2.110e-04 +3.090e+04 +0.000e+00
t = 0.15 : +2.027e-10 +2.019e-18 +0.000e+00 +1.500e+11 +4.480e+03 +0.000e+00 +1.497e+11 +4.636e+03 +0.000e+00 +2.702e-09 +4.037e-17 +0.000e+00 -8.980e-04 +2.987e+04 +0.000e+00 -2.260e-04 +3.090e+04 +0.000e+00
t = 0.16 : +2.306e-10 +2.450e-18 +0.000e+00 +1.500e+11 +4.778e+03 +0.000e+00 +1.497e+11 +4.945e+03 +0.000e+00 +2.883e-09 +4.593e-17 +0.000e+00 -9.579e-04 +2.987e+04 +0.000e+00 -2.411e-04 +3.090e+04 +0.000e+00
t = 0.17 : +2.603e-10 +2.938e-18 +0.000e+00 +1.500e+11 +5.077e+03 +0.000e+00 +1.497e+11 +5.254e+03 +0.000e+00 +3.063e-09 +5.186e-17 +0.000e+00 -1.018e-03 +2.987e+04 +0.000e+00 -2.562e-04 +3.090e+04 +0.000e+00
t = 0.18 : +2.919e-10 +3.488e-18 +0.000e+00 +1.500e+11 +5.376e+03 +0.000e+00 +1.497e+11 +5.563e+03 +0.000e+00 +3.243e-09 +5.814e-17 +0.000e+00 -1.078e-03 +2.987e+04 +0.000e+00 -2.712e-04 +3.090e+04 +0.000e+00
t = 0.19 : +3.252e-10 +4.102e-18 +0.000e+00 +1.500e+11 +5.674e+03 +0.000e+00 +1.497e+11 +5.872e+03 +0.000e+00 +3.423e-09 +6.477e-17 +0.000e+00 -1.138e-03 +2.987e+04 +0.000e+00 -2.863e-04 +3.090e+04 +0.000e+00
```


[User]
An N-gram is a sequence of N contiguous elements of a given text. Although N-grams refer sometimes to words or syllables, in this task we will consider only sequences of characters.
The task consists in, given a text and an integer size of the desired N-grams, find all the different contiguous sequences of N characters, together with the number of times they appear in the text.
For example, the 2-grams of the text "Live and let live" are:

```
 "LI" - 2
 "IV" - 2
 "VE" - 2
 " L" - 2
 "E " - 1
 " A" - 1
 "AN" - 1
 "ND" - 1
 "D " - 1
 "LE" - 1
 "ET" - 1
 "T " - 1

```

Note that space and other non-alphanumeric characters are taken into account.

See also

* Related task: Sorensen–Dice coefficient

[Assistant]
```
sub n-gram ($this, $N=2) { Bag.new( flat $this.uc.map: { .comb.rotor($N => -($N-1))».join } ) }
dd 'Live and let live'.&n-gram; # bi-gram
dd 'Live and let live'.&n-gram(3); # tri-gram

```

Output:

```
("IV"=>2,"T "=>1,"VE"=>2,"E "=>1,"LE"=>1,"AN"=>1,"LI"=>2,"ND"=>1,"ET"=>1," L"=>2," A"=>1,"D "=>1).Bag
("ET "=>1,"AND"=>1,"LIV"=>2," LI"=>1,"ND "=>1," LE"=>1,"IVE"=>2,"E A"=>1,"VE "=>1,"T L"=>1,"D L"=>1,"LET"=>1," AN"=>1).Bag
```


[User]
N-Queens: you've been there; done that; have the T-shirt. It is time to find the minimum number of Queens, Bishops or Knights that can be placed on an NxN board such that no piece attacks another but every unoccupied square is attacked.

For N=1 to 10 discover the minimum number of Queens, Bishops, and Knights required to fulfill the above requirement. For N=8 print out a possible solution for Queens and Bishops.

Links

* OEIS Independent domination number for queens
* OEIS Independent domination number for knights
* ScienceDirect | minimum dominating set of queens - ways to do it.

[Assistant]
Due to the time it's taking only a subset of the task are attempted.

**Translation of**: Go

```
# 20220705 Raku programming solution

my (@board, @diag1, @diag2, @diag1Lookup, @diag2Lookup, $n, $minCount, $layout);

my %limits   = ( my @pieces = <Q B K> ) Z=> 7,7,6; # >>=>>> 10;
my %names    = @pieces Z=> <Queens Bishops Knights>;

sub isAttacked(\piece, \row, \col) {
   given piece {
      when 'Q' {
         (^$n)>>.&{ return True if @board[$_;col] || @board[row;$_] }
	 return True if @diag1Lookup[@diag1[row;col]] ||
	                @diag2Lookup[@diag2[row;col]]
      }
      when 'B' {
         return True if @diag1Lookup[@diag1[row;col]] ||
                        @diag2Lookup[@diag2[row;col]]
      }
      default { # 'K'
         return True if (
            @board[row;col] or
            row+2 < $n && col-1 >= 0 && @board[row+2;col-1] or
            row-2 >= 0 && col-1 >= 0 && @board[row-2;col-1] or
            row+2 < $n && col+1 < $n && @board[row+2;col+1] or
            row-2 >= 0 && col+1 < $n && @board[row-2;col+1] or
            row+1 < $n && col+2 < $n && @board[row+1;col+2] or
            row-1 >= 0 && col+2 < $n && @board[row-1;col+2] or
            row+1 < $n && col-2 >= 0 && @board[row+1;col-2] or
            row-1 >= 0 && col-2 >= 0 && @board[row-1;col-2]
	 )
      }
   }
   return False
}

sub attacks(\piece, \row, \col, \trow, \tcol) {
   given piece {
      when 'Q' { row==trow || col==tcol || abs(row - trow)==abs(col - tcol) }
      when 'B' { abs(row - trow) == abs(col - tcol) }
      default  { my (\rd,\cd) = ((trow - row),(tcol - col))>>.abs; # when 'K'
                 (rd == 1 && cd == 2) || (rd == 2 && cd == 1)               }
   }
}

sub storeLayout(\piece) {
   $layout = [~] @board.map: -> @row {
      [~] ( @row.map: { $_ ??  piece~' ' !! '. ' } ) , "\n"
   }
}

sub placePiece(\piece, \countSoFar, \maxCount) {
   return if countSoFar >= $minCount;
   my ($allAttacked,$ti,$tj) = True,0,0;
   for ^$n X ^$n -> (\i,\j) {
      unless isAttacked(piece, i, j) {
         ($allAttacked,$ti,$tj) = False,i,j andthen last
      }
      last unless $allAttacked
   }
   if $allAttacked {
      $minCount = countSoFar;
      storeLayout(piece);
      return
   }
   if countSoFar <= maxCount {
      my ($si,$sj) = $ti,$tj;
      if piece eq 'K' {
         ($si,$sj) >>-=>> 2;
         $si = 0 if $si < 0;
         $sj = 0 if $sj < 0;
      }
      for ($si..^$n) X ($sj..^$n) -> (\i,\j) {
         unless isAttacked(piece, i, j) {
            if (i == $ti && j == $tj) || attacks(piece, i, j, $ti, $tj) {
               @board[i][j] = True;
               unless piece eq 'K' {
	          (@diag1Lookup[@diag1[i;j]],@diag2Lookup[@diag2[i;j]])=True xx *
               }
               placePiece(piece, countSoFar+1, maxCount);
               @board[i][j] = False;
               unless piece eq 'K' {
                  (@diag1Lookup[@diag1[i;j]],@diag2Lookup[@diag2[i;j]])=False xx *
               }
            }
	 }
      }
   }
}

for @pieces -> \piece {
   say %names{piece}~"\n=======\n";
   loop ($n = 1 ; ; $n++) {
      @board = [ [ False xx $n ] xx $n ];
      unless piece eq 'K' {
         @diag1 = ^$n .map: { $_ ... $n+$_-1 } ;
         @diag2 = ^$n .map: { $n+$_-1 ... $_ } ;
	 @diag2Lookup = @diag1Lookup = [ False xx 2*$n-1 ]
      }
      $minCount = 2³¹ - 1; # golang: math.MaxInt32
      my \nSQ   = $n*$n;
      for 1..nSQ -> \maxCount {
         placePiece(piece, 0, maxCount);
         last if $minCount <= nSQ
      }
      printf("%2d x %-2d : %d\n", $n, $n, $minCount);
      if $n == %limits{piece} {
         printf "\n%s on a %d x %d board:\n", %names{piece}, $n, $n;
         say $layout andthen last
      }
   }
}

```

Output:

```
Queens
=======

 1 x 1  : 1
 2 x 2  : 1
 3 x 3  : 1
 4 x 4  : 3
 5 x 5  : 3
 6 x 6  : 4
 7 x 7  : 4

Queens on a 7 x 7 board:
.  Q  .  .  .  .  .
.  .  .  .  .  Q  .
.  .  .  .  .  .  .
Q  .  .  .  .  .  .
.  .  .  .  Q  .  .
.  .  .  .  .  .  .
.  .  .  .  .  .  .

Bishops
=======

 1 x 1  : 1
 2 x 2  : 2
 3 x 3  : 3
 4 x 4  : 4
 5 x 5  : 5
 6 x 6  : 6
 7 x 7  : 7

Bishops on a 7 x 7 board:
.  .  .  .  .  B  .
.  .  B  .  .  .  .
.  .  B  .  B  .  .
.  .  .  .  .  .  B
.  .  .  B  .  .  .
.  .  .  B  .  .  .
.  .  .  .  .  .  .

Knights
=======

 1 x 1  : 1
 2 x 2  : 4
 3 x 3  : 4
 4 x 4  : 4
 5 x 5  : 5
 6 x 6  : 8

Knights on a 6 x 6 board:
K  .  .  .  .  K
.  .  .  .  .  .
.  .  K  K  .  .
.  .  K  K  .  .
.  .  .  .  .  .
K  .  .  .  .  K

```


[User]
Solve the eight queens puzzle.

You can extend the problem to solve the puzzle with a board of size   **N**x**N**.

For the number of solutions for small values of   **N**,   see   OEIS: A000170.

Related tasks

* A\* search algorithm
* Solve a Hidato puzzle
* Solve a Holy Knight's tour
* Knight's tour
* Peaceful chess queen armies
* Solve a Hopido puzzle
* Solve a Numbrix puzzle
* Solve the no connection puzzle

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015-11-29

Neither pretty nor efficient, a simple backtracking solution

```
sub MAIN(\N = 8) {
    sub collision(@field, $row) {
        for ^$row -> $i {
            my $distance = @field[$i] - @field[$row];
            return True if $distance == any(0, $row - $i, $i - $row);
        }
        False;
    }
    sub search(@field, $row) {
        return @field if $row == N;
        for ^N -> $i {
            @field[$row] = $i;
            return search(@field, $row + 1) || next
                unless collision(@field, $row);
        }
        ()
    }
    for 0 .. N / 2 {
        if search [$_], 1 -> @f {
            say @f;
            last;
        }
    }
}
```

Output:

```
[0 4 7 5 2 6 1 3]
```


[User]
**n-smooth**   numbers are positive integers which have no prime factors  >  **n**.

The   **n**   in the expression   **n-smooth**   is always prime;

there are   no   **9-smooth** numbers.

**1**   (unity)   is always included in n-smooth numbers.

2-smooth   numbers are non-negative powers of two.

5-smooth   numbers are also called   Hamming numbers.

7-smooth   numbers are also called   humble numbers.

A way to express   11-smooth   numbers is:

```
  11-smooth  =  2i × 3j × 5k × 7m × 11p

```

```
           where     i, j, k, m, p ≥ 0

```

Task
:   * calculate and show the first   **25**   n-smooth numbers   for   **n=2**   ───►   **n=29**
    * calculate and show   three numbers starting with   **3,000**   n-smooth numbers   for   **n=3**   ───►   **n=29**
    * calculate and show twenty numbers starting with  **30,000**   n-smooth numbers   for   **n=503**   ───►   **n=521**   (optional)

All ranges   (for   **n**)   are to be inclusive, and only prime numbers are to be used.

The (optional) n-smooth numbers for the third range are:   **503**,   **509**,   and   **521**.

Show all n-smooth numbers for any particular   **n**   in a horizontal list.

Show all output here on this page.

Related tasks
:   * Hamming numbers
    * humble numbers

References
:   * Wikipedia entry:   Hamming numbers     (this link is re-directed to   **Regular number**).
    * Wikipedia entry:   Smooth number
    * OEIS entry:   A000079    2-smooth numbers or non-negative powers of two
    * OEIS entry:   A003586    3-smooth numbers
    * Mintz 1981:   3-smooth numbers
    * OEIS entry:   A051037    5-smooth numbers or Hamming numbers
    * OEIS entry:   A002473    7-smooth numbers or humble numbers
    * OEIS entry:   A051038   11-smooth numbers
    * OEIS entry:   A080197   13-smooth numbers
    * OEIS entry:   A080681   17-smooth numbers
    * OEIS entry:   A080682   19-smooth numbers
    * OEIS entry:   A080683   23-smooth numbers

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

```
sub smooth-numbers (*@list) {
    cache my \Smooth := gather {
        my %i = (flat @list) Z=> (Smooth.iterator for ^@list);
        my %n = (flat @list) Z=> 1 xx *;

        loop {
            take my $n := %n{*}.min;

            for @list -> \k {
                %n{k} = %i{k}.pull-one * k if %n{k} == $n;
            }
        }
    }
}

sub abbrev ($n) {
   $n.chars > 50 ??
   $n.substr(0,10) ~ "...({$n.chars - 20} digits omitted)..." ~ $n.substr(* - 10) !!
   $n
}

my @primes = (2..*).grep: *.is-prime;

my $start = 3000;

for ^@primes.first( * > 29, :k ) -> $p {
    put join "\n", "\nFirst 25, and {$start}th through {$start+2}nd {@primes[$p]}-smooth numbers:",
    $(smooth-numbers(|@primes[0..$p])[^25]),
    $(smooth-numbers(|@primes[0..$p])[$start - 1 .. $start + 1]».&abbrev);
}

$start = 30000;

for 503, 509, 521 -> $p {
    my $i = @primes.first( * == $p, :k );
    put "\n{$start}th through {$start+19}th {@primes[$i]}-smooth numbers:\n" ~
    smooth-numbers(|@primes[0..$i])[$start - 1 .. $start + 18];
}

```

Output:

```
First 25, and 3000th through 3002nd 2-smooth numbers:
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216
6151159610...(883 digits omitted)...9114994688 1230231922...(884 digits omitted)...8229989376 2460463844...(884 digits omitted)...6459978752

First 25, and 3000th through 3002nd 3-smooth numbers:
1 2 3 4 6 8 9 12 16 18 24 27 32 36 48 54 64 72 81 96 108 128 144 162 192
91580367978306252441724649472 92829823186414819915547541504 94096325042746502515294076928

First 25, and 3000th through 3002nd 5-smooth numbers:
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 54
278942752080 279936000000 281250000000

First 25, and 3000th through 3002nd 7-smooth numbers:
1 2 3 4 5 6 7 8 9 10 12 14 15 16 18 20 21 24 25 27 28 30 32 35 36
50176000 50331648 50388480

First 25, and 3000th through 3002nd 11-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 18 20 21 22 24 25 27 28 30 32
2112880 2116800 2117016

First 25, and 3000th through 3002nd 13-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 18 20 21 22 24 25 26 27 28
390000 390390 390625

First 25, and 3000th through 3002nd 17-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 20 21 22 24 25 26 27
145800 145860 146016

First 25, and 3000th through 3002nd 19-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 24 25 26
74256 74358 74360

First 25, and 3000th through 3002nd 23-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
46552 46575 46585

First 25, and 3000th through 3002nd 29-smooth numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
33516 33524 33534

30000th through 30019th 503-smooth numbers:
62913 62914 62916 62918 62920 62923 62926 62928 62930 62933 62935 62937 62944 62946 62951 62952 62953 62957 62959 62964

30000th through 30019th 509-smooth numbers:
62601 62602 62604 62607 62608 62609 62611 62618 62620 62622 62624 62625 62626 62628 62629 62634 62640 62643 62645 62646

30000th through 30019th 521-smooth numbers:
62287 62288 62291 62292 62300 62304 62307 62308 62310 62315 62320 62321 62322 62325 62328 62329 62330 62331 62335 62336
```


[User]
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this.

**Note:**

:   Named parameters relies on being able to use the names given to function parameters when the function is defined, when assigning arguments when the function is called.
:   For example, if a function were to be defined as `define func1( paramname1, paramname2)`; then it could be called normally as `func1(argument1, argument2)` and in the called function paramname1 would be associated with argument1 and paramname2 with argument2.
:   `func1` **must also be able to be called in a way that visually binds each parameter to its respective argument, irrespective of argument order**, for example: `func1(paramname2=argument2, paramname1=argument1)` which *explicitly* makes the same parameter/argument bindings as before.
:   Named parameters are often a feature of languages used in safety critical areas such as Verilog and VHDL.

**See also:**

* Varargs
* Optional parameters
* Wikipedia: Named parameter

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version #22 "Thousand Oaks"

Raku's support for optional parameters is much like Python's. Consider this declaration:

```
sub funkshun ($a, $b?, $c = 15, :$d, *@e, *%f) {
   ...
}

```

In the above signature:

* `$a` is a mandatory parameter accepted by position (`funkshun 15, ...`).
* `$b` is an optional parameter that can be passed by position or by name. By default, it's undefined.
* `$c` is an optional parameter that can be passed by position or by name. Its default value is `15`.
* `$d` is an optional parameter that can only be passed by name. By default, it's undefined.
* `@e` is a slurpy array: it receives any leftover positional arguments.
* `%f` is a slurpy hash: it receives any leftover named arguments.

So, if we defined the function like this:

```
sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) {
   say "$a $b $c $d";
   say join ' ', @e;
   say join ' ', keys %f;
}

# this particularly thorny call:

funkshun
    'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1',
    d => 'Delta', 'e2', k2 => 'v2';

```

would print this:

```
Alfa Bravo Charlie Delta
e1 e2
k1 k2
```


[User]
Translate the spelled-out English name of a number to a number. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).

Support for inputs other than positive integers (like zero, negative integers, fractions and floating-point numbers) is optional.

See also

* Number names — the reverse operation.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl

```
my $phrases-with-numbers = q:to/END/;
One Hundred and One Dalmatians
Two Thousand and One: A Space Odyssey

Four  Score  And  Seven  Years  Ago
twelve dozen is one hundred forty-four, aka one gross
two hundred pairs of socks
Always give one hundred and ten percent effort
Change due: zero dollars and thirty-seven cents

One hour, fifty-nine minutes, forty point two seconds
π ≅ three point one four one five nine
END

my $pure-numbers = q:to/END/;
Twenty Nineteen
Two Thousand Nineteen
Two Thousand Zero Hundred and Nineteen
Two Thousand Ten Nine

one thousand one
ninety nine thousand nine hundred ninety nine
five hundred and twelve thousand, six hundred and nine
two billion, one hundred

One Thousand One Hundred Eleven
Eleven Hundred Eleven
one hundred eleven billion one hundred eleven
Eight Thousand Eight Hundred Eighty-Eight
Eighty-Eight Hundred Eighty-Eight

Forty-two quintillion, one quadrillion, two trillion, three billion, four million, five thousand six
END

my %nums = (
    zero        => 0,     one        => 1,     two         => 2,     three    => 3,
    four        => 4,     five       => 5,     six         => 6,     seven    => 7,
    eight       => 8,     nine       => 9,     ten         => 10,    eleven   => 11,
    twelve      => 12,    thirteen   => 13,    fourteen    => 14,    fifteen  => 15,
    sixteen     => 16,    seventeen  => 17,    eighteen    => 18,    nineteen => 19,
    twenty      => 20,    thirty     => 30,    forty       => 40,    fifty    => 50,
    sixty       => 60,    seventy    => 70,    eighty      => 80,    ninety   => 90,
    hundred     => 100,   thousand   => 1_000, million     => 1_000_000,
    billion     => 1_000_000_000,              trillion    => 1_000_000_000_000,
    quadrillion => 1_000_000_000_000_000,      quintillion => 1_000_000_000_000_000_000
);

# groupings:     thousand million billion  trillion quadrillion quintillion
my token groups { \d**4  | \d**7 | \d**10 | \d**13 | \d**16    | \d**19 };

# remove hyphens/spaces: leading, trailing, multiple
sub squeeze ($str is copy) { $str ~~ s:g/'-' | \s+ / /; $str .=trim }

# commify larger numbers for readabilty
sub comma { $^i.chars > 4 ?? $^i.flip.comb(3).join(',').flip !! $^i }

sub numify ($str is copy) {
    $str = squeeze $str.lc;
    $str ~~ s:g/(.)(<punct>)/$0 $1/;

    for %nums.kv -> $word, $number { $str ~~ s:g/ <|w> $word <|w> / $number / }

    $str ~~ s:g/(\d+)<ws> <?before \d>/$0/ if $str ~~ /(point )<ws>[(\d)<ws>]+$/;
    $str ~~ s:g/(\d+) <ws> 'score' / {$0 * 20} /;
    $str ~~ s:g/(\d) <ws> [','|'and'] <ws> (\d)/$0 $1/;

    $str ~~ s:g/ <|w> (\d) <ws> 100 <ws> (\d\d) <ws> (\d) <ws>     (<groups>) <|w> / {($0 * 100 + $1 + $2) * $3} /;
    $str ~~ s:g/ <|w> (\d) <ws> 100 <ws> (\d ** 1..2)     <ws>     (<groups>) <|w> / {($0 * 100 + $1) * $2}      /;
    $str ~~ s:g/ <|w> (\d) <ws> 100                       <ws>     (<groups>) <|w> / { $0 * 100 * $1}            /;
    $str ~~ s:g/ <|w>      <ws> 100 <ws> (\d\d) <ws> (\d) <ws>     (<groups>) <|w> / {($0 + 100 + $1) * $2}      /;
    $str ~~ s:g/ <|w>      <ws> 100 <ws> (\d ** 1..2)     <ws>     (<groups>) <|w> / {($0 + 100     ) * $1}      /;
    $str ~~ s:g/ <|w>      <ws> 100                       <ws>     (<groups>) <|w> / { $0 * 100}                 /;
    $str ~~ s:g/ <|w>              (\d\d) <ws> (\d)       <ws>     (<groups>) <|w> / {($0 + $1) * $2}            /;
    $str ~~ s:g/ <|w>              (\d ** 1..2)           <ws>     (<groups>) <|w> / { $0 * $1}                  /;
    $str ~~ s:g/ <|w>              (\d\d) <ws> (\d)       <ws> 100            <|w> / {($0 + $1) * 100}           /;
    $str ~~ s:g/ <|w>              (\d ** 1..2)           <ws> 100            <|w> / { $0 * 100}                 /;
    $str ~~ s:g/ <|w>              (\d ** 2)<ws>(\d ** 2)                     <|w> / { $0 * 100 + $1}            /;

    $str ~~ s:g/( [\d+<ws>]* \d+ ) / {[+] $0.split: ' '} /;

    $str ~~ s:g/(\d+) <ws> 'pairs of'         /  {$0 *  2} /;
    $str ~~ s:g/(\d+) <ws> 'dozen'            /  {$0 * 12} /;
    $str ~~ s:g/(\d+) <ws> 'point' <ws> (\d+) /   $0.$1    /;
    $str ~~ s:g/(\d+) <ws> 'percent'          /   $0%      /;
    $str ~~ s:g/(\d+) <ws> 'dollars'          / \$$0       /;
    $str ~~ s:g/(\d+) <ws> 'cents'            /   $0¢      /;

    squeeze $str;
}

say $_ ~ ' --> ' ~ .&numify        for $phrases-with-numbers.split("\n").grep: *.so;
say $_ ~ ' --> ' ~ .&numify.&comma for         $pure-numbers.split("\n").grep: *.so;

```

Output:

```
One Hundred and One Dalmatians --> 101 dalmatians
Two Thousand and One: A Space Odyssey --> 2001 : a space odyssey
Four  Score  And  Seven  Years  Ago   --> 87 years ago
twelve dozen is one hundred forty-four, aka one gross --> 144 is 144 , aka 1 gross
two hundred pairs of socks --> 400 socks
Always give one hundred and ten percent effort --> always give 110% effort
Change due: zero dollars and thirty-seven cents --> change due : $0 and 37¢
One hour, fifty-nine minutes, forty point two seconds --> 1 hour , 59 minutes , 40.2 seconds
π ≅ three point one four one five nine --> π ≅ 3.14159
Twenty Nineteen --> 2019
Two Thousand Nineteen --> 2019
Two Thousand Zero Hundred and Nineteen --> 2019
Two Thousand Ten Nine --> 2019
one thousand one --> 1001
ninety nine thousand nine hundred ninety nine --> 99,999
five hundred and twelve thousand, six hundred and nine --> 512,609
two billion, one hundred --> 2,000,000,100
One Thousand One Hundred Eleven --> 1111
Eleven Hundred Eleven --> 1111
one hundred eleven billion one hundred eleven --> 111,000,000,111
Eight Thousand Eight Hundred Eighty-Eight --> 8888
Eighty-Eight Hundred Eighty-Eight --> 8888
Forty-two quintillion, one quadrillion, two trillion, three billion, four million, five thousand six --> 42,001,002,003,004,005,006
```


[User]
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as *de facto* or *de jure* depending on how they are enforced,
often take the form of rules regarding prefixes, suffixes, and the use of upper-case and lower-case characters.

The naming conventions are sometimes a bit haphazard, especially if the language and/or library has gone through periods of evolution. (In this case: give a brief example and description.)

Document (with simple examples where possible) the evolution and current status of these naming conventions.
For example, name conventions for:

* Procedure and operator names. (Intrinsic or external)
* Class, Subclass and instance names.
* Built-in versus libraries names.

If possible, indicate where the naming conventions are implicit, explicit, mandatory or discretionary.
Any tools that enforced the the naming conventions.
Any cases where the naming convention as commonly violated.

If possible, indicate where the convention is used to hint at other issues. For example the C standard library uses a prefix of "\_" to "hide" raw Operating System calls from the non systems-programmer, whereas Python embeds member functions in between "\_\_" to make a member function "private".

See also

* Wikipedia: Naming convention (programming)

[Assistant]
(formerly Perl 6)

Raku is written in Unicode, and has consistent Unicode semantics regardless of the underlying text representations. By default Raku presents Unicode in "NFG" formation, where each grapheme counts as one character. A grapheme is what the user would think of as a character in their normal everyday life, including any diacritics.

Built-in object types start with an uppercase letter. This includes immutable types (e.g. Int, Num, Complex, Rat, Str, Bit, Regex, Set, Block, Iterator), as well as mutable (container) types, such as Scalar, Array, Hash, Buf, Routine, Module, and non-instantiable Roles such as Callable and Integral. The names may extend to CamelCase for compound words: IntStr, CaptureCursor, BagHash, SoftRoutine.

Non-object (native) types are lowercase: int, num, complex, rat, buf, bit.

Nearly all built-in subroutines, functions, methods and pragmas included in Raku CORE are lowercase or lower kebab-case. (Compound words joined with hyphens rather than underscores or camelCase.) .grep, .pairs, .log, .defined, .subst-rw. The few notable exceptions are those which can radically change behaviour of the executing code. They are in all-cap/kebab-case to make them stand out: EVAL, MONKEY-TYPING.

All upper case names are semi-reserved. You are free to use them, but are warned that you may encounter future collisions with internal usage. Upper case names are used for pseudo-packages: MY, OUR, CORE, GLOBAL, etc., for relative scope identifiers: CALLER, OUTER, SETTING, PARENT, etc. and other things.

Variables in Raku CORE tend be lower kebab-case for lexical variables and upper case for special or package globals. They have an attached, prefix sigil (or twigil) to indicate what type of object they hold and what methods are available to operate on them.

In user space, there are very few restrictions on how things are named. Identifiers of any type can not contain white space. Subroutines must start with a letter character, any Unicode character that has a "letter" property. Variable names can't contain any of the sigil, twigil or comment characters ($, @, %, \*, ?, =, :, #). Outside of those few restrictions, it's pretty much a free-for-all.

That being said, there are some community conventions which are encouraged, though not enforced. Descriptiveness is favoured over terseness, though this should be scaled to the scope of the object. It is perfectly fine to name an index variable in a three line loop, $i. An object in global scope with dozens of methods may be better off with a more descriptive name. It is encouraged to name subroutines for what they do to make it easier for others to follow your logic. Nouny things should have nouny names. Verby things should be verby. Finally, if you *aren't* going to follow convention, at least be consistent.


[User]
Quoting from the Esolangs wiki page:

> A **narcissist** (or **Narcissus program**) is the decision-problem version of a quine.

> A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.

For concreteness, in this task we shall assume that symbol = character.

The narcissist should be able to cope with any finite input, whatever its length.

Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.

[Assistant]
(formerly Perl 6)

For the narcissist to work you must be very careful with whitespace. The following version works if it is given to standard input as exactly one line terminated by a newline character.

Note how the code takes advantage of Raku's ability to nest quoting delimiters.

```
EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}

```

Output:

```
$ narcissist='EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}}'
$ raku -e "$narcissist" <<<"$narcissist"
Beautiful!
$ raku -e "$narcissist" <<<"$narcissist # a comment ruining it all"
Not my type.

```