[User]
A magic square is an   **NxN**   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   *and*   both long (main) diagonals are equal to the same sum (which is called the   *magic number*   or   *magic constant*).

The numbers are usually (but not always) the first   **N**2   positive integers.

A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a *semimagic square*.

|  |  |  |
| --- | --- | --- |
| **8** | **1** | **6** |
| **3** | **5** | **7** |
| **4** | **9** | **2** |

Task

For any odd   **N**,   generate a magic square with the integers    **1** ──► **N**,   and show the results here.

Optionally, show the *magic number*.

You should demonstrate the generator by showing at least a magic square for   **N** = **5**.

Related tasks

* Magic squares of singly even order
* Magic squares of doubly even order

See also

* MathWorld™ entry: Magic\_square
* Odd Magic Squares (1728.org)

[Assistant]
(formerly Perl 6)

See Magic squares/Raku for a general magic square generator.

Output:

With a parameter of 5:

```
17 24  1  8 15
23  5  7 14 16
 4  6 13 20 22
10 12 19 21  3
11 18 25  2  9

The magic number is 65
```

With a parameter of 19:

```
192 213 234 255 276 297 318 339 360   1  22  43  64  85 106 127 148 169 190
212 233 254 275 296 317 338 359  19  21  42  63  84 105 126 147 168 189 191
232 253 274 295 316 337 358  18  20  41  62  83 104 125 146 167 188 209 211
252 273 294 315 336 357  17  38  40  61  82 103 124 145 166 187 208 210 231
272 293 314 335 356  16  37  39  60  81 102 123 144 165 186 207 228 230 251
292 313 334 355  15  36  57  59  80 101 122 143 164 185 206 227 229 250 271
312 333 354  14  35  56  58  79 100 121 142 163 184 205 226 247 249 270 291
332 353  13  34  55  76  78  99 120 141 162 183 204 225 246 248 269 290 311
352  12  33  54  75  77  98 119 140 161 182 203 224 245 266 268 289 310 331
 11  32  53  74  95  97 118 139 160 181 202 223 244 265 267 288 309 330 351
 31  52  73  94  96 117 138 159 180 201 222 243 264 285 287 308 329 350  10
 51  72  93 114 116 137 158 179 200 221 242 263 284 286 307 328 349   9  30
 71  92 113 115 136 157 178 199 220 241 262 283 304 306 327 348   8  29  50
 91 112 133 135 156 177 198 219 240 261 282 303 305 326 347   7  28  49  70
111 132 134 155 176 197 218 239 260 281 302 323 325 346   6  27  48  69  90
131 152 154 175 196 217 238 259 280 301 322 324 345   5  26  47  68  89 110
151 153 174 195 216 237 258 279 300 321 342 344   4  25  46  67  88 109 130
171 173 194 215 236 257 278 299 320 341 343   3  24  45  66  87 108 129 150
172 193 214 235 256 277 298 319 340 361   2  23  44  65  86 107 128 149 170

The magic number is 3439
```


[User]
A magic square is an **NxN** square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, *and* both diagonals are equal to the same sum (which is called the *magic number* or *magic constant*).

A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

Task

Create a magic square of 6 x 6.

Related tasks

* Magic squares of odd order
* Magic squares of doubly even order

See also

* Singly Even Magic Squares (1728.org)

[Assistant]
(formerly Perl 6)

See Magic squares/Raku for a general magic square generator.

Output:

With a parameter of 6:

```
35  1  6 26 19 24
 3 32  7 21 23 25
31  9  2 22 27 20
 8 28 33 17 10 15
30  5 34 12 14 16
 4 36 29 13 18 11

The magic number is 111
```

With a parameter of 10:

```
 92  99   1   8  15  67  74  51  58  40
 98  80   7  14  16  73  55  57  64  41
  4  81  88  20  22  54  56  63  70  47
 85  87  19  21   3  60  62  69  71  28
 86  93  25   2   9  61  68  75  52  34
 17  24  76  83  90  42  49  26  33  65
 23   5  82  89  91  48  30  32  39  66
 79   6  13  95  97  29  31  38  45  72
 10  12  94  96  78  35  37  44  46  53
 11  18 100  77  84  36  43  50  27  59

The magic number is 505
```


[User]
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum.

E.G.

:   * **6425** is a magnanimous number. **6 + 425 == 431** which is prime; **64 + 25 == 89** which is prime; **642 + 5 == 647** which is prime.

:   * **3538** is **not** a magnanimous number. **3 + 538 == 541** which is prime; **35 + 38 == 73** which is prime; but **353 + 8 == 361** which is **not** prime.

Traditionally the single digit numbers 0 through 9 **are** included as magnanimous numbers as there is no place in the number where you can add a plus between two digits at all. (Kind of weaselly but there you are...) Except for the actual value 0, leading zeros are not permitted. Internal zeros are fine though, **1001** -> **1 + 001** (prime), **10 + 01** (prime) **100 + 1** (prime).

There are only 571 known magnanimous numbers. It is strongly suspected, though not rigorously proved, that there are no magnanimous numbers above **97393713331910**, the largest one known.

Task

:   * Write a routine (procedure, function, whatever) to find **magnanimous numbers**.

:   * Use that function to find and display, here on this page the first **45** magnanimous numbers.

:   * Use that function to find and display, here on this page the **241st** through **250th** magnanimous numbers.

:   * Stretch: Use that function to find and display, here on this page the **391st** through **400th** magnanimous numbers

See also

* OEIS:A252996 - Magnanimous numbers: numbers such that the sum obtained by inserting a "+" anywhere between two digits gives a prime.

[Assistant]
**Works with**: Rakudo version 2020.02

```
my @magnanimous = lazy flat ^10, (10 .. 1001).map( {
    my int $last;
    (1 ..^ .chars).map: -> \c { $last = 1 and last unless (.substr(0,c) + .substr(c)).is-prime }
    next if $last;
    $_
} ),

(1002 .. ∞).map: {
     # optimization for numbers > 1001; First and last digit can not both be even or both be odd
    next if (.substr(0,1) + .substr(*-1)) %% 2;
    my int $last;
    (1 ..^ .chars).map: -> \c { $last = 1 and last unless (.substr(0,c) + .substr(c)).is-prime }
    next if $last;
    $_
}

put 'First 45 magnanimous numbers';
put @magnanimous[^45]».fmt('%3d').batch(15).join: "\n";

put "\n241st through 250th magnanimous numbers";
put @magnanimous[240..249];

put "\n391st through 400th magnanimous numbers";
put @magnanimous[390..399];

```

Output:

```
First 45 magnanimous numbers
  0   1   2   3   4   5   6   7   8   9  11  12  14  16  20
 21  23  25  29  30  32  34  38  41  43  47  49  50  52  56
 58  61  65  67  70  74  76  83  85  89  92  94  98 101 110

241st through 250th magnanimous numbers
17992 19972 20209 20261 20861 22061 22201 22801 22885 24407

391st through 400th magnanimous numbers
486685 488489 515116 533176 551558 559952 595592 595598 600881 602081
```


[User]
GOST 28147-89 is a standard symmetric encryption based on a Feistel network.

The structure of the algorithm consists of three levels:

1. encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;
2. cycles - 32-З, 32-Р and 16-З, is a repetition of the main step;
3. *main step*, a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block.

Task

Implement the main step of this encryption algorithm.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2012-10-30

Implemented to match explanation on Discussion page:

```
# sboxes from http://en.wikipedia.org/wiki/GOST_(block_cipher)
constant sbox =
    [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],
    [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],
    [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],
    [7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],
    [6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],
    [4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],
    [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],
    [1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12];

sub infix:<rol³²>(\y, \n) { (y +< n) % 2**32 +| (y +> (32 - n)) }

sub ГОСТ-round(\R, \K) {
    my \a = (R + K) % 2**32;
    my \b = :16[ sbox[$_][(a +> (4 * $_)) % 16] for 7...0 ];
    b rol³² 11;
}

sub feistel-step(&F, \L, \R, \K) { R, L +^ F(R, K) }

my @input = 0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04;
my @key   = 0xF9, 0x04, 0xC1, 0xE2;

my ($L,$R) = @input.reverse.map: { :256[$^a,$^b,$^c,$^d] }
my ($K   ) = @key  .reverse.map: { :256[$^a,$^b,$^c,$^d] }

($L,$R) = feistel-step(&ГОСТ-round, $L, $R, $K);

say [ ($L +< 32 + $R X+> (0, 8 ... 56)) X% 256 ].fmt('%02X');

```

Output:

```
1F 88 CF 07 21 04 3B 04
```


[User]
Before writing to a file it is often advisable to make a backup of the original.
Creating such a backup file is however also not without pitfalls.

In this task you should create a backup file from an existing file and then write new text to the old file.
The following issues should be handled:

* avoid making a copy of the file but instead rename the original and then write a new file with the original filename.
* if a copy needs to be made, please explain why rename is not possible.
* keep in mind symlinks, and do not rename or copy the link but the target. (If there is a link `foo -> bar/baz`, then `bar/baz` should be renamed to `bar/baz.backup` and then the new text should be written to `bar/baz`.)
* it is assumed that you have permission to write in the target location, thus permission errors need not be handled.
* you may choose the backup filename per preference or given limitations. (It should somehow include the original filename however.)
* please try to avoid executing external commands, and especially avoid calling a shell script.

Some examples on this page assume that the original file already exists. They might fail if some user is trying to create a new file.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.10

```
# Back up the given path/filename with a default extension .bk(n)
# where n is in the range 1 - $limit (default 3).
# Prints 'File not found' to STDERR if the file does not exist.
# Will not do anything if limit is set to less than 1.
# Will not follow symlinks by default.

sub backup (Str $filepath, Int :$limit = 3, Str :$ext = 'bk', Bool :$follow-symlinks = False) {
    my $abs = $follow-symlinks ?? $filepath.IO.resolve.absolute !! $filepath.IO.absolute;
    for (1 ..^ $limit).reverse -> $bnum {
        if "{$abs}.{$ext}{$bnum}".IO.e {
            "{$abs}.{$ext}{$bnum}".IO.rename: "{$abs}.{$ext}{$bnum + 1}";
        }
    }
    if $abs.IO.e {
        if $limit > 0 {
            $abs.IO.rename: "{$abs}.{$ext}1";
            my $in  = "{$abs}.{$ext}1".IO.open :r :bin or note $! and return False;
            my $out = $abs.IO.open :w :bin or note $! and return False;
            my $buffer-size = 32768; # 32Kb
            while my $buf = $in.read($buffer-size) { $out.write($buf) };
            close $in;
            close $out;
        }
    } else {
        note "File not found: $abs" and return False;
    }
    $abs # return filepath on success
}

# back up this program
backup $*PROGRAM-NAME;

# Optionally, specify limit, back-up extension pattern and whether to follow symlinks.
# Optional parameters can be in any order, in any combination.
backup 'myfile', :follow-symlinks, :limit(2), :ext('bak');

```


[User]
Task

Create a directory and any missing parents.

This task is named after the posix `mkdir -p` command, and several libraries which implement the same behavior.

Please implement a function of a single path string (for example `./path/to/dir`) which has the above side-effect.
If the directory already exists, return successfully.
Ideally implementations will work equally well cross-platform (on windows, linux, and OS X).

It's likely that your language implements such a function as part of its standard library. If so, please also show how such a function would be implemented.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2016.06

There is a built-in function for this:

```
mkdir 'path/to/dir'

```

Alternatively, a custom solution (as per task description) that only uses the built-in mkdir non-recursively. The "triangle reduce" meta-operator `[\ ]` is used get the intermediate results of a left fold with the comma operator on the list of path elements.

```
for [\,] $*SPEC.splitdir("../path/to/dir") -> @path {
    mkdir $_ unless .e given $*SPEC.catdir(@path).IO;
}

```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Man or boy 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) |

**Background**: The **man or boy test** was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.

> I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
>  — Donald Knuth

**Task**: Imitate Knuth's example in Algol 60 in another language, as far as possible.

**Details**: Local variables of routines are often kept in activation records (also *call frames*). In many languages, these records are kept on a call stack. In Algol (and e.g. in Smalltalk), they are allocated on a heap instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the Funarg Problem.

In Knuth's example, each call to *A* allocates an activation record for the variable *A*. When *B* is called from *A*, any access to *k* now refers to this activation record. Now *B* in turn calls *A*, but passes itself as an argument. This argument remains bound to the activation record. This call to *A* also "shifts" the variables *xi* by one place, so eventually the argument *B* (still bound to its particular
activation record) will appear as *x4* or *x5* in a call to *A*. If this happens when the expression *x4 + x5* is evaluated, then this will again call *B*, which in turn will update *k* in the activation record it was originally bound to. As this activation record is shared with other instances of calls to *A* and *B*, it will influence the whole computation.

So all the example does is to set up a convoluted calling structure, where updates to *k* can influence the behavior
in completely different parts of the call tree.

Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67.

**Performance and Memory**: Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments.

The table below shows the result, call depths, and total calls for a range of *k*:

| *k* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| *A* | 1 | 0 | -2 | 0 | 1 | 0 | 1 | -1 | -10 | -30 | -67 | -138 | -291 | -642 | -1,446 | -3,250 | -7,244 | -16,065 | -35,601 | -78,985 | -175,416 | -389,695 | -865,609 | -1,922,362 | -4,268,854 | -9,479,595 | -21,051,458 | -46,750,171 | -103,821,058 | -230,560,902 | -512,016,658 |
| *A* called | 1 | 2 | 3 | 4 | 8 | 18 | 38 | 80 | 167 | 347 | 722 | 1,509 | 3,168 | 6,673 | 14,091 | 29,825 | 63,287 | 134,652 | 287,264 | 614,442 | 1,317,533 | 2,831,900 | 6,100,852 | 13,172,239 | 28,499,827 | 61,786,266 | 134,202,509 | 292,011,464 |  |  |  |
| *A* depth | 1 | 2 | 3 | 4 | 8 | 16 | 32 | 64 | 128 | 256 | 512 | 1,024 | 2,048 | 4,096 | 8,192 | 16,384 | 32,768 | 65,536 | 131,072 | 262,144 | 524,288 | 1,048,576 | 2,097,152 | 4,194,304 | 8,388,608 |  |  |  |  |  |  |
| *B* called | 0 | 1 | 2 | 3 | 7 | 17 | 37 | 79 | 166 | 346 | 721 | 1,508 | 3,167 | 6,672 | 14,090 | 29,824 | 63,286 | 134,651 | 287,263 | 614,441 | 1,317,532 | 2,831,899 | 6,100,851 | 13,172,238 | 28,499,826 |  |  |  |  |  |  |
| *B* depth | 0 | 1 | 2 | 3 | 7 | 15 | 31 | 63 | 127 | 255 | 511 | 1,023 | 2,047 | 4,095 | 8,191 | 16,383 | 32,767 | 65,535 | 131,071 | 262,143 | 524,287 | 1,048,575 | 2,097,151 | 4,194,303 | 8,388,607 |  |  |  |  |  |  |

Related tasks

* Jensen's Device

[Assistant]
(formerly Perl 6)
This solution avoids creating the closure B if $k <= 0 (that is, nearly every time).

```
sub A($k is copy, &x1, &x2, &x3, &x4, &x5) {
    $k <= 0
        ?? x4() + x5()
        !! (my &B = { A(--$k, &B, &x1, &x2, &x3, &x4) })();
};

say A(10, {1}, {-1}, {-1}, {1}, {0});

```

Output:

```
-67
```


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

Task

Generate and draw the Mandelbrot set.

Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2023.08-3-g2f8234c22

Using the hyper statement prefix for concurrency, the code below produces a graymap to standard output.

File:Mandelbrot-raku.jpg

```
constant MAX-ITERATIONS = 64;
my $width = +(@*ARGS[0] // 800);
my $height = $width + $width %% 2;
say "P2";
say "$width $height";
say MAX-ITERATIONS;

sub cut(Range $r, UInt $n where $n > 1 --> Seq) {
    $r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max
}

my @re = cut(-2 .. 1/2, $width);
my @im = cut( 0 .. 5/4, 1 + ($height div 2)) X* 1i;

sub mandelbrot(Complex $z is copy, Complex $c --> Int) {
    for 1 .. MAX-ITERATIONS {
        $z = $z*$z + $c;
        return $_ if $z.abs > 2;
    }
    return 0;
}

my @lines = hyper for @im X+ @re {
  mandelbrot(0i, $_);
}.rotor($width);

.put for @lines[1..*].reverse;
.put for @lines;
```


[User]
Given two ranges:

:   :   :   * [

              a

              1
              ,

              a

              2
              ]
              {\displaystyle {\displaystyle [a\_{1},a\_{2}]}}
                 and
            * [

              b

              1
              ,

              b

              2
              ]
              {\displaystyle {\displaystyle [b\_{1},b\_{2}]}}
              ;
            * then a value

              s
              {\displaystyle {\displaystyle s}}
                 in range

              [

              a

              1
              ,

              a

              2
              ]
              {\displaystyle {\displaystyle [a\_{1},a\_{2}]}}
            * is linearly mapped to a value

              t
              {\displaystyle {\displaystyle t}}
                 in range

              [

              b

              1
              ,

              b

              2
              ]
              {\displaystyle {\displaystyle [b\_{1},b\_{2}]}}

  where:

:   :   :   * t
              =

              b

              1
              +

              (
              s
              −

              a

              1
              )
              (

              b

              2
              −

              b

              1
              )

              (

              a

              2
              −

              a

              1
              )
              {\displaystyle {\displaystyle t=b\_{1}+{(s-a\_{1})(b\_{2}-b\_{1}) \over (a\_{2}-a\_{1})}}}

Task

Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.

Use this function to map values from the range    `[0, 10]`    to the range    `[-1, 0].`

Extra credit

Show additional idiomatic ways of performing the mapping, using tools available to the language.

[Assistant]
(formerly Perl 6)
Return a closure that does the mapping without have to supply the ranges every time.

```
sub getmapper(Range $a, Range  $b) {
  my ($a1, $a2) = $a.bounds;
  my ($b1, $b2) = $b.bounds;
  return -> $s { $b1 + (($s-$a1) * ($b2-$b1) / ($a2-$a1)) }
}

my &mapper = getmapper(0 .. 10, -1 .. 0);
for ^11 -> $x {say "$x maps to &mapper($x)"}

```

Output:

```
0 maps to -1
1 maps to -0.9
2 maps to -0.8
3 maps to -0.7
4 maps to -0.6
5 maps to -0.5
6 maps to -0.4
7 maps to -0.3
8 maps to -0.2
9 maps to -0.1
10 maps to 0
```


[User]
Task

Generate contours for a two-dimensional scalar field.

See: Marching squares

[Assistant]
**Translation of**: Phix

```
# 20220708 Raku programming solution

enum <E N W S>;
my (@dx,@dy) := (1,0,-1,0), (0,-1,0,1);
my \example   = ((0, 0, 0, 0, 0),
                 (0, 0, 0, 0, 0),
                 (0, 0, 1, 1, 0),
                 (0, 0, 1, 1, 0),
                 (0, 0, 0, 1, 0),
                 (0, 0, 0, 0, 0));

printf("X: %d, Y: %d, Path: %s\n", identifyPerimeter(example));

sub identifyPerimeter(\data) {

   my (\height,\width) = { .elems, .first.elems }(data);

   for ^width X ^height -> (\x,\y) {
      if data[y;x] {
         my ($cx,$cy,$directions,$previous) = x, y;
         repeat {
            my $mask;
            for (0,0,1),(1,0,2),(0,1,4),(1,1,8) -> (\dx,\dy,\b) {
	       my ($mx,$my) = $cx+dx,$cy+dy;
	       $mask += b if all $mx>1, $my>1, data[$my-1;$mx-1]
            }
            given do given $mask {
               when * ∈ ( 1,  5, 13 ) { N }
               when * ∈ ( 2,  3,  7 ) { E }
               when * ∈ ( 4, 12, 14 ) { W }
               when * ∈ ( 8, 10, 11 ) { S }
               when * ∈ (     6     ) { $previous == N ?? W !! E }
               when * ∈ (     9     ) { $previous == E ?? N !! S }
            } {
	       $directions ~= $previous = $_ ;
	       ($cx,$cy) <<+=<< (@dx[.value], @dy[.value])
	    }
         } until $cx==x and $cy==y ;
         return x, -y, $directions
      }
   }
   return -1, -1, "Not found!"
}

```

Output is the same as the Phix entry.


[User]
This task is about coding a Text Generator using Markov Chain algorithm.

A Markov chain algorithm basically determines the next most probable suffix word for a given prefix.

To do this, a Markov chain program typically breaks an input text (training text) into a series of words,
then by sliding along them in some fixed sized window, storing the first N words as a prefix and then
the N + 1 word as a member of a list to choose from randomly for the suffix.

As an example, take this text with N = 2:

```
now he is gone she said he is gone for good

```

this would build the following table:

```
PREFIX               SUFFIX
now he               is
he is                gone, gone
is gone              she, for
gone she             said
she said             he
said he              is
gone for             good
for good             (empty) if we get at this point, the program stops generating text

```

To generate the final text choose a random PREFIX, if it has more than one SUFFIX, get one at random,
create the new PREFIX and repeat until you have completed the text.

Following our simple example, N = 2, 8 words:

```
random prefix: gone she
suffix: said
new prefix: she + said
new suffix: he
new prefix: said + he
new suffix: is
... and so on

gone she said he is gone she said

```

The bigger the training text, the better the results.
You can try this text here: alice\_oz.txt

Create a program that is able to handle keys of any size (I guess keys smaller than 2 words would be
pretty random text but...) and create output text also in any length.
Probably you want to call your program passing those numbers as parameters. Something like: markov( "text.txt", 3, 300 )

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2017-01

```
unit sub MAIN ( :$text=$*IN, :$n=2, :$words=100, );

sub add-to-dict ( $text, :$n=2, ) {
    my @words = $text.words;
    my @prefix = @words.rotor: $n => -$n+1;

    (%).push: @prefix Z=> @words[$n .. *]
}

my %dict = add-to-dict $text, :$n;
my @start-words = %dict.keys.pick.words;
my @generated-text = lazy |@start-words, { %dict{ "@_[ *-$n .. * ]" }.pick } ...^ !*.defined;

put @generated-text.head: $words;

```

```
>raku markov.raku <alice_oz.txt --n=3 --words=200
Scarecrow. He can't hurt the straw. Do let me carry that basket for you. I shall not mind it, for I can't get tired. I'll tell you what I think, said the little man. Give me two or three pairs of tiny white kid gloves: she took up the fan and gloves, and, as the Lory positively refused to tell its age, there was no use in saying anything more till the Pigeon had finished. 'As if it wasn't trouble enough hatching the eggs,' said the Pigeon; 'but I must be very careful. When Oz gives me a heart of course I needn't mind so much. They were obliged to camp out that night under a large tree in the wood,' continued the Pigeon, raising its voice to a whisper. He is more powerful than they themselves, they would surely have destroyed me. As it was, I lived in deadly fear of them for many years; so you can see for yourself. Indeed, a jolly little clown came walking toward them, and Dorothy could see that in spite of all her coaxing. Hardly knowing what she did, she picked up a little bit of stick, and held it out to

```


[User]
Create a simple version of the board game:   Mastermind.

It must be possible to:

:   * choose the number of colors will be used in the game (2 - 20)
    * choose the color code length (4 - 10)
    * choose the maximum number of guesses the player has (7 - 20)
    * choose whether or not colors may be repeated in the code

The (computer program) game should display all the player guesses and the results of that guess.

Display (just an idea):

:   :   :   :   :   :   | Feature | Graphic Version | Text Version |
                        | --- | --- | --- |
                        | Player guess | Colored circles | Alphabet letters |
                        | Correct color & position | Black circle | X |
                        | Correct color | White circle | O |
                        | None | Gray circle | - |

A text version example:        1.   ADEF   -   XXO-

Translates to:

the first guess;

the four colors (ADEF);

result:

:   :   :   :   two correct colors and spot,
            :   one correct color/wrong spot, one color isn't in the code.

Happy coding!

Related tasks

* Bulls and cows
* Bulls and cows/Player
* Guess the number
* Guess the number/With Feedback

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.01

By default, plays classic Mastermind using letters in place of colors. ( 4 chosen from 6, no repeats, 10 guess limit. ) Pass in parameters to modify the game. Enter a string of --length (default 4) letters with or without spaces. Guesses accept lower or upper case.

```
sub MAIN (
    Int :$colors  where 1 < * < 21 = 6,  Int :$length  where 3 < * < 11 = 4,
    Int :$guesses where 7 < * < 21 = 10, Bool :$repeat = False
  ) {
    my @valid = ('A' .. 'T')[^$colors];
    my $puzzle = $repeat ?? @valid.roll($length) !! @valid.pick($length);
    my @guesses;

    my $black = '●';
    my $white = '○';

    loop {
        clearscr();
        say header();
        printf " %{$length * 2}s :: %s\n", @guesses[$_][0], @guesses[$_][1] for ^@guesses;
        say '';
        lose() if @guesses == $guesses;
        my $guess = get-guess();
        next unless $guess.&is-valid;
        my $score = score($puzzle, $guess);
        win() if $score eq ($black xx $length).join: ' ';
        @guesses.push: [$guess, $score];
    }

    sub header {
        my $num = $guesses - @guesses;
        qq:to/END/;
        Valid letter, but wrong position: ○ - Correct letter and position: ●
        Guess the {$length} element sequence containing the letters {@valid}
        Repeats are {$repeat ?? '' !! 'not '}allowed. You have $num guess{ $num == 1 ?? '' !! 'es'} remaining.
        END
    }

    sub score ($puzzle, $guess) {
        my @score;
        for ^$length {
            if $puzzle[$_] eq $guess[$_] {
                @score.push: $black;
            }
            elsif $puzzle[$_] eq any(@$guess) {
                @score.push: $white;
            }
            else {
                @score.push('-');
            }
        }
        @score.sort.reverse.join: ' ';
    }

    sub clearscr { $*KERNEL ~~ /'win32'/ ?? run('cls') !! run('clear') }

    sub get-guess { (uc prompt 'Your guess?: ').comb(/@valid/) }

    sub is-valid (@guess) { so $length == @guess }

    sub win  { say 'You Win! The correct answer is: ', $puzzle; exit }

    sub lose { say 'Too bad, you ran out of guesses. The solution was: ', $puzzle; exit }
}

```

Sample output:

```
Valid letter, but wrong position: ○ - Correct letter and position: ●
Guess the 4 element sequence containing the letters A B C D E F
Repeats are not allowed. You have 5 guesses remaining.

  A B C D :: ○ ○ ○ -
  C A B E :: ● ○ ○ -
  D A E F :: ● ○ - -
  B A E C :: ● ○ ○ -
  D E B C :: ○ ○ ○ ○

Your guess?: cdeb
You Win! The correct answer is: (C D E B)
```


[User]
Problem

Using the most straightforward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1\*n2\*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved.

For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a Catalan number, and grows exponentially with the number of factors.

Here is an example of computation of the total cost, for matrices A(5,6), B(6,3), C(3,1):

* AB costs 5\*6\*3=90 and produces a matrix of dimensions (5,3), then (AB)C costs 5\*3\*1=15. The total cost is 105.
* BC costs 6\*3\*1=18 and produces a matrix of dimensions (6,1), then A(BC) costs 5\*6\*1=30. The total cost is 48.

In this case, computing (AB)C requires more than twice as many operations as A(BC). The difference can be much more dramatic in real cases.

Task

Write a function which, given a list of the successive dimensions of matrices A1, A2... An, of arbitrary length, returns the optimal way to compute the matrix product, and the total cost. Any sensible way to describe the optimal solution is accepted. The input list does not duplicate shared dimensions: for the previous example of matrices A,B,C, one will only pass the list [5,6,3,1] (and *not* [5,6,6,3,3,1]) to mean the matrix dimensions are respectively (5,6), (6,3) and (3,1). Hence, a product of n matrices is represented by a list of n+1 dimensions.

Try this function on the following two lists:

* [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
* [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]

To solve the task, it's possible, but not required, to write a function that enumerates all possible ways to parenthesize the product. This is not optimal because of the many duplicated computations, and this task is a classic application of dynamic programming.

See also Matrix chain multiplication on Wikipedia.

[Assistant]
(formerly Perl 6)
This example is based on Moritz Lenz's code, written for Carl Mäsak's Perl 6 Coding Contest, in 2010. Slightly simplified, it fulfills the Rosetta Code task as well.

```
sub matrix-mult-chaining(@dimensions) {
    my @cp;
    # @cp has a dual function:
    # * the upper triangle of the diagonal matrix stores the cost (c) for
    #   multiplying matrices $i and $j in @cp[$j][$i], where $j > $i
    # * the lower triangle stores the path (p) that was used for the lowest cost
    #   multiplication to get from $i to $j.

    # a matrix never needs to be multiplied with itself, so it has cost 0
    @cp[$_][$_] = 0 for @dimensions.keys;
    my @path;

    my $n = @dimensions.end;
    for 1 .. $n -> $chain-length {
        for 0 .. $n - $chain-length - 1 -> $start {
            my $end = $start + $chain-length;
            @cp[$end][$start] = Inf;  # until we find a better connection
            for $start .. $end - 1 -> $step {
                my $new-cost = @cp[$step][$start]
                             + @cp[$end][$step + 1]
                             + [*] @dimensions[$start, $step+1, $end+1];
                if $new-cost < @cp[$end][$start] {
                    @cp[$end][$start] = $new-cost; # cost
                    @cp[$start][$end] = $step;     # path
                }
            }
       }
    }

    sub find-path(Int $start, Int $end) {
        if $start == $end {
            take 'A' ~ ($start + 1);
        } else {
            take '(';
            find-path($start, @cp[$start][$end]);
            find-path(@cp[$start][$end] + 1, $end);
            take ')';
        }
    }

   return @cp[$n-1][0], gather { find-path(0, $n - 1) }.join;
}

say matrix-mult-chaining(<1 5 25 30 100 70 2 1 100 250 1 1000 2>);
say matrix-mult-chaining(<1000 1 500 12 1 700 2500 3 2 5 14 10>);

```

Output:

```
(38120 ((((((((A1A2)A3)A4)A5)A6)A7)(A8(A9A10)))(A11A12)))
(1773740 (A1((((((A2A3)A4)(((A5A6)A7)A8))A9)A10)A11)))
```


[User]
Implement the Matrix Digital Rain visual effect from the movie "The Matrix" as described in Wikipedia.

Provided is a reference implementation in Common Lisp to be run in a terminal.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.11

Kind-of cheap and cheesy, but what the heck... Probably will only work in a POSIX compatible terminal. Runs until you hit ^C to exit.

The "lightning" effect is actually a bug, but I liked it so I kept it.

```
# clean up on exit, reset ANSI codes, scroll, re-show the cursor & clear screen
signal(SIGINT).tap: { print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25h"; exit(0) }

# a list of glyphs to use
my @codes = flat 'Α' .. 'Π', 'Ѐ' .. 'ѵ', 'Ҋ' .. 'ԯ', 'Ϣ' .. 'ϯ', 'ｦ'.. 'ﾝ',
                 'Ⲁ' .. '⳩', '∀' .. '∗', '℀' .. '℺', '⨀' .. '⫿';

# palette of gradient ANSI foreground colors
my @palette = flat  "\e[38;2;255;255;255m", (255,245 … 30).map({"\e[38;2;0;$_;0m"}),
              "\e[38;2;0;25;0m" xx 75;

my @screen; # buffer to hold glyphs
my @rotate; # palette rotation position buffer

my ($rows, $cols) = qx/stty size/.words; # get the terminal size
init($rows, $cols); # set up the screen buffer and palette offsets

my $size-check;

print "\e[?25l\e[48;5;232m"; # hide the cursor, set the background color

loop {
     if ++$size-check %% 20 {                         # periodically check for
         my ($r, $c) = qx/stty size/.words;           # resized terminal and
         init($r, $c) if $r != $rows or $c != $cols;  # re-initialize screen buffer
         $size-check = 0
     }
     print "\e[1;1H";                                 # set cursor to top left
     print join '', (^@screen).map: {
         @rotate[$_] = (@rotate[$_] + 1) % +@palette; # rotate the palettes
         flat @palette[@rotate[$_]], @screen[$_]      # and print foreground, glyph
     }
     @screen[(^@screen).pick] = @codes.roll for ^30;  # replace some random glyphs
}

sub init ($r, $c) {
    @screen = @codes.roll($r * $c);
    ($rows, $cols) = $r, $c;
    my @offset = (^@palette).pick xx $cols;
    for ^$rows -> $row {
        @rotate[$row * $cols ..^ $row * $cols + $cols] = @offset;
        # for no "lightning" effect, add   '1 + '  ↓ here: (1 + $_ % 3)
        @offset = (^@offset).map: {(@offset[$_] - ($_ % 3)) % +@palette};
    }
}

```

Sample output:

See matrix-digital-rain-perl6.png (offsite png image)


[User]
Task

Multiply two matrices together.

They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.

[Assistant]
(formerly Perl 6)

**Translation of**: Perl 5

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

There are three ways in which this example differs significantly from the original Perl 5 code. These are not esoteric differences; all three of these features typically find heavy use in Raku.

First, we can use a real signature that can bind two arrays as arguments, because the default in Raku is not to flatten arguments unless the signature specifically requests it.
We don't need to pass the arrays with backslashes because the binding choice is made lazily
by the signature itself at run time; in Perl 5 this choice must be made at compile time.
Also, we can bind the arrays to formal parameters that are really lexical variable names; in Perl 5 they can only be bound to global array objects (via a typeglob assignment).

Second, we use the X cross operator in conjunction with a two-parameter closure to avoid writing
nested loops. The X cross operator, along with Z, the zip operator, is a member of a class of operators that expect lists on both sides, so we call them "list infix" operators. We tend to define these operators using capital letters so that they stand out visually from the lists on both sides. The cross operator makes every possible combination of the one value from the first list followed by one value from the second. The right side varies most rapidly, just like an inner loop. (The X and Z operators may both also be used as meta-operators, Xop or Zop, distributing some other operator "op" over their generated list. All metaoperators in Raku may be applied to user-defined operators as well.)

Third is the use of prefix ^ to generate a list of numbers in a range. Here it is
used on an array to generate all the indexes of the array. We have a way of indicating a range by the infix .. operator, and you can put a ^ on either end to exclude that endpoint. We found ourselves writing 0 ..^ @a so often that we made ^@a a shorthand for that. It's pronounced "upto". The array is evaluated in a numeric context, so it returns the number of elements it contains, which is exactly what you want for the exclusive limit of the range.

```
sub mmult(@a,@b) {
    my @p;
    for ^@a X ^@b[0] -> ($r, $c) {
        @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b;
    }
    @p;
}

my @a = [1,  1,  1,   1],
        [2,  4,  8,  16],
        [3,  9, 27,  81],
        [4, 16, 64, 256];

my @b = [  4  , -3  ,  4/3,  -1/4 ],
        [-13/3, 19/4, -7/3,  11/24],
        [  3/2, -2  ,  7/6,  -1/4 ],
        [ -1/6,  1/4, -1/6,   1/24];

.say for mmult(@a,@b);
```

Output:

```
[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
```

Note that these are not rounded values, but exact, since all the math was done in rationals.
Hence we need not rely on format tricks to hide floating-point inaccuracies.

Just for the fun of it, here's a functional version that uses no temp variables or side effects.
Some people will find this more readable and elegant, and others will, well, not.

```
sub mmult(\a,\b) {
    [
        for ^a -> \r {
            [
                for ^b[0] -> \c {
                    [+] a[r;^b] Z* b[^b;c]
                }
            ]
        }
    ]
}
```

Here we use Z with an "op" of \*, which is a zip with multiply. This, along with the [+] reduction operator, replaces the inner loop. We chose to split the outer X loop back into two loops to make it convenient to collect each subarray value in [...]. It just collects all the returned values from the inner loop and makes an array of them. The outer loop simply returns the outer array.

For conciseness, the above could be written as:

```
multi infix:<×> (@A, @B) {
	@A.map: -> @a { do [+] @a Z× @B[*;$_] for ^@B[0] }
}
```

Which overloads the built-in `×` operator for `Positional` operands. You’ll notice we are using `×` inside of the definition; since the arguments there are `Scalar`, it multiplies two numbers. Also, `do` is an alternative to parenthesising the loop for getting its result.

**Works with**: Rakudo version 2022.07-3

Here is a more functional version, expressing the product of two matrices as the cross dot product of the first matrix with the transpose of the second :

```
sub infix:<·> { [+] @^a Z* @^b }
sub infix:<×>(@A, @B) { (@A X· [Z] @B).rotor(@B) }
```


[User] Transpose an arbitrarily sized rectangular Matrix.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

```
# Transposition can be done with the reduced zip meta-operator
# on list-of-lists data structures

say [Z] (<A B C D>, <E F G H>, <I J K L>);

# For native shaped arrays, a more traditional procedure of copying item-by-item
# Here the resulting matrix is also a native shaped array

my @a[3;4] =
  [
    [<A B C D>],
    [<E F G H>],
    [<I J K L>],
  ];

(my $n, my $m) = @a.shape;
my @b[$m;$n];
for ^$m X ^$n -> (\i, \j) {
   @b[i;j] = @a[j;i];
}

say @b;
```

Output:

```
((A E I) (B F J) (C G K) (D H L))
[[A E I] [B F J] [C G K] [D H L]]
```


[User]
Task

Draw a square matrix which has 1's on both diagonals but 0's elsewhere.

 If you can please use GUI

### See also

* Four sides of square
* Mosaic matrix

[Assistant]
```
sub dual-diagonal($n) { ([1, |(0 xx $n-1)], *.rotate(-1) … *[*-1]).map: { [$_ Z|| .reverse] } }

.say for dual-diagonal(6);
say '';
.say for dual-diagonal(7);

```

Output:

```
[1 0 0 0 0 1]
[0 1 0 0 1 0]
[0 0 1 1 0 0]
[0 0 1 1 0 0]
[0 1 0 0 1 0]
[1 0 0 0 0 1]

[1 0 0 0 0 0 1]
[0 1 0 0 0 1 0]
[0 0 1 0 1 0 0]
[0 0 0 1 0 0 0]
[0 0 1 0 1 0 0]
[0 1 0 0 0 1 0]
[1 0 0 0 0 0 1]
```


[User]
Most programming languages have a built-in implementation of exponentiation for integers and reals only.

Task

Demonstrate how to implement matrix exponentiation as an operator.

[Assistant]
(formerly Perl 6)

```
subset SqMat of Array where { .elems == all(.[]».elems) }

multi infix:<*>(SqMat $a, SqMat $b) {[
    for ^$a -> $r {[
        for ^$b[0] -> $c {
            [+] ($a[$r][] Z* $b[].map: *[$c])
        }
    ]}
]}

multi infix:<**> (SqMat $m, Int $n is copy where { $_ >= 0 }) {
    my $tmp = $m;
    my $out = [for ^$m -> $i { [ for ^$m -> $j { +($i == $j) } ] } ];
    loop {
        $out = $out * $tmp if $n +& 1;
        last unless $n +>= 1;
        $tmp = $tmp * $tmp;
    }

    $out;
}

multi show (SqMat $m) {
    my $size = $m.map( *.list».chars ).flat.max;
    say .fmt("%{$size}s", ' ') for $m.list;
}

my @m = [1, 2, 0],
        [0, 3, 1],
        [1, 0, 0];

for 0 .. 10 -> $order {
    say "### Order $order";
    show @m ** $order;
}

```

Output:

```
### Order 0
1 0 0
0 1 0
0 0 1
### Order 1
1 2 0
0 3 1
1 0 0
### Order 2
1 8 2
1 9 3
1 2 0
### Order 3
 3 26  8
 4 29  9
 1  8  2
### Order 4
11 84 26
13 95 29
 3 26  8
### Order 5
 37 274  84
 42 311  95
 11  84  26
### Order 6
 121  896  274
 137 1017  311
  37  274   84
### Order 7
 395 2930  896
 448 3325 1017
 121  896  274
### Order 8
 1291  9580  2930
 1465 10871  3325
  395  2930   896
### Order 9
 4221 31322  9580
 4790 35543 10871
 1291  9580  2930
### Order 10
 13801 102408  31322
 15661 116209  35543
  4221  31322   9580
```


[User]
Task

Find maximum difference between adjacent elements of list.

The list may have negative values, zero values, real numbers.

List   =    [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]

Output would be   (which could have more verbiage):

```
  1,8 ==> 7
  2,9 ==> 7
  10,3 ==> 7

```

[Assistant]
```
sub max-diff (*@list) {
   return 0 if +@list < 2;
   my $max = @list.rotor(2 => -1).max({ (.[0] - .[1]).abs }).map( (* - *).abs )[0];
   "$max @ elements { @list.rotor(2 => -1).grep( { (.[0] - .[1]).abs == $max } ).gist }"
}

sub min-diff (*@list) {
   return 0 if +@list < 2;
   my $min = @list.rotor(2 => -1).min({ (.[0] - .[1]).abs }).map( (* - *).abs )[0];
   "$min @ elements { @list.rotor(2 => -1).grep( { (.[0] - .[1]).abs == $min } ).gist }"
}

sub avg-diff (*@list) { (+@list > 1) ?? (@list.sum / +@list) !! 0 }

# TESTING

for (
      [ 1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3 ]
     ,[(rand × 1e6) xx 6]
     ,[ e, i, τ, π, ∞ ]
     ,[ 1.9+3.7i, 2.07-13.2i, 0.2+-2.2i, 4.6+0i ]
     ,[ 6 ]
     ,[]
     ,[<One Two Three>]
    )
-> @list {
    say 'List: ', ~ @list.raku;
    for ('  Maximum', &max-diff ,'  Minimum', &min-diff, '  Average', &avg-diff)
    -> $which, &sub {
        say "$which distance between list elements: " ~ &sub(@list);
    }
    say '';
}

```

Output:

```
List: [1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]
  Maximum distance between list elements: 7 @ elements ((1 8) (2 9) (10 3))
  Minimum distance between list elements: 0 @ elements ((1 1))
  Average distance between list elements: 3.658824

List: [480470.3324944039e0, 719954.3173377671e0, 648221.5674277907e0, 340053.78585537826e0, 540629.6741075241e0, 4336.700602958543e0]
  Maximum distance between list elements: 536292.9735045655 @ elements ((540629.6741075241 4336.700602958543))
  Minimum distance between list elements: 71732.74990997638 @ elements ((719954.3173377671 648221.5674277907))
  Average distance between list elements: 455611.06297097047

List: [2.718281828459045e0, <0+1i>, 6.283185307179586e0, 3.141592653589793e0, Inf]
  Maximum distance between list elements: Inf @ elements ((3.141592653589793 Inf))
  Minimum distance between list elements: 2.896386731590008 @ elements ((2.718281828459045 0+1i))
  Average distance between list elements: Inf+0.2i

List: [<1.9+3.7i>, <2.07-13.2i>, <0.2-2.2i>, <4.6+0i>]
  Maximum distance between list elements: 16.900855007957436 @ elements ((1.9+3.7i 2.07-13.2i))
  Minimum distance between list elements: 4.919349550499537 @ elements ((0.2-2.2i 4.6+0i))
  Average distance between list elements: 2.1925-2.925i

List: [6]
  Maximum distance between list elements: 0
  Minimum distance between list elements: 0
  Average distance between list elements: 0

List: []
  Maximum distance between list elements: 0
  Minimum distance between list elements: 0
  Average distance between list elements: 0

List: ["One", "Two", "Three"]
Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏Two' (indicated by ⏏)
  in sub max-diff at listdiff.p6 line 3
  in block  at listdiff.p6 line 33
  in block <unit> at listdiff.p6 line 20

```


[User]
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:

```
                          55
                        94 48
                       95 30 96
                     77 71 26 67

```

One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.

Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.

Task

Find the maximum total in the triangle below:

```
                          55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93

```

Such numbers can be included in the solution code, or read from a "triangle.txt" file.

This task is derived from the Euler Problem #18.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

The Z+ and Zmax are examples of the zipwith metaoperator. Note also we can use the Zmax metaoperator form because max is define as an infix in Perl 6.

```
my $triangle = q|         55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93|;

my @rows = $triangle.lines.map: { [.words] }
while @rows > 1 {
    my @last := @rows.pop;
    @rows[*-1] = (@rows[*-1][] Z+ (@last Zmax @last[1..*])).List;
}
put @rows;

# Here's a more FPish version. We define our own operator and the use it in the reduction metaoperator form, [op], which turns any infix into a list operator.
sub infix:<op>(@a,@b) { (@a Zmax @a[1..*]) Z+ @b }
put [op] $triangle.lines.reverse.map: { [.words] }

# Or, instead of using reverse, one could also define the op as right-associative.
sub infix:<rop>(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b[1..*]) }
put [rop] $triangle.lines.map: { [.words] }

```

Output:

```
1320
1320
1320
```


[User]
The ancient Maya people had two somewhat distinct calendar systems.

In somewhat simplified terms, one is a cyclical calendar known as **The Calendar Round**,
that meshes several sacred and civil cycles; the other is an offset calendar
known as **The Long Count**, similar in many ways to the Gregorian calendar.

**The Calendar Round**

**The Calendar Round** has several intermeshing sacred and civil cycles that uniquely identify a specific date in an approximately 52 year cycle.

**The Tzolk’in**

The sacred cycle in the Mayan calendar round was called the **Tzolk’in**. The **Tzolk'in** has a cycle of 20 day names:

```
   Imix’
   Ik’
   Ak’bal
   K’an
   Chikchan
   Kimi
   Manik’
   Lamat
   Muluk
   Ok
   Chuwen
   Eb
   Ben
   Hix
   Men
   K’ib’
   Kaban
   Etz’nab’
   Kawak
   Ajaw

```

Intermeshed with the named days, the **Tzolk’in** has a cycle of 13 numbered days; 1
through 13. Every day has both a number and a name that repeat in a 260 day cycle.

For example:

```
   1 Imix’
   2 Ik’
   3 Ak’bal
   ...
   11 Chuwen
   12 Eb
   13 Ben
   1 Hix
   2 Men
   3 K’ib’
   ... and so on.

```

**The Haab’**

The Mayan civil calendar is called the **Haab’**. This calendar has 365 days per
year, and is sometimes called the ‘vague year.’ It is substantially the same as
our year, but does not make leap year adjustments, so over long periods of time,
gets out of synchronization with the seasons. It consists of 18 months with 20 days each,
and the end of the year, a special month of only 5 days, giving a total of 365.
The 5 days of the month of **Wayeb’** (the last month), are usually considered to be
a time of bad luck.

Each month in the **Haab’** has a name. The Mayan names for the civil months are:

```
   Pop
   Wo’
   Sip
   Sotz’
   Sek
   Xul
   Yaxk’in
   Mol
   Ch’en
   Yax
   Sak’
   Keh
   Mak
   K’ank’in
   Muwan
   Pax
   K’ayab
   Kumk’u
   Wayeb’ (Short, "unlucky" month)

```

The months function very much like ours do. That is, for any given month we
count through all the days of that month, and then move on to the next month.

Normally, the day **1 Pop** is considered the first day of the civil year, just as **1 January**
is the first day of our year. In 2019, **1 Pop** falls on **April 2nd**. But,
because of the leap year in 2020, **1 Pop** falls on **April 1st** in the years 2020-2023.

The only really unusual aspect of the **Haab’** calendar is that, although there are
20 (or 5) days in each month, the last day of the month is not called
the 20th (5th). Instead, the last day of the month is referred to as the
‘seating,’ or ‘putting in place,’ of the next month. (Much like how in our
culture, December 24th is Christmas Eve and December 31st is 'New-Years Eve'.) In
the language of the ancient Maya, the word for seating was **chum**, So you might
have:

```
   ...
   18 Pop (18th day of the first month)
   19 Pop (19th day of the first month)
   Chum Wo’ (20th day of the first month)
   1 Wo’ (1st day of the second month)
   ... and so on.

```

Dates for any particular day are a combination of the **Tzolk’in** sacred date,
and **Haab’** civil date. When put together we get the **“Calendar Round.”**

**Calendar Round** dates always have two numbers and two names, and they are
always written in the same order:

```
   (1) the day number in the Tzolk’in
   (2) the day name in the  Tzolk’in
   (3) the day of the month in the Haab’
   (4) the month name in the Haab’

```

A calendar round is a repeating cycle with a period of just short of 52
Gregorian calendar years. To be precise: it is 52 x 365 days. (No leap days)

**Lords of the Night**

A third cycle of nine days honored the nine **Lords of the Night**; nine deities
that were associated with each day in turn. The names of the nine deities are
lost; they are now commonly referred to as **G1** through **G9**. The Lord of the Night
may or may not be included in a Mayan date, if it is, it is typically
just the appropriate **G(*x*)** at the end.

**The Long Count**

Mayans had a separate independent way of measuring time that did not run in
cycles. (At least, not on normal human scales.) Instead, much like our yearly
calendar, each day just gets a little further from the starting point. For the
ancient Maya, the starting point was the ‘creation date’ of the current world.
This date corresponds to our date of August 11, 3114 B.C. Dates are calculated
by measuring how many days have transpired since this starting date; This is
called **“The Long Count.”** Rather than just an absolute count of days, the long
count is broken up into unit blocks, much like our calendar has months, years,
decades and centuries.

```
   The basic unit is a k’in - one day.
   A 20 day month is a winal.
   18 winal (360 days) is a tun - sometimes referred to as a short year.
   20 short years (tun) is a k’atun
   20 k’atun is a bak’tun

```

There are longer units too:

```
   Piktun == 20 Bak’tun (8,000 short years)
   Kalabtun  == 20 Piktun (160,000 short years)
   Kinchiltun  == 20 Kalabtun (3,200,000 short years)

```

For the most part, the Maya only used the blocks of time up to the **bak’tun**. One
**bak’tun** is around 394 years, much more than a human life span, so that was all
they usually needed to describe dates in this era, or this world. It is worth
noting, the two calendars working together allow much more accurate and reliable
notation for dates than is available in many other calendar systems; mostly due
to the pragmatic choice to make the calendar simply track days, rather than
trying to make it align with seasons and/or try to conflate it with the notion
of time.

**Mayan Date correlations**

There is some controversy over finding a correlation point between the Gregorian
and Mayan calendars. The Gregorian calendar is full of jumps and skips to keep
the calendar aligned with the seasons so is much more difficult to work with.
The most commonly used correlation
factor is The **GMT: 584283**. Julian 584283 is a day count corresponding **Mon, Aug 11, 3114 BCE**
in the Gregorian calendar, and the final day in the last Mayan long count
cycle: 13.0.0.0.0 which is referred to as "the day of creation" in the Mayan
calendar. There is nothing in known Mayan writing or history that suggests that
a long count "cycle" resets *every* 13 **bak’tun**. Judging by their other practices,
it would make much more sense for it to reset at 20, if at all.

The reason there was much interest at all, outside historical scholars, in
the Mayan calendar is that the long count recently (relatively speaking) rolled over to 13.0.0.0.0 (the same as the historic day of creation Long Count date) on Fri,
Dec 21, 2012 (using the most common GMT correlation factor), prompting conspiracy
theorists to predict a cataclysmic "end-of-the-world" scenario.

**Excerpts taken from, and recommended reading:**

* *From the website of the Foundation for the Advancement of Meso-America Studies, Inc.*
  Pitts, Mark. The complete Writing in Maya Glyphs Book 2 – Maya Numbers and the Maya Calendar. 2009. Accessed 2019-01-19.
  http://www.famsi.org/research/pitts/MayaGlyphsBook2.pdf

* wikipedia: Maya calendar

* wikipedia: Mesoamerican Long Count calendar

**The Task:**

Write a reusable routine that takes a Gregorian date and returns the equivalent date in Mayan in the Calendar Round and the Long Count. At a minimum, use the GMT correlation. *If desired, support other correlations.*

Using the GMT correlation, the following Gregorian and Mayan dates are equivalent:

```
  Dec 21, 2012 (Gregorian)
  4 Ajaw 3 K’ank’in G9 (Calendar round)
  13.0.0.0.0 (Long count)

```

Support looking up dates for at least 50 years before and after the Mayan Long Count **13 bak’tun** rollover: *Dec 21, 2012*. *(Will require taking into account Gregorian leap days.)*

Show the output here, on this page, for *at least* the following dates:

*(Note that these are in ISO-8601 format: YYYY-MM-DD. There is no requirement to use ISO-8601 format in your program, but if you differ, make a note of the expected format.)*

```
   2004-06-19
   2012-12-18
   2012-12-21
   2019-01-19
   2019-03-27
   2020-02-29
   2020-03-01

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.12

```
my @sacred = <Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok
              Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw>;

my @civil = <Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh
             Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’>;

my %correlation = :GMT({
    :gregorian(Date.new('2012-12-21')),
    :round([3,19,263,8]),
    :long(1872000)
});

sub mayan-calendar-round ($date) { .&tzolkin, .&haab given $date }

sub offset ($date, $factor = 'GMT') { Date.new($date) - %correlation{$factor}<gregorian> }

sub haab ($date, $factor = 'GMT') {
    my $index = (%correlation{$factor}<round>[2] + offset $date) % 365;
    my ($day, $month);
    if $index > 360 {
        $day = $index - 360;
        $month = @civil[18];
        if $day == 5 {
            $day = 'Chum';
            $month = @civil[0];
        }
    } else {
        $day = $index % 20;
        $month = @civil[$index div 20];
        if $day == 0 {
            $day = 'Chum';
            $month = @civil[(1 + $index) div 20];
        }
    }
    $day, $month
}

sub tzolkin ($date, $factor = 'GMT') {
    my $offset = offset $date;
    1 + ($offset + %correlation{$factor}<round>[0]) % 13,
    @sacred[($offset + %correlation{$factor}<round>[1]) % 20]
}

sub lord ($date, $factor = 'GMT') {
    'G' ~ 1 + (%correlation{$factor}<round>[3] + offset $date) % 9
}

sub mayan-long-count ($date, $factor = 'GMT') {
    my $days = %correlation{$factor}<long> + offset $date;
    reverse $days.polymod(20,18,20,20);
}

# HEADER
say ' Gregorian   Tzolk’in         Haab’             Long           Lord of ';
say '   Date       # Name       Day Month            Count         the Night';
say '-----------------------------------------------------------------------';

# DATES
<
1963-11-21
2004-06-19
2012-12-18
2012-12-21
2019-01-19
2019-03-27
2020-02-29
2020-03-01
2071-05-16
>.map: -> $date {
    printf "%10s   %2s %-9s %4s %-10s     %-14s %6s\n", Date.new($date),
      flat mayan-calendar-round($date), mayan-long-count($date).join('.'), lord($date);
}

```

Output:

```
 Gregorian   Tzolk’in        Haab’              Long           Lord of
   Date       # Name       Day Month            Count         the Night
-----------------------------------------------------------------------
1963-11-21    3 Eb        Chum Keh            12.17.10.3.12      G9
2004-06-19    4 Ben         16 Sotz’          12.19.11.6.13      G7
2012-12-18    1 Kaban     Chum K’ank’in       12.19.19.17.17     G6
2012-12-21    4 Ajaw         3 K’ank’in       13.0.0.0.0         G9
2019-01-19    1 Ajaw        13 Muwan’         13.0.6.3.0         G6
2019-03-27    3 Manik’    Chum Wayeb’         13.0.6.6.7         G1
2020-02-29    4 Kimi        14 K’ayab         13.0.7.5.6         G7
2020-03-01    5 Manik’      15 K’ayab         13.0.7.5.7         G8
2071-05-16    1 Ok          18 Sip            13.2.19.4.10       G9
```


[User]
Task

Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche).

Mayan numbers

Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant
numeral at the top   (in the sense that decimal numbers are written left─to─right with the most significant
digit at the left).   This task will be using a left─to─right (horizontal) format,   mostly for familiarity and
readability,   and to conserve screen space (when showing the output) on this task page.

Mayan numerals

Mayan numerals   (a base─20 "digit" or glyph)   are written in two orientations,   this
task will be using the "vertical" format   (as displayed below).   Using the vertical format makes
it much easier to draw/construct the Mayan numerals (glyphs) with simple dots (**.**)
and hyphen (**-**);     (however, round bullets (**•**) and long dashes (**─**)
make a better presentation on Rosetta Code).

Furthermore, each Mayan numeral   (for this task)   is to be displayed as a
cartouche   (enclosed in a box)   to make it easier to parse (read);   the box may be
drawn with any suitable (ASCII or Unicode) characters that are presentable/visible in all web browsers.

Mayan numerals added to Unicode

Mayan numerals (glyphs) were added to the Unicode Standard in June of 2018   (this corresponds with
version 11.0).   But since most web browsers don't support them at this time,   this Rosetta Code
task will be constructing the glyphs with "simple" characters and/or ASCII art.

The "zero" glyph

The Mayan numbering system has the concept of   **zero**,   and should be shown by a glyph that represents
an upside─down (sea) shell,   or an egg.   The Greek letter **theta**   (**Θ**)   can be
used   (which more─or─less, looks like an
egg).   A   *commercial at*   symbol   (**@**)   could make a poor substitute.

Mayan glyphs (constructed)

The Mayan numbering system is
a   [vigesimal (base 20)]   positional numeral system.

The Mayan numerals   (and some random numbers)   shown in the   *vertical*   format would be shown as

```
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║    ║                            ║    ║    ║
      ║    ║                      ║ ∙  ║                            ║    ║    ║
 1──► ║    ║                11──► ║────║                      21──► ║    ║    ║
      ║ ∙  ║                      ║────║                            ║ ∙  ║ ∙  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║    ║                            ║    ║    ║
      ║    ║                      ║ ∙∙ ║                            ║    ║    ║
 2──► ║    ║                12──► ║────║                      22──► ║    ║    ║
      ║ ∙∙ ║                      ║────║                            ║ ∙  ║ ∙∙ ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║    ║                            ║    ║    ║
      ║    ║                      ║∙∙∙ ║                            ║    ║    ║
 3──► ║    ║                13──► ║────║                      40──► ║    ║    ║
      ║∙∙∙ ║                      ║────║                            ║ ∙∙ ║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║    ║                            ║    ║    ║
      ║    ║                      ║∙∙∙∙║                            ║    ║    ║
 4──► ║    ║                14──► ║────║                      80──► ║    ║    ║
      ║∙∙∙∙║                      ║────║                            ║∙∙∙∙║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║    ║                            ║    ║    ║
      ║    ║                      ║────║                            ║    ║    ║
 5──► ║    ║                15──► ║────║                      90──► ║    ║────║
      ║────║                      ║────║                            ║∙∙∙∙║────║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║ ∙  ║                            ║    ║    ║
      ║    ║                      ║────║                            ║    ║    ║
 6──► ║ ∙  ║                16──► ║────║                     100──► ║    ║    ║
      ║────║                      ║────║                            ║────║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║ ∙∙ ║                            ║    ║    ║
      ║    ║                      ║────║                            ║    ║    ║
 7──► ║ ∙∙ ║                17──► ║────║                     200──► ║────║    ║
      ║────║                      ║────║                            ║────║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╗
      ║    ║                      ║∙∙∙ ║                            ║    ║    ║
      ║    ║                      ║────║                     300──► ║────║    ║
 8──► ║∙∙∙ ║                18──► ║────║                            ║────║    ║
      ║────║                      ║────║                            ║────║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╝
      ╔════╗                      ╔════╗                            ╔════╦════╦════╗
      ║    ║                      ║∙∙∙∙║                            ║    ║    ║    ║
      ║    ║                      ║────║                     400──► ║    ║    ║    ║
 9──► ║∙∙∙∙║                19──► ║────║                            ║    ║    ║    ║
      ║────║                      ║────║                            ║ ∙  ║ Θ  ║ Θ  ║
      ╚════╝                      ╚════╝                            ╚════╩════╩════╝
      ╔════╗                      ╔════╦════╗                       ╔════╦════╦════╦════╗
      ║    ║                      ║    ║    ║                       ║    ║    ║    ║    ║
      ║    ║                      ║    ║    ║                       ║    ║    ║    ║    ║
10──► ║────║                20──► ║    ║    ║             16,000──► ║    ║    ║    ║    ║
      ║────║                      ║ ∙  ║ Θ  ║                       ║ ∙∙ ║ Θ  ║ Θ  ║ Θ  ║
      ╚════╝                      ╚════╩════╝                       ╚════╩════╩════╩════╝

```

Note that the Mayan numeral   **13**   in   *horizontal*   format would be shown as:

```
                                  ╔════╗
                                  ║  ││║
                                  ║ ∙││║
                            13──► ║ ∙││║        ◄─── this glyph form won't be used in this Rosetta Code task.
                                  ║ ∙││║
                                  ╚════╝

```

Other forms of cartouches (boxes) can be used for this task.

Task requirements
:   * convert the following decimal numbers to Mayan numbers:

    :   :   * 4,005
            * 8,017
            * 326,205
            * 886,205

    * show a   unique   *interesting/pretty/unusual/intriguing/odd/amusing/weird*   Mayan number
    * show all output here

Related tasks
:   * Roman numerals/Encode   ─── convert numeric values into Roman numerals
    * Roman numerals/Decode   ─── convert Roman numerals into Arabic numbers

See also
:   * The Wikipedia entry:   [Mayan numerals]

[Assistant]
(formerly Perl 6)

Just a matter of converting to base twenty, then divmod 5 each digit and map to the appropriate glyph. Most of this is display code to deal with the cartouche requirement.

I actually spent a little time looking into what exactly a Mayan cartouche was supposed to look like. The classic Mayan cartouche was kind of a rounded rectangle with three little semi-circles underneath. Kind of looks like a picture frame. In general, they were only used when expressing significant "holy" dates in the Mayan calender.

These don't particularly resemble the Mayan cartouche, more like mahjong tiles actually. It would have been *so* much easier and more compact if I could have put all the styling into a CSS file instead of inlining it, but oh well, it was entertaining to do.

```
### Formatting ###
my $t-style = '"border-collapse: separate; text-align: center; border-spacing: 3px 0px;"';
my $c-style = '"border: solid black 2px;background-color: #fffff0;border-bottom: double 6px;'~
  'border-radius: 1em;-moz-border-radius: 1em;-webkit-border-radius: 1em;'~
  'vertical-align: bottom;width: 3.25em;"';
my $joiner = '<br>';

sub display ($num, @digits) { join "\n", "\{| style=$t-style", "|+ $num", '|-', (|@digits.map: {"| style=$c-style | $_"}), '|}' }

### Logic ###

sub mayan ($int) { $int.polymod(20 xx *).reverse.map: *.polymod(5) }

my @output = <4005 8017 326205 886205 16160025 1081439556 503491211079>.map: {
  display $_, .&mayan.map: { [flat '' xx 3, '●' x .[0], '───' xx .[1], ('Θ' if !.[0,1].sum)].tail(4).join: $joiner }
}

say @output.join: "\n$joiner\n";

```

Output:

4005

|  |  |  |
| --- | --- | --- |
| ─── ─── | Θ | ─── |

8017

|  |  |  |  |
| --- | --- | --- | --- |
| ● | Θ | Θ | ●● ─── ─── ─── |

326205

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| ●● | Θ | ─── ─── ─── | ─── ─── | ─── |

886205

|  |  |  |  |  |
| --- | --- | --- | --- | --- |
| ─── | ─── ─── | ─── ─── ─── | ─── ─── | ─── |

16160025

|  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- |
| ─── | ● | Θ | Θ | ● | ─── |

1081439556

|  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- |
| ● ─── ─── ─── | ●● ─── ─── ─── | ●●● ─── ─── ─── | ●●●● ─── ─── ─── | ●●● ─── ─── ─── | ●● ─── ─── ─── | ● ─── ─── ─── |

503491211079

|  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| ●●●● ─── ─── ─── | ●●● ─── ─── | ●● ─── | ● | Θ | ● | ●● ─── | ●●● ─── ─── | ●●●● ─── ─── ─── |

Or, plain old text mode. Not as pretty, but still serviceable.

```
### Formatting ###
use Terminal::Boxer;
my $joiner = "\n";

sub display ($num, @digits) { "$num\n" ~ dd-box( :6cw, :4ch, @digits ) }

### Logic ###

sub mayan ($int) { $int.polymod(20 xx *).reverse.map: *.polymod(5) }

my @output = <4005 8017 326205 886205 16160025 1081439556 503491211079>.map: {
  display $_, .&mayan.map: { [flat '' xx 3, '●' x .[0], '────' xx .[1], ('Θ' if !.[0,1].sum)].tail(4).join: $joiner }
}

say @output.join: $joiner;

```

Output:

```
4005
╔══════╦══════╦══════╗
║      ║      ║      ║
║      ║      ║      ║
║ ──── ║      ║      ║
║ ──── ║   Θ  ║ ──── ║
╚══════╩══════╩══════╝

8017
╔══════╦══════╦══════╦══════╗
║      ║      ║      ║  ●●  ║
║      ║      ║      ║ ──── ║
║      ║      ║      ║ ──── ║
║   ●  ║   Θ  ║   Θ  ║ ──── ║
╚══════╩══════╩══════╩══════╝

326205
╔══════╦══════╦══════╦══════╦══════╗
║      ║      ║      ║      ║      ║
║      ║      ║ ──── ║      ║      ║
║      ║      ║ ──── ║ ──── ║      ║
║  ●●  ║   Θ  ║ ──── ║ ──── ║ ──── ║
╚══════╩══════╩══════╩══════╩══════╝

886205
╔══════╦══════╦══════╦══════╦══════╗
║      ║      ║      ║      ║      ║
║      ║      ║ ──── ║      ║      ║
║      ║ ──── ║ ──── ║ ──── ║      ║
║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║
╚══════╩══════╩══════╩══════╩══════╝

16160025
╔══════╦══════╦══════╦══════╦══════╦══════╗
║      ║      ║      ║      ║      ║      ║
║      ║      ║      ║      ║      ║      ║
║      ║      ║      ║      ║      ║      ║
║ ──── ║   ●  ║   Θ  ║   Θ  ║   ●  ║ ──── ║
╚══════╩══════╩══════╩══════╩══════╩══════╝

1081439556
╔══════╦══════╦══════╦══════╦══════╦══════╦══════╗
║   ●  ║  ●●  ║  ●●● ║ ●●●● ║  ●●● ║  ●●  ║   ●  ║
║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║
║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║
║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║ ──── ║
╚══════╩══════╩══════╩══════╩══════╩══════╩══════╝

503491211079
╔══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╦══════╗
║ ●●●● ║      ║      ║      ║      ║      ║      ║      ║ ●●●● ║
║ ──── ║  ●●● ║      ║      ║      ║      ║      ║  ●●● ║ ──── ║
║ ──── ║ ──── ║  ●●  ║      ║      ║      ║  ●●  ║ ──── ║ ──── ║
║ ──── ║ ──── ║ ──── ║   ●  ║   Θ  ║   ●  ║ ──── ║ ──── ║ ──── ║
╚══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╩══════╝

```


[User]
|  |
| --- |
| This page uses content from **Wikipedia**. The original article was at Maze generation algorithm. 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) |

a maze

Task

Generate and show a maze, using the simple Depth-first search algorithm.

1. Start at a random cell.
2. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:

   :   If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.

Related tasks

* Maze solving.

[Assistant]
(formerly Perl 6)

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

Supply a width and height and optionally the x,y grid coords for the starting cell. If no starting cell is supplied, a random one will be selected automatically. 0,0 is the top left corner.

```
constant mapping = :OPEN(' '),
		      :N< ╵ >,
		      :E< ╶ >,
		     :NE< └ >,
		      :S< ╷ >,
		     :NS< │ >,
		     :ES< ┌ >,
		    :NES< ├ >,
		      :W< ╴ >,
		     :NW< ┘ >,
		     :EW< ─ >,
		    :NEW< ┴ >,
		     :SW< ┐ >,
		    :NSW< ┤ >,
		    :ESW< ┬ >,
		   :NESW< ┼ >,
		   :TODO< x >,
	          :TRIED< · >;

enum Sym (mapping.map: *.key);
my @ch = mapping.map: *.value;

enum Direction <DeadEnd Up Right Down Left>;

sub gen_maze ( $X,
               $Y,
               $start_x = (^$X).pick * 2 + 1,
               $start_y = (^$Y).pick * 2 + 1 )
{
    my @maze;
    push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ];
    push @maze, $[ flat (NS, TODO) xx $X, NS ];
    for 1 ..^ $Y {
	push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ];
	push @maze, $[ flat (NS, TODO) xx $X, NS ];
    }
    push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ];
    @maze[$start_y][$start_x] = OPEN;

    my @stack;
    my $current = [$start_x, $start_y];
    loop {
        if my $dir = pick_direction( $current ) {
            @stack.push: $current;
            $current = move( $dir, $current );
        }
        else {
            last unless @stack;
            $current = @stack.pop;
        }
    }
    return @maze;

    sub pick_direction([$x,$y]) {
	my @neighbors =
	    (Up    if @maze[$y - 2][$x]),
	    (Down  if @maze[$y + 2][$x]),
	    (Left  if @maze[$y][$x - 2]),
	    (Right if @maze[$y][$x + 2]);
	@neighbors.pick or DeadEnd;
    }

    sub move ($dir, @cur) {
	my ($x,$y) = @cur;
	given $dir {
	    when Up    { @maze[--$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y--][$x+1] -= W; }
	    when Down  { @maze[++$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y++][$x+1] -= W; }
	    when Left  { @maze[$y][--$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x--] -= N; }
	    when Right { @maze[$y][++$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x++] -= N; }
	}
	@maze[$y][$x] = 0;
	[$x,$y];
    }
}

sub display (@maze) {
    for @maze -> @y {
	for @y.rotor(2) -> ($w, $c) {
	    print @ch[abs $w];
	    if $c >= 0 { print @ch[$c] x 3 }
	    else { print ' ', @ch[abs $c], ' ' }
	}
	say @ch[@y[*-1]];
    }
}

display gen_maze( 29, 19 );

```

Output:

```
┌ ╵ ────────────────────────────┬───────────────────────────────────────────┬───────────┬───────────────────────────┐
│                               │                                           │           │                           │
│   ╶───────────┬───────────┐   │   ┌───────────────────────╴   ┌───────┐   ├───╴   ╷   │   ┌───────────┬───┬───╴   │
│               │           │   │   │                           │       │   │       │   │   │           │   │       │
│   ┌───────┐   ╵   ┌───┐   ├───┘   │   ┌───────────┬───────────┤   ╶───┤   │   ╶───┴───┤   │   ┌───┐   │   │   ╶───┤
│   │       │       │   │   │       │   │           │           │       │   │           │   │   │   │   │   │       │
│   └───╴   └───────┤   │   ╵   ┌───┘   │   ╷   ╶───┤   ┌───┐   │   ╷   │   ├───────╴   │   ╵   │   │   │   └───┐   │
│                   │   │       │       │   │       │   │   │   │   │   │   │           │       │   │   │       │   │
├───────┬───────┐   │   ├───────┤   ╶───┤   └───┐   ╵   │   │   ╵   │   ╵   │   ┌───┐   └───┬───┘   │   │   ╷   │   │
│       │       │   │   │       │       │       │       │   │       │       │   │   │       │       │   │   │   │   │
│   ╶───┤   ╷   ╵   │   ╵   ╷   └───┐   ├───┐   ├───────┤   └───────┴───────┘   │   └───┐   └───╴   │   ╵   ├───┘   │
│       │   │       │       │       │   │   │   │       │                       │       │           │       │       │
├───╴   │   ├───────┴───┐   ├───╴   │   │   │   ╵   ╷   └───┐   ╶───┬───────┬───┘   ┌───┴───────╴   │   ┌───┘   ╷   │
│       │   │           │   │       │   │   │       │       │       │       │       │               │   │       │   │
│   ╷   │   │   ╶───┐   └───┤   ╷   │   │   └───────┴───┐   └───╴   │   ╷   ╵   ╷   ╵   ╶───────┬───┤   │   ┌───┴───┤
│   │   │   │       │       │   │   │   │               │           │   │       │               │   │   │   │       │
│   │   │   │   ╷   ├───╴   ╵   │   │   │   ┌───────┐   └───────────┤   └───┬───┴───────────┐   ╵   │   │   ╵   ╷   │
│   │   │   │   │   │           │   │   │   │       │               │       │               │       │   │       │   │
│   │   │   ├───┘   │   ┌───────┴───┘   │   ╵   ┌───┴───────╴   ╷   ├───┐   │   ╶───────┐   └───┐   │   └───┬───┘   │
│   │   │   │       │   │               │       │               │   │   │   │           │       │   │       │       │
│   └───┘   │   ┌───┘   │   ┌───┬───────┼───╴   │   ╶───┬───────┤   ╵   │   └───┬───╴   ├───┐   │   └───┐   │   ╷   │
│           │   │       │   │   │       │       │       │       │       │       │       │   │   │       │   │   │   │
│   ┌───────┘   ├───────┤   │   ╵   ╷   │   ┌───┴───┐   │   ╶───┘   ┌───┴───╴   │   ┌───┘   │   │   ┌───┘   │   │   │
│   │           │       │   │       │   │   │       │   │           │           │   │       │   │   │       │   │   │
│   └───╴   ╷   │   ╷   │   └───┐   │   ╵   │   ╷   ╵   ├───────┐   │   ╶───────┤   └───┐   │   └───┤   ┌───┘   │   │
│           │   │   │   │       │   │       │   │       │       │   │           │       │   │       │   │       │   │
├───────────┤   │   │   └───╴   │   └───────┤   └───────┘   ╷   └───┴───┬───╴   ├───╴   │   └───┐   │   │   ╶───┴───┤
│           │   │   │           │           │               │           │       │       │       │   │   │           │
│   ┌───╴   │   │   ├───╴   ┌───┴───────┬───┴───┐   ┌───────┴───────┐   ╵   ┌───┤   ╶───┤   ╷   │   ╵   └───┬───╴   │
│   │       │   │   │       │           │       │   │               │       │   │       │   │   │           │       │
│   │   ╶───┘   │   │   ╶───┤   ╶───┐   ╵   ╷   │   └───╴   ┌───╴   └───────┘   ├───╴   │   ├───┴───────┬───┘   ╷   │
│   │           │   │       │       │       │   │           │                   │       │   │           │       │   │
│   ├───────┬───┘   ├───────┴───┐   ├───────┤   └───────────┤   ┌───────────┐   │   ┌───┘   │   ╶───┐   ╵   ┌───┘   │
│   │       │       │           │   │       │               │   │           │   │   │       │       │       │       │
│   └───╴   │   ╷   │   ╶───┐   ╵   │   ╷   └───────────┐   │   │   ┌───┐   └───┘   │   ╶───┴───┐   └───────┴───────┤
│           │   │   │       │       │   │               │   │   │   │   │           │           │                   │
├───────╴   │   └───┴───╴   └───────┴───┴───────────╴   │   └───┘   ╵   └───────────┴───╴   ╷   └───────────────┐   │
│           │                                           │                                   │                   │   │
└───────────┴───────────────────────────────────────────┴───────────────────────────────────┴───────────────────┴ │ ┘
```


[User]
Task

For a maze generated by this task, write a function
that finds (and displays) the shortest path between two cells.

Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths,
and a simple depth-first tree search can be used.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.02

(Includes maze generation code.)

```
constant mapping = :OPEN(' '),
		      :N< ╵ >,
		      :E< ╶ >,
		     :NE< └ >,
		      :S< ╷ >,
		     :NS< │ >,
		     :ES< ┌ >,
		    :NES< ├ >,
		      :W< ╴ >,
		     :NW< ┘ >,
		     :EW< ─ >,
		    :NEW< ┴ >,
		     :SW< ┐ >,
		    :NSW< ┤ >,
		    :ESW< ┬ >,
		   :NESW< ┼ >,
		   :TODO< x >,
	          :TRIED< · >;

enum Sym (mapping.map: *.key);
my @ch = mapping.map: *.value;

enum Direction <DeadEnd Up Right Down Left>;

sub gen_maze ( $X,
               $Y,
               $start_x = (^$X).pick * 2 + 1,
               $start_y = (^$Y).pick * 2 + 1 )
{
    my @maze;
    push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ];
    push @maze, $[ flat (NS, TODO) xx $X, NS ];
    for 1 ..^ $Y {
	push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ];
	push @maze, $[ flat (NS, TODO) xx $X, NS ];
    }
    push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ];
    @maze[$start_y][$start_x] = OPEN;

    my @stack;
    my $current = [$start_x, $start_y];
    loop {
        if my $dir = pick_direction( $current ) {
            @stack.push: $current;
            $current = move( $dir, $current );
        }
        else {
            last unless @stack;
            $current = @stack.pop;
        }
    }
    return @maze;

    sub pick_direction([$x,$y]) {
	my @neighbors =
	    (Up    if @maze[$y - 2][$x]),
	    (Down  if @maze[$y + 2][$x]),
	    (Left  if @maze[$y][$x - 2]),
	    (Right if @maze[$y][$x + 2]);
	@neighbors.pick or DeadEnd;
    }

    sub move ($dir, @cur) {
	my ($x,$y) = @cur;
	given $dir {
	    when Up    { @maze[--$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y--][$x+1] -= W; }
	    when Down  { @maze[++$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y++][$x+1] -= W; }
	    when Left  { @maze[$y][--$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x--] -= N; }
	    when Right { @maze[$y][++$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x++] -= N; }
	}
	@maze[$y][$x] = 0;
	[$x,$y];
    }
}

sub display (@maze) {
    for @maze -> @y {
	for @y.rotor(2) -> ($w, $c) {
	    print @ch[abs $w];
	    if $c >= 0 { print @ch[$c] x 3 }
	    else { print ' ', @ch[abs $c], ' ' }
	}
	say @ch[@y[*-1]];
    }
}

sub solve (@maze is copy, @from = [1, 1], @to = [@maze[0] - 2, @maze - 2]) {
    my ($x, $y) = @from;
    my ($xto, $yto) = @to;
    my @stack;

    sub drop-crumb($x,$y,$c) { @maze[$y][$x] = -$c }
    drop-crumb($x,$y,N);

    loop {
	my $dir = pick_direction([$x,$y]);
	if $dir {
	    ($x, $y) = move($dir, [$x,$y]);
	    return @maze if $x == $xto and $y == $yto;
	}
	else {
	    @maze[$y][$x] = -TRIED;
	    ($x,$y) = @stack.pop;
	    @maze[$y][$x] = -TRIED;
	    ($x,$y) = @stack.pop;
	}
    }

    sub pick_direction([$x,$y]) {
	my @neighbors =
	    (Up    unless @maze[$y - 1][$x]),
	    (Down  unless @maze[$y + 1][$x]),
	    (Left  unless @maze[$y][$x - 1]),
	    (Right unless @maze[$y][$x + 1]);
	@neighbors.pick or DeadEnd;
    }

    sub move ($dir, @cur) {
	my ($x,$y) = @cur;
	given $dir {
	    when Up    { for ^2 { push @stack, $[$x,$y--]; drop-crumb $x,$y,S; } }
	    when Down  { for ^2 { push @stack, $[$x,$y++]; drop-crumb $x,$y,N; } }
	    when Left  { for ^2 { push @stack, $[$x--,$y]; drop-crumb $x,$y,E; } }
	    when Right { for ^2 { push @stack, $[$x++,$y]; drop-crumb $x,$y,W; } }
	}
	$x,$y;
    }
}

display solve gen_maze( 29, 19 );

```

Output:

```
┌ ╵ ────┬───────────────┬───────────────┬───────────────────────────────┬───────────┬───────────────┬───────────────┐
│ ╵ · · │ ╷ ╴ ╴ ╴ ╴     │               │ ╷ ╴ ╴ · · · · · · · · · · · · │ ╷ ╴ ╴ · · │ · · · · · · · │ · · · · · · · │
│ ╵ ╶───┘ ╷ ╶───┐ ╵ ╷   │   ╷   ╶───────┤ ╷ ╷ ╵ ╶───────┬───────┐ · ┌───┘ ╷ ╷ ╵ ╷ · │ · ╶───┬───╴ · │ · ╷ · ┌───╴ · │
│ ╵ ╴ ╴ ╴ ╴ · · │ ╵ │   │   │           │ ╷ │ ╵ ╴ ╴ ╴ ╴ │ ╷ ╴ ╴ │ · │ ╷ ╴ ╴ │ ╵ │ · │ · · · │ · · · │ · │ · │ · · · │
│ · ┌───────────┤ ╵ │   └───┴───────╴   │ ╷ ├───────┐ ╵ ╵ ╷ ╷ ╵ └───┘ ╷ ┌───┘ ╵ │ · │ · ╷ · │ · ┌───┴───┘ · │ · ╶───┤
│ · │ ╶ ╶ ╶ ╶ ╷ │ ╵ │                   │ ╷ │       │ ╵ ╴ ╴ │ ╵ ╴ ╴ ╴ ╴ │ ╶ ╶ ╵ │ · │ · │ · │ · │ · · · · · │ · · · │
│ · │ ╵ ╶───┐ ╷ ╵ ╵ ├───────────────╴   │ ╷ └───╴   └───────┼───┬───────┤ ╵ ┌───┤ · ├───┘ · │ · │ · ╷ · ┌───┴───┐ · │
│ · │ ╵ ╴ ╴ │ ╶ ╶ ╵ │                   │ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╶ ╷ │ · │ ╶ ╶ ╷ │ ╵ │ · │ · │ · · · │ · │ · │ · │ · · · │ · │
│ · └───┐ ╵ ├───────┴───────┐   ╶───────┴───────┬───────╴ ╷ │ · │ ╵ ╷ ╷ │ ╵ │ · │ · │ · ┌───┤ · │ · │ · │ · ╷ · ╵ · │
│ · · · │ ╵ │ ╷ ╴ ╴ ╴ ╴ ╴ ╴ │                   │ ╷ ╴ ╴ ╴ ╴ │ · │ ╵ │ ╷ │ ╵ │ · │ · │ · │ · │ · │ · │ · │ · │ · · · │
├───╴ · │ ╵ │ ╷ ╶───────┐ ╵ ├───────────────┐   │ ╷ ╶───┬───┘ · │ ╵ │ ╷ ╵ ╵ │ · ╵ · ╵ · │ · ╵ · └───┘ · │ · ├───────┤
│ · · · │ ╵ │ ╶ ╶ ╶ ╶ ╷ │ ╵ │ ╷ ╴ ╴ ╴ ╴ ╴ ╴ │   │ ╶ ╶ ╷ │ · · · │ ╵ │ ╶ ╶ ╵ │ · · · · · │ · · · · · · · │ · │ · · · │
│ · ┌───┤ ╵ └───────╴ ╷ │ ╵ ╵ ╷ ┌───────┐ ╵ │   └───┐ ╷ └───┐ · │ ╵ ├───────┼───────┬───┴───────┬───┬───┘ · ├───╴ · │
│ · │ · │ ╵ ╴ ╴ ╴ ╴ ╴ ╴ │ ╵ ╴ ╴ │ · · · │ ╵ │       │ ╶ ╶ ╷ │ · │ ╵ │ ╷ ╴ ╴ │ ╷ ╴ ╴ │ ╷ ╴ ╴ ╴ ╴ │ · │ · · · │ · · · │
│ · ╵ · ├───────────────┴───────┴───┐ · │ ╵ └───────┴───┐ ╷ │ · │ ╵ ╵ ╷ ╷ ╵ ╵ ╷ ╷ ╵ │ ╷ ┌───╴ ╵ │ · │ · ╶───┤ · ╶───┤
│ · · · │ · · · · · · · · · · · · · │ · │ ╵ ╴ ╴ ╴ ╴ · · │ ╷ │ · │ ╵ ╴ ╴ │ ╵ ╴ ╴ │ ╵ │ ╷ │ ╶ ╶ ╵ │ · │ · · · │ · · · │
├───┐ · │ · ┌───────────╴ · ┌───┐ · │ · └───┬───╴ ╵ ┌───┘ ╷ │ · ├───────┴───────┤ ╵ ╵ ╷ │ ╵ ╶───┤ · └───┐ · │ · ╷ · │
│ · │ · │ · │ · · · · · · · │ · │ · │ · · · │ ╶ ╶ ╵ │ ╷ ╴ ╴ │ · │ · · · · · · · │ ╵ ╴ ╴ │ ╵ ╴ ╴ │ · · · │ · │ · │ · │
│ · │ · └───┘ · ┌───────────┘ · │ · ├───╴ · │ ╵ ┌───┘ ╷ ┌───┘ · │ · ╷ · ┌───╴ · └───────┴───┐ ╵ └───┐ · ╵ · ├───┘ · │
│ · │ · · · · · │ · · · · · · · │ · │ · · · │ ╵ │ ╷ ╴ ╴ │ · · · │ · │ · │ · · · · · · · · · │ ╵ ╴ ╴ │ · · · │ · · · │
│ · ├───────╴ · ├───┐ · ┌───┐ · ╵ · │ · ╶───┤ ╵ ╵ ╷ ┌───┘ · ╶───┤ · │ · └───┬───╴ · ┌───────┤ · ╷ ╵ │ · ╶───┘ · ╷ · │
│ · │ · · · · · │   │ · │ · │ · · · │ · · · │ ╵ ╴ ╴ │ · · · · · │ · │ · · · │ · · · │ ╶ ╶ ╷ │ · │ ╵ │ · · · · · │ · │
│ · ╵ · ┌───────┘   │ · ╵ · └───────┤ · ╷ · └───────┴───────┐ · ╵ · └───┐ · └───┐ · │ ╵ ╷ ╷ └───┘ ╵ ├───────────┤ · │
│ · · · │           │ · · · · · · · │ · │ · · · · · · · · · │ · · · · · │ · · · │ · │ ╵ │ ╶ ╶ ╶ ╶ ╵ │ ╷ ╴ ╴ ╴ ╴ │ · │
│ · ╶───┤   ╶───────┴───┬───────┐ · ├───┘ · ┌───────────┐ · ├───────────┴───╴ · │ · │ ╵ └───────┐ · │ ╷ ┌───╴ ╵ │ · │
│ · · · │               │ · · · │ · │ · · · │ · · · · · │ · │ · · · · · · · · · │ · │ ╵ ╴ ╴ ╴ ╴ │ · │ ╷ │ ╶ ╶ ╵ │ · │
├───┐ · ├───────┬───╴   │ · ╷ · │ · │ · ┌───┤ · ╶───────┤ · │ · ╶───────┬───┐ · ├───┴───────┐ ╵ └───┘ ╷ │ ╵ ┌───┴───┤
│ · │ · │       │       │ · │ · │ · │ · │ · │ · · · · · │ · │ · · · · · │ · │ · │           │ ╵ ╴ ╴ ╴ ╴ │ ╵ │ ╷ ╴ ╴ │
│ · │ · │   ╷   ╵   ┌───┘ · │ · ╵ · ╵ · │ · ╵ · ┌───┐ · ╵ · └───────╴ · │ · ╵ · │   ┌───╴   └───────┐ · │ ╵ ╵ ╷ ╷ ╵ │
│ · │ · │   │       │ · · · │ · · · · · │ · · · │ · │ · · · · · · · · · │ · · · │   │               │ · │ ╵ ╴ ╴ │ ╵ │
│ · │ · │   └───┬───┴───────┴───┬───────┤ · ┌───┘ · ├───────────────────┴───────┤   └───────────┐   └───┴───────┤ ╵ │
│ · │ · │       │               │       │ · │ · · · │                           │               │               │ ╵ │
│ · ╵ · ├───┐   │   ╶───────┐   ╵   ╷   │ · ╵ · ╷ · │   ╶───────────────────┐   └───┬───────┐   └───────┬───┐   │ ╵ │
│ · · · │ · │   │           │       │   │ · · · │ · │                       │       │       │           │   │   │ ╵ │
│ · ╶───┤ · │   └───────┐   ├───────┤   └───┬───┴───┼───────────┬───────┐   ├───┐   ╵   ╷   ├───────┐   │   │   │ ╵ │
│ · · · │ · │           │   │       │       │       │           │       │   │   │       │   │       │   │   │   │ ╵ │
├───╴ · ╵ · └───────┐   ╵   │   ╷   └───╴   ╵   ╷   ╵   ┌───╴   ╵   ╷   ╵   │   └───────┘   ╵   ╷   ╵   │   ╵   ╵ ╵ │
│ · · · · · · · · · │       │   │               │       │           │       │                   │       │         ╵ │
└───────────────────┴───────┴───┴───────────────┴───────┴───────────┴───────┴───────────────────┴───────┴──────── │ ┘
```


[User]
From Wikipedia:

```
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.

```

Task

Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number *n* which cannot be expressed with *6x + 9y + 20z = n*
where *x*, *y* and *z* are natural numbers).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.09

No hard coded limits, no hard coded values. General purpose 3 value solver. Count values may be any 3 different positive integers, in any order, that are relatively prime.

Finds the smallest count value, then looks for the first run of consecutive count totals able to be generated, that is at least the length of the smallest count size. From then on, every number can be generated by simply adding multiples of the minimum count to each of the totals in that run.

```
sub Mcnugget-number (*@counts) {

    return '∞' if 1 < [gcd] @counts;

    my $min = min @counts;
    my @meals;
    my @min;

    for ^Inf -> $a {
        for 0..$a -> $b {
            for 0..$b -> $c {
                ($a, $b, $c).permutations.map: { @meals[ sum $_ Z* @counts ] = True }
            }
        }
        for @meals.grep: so *, :k {
            if @min.tail and @min.tail + 1 == $_ {
                @min.push: $_;
                last if $min == +@min
            } else {
                @min = $_;
            }
        }
        last if $min == +@min
    }
    @min[0] ?? @min[0] - 1 !! 0
}

for (6,9,20), (6,7,20), (1,3,20), (10,5,18), (5,17,44), (2,4,6), (3,6,15) -> $counts {
    put "Maximum non-Mcnugget number using {$counts.join: ', '} is: ",
        Mcnugget-number(|$counts)
}

```

Output:

```
Maximum non-Mcnugget number using 6, 9, 20 is: 43
Maximum non-Mcnugget number using 6, 7, 20 is: 29
Maximum non-Mcnugget number using 1, 3, 20 is: 0
Maximum non-Mcnugget number using 10, 5, 18 is: 67
Maximum non-Mcnugget number using 5, 17, 44 is: 131
Maximum non-Mcnugget number using 2, 4, 6 is: ∞
Maximum non-Mcnugget number using 3, 6, 15 is: ∞
```


[User]
Find the MD4 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code” (without quotes).
You may either call an MD4 library, or implement MD4 in your language.

**MD4** is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.

RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.

[Assistant]
(formerly Perl 6)

```
sub md4($str) {
    my buf8 $buf .= new: $str.encode;
    my $buf-length = $buf.elems;
    $buf.push: 0x80;
    $buf.push: 0 until ($buf - (448 div 8)) %% (512 div 8);
    # raku serializes in little endian by default
    $buf.write-uint64: $buf.elems, $buf-length*8;

    my (&f, &g, &h, &r) =
      { $^x +& $^y +| +^$x +& $^z },
      { $^x +& $^y +| $x +& $^z +| $y +& $z },
      { $^x +^ $^y +^ $^z },
      # for some reason we have to type v here
      -> uint32 $v, $s { $v +< $s +| $v +> (32 - $s) }

    my uint32 ($a, $b, $c, $d) = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476;

    loop (my $pos = 0; $pos < $buf.elems; $pos+=64) {
        my ($aa, $bb, $cc, $dd) = $a, $b, $c, $d;
        for 0, 4, 8, 12 -> $i {
            $a = r($a + f($b, $c, $d) + $buf.read-uint32($pos+($i+0)*4),  3);
            $d = r($d + f($a, $b, $c) + $buf.read-uint32($pos+($i+1)*4),  7);
            $c = r($c + f($d, $a, $b) + $buf.read-uint32($pos+($i+2)*4), 11);
            $b = r($b + f($c, $d, $a) + $buf.read-uint32($pos+($i+3)*4), 19);
        }
        for 0, 1, 2, 3 -> $i {
            $a = r($a + g($b, $c, $d) + $buf.read-uint32($pos+($i+0 )*4) + 0x5a827999,  3);
            $d = r($d + g($a, $b, $c) + $buf.read-uint32($pos+($i+4 )*4) + 0x5a827999,  5);
            $c = r($c + g($d, $a, $b) + $buf.read-uint32($pos+($i+8 )*4) + 0x5a827999,  9);
            $b = r($b + g($c, $d, $a) + $buf.read-uint32($pos+($i+12)*4) + 0x5a827999, 13);
        }
        for 0, 2, 1, 3 -> $i {
            $a = r($a + h($b, $c, $d) + $buf.read-uint32($pos+($i+0 )*4) + 0x6ed9eba1,  3);
            $d = r($d + h($a, $b, $c) + $buf.read-uint32($pos+($i+4 )*4) + 0x6ed9eba1,  9);
            $c = r($c + h($d, $a, $b) + $buf.read-uint32($pos+($i+8 )*4) + 0x6ed9eba1, 11);
            $b = r($b + h($c, $d, $a) + $buf.read-uint32($pos+($i+12)*4) + 0x6ed9eba1, 15);
        }
        ($a,$b,$c,$d) Z[+=] ($aa,$bb,$cc,$dd);
    }

    reduce { $^buf.write-uint32: $buf.elems, $^x; $buf }, buf8.new, $a, $b, $c, $d;
}

CHECK {
  use Test;
  plan 1;
  is md4('Rosetta Code').list.fmt('%02X'), 'A5 2B CF C6 A0 D0 D3 00 CD C5 DD BF BE FE 47 8B';
}

```

Output:

```
1..1
ok 1 -

```


[User]
Task

Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia.

Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5.

Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article.

|  |
| --- |
| **Warning:**   MD5 has known weaknesses, including **collisions** and forged signatures.   Users may consider a stronger alternative when doing production-grade cryptography, such as SHA-256 (from the SHA-2 family), or the upcoming SHA-3. |

If the solution on this page is a library solution, see   MD5/Implementation   for an implementation from scratch.

[Assistant]
(formerly Perl 6)
Library Digest::MD5

```
use Digest::MD5;
say Digest::MD5.md5_hex: "The quick brown fox jumped over the lazy dog's back";

```