[User]
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321).

* The implementation needs to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
* In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
* Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
* The following are acceptable:
  + An original implementation from the specification, reference implementation, or pseudo-code
  + A translation of a correct implementation from another language
  + A library routine in the same language; however, the source must be included here.

The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.

The following verification strings and hashes come from RFC 1321:

```
                            hash code <== string
   0xd41d8cd98f00b204e9800998ecf8427e <== ""
   0x0cc175b9c0f1b6a831c399e269772661 <== "a"
   0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
   0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
   0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
   0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
   0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
```

In addition, intermediate outputs to aid in developing an implementation can be found here.

The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.

|  |
| --- |
| **Warning** Rosetta Code is **not** a place you should rely on for examples of code in critical roles, including security. Also, note that MD5 has been *broken* and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3. |

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2024-06

```
proto md5($msg) returns Blob is export {*}
multi md5(Str $msg) { md5 $msg.encode }
multi md5(Blob $msg) {
  [~] map { buf8.new.write-uint32: 0, $_, LittleEndian },
    |reduce -> Blob $blob, blob32 $X {
      blob32.new: $blob Z+
        reduce -> $b, $i {
          blob32.new:
            $b[3],
            $b[1] +
              -> uint32 \x, \n { (x +< n) +| (x +> (32-n)) }(
              ($b[0] + (BEGIN Array.new:
              { ($^x +& $^y) +| (+^$x +& $^z) },
              { ($^x +& $^z) +| ($^y +& +^$z) },
              { $^x +^ $^y +^ $^z },
              { $^y +^ ($^x +| +^$^z) }
              )[$i div 16](|$b[1..3]) +
              (BEGIN blob32.new: map &floor ∘ * * 2**32 ∘ &abs ∘ &sin ∘ * + 1, ^64)[$i] +
              $X[(BEGIN Blob.new: 16 X[R%] flat ($++, 5*$++ + 1, 3*$++ + 5, 7*$++) Xxx 16)[$i]]
              ) mod 2**32,
              (BEGIN flat < 7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21 >.rotor(4) Xxx 4)[$i]
            ),
            $b[1],
            $b[2]
        }, $blob, |^64;
    },
    (BEGIN blob32.new: 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476),
    |map { blob32.new: @$_ },
      {
        $^b.push(blob8.new(@$_).read-uint32(0)) for (@$msg, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64))
            .flat.rotor(4);
        $b.write-uint64: $b.elems, 8*$msg.elems, LittleEndian;
        $b;
      }(buf32.new)
    .rotor(16);
}

CHECK {
  use Test;

  for 'd41d8cd98f00b204e9800998ecf8427e', '',
      '0cc175b9c0f1b6a831c399e269772661', 'a',
      '900150983cd24fb0d6963f7d28e17f72', 'abc',
      'f96b697d7cb7938d525a2f31aaf161d0', 'message digest',
      'c3fcd3d76192e4007dfb496cca67e13b', 'abcdefghijklmnopqrstuvwxyz',
      'd174ab98d277d9f5a5611c2c9f419d9f', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
      '57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
        -> $expected, $msg {
          my $digest = md5($msg).list».fmt('%02x').join;
          is($digest, $expected, "$digest is MD5 digest of '$msg'");
        }
  done-testing;
}

```

Output:

```
1..7
ok 1 - d41d8cd98f00b204e9800998ecf8427e is MD5 digest of ''
ok 2 - 0cc175b9c0f1b6a831c399e269772661 is MD5 digest of 'a'
ok 3 - 900150983cd24fb0d6963f7d28e17f72 is MD5 digest of 'abc'
ok 4 - f96b697d7cb7938d525a2f31aaf161d0 is MD5 digest of 'message digest'
ok 5 - c3fcd3d76192e4007dfb496cca67e13b is MD5 digest of 'abcdefghijklmnopqrstuvwxyz'
ok 6 - d174ab98d277d9f5a5611c2c9f419d9f is MD5 digest of 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
ok 7 - 57edf4a22be3c955ac49da2e2107b67a is MD5 digest of '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
```


[User]
The median filter takes in the neighbourhood the median color (see Median filter)

*(to test the function below, you can use these input and output solutions)*

[Assistant]
(formerly Perl 6)
Clone of Perl 5, for now.

```
use PDL:from<Perl5>;
use PDL::Image2D:from<Perl5>;

my $image = rpic 'plasma.png';
my $smoothed = med2d($image, ones(3,3), {Boundary => 'Truncate'});
wpic $smoothed, 'plasma_median.png';

```

Compare offsite images: plasma.png vs.
plasma\_median.png


[User]
Task

Calculate Meissel–Mertens constant up to a precision your language can handle.

Motivation

Analogous to Euler's constant, which is important in determining the sum of reciprocal natural numbers, Meissel-Mertens' constant is important in calculating the sum of reciprocal primes.

Example

We consider the finite sum of reciprocal natural numbers:

*1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n*

this sum can be well approximated with:

*log(n) + E*

where *E* denotes Euler's constant: 0.57721...

*log(n)* denotes the natural logarithm of *n*.

Now consider the finite sum of reciprocal primes:

*1/2 + 1/3 + 1/5 + 1/7 + 1/11 ... 1/p*

this sum can be well approximated with:

*log( log(p) ) + M*

where *M* denotes Meissel-Mertens constant: 0.26149...

See
:   * Details in the Wikipedia article:  Meissel–Mertens constant

[Assistant]
**Translation of**: FreeBASIC

```
# 20221011 Raku programming solution

my $s;
.is-prime and $s += log(1-1/$_)+1/$_ for 2 .. 10**8;
say $s + .57721566490153286

```

Output:

```
0.26149721310571383
```


[User]
Task

Show how to explicitly allocate and deallocate blocks of memory in your language.

Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.

[Assistant]
(formerly Perl 6)

Like Perl 5, Raku is intended to run largely stackless, so all allocations are really on the heap, including activation records. Allocations are managed automatically. It is easy enough to allocate a memory buffer of a particular size however, if you really need it:

```
my $buffer = Buf.new(0 xx 1024);

```


[User]
It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.

```
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
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
_________________
1  2  3  4  5
6  7  8  9
25 pin                        9 pin
1 - PG   Protective ground
2 - TD   Transmitted data     3
3 - RD   Received data        2
4 - RTS  Request to send      7
5 - CTS  Clear to send        8
6 - DSR  Data set ready       6
7 - SG   Signal ground        5
8 - CD   Carrier detect       1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD  Secondary CD
13 - SCS  Secondary CTS
14 - STD  Secondary TD
15 - TC   Transmit clock
16 - SRD  Secondary RD
17 - RC   Receiver clock
18 -
19 - SRS  Secondary RTS
20 - DTR  Data terminal ready      4
21 - SQD  Signal quality detector
22 - RI   Ring indicator           9
23 - DRS  Data rate select
24 - XTC  External clock
25 -

```

[Assistant]
(formerly Perl 6)
The following is specced to work, but implementation of shaped arrays is not quite complete.

```
enum T_RS232 <
    carrier_detect
    received_data
    transmitted_data
    data_terminal_ready
    signal_ground
    data_set_ready
    request_to_send
    clear_to_send
    ring_indicator
>;

my bit @signal[T_RS232];

@signal[signal_ground] = 1;

```

In the absence of shaped arrays, you can do the usual bit-twiddling tricks on a native integer of sufficient size. (Such an integer could presumably be mapped directly to a device register.)

```
$signal +|= 1 +< signal_ground;

```

Using a native int is likelier to work on a big-endian machine in any case. Another almost-there solution is the mapping of C representational types into Raku for native interfaces, but it does not yet support bit fields.


[User]
Task

Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:

* prints a textual menu formatted as an index value followed by its corresponding string for each item in the list;
* prompts the user to enter a number;
* returns the string corresponding to the selected index number.

The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.

For test purposes use the following four phrases in a list:

```
   fee fie
   huff and puff
   mirror mirror
   tick tock

```

Note

This task is fashioned after the action of the Bash select statement.

[Assistant]
(formerly Perl 6)

```
sub menu ( $prompt, @items ) {
    return '' unless @items.elems;
    repeat until my $selection ~~ /^ \d+ $/ && @items[--$selection] {
        my $i = 1;
        say "  {$i++}) $_" for @items;
        $selection = prompt $prompt;
    }
    return @items[$selection];
}

my @choices = 'fee fie', 'huff and puff', 'mirror mirror', 'tick tock';
my $prompt = 'Enter the number corresponding to your selection: ';

my $answer = menu( $prompt, [] );
say "You chose: $answer" if $answer.chars;

$answer = menu( $prompt, @choices );
say "You chose: $answer" if $answer.chars;

```


[User]
Merge and aggregate datasets

Task

Merge and aggregate two datasets as provided in   **.csv**   files into a new resulting dataset.

Use the appropriate methods and data structures depending on the programming language.

Use the most common libraries only when built-in functionality is not sufficient.

Note

Either load the data from the   **.csv**   files or create the required data structures hard-coded.

**patients.csv**   file contents:

```
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz

```

**visits.csv**   file contents:

```
PATIENT_ID,VISIT_DATE,SCORE
2002,2020-09-10,6.8
1001,2020-09-17,5.5
4004,2020-09-24,8.4
2002,2020-10-08,
1001,,6.6
3003,2020-11-12,
4004,2020-11-05,7.0
1001,2020-11-19,5.3

```

Create a resulting dataset in-memory or output it to screen or file, whichever is appropriate for the programming language at hand.

Merge and group per patient id and last name,   get the maximum visit date,   and get the sum and average of the scores per patient to get the resulting dataset.

Note that the visit date is purposefully provided as ISO format,   so that it could also be processed as text and sorted alphabetically to determine the maximum date.

```
| PATIENT_ID | LASTNAME | LAST_VISIT |  SCORE_SUM | SCORE_AVG |
| 1001       |  Hopper  | 2020-11-19 |  17.4      | 5.80      |
| 2002       |  Gosling | 2020-10-08 |   6.8      | 6.80      |
| 3003       |  Kemeny  | 2020-11-12 |            |           |
| 4004       |  Wirth   | 2020-11-05 |  15.4      | 7.70      |
| 5005       |  Kurtz   |            |            |           |

```

Note

This task is aimed in particular at programming languages that are used in data science and data processing, such as F#, Python, R, SPSS, MATLAB etc.

Related tasks

* CSV data manipulation
* CSV to HTML translation
* Read entire file
* Read a file line by line

[Assistant]
```
my @names = map { ( <PATIENT_ID LASTNAME> Z=> .list ).hash },
    ( 1001, 'Hopper'  ),
    ( 4004, 'Wirth'   ),
    ( 3003, 'Kemeny'  ),
    ( 2002, 'Gosling' ),
    ( 5005, 'Kurtz'   ),
;
my @visits = map { ( <PATIENT_ID VISIT_DATE SCORE> Z=> .list ).hash },
    ( 2002, '2020-09-10', 6.8 ),
    ( 1001, '2020-09-17', 5.5 ),
    ( 4004, '2020-09-24', 8.4 ),
    ( 2002, '2020-10-08', Nil ),
    ( 1001,         Nil , 6.6 ),
    ( 3003, '2020-11-12', Nil ),
    ( 4004, '2020-11-05', 7.0 ),
    ( 1001, '2020-11-19', 5.3 ),
;

my %v = @visits.classify: *.<PATIENT_ID>;

my @result = gather for @names -> %n {
    my @p = %v{ %n.<PATIENT_ID> }<>;

    my @dates  = @p».<VISIT_DATE>.grep: *.defined;
    my @scores = @p».<     SCORE>.grep: *.defined;

    take {
        %n,
        LAST_VISIT => ( @dates.max          if @dates  ),
        SCORE_AVG  => ( @scores.sum/@scores if @scores ),
        SCORE_SUM  => ( @scores.sum         if @scores ),
    };
}

my @out_field_names = <PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG>;
my @rows = @result.sort(*.<PATIENT_ID>).map(*.{@out_field_names});
say .map({$_ // ''}).fmt('%-10s', ' | ') for @out_field_names, |@rows;

```

Output:

```
PATIENT_ID | LASTNAME   | LAST_VISIT | SCORE_SUM  | SCORE_AVG
1001       | Hopper     | 2020-11-19 | 17.4       | 5.8
2002       | Gosling    | 2020-10-08 | 6.8        | 6.8
3003       | Kemeny     | 2020-11-12 |            |
4004       | Wirth      | 2020-11-05 | 15.4       | 7.7
5005       | Kurtz      |            |            |

```


[User]
Task

Create code that will list (preferably calculate) all of the   *Mersenne primes*   until some limitation is reached.

The number of   *known*   Mersenne primes is   **51**   (as of June, 2020),   and the largest known Mersenne prime contains contains   **24,862,048**   decimal digits.

Also see

* the Wikipedia entry:   Mersenne prime.
* the MathWorld entry;   Mersenne prime.
* For a list of all the know Mersenne primes:   [https://primes.utm.edu/mersenne/index.html#known list of Mersenne
* For a general website about primes: prime pages.
* the OEIS entry: Mersenne primes.
* the OEIS entry: A000043 Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.01

We already have a multitude of tasks that demonstrate **how** to find Mersenne primes; Prime decomposition, Primality by trial division, Trial factoring of a Mersenne number, Lucas-Lehmer test, Miller–Rabin primality\_test, etc. that all have Raku entries. I'm not sure what I could add here that would be useful.

Hmmm.

> *Create code that will list all of the Mersenne primes until some limitation is reached.*

It doesn't specify to *calculate* them, only to *list* them; why throw away all of the computer **millenia** of processing power that the GIMPS has invested?

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

my $table = parse-html(HTTP::UserAgent.new.get('https://www.mersenne.org/primes/').content, :TAG<table>);

say 'All known Mersenne primes as of ', Date(now);

say 'M', ++$, ": 2$_ - 1"
  for $table[1]».[*][0][*].comb(/'perfect'\d+/)».subst(/\D/, '',:g)
  .trans([<0123456789>.comb] => [<⁰¹²³⁴⁵⁶⁷⁸⁹>.comb]).words;

```

Output:

```
All known Mersenne primes as of 2024-11-07
M1: 2² - 1
M2: 2³ - 1
M3: 2⁵ - 1
M4: 2⁷ - 1
M5: 2¹³ - 1
M6: 2¹⁷ - 1
M7: 2¹⁹ - 1
M8: 2³¹ - 1
M9: 2⁶¹ - 1
M10: 2⁸⁹ - 1
M11: 2¹⁰⁷ - 1
M12: 2¹²⁷ - 1
M13: 2⁵²¹ - 1
M14: 2⁶⁰⁷ - 1
M15: 2¹²⁷⁹ - 1
M16: 2²²⁰³ - 1
M17: 2²²⁸¹ - 1
M18: 2³²¹⁷ - 1
M19: 2⁴²⁵³ - 1
M20: 2⁴⁴²³ - 1
M21: 2⁹⁶⁸⁹ - 1
M22: 2⁹⁹⁴¹ - 1
M23: 2¹¹²¹³ - 1
M24: 2¹⁹⁹³⁷ - 1
M25: 2²¹⁷⁰¹ - 1
M26: 2²³²⁰⁹ - 1
M27: 2⁴⁴⁴⁹⁷ - 1
M28: 2⁸⁶²⁴³ - 1
M29: 2¹¹⁰⁵⁰³ - 1
M30: 2¹³²⁰⁴⁹ - 1
M31: 2²¹⁶⁰⁹¹ - 1
M32: 2⁷⁵⁶⁸³⁹ - 1
M33: 2⁸⁵⁹⁴³³ - 1
M34: 2¹²⁵⁷⁷⁸⁷ - 1
M35: 2¹³⁹⁸²⁶⁹ - 1
M36: 2²⁹⁷⁶²²¹ - 1
M37: 2³⁰²¹³⁷⁷ - 1
M38: 2⁶⁹⁷²⁵⁹³ - 1
M39: 2¹³⁴⁶⁶⁹¹⁷ - 1
M40: 2²⁰⁹⁹⁶⁰¹¹ - 1
M41: 2²⁴⁰³⁶⁵⁸³ - 1
M42: 2²⁵⁹⁶⁴⁹⁵¹ - 1
M43: 2³⁰⁴⁰²⁴⁵⁷ - 1
M44: 2³²⁵⁸²⁶⁵⁷ - 1
M45: 2³⁷¹⁵⁶⁶⁶⁷ - 1
M46: 2⁴²⁶⁴³⁸⁰¹ - 1
M47: 2⁴³¹¹²⁶⁰⁹ - 1
M48: 2⁵⁷⁸⁸⁵¹⁶¹ - 1
M49: 2⁷⁴²⁰⁷²⁸¹ - 1
M50: 2⁷⁷²³²⁹¹⁷ - 1
M51: 2⁸²⁵⁸⁹⁹³³ - 1
M52: 2¹³⁶²⁷⁹⁸⁴¹ - 1
```


[User]
The Mertens function **M(x)** is the **count** of **square-free integers** up to **x** that have an **even number** of prime factors, **minus** the **count** of those that have an **odd number**.

It is an extension of the Möbius function. Given the Möbius function **μ(n)**, the Mertens function **M(x)** is the sum of the Möbius numbers from **n == 1** through **n == x**.

Task

:   * Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer **x**.

:   * 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.)

:   * Use that routine to find and display here, on this page, the number of times the Mertens function sequence **is equal to zero** in the range **M(1)** through **M(1000)**.

:   * Use that routine to find and display here, on this page, the number of times the Mertens function sequence **crosses zero** in the range **M(1)** through **M(1000)**. (Crossing defined as this term equal to zero but preceding term **not**.)

See also
:   * Wikipedia: Mertens function
    * Wikipedia: Möbius function
    * OEIS: A002321 - Mertens's function
    * OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
    * Numberphile - Mertens Conjecture
    * Stackexchange: compute the mertens function

*This is not code golf.   The stackexchange link is provided as an algorithm reference, not as a guide.*

Related tasks
:   * Möbius function

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

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

```
use Prime::Factor;

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

my @mertens = lazy [\+] flat '', 1, (2..*).hyper.map: -> \n { μ(n) };

put "Mertens sequence - First 199 terms:\n",
    @mertens[^200]».fmt('%3s').batch(20).join("\n"),
    "\n\nEquals zero ", +@mertens[1..1000].grep( !* ),
    ' times between 1 and 1000', "\n\nCrosses zero ",
    +@mertens[1..1000].kv.grep( {!$^v and @mertens[$^k]} ),
    " times between 1 and 1000\n\nFirst Mertens equal to:";

for 10, 20, 30 … 100 -> $threshold {
    printf "%4d: M(%d)\n", -$threshold, @mertens.first: * == -$threshold, :k;
    printf "%4d: M(%d)\n",  $threshold, @mertens.first: * ==  $threshold, :k;
}

```

Output:

```
Mertens sequence - First 199 terms:
      1   0  -1  -1  -2  -1  -2  -2  -2  -1  -2  -2  -3  -2  -1  -1  -2  -2  -3
 -3  -2  -1  -2  -2  -2  -1  -1  -1  -2  -3  -4  -4  -3  -2  -1  -1  -2  -1   0
  0  -1  -2  -3  -3  -3  -2  -3  -3  -3  -3  -2  -2  -3  -3  -2  -2  -1   0  -1
 -1  -2  -1  -1  -1   0  -1  -2  -2  -1  -2  -3  -3  -4  -3  -3  -3  -2  -3  -4
 -4  -4  -3  -4  -4  -3  -2  -1  -1  -2  -2  -1  -1   0   1   2   2   1   1   1
  1   0  -1  -2  -2  -3  -2  -3  -3  -4  -5  -4  -4  -5  -6  -5  -5  -5  -4  -3
 -3  -3  -2  -1  -1  -1  -1  -2  -2  -1  -2  -3  -3  -2  -1  -1  -1  -2  -3  -4
 -4  -3  -2  -1  -1   0   1   1   1   0   0  -1  -1  -1  -2  -1  -1  -2  -1   0
  0   1   1   0   0  -1   0  -1  -1  -1  -2  -2  -2  -3  -4  -4  -4  -3  -2  -3
 -3  -4  -5  -4  -4  -3  -4  -3  -3  -3  -4  -5  -5  -6  -5  -6  -6  -7  -7  -8

Equals zero 92 times between 1 and 1000

Crosses zero 59 times between 1 and 1000

First Mertens equal to:
 -10: M(659)
  10: M(1393)
 -20: M(2791)
  20: M(3277)
 -30: M(9717)
  30: M(8503)
 -40: M(9831)
  40: M(11770)
 -50: M(24018)
  50: M(19119)
 -60: M(24105)
  60: M(31841)
 -70: M(24170)
  70: M(31962)
 -80: M(42789)
  80: M(48202)
 -90: M(59026)
  90: M(48405)
-100: M(59426)
 100: M(114717)
```


[User]
Many people have heard of the **Golden ratio**, phi (**φ**). Phi is just one of a series
of related ratios that are referred to as the "**Metallic ratios**".

The **Golden ratio** was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The **Silver ratio** was was
also known to the early Greeks, though was not named so until later as a nod to
the **Golden ratio** to which it is closely related. The series has been extended to
encompass all of the related ratios and was given the general name **Metallic ratios** (or *Metallic means*).
*Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".*

**Metallic ratios** are the real roots of the general form equation:

```
         x2 - bx - 1 = 0

```

where the integer **b** determines which specific one it is.

Using the quadratic equation:

```
         ( -b ± √(b2 - 4ac) ) / 2a = x

```

Substitute in (from the top equation) **1** for **a**, **-1** for **c**, and recognising that -b is negated we get:

```
         ( b ± √(b2 + 4) ) ) / 2 = x

```

We only want the real root:

```
         ( b + √(b2 + 4) ) ) / 2 = x

```

When we set **b** to **1**, we get an irrational number: the **Golden ratio**.

```
         ( 1 + √(12 + 4) ) / 2  =  (1 + √5) / 2 = ~1.618033989...

```

With **b** set to **2**, we get a different irrational number: the **Silver ratio**.

```
         ( 2 + √(22 + 4) ) / 2  =  (2 + √8) / 2 = ~2.414213562...

```

When the ratio **b** is **3**, it is commonly referred to as the **Bronze** ratio, **4** and **5**
are sometimes called the **Copper** and **Nickel** ratios, though they aren't as
standard. After that there isn't really any attempt at standardized names. They
are given names here on this page, but consider the names fanciful rather than
canonical.

Note that technically, **b** can be **0** for a "smaller" ratio than the **Golden ratio**.
We will refer to it here as the **Platinum ratio**, though it is kind-of a
degenerate case.

**Metallic ratios** where **b** > **0** are also defined by the irrational continued fractions:

```
         [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...]

```

So, The first ten **Metallic ratios** are:

:   :   :   :   :   :   Metallic ratios

                        | Name | **b** | Equation | Value | Continued fraction | OEIS link |
                        | --- | --- | --- | --- | --- | --- |
                        | Platinum | 0 | (0 + √4) / 2 | 1 | - | - |
                        | Golden | 1 | (1 + √5) / 2 | 1.618033988749895... | [1;1,1,1,1,1,1,1,1,1,1...] | OEIS:A001622 |
                        | Silver | 2 | (2 + √8) / 2 | 2.414213562373095... | [2;2,2,2,2,2,2,2,2,2,2...] | OEIS:A014176 |
                        | Bronze | 3 | (3 + √13) / 2 | 3.302775637731995... | [3;3,3,3,3,3,3,3,3,3,3...] | OEIS:A098316 |
                        | Copper | 4 | (4 + √20) / 2 | 4.23606797749979... | [4;4,4,4,4,4,4,4,4,4,4...] | OEIS:A098317 |
                        | Nickel | 5 | (5 + √29) / 2 | 5.192582403567252... | [5;5,5,5,5,5,5,5,5,5,5...] | OEIS:A098318 |
                        | Aluminum | 6 | (6 + √40) / 2 | 6.16227766016838... | [6;6,6,6,6,6,6,6,6,6,6...] | OEIS:A176398 |
                        | Iron | 7 | (7 + √53) / 2 | 7.140054944640259... | [7;7,7,7,7,7,7,7,7,7,7...] | OEIS:A176439 |
                        | Tin | 8 | (8 + √68) / 2 | 8.123105625617661... | [8;8,8,8,8,8,8,8,8,8,8...] | OEIS:A176458 |
                        | Lead | 9 | (9 + √85) / 2 | 9.109772228646444... | [9;9,9,9,9,9,9,9,9,9,9...] | OEIS:A176522 |

---

There are other ways to find the **Metallic ratios**; one, (the focus of this task)
is through **successive approximations of Lucas sequences**.

A traditional **Lucas sequence** is of the form:

```
   xn = P * xn-1 - Q * xn-2

```

and starts with the first 2 values **0, 1**.

For our purposes in this task, to find the metallic ratios we'll use the form:

```
   xn = b * xn-1 + xn-2

```

( **P** is set to **b** and **Q** is set to **-1**. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms **1, 1**. The initial starting value has very little effect on the final ratio or convergence rate. *Perhaps it would be more accurate to call it a Lucas-like sequence.*

At any rate, when **b = 1** we get:

```
   xn = xn-1 + xn-2

```

```
   1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...

```

more commonly known as the Fibonacci sequence.

When **b = 2**:

```
   xn = 2 * xn-1 + xn-2

```

```
   1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...

```

And so on.

To find the ratio by successive approximations, divide the (**n+1**)th term by the
**n**th. As **n** grows larger, the ratio will approach the **b** metallic ratio.

For **b = 1** (Fibonacci sequence):

```
   1/1   = 1
   2/1   = 2
   3/2   = 1.5
   5/3   = 1.666667
   8/5   = 1.6
   13/8  = 1.625
   21/13 = 1.615385
   34/21 = 1.619048
   55/34 = 1.617647
   89/55 = 1.618182
   etc.

```

It converges, but pretty slowly. In fact, the **Golden ratio** has the slowest
possible convergence for any irrational number.

Task

For each of the first **10 Metallic ratios**; **b** = **0** through **9**:

* Generate the corresponding "Lucas" sequence.
* Show here, on this page, at least the first **15** elements of the "Lucas" sequence.
* Using successive approximations, calculate the value of the ratio accurate to **32** decimal places.
* Show the **value** of the **approximation** at the required accuracy.
* Show the **value** of **n** when the approximation reaches the required accuracy (How many iterations did it take?).

Optional, stretch goal - Show the **value** and number of iterations **n**, to approximate the **Golden ratio** to **256** decimal places.

You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.

See also

* Wikipedia: Metallic mean
* Wikipedia: Lucas sequence

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.07.1

Note: Arrays, Lists and Sequences are zero indexed in Raku.

```
use Rat::Precise;
use Lingua::EN::Numbers;

sub lucas ($b) { 1, 1, * + $b * * … * }

sub metallic ($seq, $places = 32) {
    my $n = 0;
    my $last = 0;
    loop {
        my $approx = FatRat.new($seq[$n + 1], $seq[$n]);
        my $this = $approx.precise($places, :z);
        last if $this eq $last;
        $last = $this;
        $n++;
    }
    $last, $n
}

sub display ($value, $n) {
    "Approximated value:", $value, "Reached after {$n} iterations: " ~
    "{ordinal-digit $n}/{ordinal-digit $n - 1} element."
}

for <Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead>.kv
  -> \b, $name {
    my $lucas = lucas b;
    print "\nLucas sequence for $name ratio; where b = {b}:\nFirst 15 elements: ";
    say join ', ', $lucas[^15];
    say join ' ', display |metallic($lucas);
}

# Stretch goal
say join "\n", "\nGolden ratio to 256 decimal places:", display |metallic lucas(1), 256;

```

Output:

```
Lucas sequence for Platinum ratio; where b = 0:
First 15 elements: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
Approximated value: 1.00000000000000000000000000000000 Reached after 1 iterations: 1st/0th element.

Lucas sequence for Golden ratio; where b = 1:
First 15 elements: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
Approximated value: 1.61803398874989484820458683436564 Reached after 78 iterations: 78th/77th element.

Lucas sequence for Silver ratio; where b = 2:
First 15 elements: 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393, 3363, 8119, 19601, 47321, 114243
Approximated value: 2.41421356237309504880168872420970 Reached after 44 iterations: 44th/43rd element.

Lucas sequence for Bronze ratio; where b = 3:
First 15 elements: 1, 1, 4, 13, 43, 142, 469, 1549, 5116, 16897, 55807, 184318, 608761, 2010601, 6640564
Approximated value: 3.30277563773199464655961063373525 Reached after 34 iterations: 34th/33rd element.

Lucas sequence for Copper ratio; where b = 4:
First 15 elements: 1, 1, 5, 21, 89, 377, 1597, 6765, 28657, 121393, 514229, 2178309, 9227465, 39088169, 165580141
Approximated value: 4.23606797749978969640917366873128 Reached after 28 iterations: 28th/27th element.

Lucas sequence for Nickel ratio; where b = 5:
First 15 elements: 1, 1, 6, 31, 161, 836, 4341, 22541, 117046, 607771, 3155901, 16387276, 85092281, 441848681, 2294335686
Approximated value: 5.19258240356725201562535524577016 Reached after 25 iterations: 25th/24th element.

Lucas sequence for Aluminum ratio; where b = 6:
First 15 elements: 1, 1, 7, 43, 265, 1633, 10063, 62011, 382129, 2354785, 14510839, 89419819, 551029753, 3395598337, 20924619775
Approximated value: 6.16227766016837933199889354443272 Reached after 23 iterations: 23rd/22nd element.

Lucas sequence for Iron ratio; where b = 7:
First 15 elements: 1, 1, 8, 57, 407, 2906, 20749, 148149, 1057792, 7552693, 53926643, 385039194, 2749201001, 19629446201, 140155324408
Approximated value: 7.14005494464025913554865124576352 Reached after 22 iterations: 22nd/21st element.

Lucas sequence for Tin ratio; where b = 8:
First 15 elements: 1, 1, 9, 73, 593, 4817, 39129, 317849, 2581921, 20973217, 170367657, 1383914473, 11241683441, 91317382001, 741780739449
Approximated value: 8.12310562561766054982140985597408 Reached after 20 iterations: 20th/19th element.

Lucas sequence for Lead ratio; where b = 9:
First 15 elements: 1, 1, 10, 91, 829, 7552, 68797, 626725, 5709322, 52010623, 473804929, 4316254984, 39320099785, 358197153049, 3263094477226
Approximated value: 9.10977222864644365500113714088140 Reached after 20 iterations: 20th/19th element.

Golden ratio to 256 decimal places:
Approximated value:
1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374847540880753868917521266338622235369317931800607667263544333890865959395829056383226613199282902678806752087668925017116962070322210432162695486262963136144
Reached after 615 iterations: 615th/614th element.
```


[User]
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.

For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor `eval` count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.

[Assistant]
(formerly Perl 6)

Raku makes it very easy to do metaprogramming. It is a basic goal of the language.

It is trivial to add a new operator. Most Raku operators are written as normal multiple-dispatch functions in the setting (known as a "prelude" in other languages, but in Raku the setting is a lexical scope notionally surrounding your compilation unit).

There is no a built in factorial operator Raku. It was purposely left out to use as a demonstration of how easy it is to add it. :-)

```
sub postfix:<!> { [*] 1..$^n }
say 5!;  # prints 120

```

You may augment a base class with a new method, as long as you declare that you are going to cheat.

Here we add a new method to do natural sorting to the base class Any. (List and Array are both subclasses of Any)

```
use MONKEY-TYPING; # Needed to do runtime augmentation of a base class.

augment class List {
    method nsort { self.list.sort: {$^a.lc.subst(/(\d+)/, -> $/ {0 ~ $0.chars.chr ~ $0 }, :g) ~ "\x0" ~ $^a} }
};

say ~<a201st a32nd a3rd a144th a17th a2 a95>.nsort;
say ~<a201st a32nd a3rd a144th a17th a2 a95>.sort;

```

Prints

```
a2 a3rd a17th a32nd a95 a144th a201st
a144th a17th a2 a201st a32nd a3rd a95
```

Grammar mixins work in Raku because grammar rules are just methods in grammar classes, and Raku automatically writes a JIT lexer for you whenever you derive a new language. This functionality already works internally in the standard parser—what is not yet implemented is the augment slang hook to allow user code to do this mixin. Raku itself is already parsed using such grammar mixins to provide extensible quoting and regex syntax. For example, every time you pick your own quote characters, you're actually deriving a new Raku dialect that supports those start and stop characters. Likewise any switches to impose single or double-quote semantics, or heredoc semantics, is merely a grammar mixin on the basic Q language.

```
say "Foo = $foo\n";  # normal double quotes
say Q:qq 【Foo = $foo\n】; # a more explicit derivation, new quotes

```


[User] The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are *acquire*, *release*, and *count*. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.

[Assistant]
(formerly Perl 6)
Uses a buffered channel to hand out a limited number of tickets.

```
class Semaphore {
    has $.tickets = Channel.new;
    method new ($max) {
        my $s = self.bless;
        $s.tickets.send(True) xx $max;
        $s;
    }
    method acquire { $.tickets.receive }
    method release { $.tickets.send(True) }
}

sub MAIN ($units = 5, $max = 2) {
    my $sem = Semaphore.new($max);

    my @units = do for ^$units -> $u {
        start {
            $sem.acquire; say "unit $u acquired";
            sleep 2;
            $sem.release; say "unit $u released";
        }
    }
    await @units;
}

```

Output:

```
unit 0 acquired
unit 1 acquired
unit 0 released
unit 1 released
unit 3 acquired
unit 2 acquired
unit 3 released
unit 2 released
unit 4 acquired
unit 4 released
```


[User]
The task is to implement a   metronome.

The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.

For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.

However, the playing of the sounds should not interfere with the timing of the metronome.

The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.

If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.

[Assistant]
(formerly Perl 6)

This code only uses textual output, but any noise-generating commands may be substituted; as long as they are executed synchronously, and do not run longer than the specified duration, the timing loop will compensate, since the sequence operator is determining a list of absolute times for each sleep to target.

```
sub MAIN ($beats-per-minute = 72, $beats-per-bar = 4) {
    my $duration = 60 / $beats-per-minute;
    my $base-time = now + $duration;
    my $i;

    for $base-time, $base-time + $duration ... * -> $next-time {
        if $i++ %% $beats-per-bar {
            print "\nTICK";
        }
        else {
            print  " tick";
        }
        sleep $next-time - now;
    }
}

```

Sample run:

```
$ metronome 120 6

TICK tick tick tick tick tick
TICK tick tick tick tick tick
TICK tick tick tick tick tick
TICK tick tick tick tick tick
TICK tick tick^C

```


[User]
The Mian–Chowla sequence is an integer sequence defined recursively.

Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences.

The sequence starts with:

:   :   a1 = 1

then for n > 1, an is the smallest positive integer such that every pairwise sum

:   :   ai + aj

is distinct, for all i and j less than or equal to n.

The Task

:   * Find and display, here, on this page the first 30 terms of the Mian–Chowla sequence.
    * Find and display, here, on this page the 91st through 100th terms of the Mian–Chowla sequence.

Demonstrating working through the first few terms longhand:

:   :   a1 = 1

:   :   1 + 1 = 2

Speculatively try a2 = 2

:   :   1 + 1 = 2
    :   1 + 2 = 3
    :   2 + 2 = 4

There are no repeated sums so **2** is the next number in the sequence.

Speculatively try a3 = 3

:   :   1 + 1 = 2
    :   1 + 2 = 3
    :   1 + 3 = 4
    :   2 + 2 = 4
    :   2 + 3 = 5
    :   3 + 3 = 6

Sum of **4** is repeated so **3** is rejected.

Speculatively try a3 = 4

:   :   1 + 1 = 2
    :   1 + 2 = 3
    :   1 + 4 = 5
    :   2 + 2 = 4
    :   2 + 4 = 6
    :   4 + 4 = 8

There are no repeated sums so **4** is the next number in the sequence.

And so on...

See also

:   * OEIS:A005282 Mian-Chowla sequence

[Assistant]
(formerly Perl 6)

```
my @mian-chowla = 1, |(2..Inf).map: -> $test {
    state $index = 1;
    state %sums  = 2 => 1;
    my $next;
    my %these;
    @mian-chowla[^$index].map: { ++$next and last if %sums{$_ + $test}:exists; ++%these{$_ + $test} };
    next if $next;
    ++%sums{$test + $test};
    %sums.push: %these;
    ++$index;
    $test
};

put "First 30 terms in the Mian–Chowla sequence:\n", @mian-chowla[^30];
put "\nTerms 91 through 100:\n", @mian-chowla[90..99];

```

Output:

```
First 30 terms in the Mian–Chowla sequence:
1 2 4 8 13 21 31 45 66 81 97 123 148 182 204 252 290 361 401 475 565 593 662 775 822 916 970 1016 1159 1312

Terms 91 through 100:
22526 23291 23564 23881 24596 24768 25631 26037 26255 27219
```


[User]
Task

Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.

Note: The order of the middle digits should be preserved.

Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:

```
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0

```

Show your output on this page.

[Assistant]
(formerly Perl 6)

```
sub middle-three($n) {
    given $n.abs {
        when .chars < 3  { "$n is too short" }
        when .chars %% 2 { "$n has an even number of digits" }
        default          { "The three middle digits of $n are: ", .substr: (.chars - 3)/2, 3 }
    }
}

say middle-three($_) for <
    123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345
    1 2 -1 -10 2002 -2002 0
>;

```

Output:

```
The three middle digits of 123 are:  123
The three middle digits of 12345 are:  234
The three middle digits of 1234567 are:  345
The three middle digits of 987654321 are:  654
The three middle digits of 10001 are:  000
The three middle digits of -10001 are:  000
The three middle digits of -123 are:  123
The three middle digits of -100 are:  100
The three middle digits of 100 are:  100
The three middle digits of -12345 are:  234
1 is too short
2 is too short
-1 is too short
-10 is too short
2002 has an even number of digits
-2002 has an even number of digits
0 is too short
```

It is also possible to write a regular expression with a code assertion:

```
for [\~] ^10 { say "$_ => $()" if m/^^(\d+) <(\d**3)> (\d+) $$ <?{ $0.chars == $1.chars}> / }

```

Output:

```
01234 => 123
0123456 => 234
012345678 => 345
```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |

The Miller–Rabin primality test or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not.

The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.

The pseudocode, from Wikipedia is:

```
Input: n > 2, an odd integer to be tested for primality;
       k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
   pick a randomly in the range [2, n − 1]
   x ← ad mod n
   if x = 1 or x = n − 1 then do next LOOP
   repeat s − 1 times:
      x ← x2 mod n
      if x = 1 then return composite
      if x = n − 1 then do next LOOP
   return composite
return probably prime

```

* The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but **not** mandatory.
* Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015-09-22

```
# the expmod-function from: http://rosettacode.org/wiki/Modular_exponentiation
sub expmod(Int $a is copy, Int $b is copy, $n) {
	my $c = 1;
	repeat while $b div= 2 {
		($c *= $a) %= $n if $b % 2;
		($a *= $a) %= $n;
	}
	$c;
}

subset PrimeCandidate of Int where { $_ > 2 and $_ % 2 };

my Bool multi sub is_prime(Int $n, Int $k)            { return False; }
my Bool multi sub is_prime(2, Int $k)                 { return True; }
my Bool multi sub is_prime(PrimeCandidate $n, Int $k) {
	my Int $d = $n - 1;
	my Int $s = 0;

	while $d %% 2 {
		$d div= 2;
		$s++;
	}

	for (2 ..^ $n).pick($k) -> $a {
		my $x = expmod($a, $d, $n);

		# one could just write "next if $x == 1 | $n - 1"
		# but this takes much more time in current rakudo/nom
		next if $x == 1 or $x == $n - 1;

		for 1 ..^ $s {
			$x = $x ** 2 mod $n;
			return False if $x == 1;
			last if $x == $n - 1;
		}
		return False if $x !== $n - 1;
	}

	return True;
}

say (1..1000).grep({ is_prime($_, 10) }).join(", ");

```


[User]
Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos.

The task is to simulate the trick in a way that mimics the steps shown in the video.

1. Cards.

1. Create a common deck of cards of 52 cards   (which are half red, half black).
2. Give the pack a good shuffle.

2. Deal from the shuffled deck, you'll be creating three piles.

1. Assemble the cards face down.
   1. Turn up the   *top card*   and hold it in your hand.
      1. if the card is   black,   then add the   *next*   card (unseen) to the "black" pile.
      2. If the card is     red,    then add the   *next*   card (unseen) to the   "red"  pile.
   2. Add the   *top card*   that you're holding to the **discard** pile.   (You might optionally show these discarded cards to get an idea of the randomness).
2. Repeat the above for the rest of the shuffled deck.

3. Choose a random number   (call it **X**)   that will be used to swap cards from the "red" and "black" piles.

1. Randomly choose   **X**   cards from the   "red"  pile (unseen), let's call this the   "red"  bunch.
2. Randomly choose   **X**   cards from the "black" pile (unseen), let's call this the "black" bunch.
3. Put the     "red"    bunch into the   "black" pile.
4. Put the   "black"   bunch into the     "red"  pile.
5. (The above two steps complete the swap of   **X**   cards of the "red" and "black" piles.
    (Without knowing what those cards are --- they could be red or black, nobody knows).

4. Order from randomness?

1. Verify (or not) the mathematician's assertion that:

```
     The number of black cards in the "black" pile equals the number of red cards in the "red" pile.

```

(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)

Show output on this page.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.08

```
# Generate a shuffled deck
my @deck = shuffle;
put 'Shuffled deck:          ', @deck;

my (@discard, @red, @black);
# Deal cards following task description
deal(@deck, @discard, @red, @black);

put 'Discard pile:           ', @discard;
put '"Red"   pile:           ', @red;
put '"Black" pile:           ', @black;

# swap the same random number of random
# cards between the red and black piles
my $amount = ^(+@red min +@black) .roll;
put 'Number of cards to swap: ', $amount;
swap(@red, @black, $amount);

put 'Red pile after swaps:   ', @red;
put 'Black pile after swaps: ', @black;

say 'Number of Red   cards in the Red   pile: ', +@red.grep('R');
say 'Number of Black cards in the Black pile: ', +@black.grep('B');

sub shuffle { (flat 'R' xx 26, 'B' xx 26).pick: * }

sub deal (@deck, @d, @r, @b) {
    while @deck.elems {
        my $top = @deck.shift;
        if $top eq 'R' {
            @r.push: @deck.shift;
        }
        else {
            @b.push: @deck.shift;
        }
        @d.push: $top;
    }
}

sub swap (@r, @b, $a) {
    my @ri  = ^@r .pick($a);
    my @bi  = ^@b .pick($a);
    my @rs  = @r[@ri];
    my @bs  = @b[@bi];
    @r[@ri] = @bs;
    @b[@bi] = @rs;
}

```

Sample output:

```
Shuffled deck:          B B B R B R R R B B R R R B R B R B R R R B R B B R R B B R R B R B R R R R B R R B B B B B B R R B B B
Discard pile:           B B B R B R R R R R R R B R B R R R R B R B B B R B
"Red"   pile:           R R B B B R B B B B B R R B B
"Black" pile:           B R R B R R R B B R B
Number of cards to swap: 6
Red pile after swaps:   R R B B R R R R B B B R B B B
Black pile after swaps: B R B R R B B B B R B
Number of Red   cards in the Red   pile: 7
Number of Black cards in the Black pile: 7
```


[User]
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found.

Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid and the second vertical. The top left of the grid is position 1,1; the bottom right is at n,m.

* The total number of mines to be found is shown at the beginning of the game.
* Each mine occupies a single grid point, and its position is initially unknown to the player
* The grid is shown as a rectangle of characters between moves.
* You are initially shown all grids as obscured, by a single dot '.'
* You may mark what you think is the position of a mine which will show as a '?'
* You can mark what you think is free space by entering its coordinates.

:   * If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine.

    :   * Points marked as a mine show as a '?'.
        * Other free points show as an integer count of the number of adjacent true mines in its immediate neighborhood, or as a single space ' ' if the free point is not adjacent to any true mines.

* Of course you lose if you try to clear space that has a hidden mine.
* You win when you have correctly identified all mines.

The Task is to **create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly** and so checking inputs for correct form may be omitted.
You may also omit all GUI parts of the task and work using text input and output.

Note: Changes may be made to the method of clearing mines to more closely follow a particular implementation of the game so long as such differences and the implementation that they more accurately follow are described.

C.F: wp:Minesweeper (computer game)

[Assistant]
(formerly Perl 6)

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

```
enum Tile-Type <Empty Mine>;

class Tile {
    has Tile-Type $.type;
    has $.face is rw;
    method Str { with $!face { ~$!face } else { '.' } }
}

class Field {
    has @.grid;
    has Int $.width;
    has Int $.height;
    has Int $.mine-spots;
    has Int $.empty-spots;

    method new (Int $height, Int $width, Rat $mines-ratio=0.1) {

        my $mine-spots = round $width*$height*$mines-ratio;
        my $empty-spots = $width*$height - $mine-spots;

        my @grid;
        for ^$height X ^$width -> ($y, $x) {
            @grid[$y][$x] = Tile.new(type => Empty);
        }
        for (^$height).pick($mine-spots) Z (^$width).pick($mine-spots) -> ($y, $x) {
            @grid[$y][$x] = Tile.new( type => Mine);
        }
        self.bless(:$height, :$width, :@grid, :$mine-spots, :$empty-spots);
    }

    method open( $y, $x) {
        return if @!grid[$y][$x].face.defined;

        self.end-game("KaBoom") if @!grid[$y][$x].type ~~ Mine;

        my @neighbors = gather do
	    take [$y+.[0],$x+.[1]]
		if 0 <= $y + .[0] < $!height && 0 <= $x + .[1] < $!width
		 for [-1,-1],[+0,-1],[+1,-1],
		     [-1,+0],        [+1,+0],
		     [-1,+1],[+0,+1],[+1,+1];

        my $mines = +@neighbors.grep: { @!grid[.[0]][.[1]].type ~~ Mine };

        $!empty-spots--;
        @!grid[$y][$x].face = $mines || ' ';

        if $mines == 0 {
            self.open(.[0], .[1]) for @neighbors;
        }
        self.end-game("You won") if $!empty-spots == 0;
    }

    method end-game(Str $msg ) {
        for ^$!height X ^$!width -> ($y, $x) {
            @!grid[$y][$x].face = '*' if @!grid[$y][$x].type ~~ Mine
        }
        die $msg;
    }

    method mark ( $y, $x) {
        if !@!grid[$y][$x].face.defined {
            @!grid[$y][$x].face = "⚐";
            $!mine-spots-- if @!grid[$y][$x].type ~~ Mine;
        }
	elsif !@!grid[$y][$x].face eq "⚐" {
            undefine @!grid[$y][$x].face;
            $!mine-spots++ if @!grid[$y][$x].type ~~ Mine;
        }
        self.end-game("You won") if $!mine-spots == 0;
    }

    constant @digs = |('a'..'z') xx *;

    method Str {
        [~] flat '  ', @digs[^$!width], "\n",
	         ' ┌', '─' xx $!width, "┐\n",
	    join '', do for ^$!height -> $y {
	      $y, '│', @!grid[$y][*],   "│\n"; },
	         ' └', '─' xx $!width, '┘';
	}

    method valid ($y, $x) {
        0 <= $y < $!height && 0 <= $x < $!width
    }
}

sub a2n($a) { $a.ord > 64 ?? $a.ord % 32 - 1 !! +$a }

my $f = Field.new(6,10);

loop {
    say ~$f;
    my @w = prompt("[open loc|mark loc|loc]: ").words;
    last unless @w;
    unshift @w, 'open' if @w < 2;
    my ($x,$y) = $0, $1 if @w[1] ~~ /(<alpha>)(<digit>)|$1=<digit>$0=<alpha>/;
    $x = a2n($x);
    given @w[0] {
	when !$f.valid($y,$x) { say "invalid coordinates" }
	when /^o/ { $f.open($y,$x)   }
	when /^m/ { $f.mark($y,$x)   }
	default     { say "invalid cmd" }
    }
    CATCH {
	say "$_: end of game.";
	last;
    }
}

say ~$f;

```


[User]
Given:

* A starting, positive integer (greater than one), N.
* A selection of possible integer perfect divisors, D.
* And a selection of possible subtractors, S.

The goal is find the minimum number of steps necessary to reduce N down to one.

At any step, the number may be:

* Divided by any member of D if it is perfectly divided by D, (remainder zero).
* OR have one of S subtracted from it, if N is greater than the member of S.

There may be many ways to reduce the initial N down to 1. Your program needs to:

* Find the *minimum* number of *steps* to reach 1.
* Show **one** way of getting fron N to 1 in those minimum steps.

Examples

No divisors, D. a single subtractor of 1.

:   Obviousely N will take N-1 subtractions of 1 to reach 1

Single divisor of 2; single subtractor of 1:

:   N = 7 Takes 4 steps N -1=> 6, /2=> 3, -1=> 2, /2=> 1
:   N = 23 Takes 7 steps N -1=>22, /2=>11, -1=>10, /2=> 5, -1=> 4, /2=> 2, /2=> 1

Divisors 2 and 3; subtractor 1:

:   N = 11 Takes 4 steps N -1=>10, -1=> 9, /3=> 3, /3=> 1

Task

Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 1:

:   1. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:   2. Show a count of, and the numbers that: have the maximum minimal\_steps\_to\_1, in the range 1 to 2,000.

Using the possible divisors D, of 2 and 3; together with a possible subtractor S, of 2:

:   3. Show the number of steps and possible way of diminishing the numbers 1 to 10 down to 1.
:   4. Show a count of, and the numbers that: have the maximum minimal\_steps\_to\_1, in the range 1 to 2,000.

Optional stretch goal
:   2a, and 4a: As in 2 and 4 above, but for N in the range 1 to 20\_000

Reference

* Learn Dynamic Programming (Memoization & Tabulation) Video of similar task.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

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

for [2,3], 1, 2000,
    [2,3], 1, 50000,
    [2,3], 2, 2000,
    [2,3], 2, 50000
  -> @div, $sub, $limit {
    my %min = 1 => {:op(''), :v(1), :s(0)};
    (2..$limit).map( -> $n {
       my @ops;
       @ops.push: ($n / $_, "/$_") if $n %% $_ for @div;
       @ops.push: ($n - $sub, "-$sub") if $n > $sub;
       my $op = @ops.min( {%min{.[0]}<s>} );
       %min{$n} = {:op($op[1]), :v($op[0]), :s(1 + %min{$op[0]}<s>)};
    });

    my $max = %min.max( {.value<s>} ).value<s>;
    my @max = %min.grep( {.value.<s> == $max} )».key.sort(+*);

    if $limit == 2000 {
        say "\nDivisors: {@div.perl}, subtract: $sub";
        steps(1..10);
    }
    say "\nUp to {comma $limit} found {+@max} number{+@max == 1 ?? '' !! 's'} " ~
        "that require{+@max == 1 ?? 's' !! ''} at least $max steps.";
    steps(@max);

    sub steps (*@list) {
        for @list -> $m {
            my @op;
            my $n = $m;
            while %min{$n}<s> {
                @op.push: "{%min{$n}<op>}=>{%min{$n}<v>}";
                $n = %min{$n}<v>;
            }
            say "($m) {%min{$m}<s>} steps: ", @op.join(', ');
        }
    }
}

```

Output:

```
Divisors: [2, 3], subtract: 1
(1) 0 steps:
(2) 1 steps: /2=>1
(3) 1 steps: /3=>1
(4) 2 steps: /2=>2, /2=>1
(5) 3 steps: -1=>4, /2=>2, /2=>1
(6) 2 steps: /2=>3, /3=>1
(7) 3 steps: -1=>6, /2=>3, /3=>1
(8) 3 steps: /2=>4, /2=>2, /2=>1
(9) 2 steps: /3=>3, /3=>1
(10) 3 steps: -1=>9, /3=>3, /3=>1

Up to 2,000 found 16 numbers that require at least 14 steps.
(863) 14 steps: -1=>862, -1=>861, /3=>287, -1=>286, -1=>285, /3=>95, -1=>94, -1=>93, /3=>31, -1=>30, /3=>10, -1=>9, /3=>3, /3=>1
(1079) 14 steps: -1=>1078, /2=>539, -1=>538, /2=>269, -1=>268, /2=>134, /2=>67, -1=>66, /2=>33, /3=>11, -1=>10, -1=>9, /3=>3, /3=>1
(1295) 14 steps: -1=>1294, /2=>647, -1=>646, /2=>323, -1=>322, /2=>161, -1=>160, /2=>80, /2=>40, /2=>20, /2=>10, -1=>9, /3=>3, /3=>1
(1439) 14 steps: -1=>1438, -1=>1437, /3=>479, -1=>478, -1=>477, /3=>159, /3=>53, -1=>52, /2=>26, /2=>13, -1=>12, /2=>6, /2=>3, /3=>1
(1511) 14 steps: -1=>1510, /2=>755, -1=>754, /2=>377, -1=>376, /2=>188, /2=>94, -1=>93, /3=>31, -1=>30, /3=>10, -1=>9, /3=>3, /3=>1
(1583) 14 steps: -1=>1582, /2=>791, -1=>790, -1=>789, /3=>263, -1=>262, -1=>261, /3=>87, /3=>29, -1=>28, -1=>27, /3=>9, /3=>3, /3=>1
(1607) 14 steps: -1=>1606, /2=>803, -1=>802, /2=>401, -1=>400, /2=>200, /2=>100, /2=>50, /2=>25, -1=>24, /2=>12, /2=>6, /2=>3, /3=>1
(1619) 14 steps: -1=>1618, /2=>809, -1=>808, /2=>404, /2=>202, /2=>101, -1=>100, /2=>50, /2=>25, -1=>24, /2=>12, /2=>6, /2=>3, /3=>1
(1691) 14 steps: -1=>1690, /2=>845, -1=>844, -1=>843, /3=>281, -1=>280, -1=>279, /3=>93, /3=>31, -1=>30, /3=>10, -1=>9, /3=>3, /3=>1
(1727) 14 steps: -1=>1726, -1=>1725, /3=>575, -1=>574, -1=>573, /3=>191, -1=>190, -1=>189, /3=>63, /3=>21, /3=>7, -1=>6, /2=>3, /3=>1
(1823) 14 steps: -1=>1822, /2=>911, -1=>910, -1=>909, /3=>303, /3=>101, -1=>100, /2=>50, /2=>25, -1=>24, /2=>12, /2=>6, /2=>3, /3=>1
(1871) 14 steps: -1=>1870, -1=>1869, /3=>623, -1=>622, -1=>621, /3=>207, /3=>69, /3=>23, -1=>22, /2=>11, -1=>10, -1=>9, /3=>3, /3=>1
(1895) 14 steps: -1=>1894, /2=>947, -1=>946, /2=>473, -1=>472, /2=>236, /2=>118, -1=>117, /3=>39, /3=>13, -1=>12, /2=>6, /2=>3, /3=>1
(1907) 14 steps: -1=>1906, /2=>953, -1=>952, /2=>476, /2=>238, /2=>119, -1=>118, -1=>117, /3=>39, /3=>13, -1=>12, /2=>6, /2=>3, /3=>1
(1919) 14 steps: -1=>1918, -1=>1917, /3=>639, /3=>213, /3=>71, -1=>70, /2=>35, -1=>34, /2=>17, -1=>16, /2=>8, /2=>4, /2=>2, /2=>1
(1943) 14 steps: -1=>1942, /2=>971, -1=>970, /2=>485, -1=>484, /2=>242, /2=>121, -1=>120, /2=>60, /2=>30, /3=>10, -1=>9, /3=>3, /3=>1

Up to 50,000 found 3 numbers that require at least 22 steps.
(25919) 22 steps: -1=>25918, /2=>12959, -1=>12958, /2=>6479, -1=>6478, /2=>3239, -1=>3238, /2=>1619, -1=>1618, /2=>809, -1=>808, /2=>404, /2=>202, /2=>101, -1=>100, /2=>50, /2=>25, -1=>24, /2=>12, /2=>6, /2=>3, /3=>1
(31103) 22 steps: -1=>31102, /2=>15551, -1=>15550, /2=>7775, -1=>7774, /2=>3887, -1=>3886, /2=>1943, -1=>1942, /2=>971, -1=>970, /2=>485, -1=>484, /2=>242, /2=>121, -1=>120, /2=>60, /2=>30, /3=>10, -1=>9, /3=>3, /3=>1
(38879) 22 steps: -1=>38878, /2=>19439, -1=>19438, /2=>9719, -1=>9718, /2=>4859, -1=>4858, /2=>2429, -1=>2428, /2=>1214, /2=>607, -1=>606, /2=>303, /3=>101, -1=>100, /2=>50, /2=>25, -1=>24, /2=>12, /2=>6, /2=>3, /3=>1

Divisors: [2, 3], subtract: 2
(1) 0 steps:
(2) 1 steps: /2=>1
(3) 1 steps: /3=>1
(4) 2 steps: /2=>2, /2=>1
(5) 2 steps: -2=>3, /3=>1
(6) 2 steps: /2=>3, /3=>1
(7) 3 steps: -2=>5, -2=>3, /3=>1
(8) 3 steps: /2=>4, /2=>2, /2=>1
(9) 2 steps: /3=>3, /3=>1
(10) 3 steps: /2=>5, -2=>3, /3=>1

Up to 2,000 found 1 number that requires at least 17 steps.
(1699) 17 steps: -2=>1697, -2=>1695, /3=>565, -2=>563, -2=>561, /3=>187, -2=>185, -2=>183, /3=>61, -2=>59, -2=>57, /3=>19, -2=>17, -2=>15, /3=>5, -2=>3, /3=>1

Up to 50,000 found 1 number that requires at least 26 steps.
(45925) 26 steps: -2=>45923, -2=>45921, /3=>15307, -2=>15305, -2=>15303, /3=>5101, -2=>5099, -2=>5097, /3=>1699, -2=>1697, -2=>1695, /3=>565, -2=>563, -2=>561, /3=>187, -2=>185, -2=>183, /3=>61, -2=>59, -2=>57, /3=>19, -2=>17, -2=>15, /3=>5, -2=>3, /3=>1
```


[User]
Generate the sequence **a(n)** when each element is the minimum integer multiple **m** such that the digit sum of **n** times **m** is equal to **n**.

Task

* Find the first 40 elements of the sequence.

Stretch

* Find the next 30 elements of the sequence.

See also

* OEIS:A131382 - Minimal number m such that Sum\_digits(n\*m)=n

[Assistant]
```
sub min-mult-dsum ($n) { (1..∞).first: (* × $n).comb.sum == $n }

say .fmt("%2d: ") ~ .&min-mult-dsum for flat 1..40, 41..70;

```

Output:

```
 1: 1
 2: 1
 3: 1
 4: 1
 5: 1
 6: 1
 7: 1
 8: 1
 9: 1
10: 19
11: 19
12: 4
13: 19
14: 19
15: 13
16: 28
17: 28
18: 11
19: 46
20: 199
21: 19
22: 109
23: 73
24: 37
25: 199
26: 73
27: 37
28: 271
29: 172
30: 1333
31: 289
32: 559
33: 1303
34: 847
35: 1657
36: 833
37: 1027
38: 1576
39: 1282
40: 17497
41: 4339
42: 2119
43: 2323
44: 10909
45: 11111
46: 12826
47: 14617
48: 14581
49: 16102
50: 199999
51: 17449
52: 38269
53: 56413
54: 37037
55: 1108909
56: 142498
57: 103507
58: 154981
59: 150661
60: 1333333
61: 163918
62: 322579
63: 315873
64: 937342
65: 1076923
66: 1030303
67: 880597
68: 1469116
69: 1157971
70: 12842857
```


[User]
Task

Find and show on this page the minimum number of cells after, before, above and below   **N×N**   squares,   where   **N = 10**.

[Assistant]
```
sub distance-to-edge (\N) {
   my $c = ceiling N / 2;
   my $f = floor   N / 2;
   my @ul = ^$c .map: -> $x { [ ^$c .map: { min($x, $_) } ] }
   @ul[$_].append: reverse @ul[$_; ^$f] for ^$c;
   @ul.push: [ reverse @ul[$_] ] for reverse ^$f;
   @ul
}

for 0, 1, 2, 6, 9, 23 {
    my @dte = .&distance-to-edge;
    my $max = chars max flat @dte».Slip;

    say "\n$_ x $_ distance to nearest edge:";
    .fmt("%{$max}d").say for @dte;
}

```

Output:

```
0 x 0 distance to nearest edge:

1 x 1 distance to nearest edge:
0

2 x 2 distance to nearest edge:
0 0
0 0

6 x 6 distance to nearest edge:
0 0 0 0 0 0
0 1 1 1 1 0
0 1 2 2 1 0
0 1 2 2 1 0
0 1 1 1 1 0
0 0 0 0 0 0

9 x 9 distance to nearest edge:
0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 0
0 1 2 2 2 2 2 1 0
0 1 2 3 3 3 2 1 0
0 1 2 3 4 3 2 1 0
0 1 2 3 3 3 2 1 0
0 1 2 2 2 2 2 1 0
0 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0

23 x 23 distance to nearest edge:
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 0  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  0
 0  1  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  1  0
 0  1  2  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  2  1  0
 0  1  2  3  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  3  2  1  0
 0  1  2  3  4  5  5  5  5  5  5  5  5  5  5  5  5  5  4  3  2  1  0
 0  1  2  3  4  5  6  6  6  6  6  6  6  6  6  6  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  7  7  7  7  7  7  7  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  8  8  8  8  8  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  9  9  9  9  9  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  9 10 10 10  9  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  9 10 11 10  9  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  9 10 10 10  9  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  9  9  9  9  9  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  8  8  8  8  8  8  8  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  7  7  7  7  7  7  7  7  7  6  5  4  3  2  1  0
 0  1  2  3  4  5  6  6  6  6  6  6  6  6  6  6  6  5  4  3  2  1  0
 0  1  2  3  4  5  5  5  5  5  5  5  5  5  5  5  5  5  4  3  2  1  0
 0  1  2  3  4  4  4  4  4  4  4  4  4  4  4  4  4  4  4  3  2  1  0
 0  1  2  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  2  1  0
 0  1  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  1  0
 0  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  0
 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
```


[User]
Task

Given three lists:

* Numbers1 = [5,45,23,21,67]
* Numbers2 = [43,22,78,46,38]
* Numbers3 = [9,98,12,98,53]

then:

1. Select the minimum of Numbers[n], Numbers2[n] and Numbers3[n], where **n <= 5** (one based).
2. Add minimum to a new list (Numbers).
3. Show Numbers on this page.

[Assistant]
```
say [Zmin] (5,45,23,21,67), (43,22,78,46,38), (9,98,12,98,53);

```

Output:

```
(5 22 12 21 38)
```


[User]
Every positive integer has infinitely many base-10 multiples that only use the digits **0** and **1**. The goal of this task is to find and display the **minimum** multiple that has this property.

This is simple to do, but can be challenging to do efficiently.

To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "**B10**".

Task

Write a routine to find the B10 of a given integer.

E.G.

```
      n                  B10      n  × multiplier
      1                    1    ( 1  × 1         )
      2                   10    ( 2  × 5         )
      7                 1001    ( 7  x 143       )
      9            111111111    ( 9  x 12345679  )
     10                   10    ( 10 x 1         )

```

and so on.

Use the routine to find and display here, on this page, the **B10** value for:

```
   1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999

```

Optionally find **B10** for:

```
   1998, 2079, 2251, 2277

```

Stretch goal; find **B10** for:

```
   2439, 2997, 4878

```

There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you *do* use magic numbers, explain briefly why and what they do for your implementation.

See also

:   * OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
    * How to find Minimum Positive Multiple in base 10 using only 0 and 1

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.02

Naive, brute force. Simplest thing that could possibly work. Will find any B10 eventually (until you run out of memory or patience) but sloooow, especially for larger multiples of 9.

```
say $_ , ': ', (1..*).map( *.base(2) ).first: * %% $_ for flat 1..10, 95..105; # etc.

```

Based on Ed Pegg jr.s C code from Mathpuzzlers.com. Similar to Phix and Go entries.

```
sub Ed-Pegg-jr (\n) {
    return 1 if n == 1;
    my ($count, $power-mod-n) = 0, 1;
    my @oom-mod-n = 0; # orders of magnitude of 10 mod n
    my @dig-mod = 0;   # 1 to n + oom mod n
    for 1..n -> \i {
        @oom-mod-n[i] = $power-mod-n;
        for 1..n -> \j {
            my \k = (j + $power-mod-n - 1) % n + 1;
            @dig-mod[k] = i if @dig-mod[j] and @dig-mod[j] != i and !@dig-mod[k];
        }
        @dig-mod[$power-mod-n + 1] ||= i;
        ($power-mod-n *= 10) %= n;
        last if @dig-mod[1];
    }
    my ($b10, $remainder) = '', n;
    while $remainder {
        my $place = @dig-mod[$remainder % n + 1];
        $b10 ~= '0' x ($count - $place) if $count > $place;
        $count = $place - 1;
        $b10 ~= '1';
        $remainder = (n + $remainder - @oom-mod-n[$place]) % n;
    }
    $b10 ~ '0' x $count
}

printf "%5s: %28s  %s\n", 'Number', 'B10', 'Multiplier';

for flat 1..10, 95..105, 297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878 {
    printf "%6d: %28s  %s\n", $_, my $a = Ed-Pegg-jr($_), $a / $_;
}

```

Output:

```
Number:                          B10  Multiplier
     1:                            1  1
     2:                           10  5
     3:                          111  37
     4:                          100  25
     5:                           10  2
     6:                         1110  185
     7:                         1001  143
     8:                         1000  125
     9:                    111111111  12345679
    10:                           10  1
    95:                       110010  1158
    96:                     11100000  115625
    97:                     11100001  114433
    98:                     11000010  112245
    99:           111111111111111111  1122334455667789
   100:                          100  1
   101:                          101  1
   102:                      1000110  9805
   103:                     11100001  107767
   104:                      1001000  9625
   105:                       101010  962
   297:          1111011111111111111  3740778151889263
   576:              111111111000000  192901234375
   594:         11110111111111111110  18703890759446315
   891:          1111111111111111011  1247038284075321
   909:          1011111111111111111  1112333455567779
   999:  111111111111111111111111111  111222333444555666777889
  1998: 1111111111111111111111111110  556111667222778333889445
  2079:       1001101101111111111111  481530111164555609
  2251:                 101101101111  44913861
  2277:         11110111111111111011  4879275850290343
  2439:   10000101011110111101111111  4100082415379299344449
  2997: 1111110111111111111111111111  370740777814851888925963
  4878:  100001010111101111011111110  20500412076896496722245
```


[User]
Task

Given three lists:

* Numbers1 = [5,45,23,21,67]
* Numbers2 = [43,22,78,46,38]
* Numbers3 = [9,98,12,54,53]

then:

1. Select the maximum (max) of Numbers[n], Numbers2[n] and Numbers3[n], where **n <= 5** (one based).
2. For each value of max, find the least prime, minPrime, such that **minPrime >= max**
3. Add minPrime to a new list (Primes)
4. Show Primes on this page.

[Assistant]
Seems kind of pointless to specify a maximum of 5 terms when there are only 5 elements in each list but... ¯\\_(ツ)\_/¯

```
say ([Zmax] <5 45 23 21 67>, <43 22 78 46 38>, <9 98 12 54 53>)».&next-prime[^5];

sub next-prime { ($^m..*).first: &is-prime }

```

Output:

```
(43 101 79 59 67)
```


[User]
The **Minkowski question-mark function** converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place of the first zero.

Thus, ?(31/7) = 71/16 because 31/7 has the continued fraction representation [4;2,3] giving the binary expansion 4 + 0.01112.

Among its interesting properties is that it maps roots of quadratic equations, which have repeating continued fractions, to rational numbers, which have repeating binary digits.

The question-mark function is continuous and monotonically increasing, so it has an inverse.

* Produce a function for ?(x).   Be careful: rational numbers have two possible continued fraction representations:

:   :   :   * [a0;a1,... an−1,an]     and
            * [a0;a1,... an−1,an−1,1]

* Choose one of the above that will give a binary expansion ending with a   **1**.
* Produce the inverse function ?-1(x)
* Verify that ?(φ) = 5/3, where φ is the Greek golden ratio.
* Verify that ?-1(-5/9) = (√13 - 7)/6
* Verify that the two functions are inverses of each other by showing that ?-1(?(x))=x and ?(?-1(y))=y for x, y of your choice

Don't worry about precision error in the last few digits.

See also

* Wikipedia entry: Minkowski's question-mark function

[Assistant]
**Translation of**: Go

```
# 20201120 Raku programming solution

my \MAXITER = 151;

sub minkowski(\x) {

   return x.floor + minkowski( x - x.floor ) if x > 1 || x < 0 ;

   my $y = my $p = x.floor;
   my ($q,$s,$d) = 1 xx 3;
   my $r = $p + 1;

   loop {
      last if ( $y + ($d /= 2)  == $y )        ||
              ( my $m = $p + $r) <  0 | $p < 0 ||
              ( my $n = $q + $s) <  0           ;
      x < $m/$n ?? ( ($r,$s) = ($m, $n) ) !! ( $y += $d; ($p,$q) = ($m, $n) );
   }
   return $y + $d
}

sub minkowskiInv($x is copy) {

   return $x.floor + minkowskiInv($x - $x.floor) if  $x > 1 || $x < 0 ;

   return $x if $x == 1 || $x == 0 ;

   my @contFrac = 0;
   my $i = my $curr = 0 ; my $count = 1;

   loop {
      $x *= 2;
      if $curr == 0 {
         if $x < 1 {
            $count++
         } else {
            $i++;
            @contFrac.append: 0;
            @contFrac[$i-1] = $count;
            ($count,$curr) = 1,1;
            $x--;
         }
      } else {
         if $x > 1 {
            $count++;
            $x--;
         } else {
            $i++;
            @contFrac.append: 0;
            @contFrac[$i-1] = $count;
            ($count,$curr) = 1,0;
         }
      }
      if $x == $x.floor { @contFrac[$i] = $count ; last }
      last if $i == MAXITER;
    }
    my $ret = 1 / @contFrac[$i];
    loop (my $j = $i - 1; $j ≥ 0; $j--) { $ret = @contFrac[$j] + 1/$ret }
    return 1 / $ret
}

printf "%19.16f %19.16f\n", minkowski(0.5*(1 + 5.sqrt)), 5/3;
printf "%19.16f %19.16f\n", minkowskiInv(-5/9), (13.sqrt-7)/6;
printf "%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)),
   minkowskiInv(minkowski(0.1213141516171819))

```

Output:

```
 1.6666666666696983  1.6666666666666667
-0.5657414540893351 -0.5657414540893352
 0.7182818280000092  0.1213141516171819
```


[User]
Given a random number generator, (rng), generating numbers in the range 0.0 .. 1.0 called rgen, for example; and a function modifier(x)
taking an number in the same range and generating the probability that the input should be generated, in the same range 0..1; then implement the following algorithm for generating random numbers to the probability given by function modifier:

```
while True:
    random1 = rgen()
    random2 = rgen()
    if random2 < modifier(random1):
        answer = random1
        break
    endif
endwhile
```

Task

* Create a modifier function that generates a 'V' shaped probability of number generation using something like, for example:

```
                      modifier(x)  =  2*(0.5 - x)  if x < 0.5  else 2*(x - 0.5)

```

* Create a generator of random numbers with probabilities modified by the above function.
* Generate >= 10,000 random numbers subject to the probability modification.
* Output a textual histogram with from 11 to 21 bins showing the distribution of the random numbers generated.

Show your output here, on this page.

[Assistant]
```
sub modified_random_distribution ( Code $modifier --> Seq ) {
    return lazy gather loop {
        my ( $r1, $r2 ) = rand, rand;
        take $r1 if $modifier.($r1) > $r2;
    }
}
sub modifier ( Numeric $x --> Numeric ) {
    return 2 * ( $x < 1/2 ?? ( 1/2 - $x  )
                          !! ( $x  - 1/2 ) );
}
sub print_histogram ( @data, :$n-bins, :$width ) { # Assumes minimum of zero.
    my %counts = bag @data.map: { floor( $_ * $n-bins ) / $n-bins };
    my $max_value = %counts.values.max;
    sub hist { '■' x ( $width * $^count / $max_value ) }
    say ' Bin, Counts: Histogram';
    printf "%4.2f, %6d: %s\n", .key, .value, hist(.value) for %counts.sort;
}

my @d = modified_random_distribution( &modifier );

print_histogram( @d.head(50_000), :n-bins(20), :width(64) );

```

Output:

```
 Bin, Counts: Histogram
0.00,   4718: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.05,   4346: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.10,   3685: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.15,   3246: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.20,   2734: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.25,   2359: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.30,   1702: ■■■■■■■■■■■■■■■■■■■■■■
0.35,   1283: ■■■■■■■■■■■■■■■■■
0.40,    702: ■■■■■■■■■
0.45,    250: ■■■
0.50,    273: ■■■
0.55,    745: ■■■■■■■■■■
0.60,   1231: ■■■■■■■■■■■■■■■■
0.65,   1757: ■■■■■■■■■■■■■■■■■■■■■■■
0.70,   2209: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.75,   2738: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.80,   3255: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.85,   3741: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.90,   4268: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
0.95,   4758: ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

```


[User]
**Modular arithmetic** is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called *congruence*.

For any positive integer

p
{\displaystyle {\displaystyle p}}
 called the *congruence modulus*,
two numbers

a
{\displaystyle {\displaystyle a}}
 and

b
{\displaystyle {\displaystyle b}}
 are said to be *congruent modulo p* whenever there exists an integer

k
{\displaystyle {\displaystyle k}}
 such that:

:   a
    =
    b
    +
    k

    p
    {\displaystyle {\displaystyle a=b+k\,p}}

The corresponding set of equivalence classes forms a ring denoted

Z

p

Z
{\displaystyle {\displaystyle {\frac {\mathbb {Z} }{p\mathbb {Z} }}}}
. When p is a prime number, this ring becomes a field denoted

F

p
{\displaystyle {\displaystyle \mathbb {F} \_{p}}}
, but you won't have to implement the multiplicative inverse for this task.

Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.

The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.

You will use the following function for demonstration:

:   f
    (
    x
    )
    =

    x

    100
    +
    x
    +
    1
    {\displaystyle {\displaystyle f(x)=x^{100}+x+1}}

You will use

13
{\displaystyle {\displaystyle 13}}
 as the congruence modulus and you will compute

f
(
10
)
{\displaystyle {\displaystyle f(10)}}
.

It is important that the function

f
{\displaystyle {\displaystyle f}}
 is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.

Related tasks

Modular exponentiation

[Assistant]
(formerly Perl 6)

We'll use the FiniteFields repo.

```
use FiniteField;
$*modulus = 13;

sub f(\x) { x**100 + x + 1};

say f(10);

```

Output:

```
1
```


[User]
Find the last   **40**   decimal digits of

a

b
{\displaystyle {\displaystyle a^{b}}}
,   where

:   :   * a
          =
          2988348162058574136915891421498819466320163312926952423791023078876139
          {\displaystyle {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}}
        * b
          =
          2351399303373464486466122544523690094744975233415544072992656881240319
          {\displaystyle {\displaystyle b=2351399303373464486466122544523690094744975233415544072992656881240319}}

A computer is too slow to find the entire value of

a

b
{\displaystyle {\displaystyle a^{b}}}
.

Instead, the program must use a fast algorithm for modular exponentiation:

a

b

mod

m
{\displaystyle {\displaystyle a^{b}\mod m}}
.

The algorithm must work for any integers

a
,
b
,
m
{\displaystyle {\displaystyle a,b,m}}
,     where

b
≥
0
{\displaystyle {\displaystyle b\geq 0}}
   and

m
>
0
{\displaystyle {\displaystyle m>0}}
.

[Assistant]
(formerly Perl 6)
This is specced as a built-in, but here's an explicit version:

```
sub expmod(Int $a is copy, Int $b is copy, $n) {
    my $c = 1;
    repeat while $b div= 2 {
        ($c *= $a) %= $n if $b % 2;
        ($a *= $a) %= $n;
    }
    $c;
}

say expmod
    2988348162058574136915891421498819466320163312926952423791023078876139,
    2351399303373464486466122544523690094744975233415544072992656881240319,
    10**40;

```

Output:

```
1527229998585248450016808958343740453059
```


[User]
From Wikipedia:

In modular arithmetic,   the **modular multiplicative inverse** of an integer    *a*    modulo    *m*    is an integer    *x*    such that

:   :   a

        x
        ≡
        1

        (
        mod

        m
        )
        .
        {\displaystyle {\displaystyle a\,x\equiv 1{\pmod {m}}.}}

Or in other words, such that:

:   :   ∃
        k
        ∈

        Z
        ,

        a

        x
        =
        1
        +
        k

        m
        {\displaystyle {\displaystyle \exists k\in \mathbb {Z} ,\qquad a\,x=1+k\,m}}

It can be shown that such an inverse exists   if and only if    *a*    and    *m*    are coprime,   but we will ignore this for this task.

Task

Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language,   compute the modular inverse of   42 modulo 2017.

[Assistant]
(formerly Perl 6)

```
sub inverse($n, :$modulo) {
    my ($c, $d, $uc, $vc, $ud, $vd) = ($n % $modulo, $modulo, 1, 0, 0, 1);
    my $q;
    while $c != 0 {
        ($q, $c, $d) = ($d div $c, $d % $c, $c);
        ($uc, $vc, $ud, $vd) = ($ud - $q*$uc, $vd - $q*$vc, $uc, $vc);
    }
    return $ud % $modulo;
}

say inverse 42, :modulo(2017)

# or use a built-in routine - https://docs.raku.org/routine/expmod , kudos to trizen++

say expmod(42, -1, 2017);

```

You may Attempt This Online!


[User]
It is useful to be able to execute a main() function only when a program is run directly. This is a central feature in programming scripts. A script that behaves this way is called a modulino.

Examples from https://github.com/mcandre/modulinos

Sometimes getting the ScriptName is required in order to determine when to run main().

Care when manipulating command line arguments, due to subtle exec security constraints that may or not be enforced on implicit argv[0]. https://ryiron.wordpress.com/2013/12/16/argv-silliness/

:   *This is still a draft task, and the current task description has caused mega confusion. See **Talk:Modulinos** for numerous attempts to understand the task and to rewrite the task description.*

:   **The task Executable library is written to replace this task.** *This task's future is in doubt as its aims are not clear enough.*

[Assistant]
(formerly Perl 6)
Raku automatically calls MAIN on direct invocation, but this may be a multi dispatch, so a library may have multiple "scripted mains".

```
class LUE {
    has $.answer = 42;
}

multi MAIN ('test') {
    say "ok" if LUE.new.answer == 42;
}

multi MAIN ('methods') {
    say ~LUE.^methods;
}
```


[User]
A Monad is a combination of a data-type with two helper functions written for that type.

The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as **eta** and **mu**, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.

The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.

A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.

The natural implementation of bind for the List monad is a composition of **concat** and **map**, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.

Demonstrate in your programming language the following:

1. Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
2. Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String
3. Compose the two functions with bind

[Assistant]
(formerly Perl 6)
Raku does not have Monad types built in but they can be emulated/implemented without a great deal of difficulty. List Monads especially are of questionable utility in Raku. Most item types and Listy types have a Cool role in Raku. (Cool being a play on the slang term "cool" as in: "That's cool with me." (That's ok with me). So Ints are pretty much treated like one item lists for operators that work with lists. ("I work on a list." "Here's an Int." "Ok, that's cool.") Explicitly wrapping an Int into a List is worse than useless. It won't do anything Raku can't do natively, and will likely **remove** some functionality that it would normally have. That being said, just because it is a bad idea (in Raku) doesn't mean it can't be done.

In Raku, bind is essentially map. I'll shadow map here but again, it **removes** capability, not adds it. Raku also provided "hyper" operators which will descend into data structures and apply an operator / function to each member of that data structure.

Here's a simple, if contrived example. take the numbers from 0 to 9, add 3 to each, find the divisors of those sums and print the list of divisors for each sum... in base 2. Again, a bind function was implemented but it is more limited than if we just used map directly. The built in map method will work with either items or lists, here we need to implement a multi sub to handle either.

The \* in the bind blocks are typically referred to as "whatever"; whatever + 3 etc. The guillemot (») is the hyper operator; descend into the data structure and apply the following operator/function to each member.

```
multi bind (@list, &code) { @list.map: &code };

multi bind ($item, &code) { $item.&code };

sub divisors (Int $int) { gather for 1 .. $int { .take if $int %% $_ } }

put (^10).&bind(* + 3).&bind(&divisors)».&bind(*.base: 2).join: "\n";

```

Output:

```
1 11
1 10 100
1 101
1 10 11 110
1 111
1 10 100 1000
1 11 1001
1 10 101 1010
1 1011
1 10 11 100 110 1100
```


[User]
Demonstrate in your programming language the following:

1. Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
2. Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
3. Compose the two functions with bind

A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.

A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.11

It is exceptionally difficult to come up with a compelling valuable use for
a Maybe monad in Raku. Monads are most useful in languages that don't have
exceptions and/or only allow a single point of entry/exit from a subroutine.

There are very good reasons to have those restrictions. It makes it much less
complex to reason about a programs correctness and actually *prove* that a
program is correct, but those restrictions also lead to oddities like Monads,
just as a way to work around those restrictions.

The task description asks for two functions that take an Int and return a Maybe
Int or Maybe Str, but those distinctions are nearly meaningless in Raku. See
below.

```
my $monad = <42>;
say 'Is $monad an Int?: ', $monad ~~ Int;
say 'Is $monad a  Str?: ', $monad ~~ Str;
say 'Wait, what? What exactly is $monad?: ', $monad.^name;

```

Output:

```
Is $monad an Int?: True
Is $monad a  Str?: True
Wait, what? What exactly is $monad?: IntStr
```

$monad is both an Int **and** a Str. It exists in a sort-of quantum state
where what-it-is depends on how-it-is-used. Bolting on some 'Monad' type to do
this will only *remove* functionality that Raku already has.

Ok, say you have a situation where you absolutely do not want an incalculable
value to halt processing. (In a web process perhaps.) In that case, it *might*
be useful to subvert the normal exception handler and just return a "Nothing"
type. Any routine that needs to be able to handle a Nothing type will need to be
informed of it, but for the most part, that just means adding a multi-dispatch
candidate.

```
# Build a Nothing type. When treated as a string it returns the string 'Nothing'.
# When treated as a Numeric, returns the value 'Nil'.
class NOTHING {
    method Str { 'Nothing' }
    method Numeric { Nil }
}

# A generic instance of a Nothing type.
my \Nothing = NOTHING.new;

# A reimplementation of the square-root function. Could just use the CORE one
# but this more fully shows how multi-dispatch candidates are added.

# Handle positive numbers & 0
multi root (Numeric $n where * >= 0) { $n.sqrt }
# Handle Negative numbers (Complex number handling is built in.)
multi root (Numeric $n where * <  0) { $n.Complex.sqrt }
# Else return Nothing
multi root ($n) { Nothing }

# Handle numbers > 0
multi ln (Real $n where * > 0) { log $n, e }
# Else return Nothing
multi ln ($n) { Nothing }

# Handle fraction where the denominator != 0
multi recip (Numeric $n where * != 0) { 1/$n }
# Else return Nothing
multi recip ($n) { Nothing }

# Helper formatting routine
sub center ($s) {
    my $pad = 21 - $s.Str.chars;
    ' ' x ($pad / 2).floor ~ $s ~ ' ' x ($pad / 2).ceiling;
}

# Display the "number" the reciprocal, the root, natural log and the 3 functions
# composed together.
put ('"Number"', 'Reciprocal', 'Square root', 'Natural log', 'Composed')».&center;

# Note how it handles the last two "values". The string 'WAT' is not numeric at
# all; but Ethiopic number 30, times vulgar fraction 1/7, is.
put ($_, .&recip, .&root, .&ln, .&(&ln o &root o &recip) )».&center
  for -2, -1, -0.5, 0, exp(-1), 1, 2, exp(1), 3, 4, 5, 'WAT', ፴ × ⅐;

```

Output:

```
      "Number"             Reciprocal            Square root           Natural log            Composed
         -2                   -0.5          0+1.4142135623730951i        Nothing               Nothing
         -1                    -1                   0+1i                 Nothing               Nothing
        -0.5                   -2           0+0.7071067811865476i        Nothing               Nothing
          0                  Nothing                  0                  Nothing               Nothing
 0.36787944117144233    2.718281828459045    0.6065306597126334            -1                    0.5
          1                     1                     1                     0                     0
          2                    0.5           1.4142135623730951    0.6931471805599453    -0.3465735902799726
  2.718281828459045    0.36787944117144233   1.6487212707001282             1                   -0.5
          3                 0.333333         1.7320508075688772    1.0986122886681098    -0.5493061443340549
          4                   0.25                    2            1.3862943611198906    -0.6931471805599453
          5                    0.2            2.23606797749979     1.6094379124341003    -0.8047189562170503
         WAT                 Nothing               Nothing               Nothing               Nothing
      4.285714              0.233333         2.0701966780270626     1.455287232606842    -0.727643616303421
```


[User]
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.

Demonstrate in your programming language the following:

1. Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
2. Write three simple functions: root, addOne, and half
3. Derive Writer monad versions of each of these functions
4. Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)

[Assistant]
Basic semantic borrowed from the Monads/List monad entry

**Translation of**: Go

```
# 20200508 Raku programming solution

class Writer { has Numeric $.value ; has Str $.log }

sub Bind (Writer \v, &code) {
   my \n = v.value.&code;
   Writer.new: value => n.value, log => v.log ~ n.log
};

sub Unit(\v, \s) { Writer.new: value=>v, log=>sprintf "%-17s: %.12f\n",s,v}

sub root(\v) { Unit v.sqrt, "Took square root" }

sub addOne(\v) { Unit v+1, "Added one" }

sub half(\v) { Unit v/2, "Divided by two" }

say Unit(5, "Initial value").&Bind(&root).&Bind(&addOne).&Bind(&half).log;

```

Output:

```
Initial value    : 5.000000000000
Took square root : 2.236067977500
Added one        : 3.236067977500
Divided by two   : 1.618033988750

```


[User]
A **Monte Carlo Simulation** is a way of approximating the value of a function
where calculating the actual value is difficult or impossible.
It uses random sampling to define constraints on the value
and then makes a sort of "best guess."

A simple Monte Carlo Simulation can be used to calculate the value for

π
{\displaystyle {\displaystyle \pi }}
.

If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be

π

/
4
{\displaystyle {\displaystyle \pi /4}}
.

So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately

π

/
4
{\displaystyle {\displaystyle \pi /4}}
.

Task

Write a function to run a simulation like this, with a variable number of random points to select.

Also, show the results of a few different sample sizes.

For software where the number

π
{\displaystyle {\displaystyle \pi }}
 is not built-in,
we give

π
{\displaystyle {\displaystyle \pi }}
 as a number of digits:

```
            3.141592653589793238462643383280

```

[Assistant]
(formerly Perl 6)

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

We'll consider the upper-right quarter of the unitary disk centered at the origin. Its area is

π
4
{\displaystyle {\displaystyle \pi \over 4}}
.

```
my @random_distances = ([+] rand**2 xx 2) xx *;

sub approximate_pi(Int $n) {
    4 * @random_distances[^$n].grep(* < 1) / $n
}

say "Monte-Carlo π approximation:";
say "$_ iterations:  ", approximate_pi $_
    for 100, 1_000, 10_000;

```

Output:

```
Monte-Carlo π approximation:
100 iterations:  2.88
1000 iterations:  3.096
10000 iterations:  3.1168
```

We don't really need to write a function, though. A lazy list would do:

```
my @pi = ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *;
say @pi[10, 1000, 10_000];

```


[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.

Implement the Montgomery reduction algorithm, as explained in "Handbook of Applied Cryptography, Section 14.3.2, page 600. Montgomery reduction calculates

T

R

−
1

m
o
d
m
{\displaystyle {\displaystyle TR^{-1}\mathrm {mod} m}}
, without having to divide by

m
{\displaystyle {\displaystyle m}}
.

* Let

  M
  {\displaystyle {\displaystyle M}}
   be a positive integer, and

  R
  {\displaystyle {\displaystyle R}}
   and

  T
  {\displaystyle {\displaystyle T}}
   integers such that

  R
  >
  m
  {\displaystyle {\displaystyle R>m}}
  ,

  g
  c
  d
  (
  m
  ,
  R
  )
  =
  1
  {\displaystyle {\displaystyle \mathrm {gcd} (m,R)=1}}
  , and

  0
  ≤
  T
  <
  m
  R
  {\displaystyle {\displaystyle 0\leq T<mR}}
  .
* R
  {\displaystyle {\displaystyle R}}
   is usually chosen as

  b

  n
  {\displaystyle {\displaystyle b^{n}}}
  , where

  b
  {\displaystyle {\displaystyle b}}
   = base (radix) in which the numbers in the calculation as represented in (so

  b
  =
  10
  {\displaystyle {\displaystyle b=10}}
   in ‘normal’ paper arithmetic,

  b
  =
  2
  {\displaystyle {\displaystyle b=2}}
   for computer implementations) and

  n
  {\displaystyle {\displaystyle n}}
   = number of digits in base

  m
  {\displaystyle {\displaystyle m}}
* The numbers

  m
  {\displaystyle {\displaystyle m}}
   (

  n
  {\displaystyle {\displaystyle n}}
   digits long),

  T
  {\displaystyle {\displaystyle T}}
   (

  2
  n
  {\displaystyle {\displaystyle 2n}}
   digits long),

  R
  {\displaystyle {\displaystyle R}}
  ,

  b
  {\displaystyle {\displaystyle b}}
  ,

  n
  {\displaystyle {\displaystyle n}}
   are known entities, a number

  m
  ′
  {\displaystyle {\displaystyle m'}}
   (often represented as `m_dash` in code) =

  −

  m

  −
  1

  m
  o
  d
  b
  {\displaystyle {\displaystyle -m^{-1}\mathrm {mod} b}}
   is precomputed.

See the Handbook of Applied Cryptography for brief introduction to theory and numerical example in radix 10. Individual chapters of the book can be viewed online as provided by the authors. The said algorithm can be found at [1] at page 600 (page 11 of pdf file)

Algorithm:

```
A ← T (temporary variable)
For i from 0 to (n-1) do the following:
   ui ← ai* m' mod b      // ai is the ith digit of A, ui is a single digit number in radix b
   A ← A + ui*m*bi
A ← A/bn
if A >= m,
   A ← A - m
Return (A)

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

**Translation of**: Sidef

```
sub montgomery-reduce($m, $a is copy) {
    for 0..$m.msb {
        $a += $m if $a +& 1;
        $a +>= 1
    }
    $a % $m
}

my $m  = 750791094644726559640638407699;
my $t1 = 323165824550862327179367294465482435542970161392400401329100;

my $r1 = 440160025148131680164261562101;
my $r2 = 435362628198191204145287283255;

my $x1 = 540019781128412936473322405310;
my $x2 = 515692107665463680305819378593;

say "Original x1:       ", $x1;
say "Recovered from r1: ", montgomery-reduce($m, $r1);
say "Original x2:       ", $x2;
say "Recovered from r2: ", montgomery-reduce($m, $r2);

print "\nMontgomery  computation x1**x2 mod m: ";
my $prod = montgomery-reduce($m, $t1/$x1);
my $base = montgomery-reduce($m, $t1);

for $x2, {$_ +> 1} ... 0 -> $exponent {
    $prod = montgomery-reduce($m, $prod * $base) if $exponent +& 1;
    $base = montgomery-reduce($m, $base * $base);
}

say montgomery-reduce($m, $prod);
say "Built-in op computation x1**x2 mod m: ", $x1.expmod($x2, $m);

```

Output:

```
Original x1:       540019781128412936473322405310
Recovered from r1: 540019781128412936473322405310
Original x2:       515692107665463680305819378593
Recovered from r2: 515692107665463680305819378593

Montgomery  computation x1**x2 mod m: 151232511393500655853002423778
Built-in op computation x1**x2 mod m: 151232511393500655853002423778

```