[User]
Task

Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.

That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.

Example

Given   **87.70.141.1/22**,   your code should output   **87.70.140.0/22**

Explanation

An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.

In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.

The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 → 87.70.140.0.

More examples for testing

```
        36.18.154.103/12    →  36.16.0.0/12
        62.62.197.11/29     →  62.62.197.8/29
        67.137.119.181/4    →  64.0.0.0/4
        161.214.74.21/24    →  161.214.74.0/24
        184.232.176.184/18  →  184.232.128.0/18

```

[Assistant]
### Using library

**Library:** raku-IP-Addr

```
use IP::Addr;
for «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18» -> $cidr {
   say "$cidr -> $(IP::Addr.new($cidr).network)";
}

```

### String manipulation

**Translation of**: Perl

```
#!/usr/bin/env raku
unit sub MAIN(*@cidrs);

if !@cidrs {
  # test data
  @cidrs = «87.70.141.1/22 36.18.154.103/12 62.62.197.11/29 67.137.119.181/4 161.214.74.21/24 184.232.176.184/18»;
}

for @cidrs -> $cidr {
  say "$cidr -> $(canonicalize $cidr)";
}

# canonicalize a CIDR block: make sure none of the host bits are set
sub canonicalize($cidr) {
  # dotted-decimal / bits in network part
  my ($dotted, $size) = $cidr.split: '/';

  # get network part of the IP as binary string
  my $binary = $dotted.split('.')».fmt('%08b').join.substr(0, $size);

  # Add host part with all zeroes
  $binary ~= 0 x (32 - $size);

  # Convert back to dotted-decimal
  my $canon = $binary.comb(8)».parse-base(2).join: '.';

  # And output
  say "$canon/$size";
}

```

Output:

```
87.70.141.1/22 -> 87.70.140.0/22
36.18.154.103/12 -> 36.16.0.0/12
62.62.197.11/29 -> 62.62.197.8/29
67.137.119.181/4 -> 64.0.0.0/4
161.214.74.21/24 -> 161.214.74.0/24
184.232.176.184/18 -> 184.232.128.0/18
```

### Bit mask and shift

```
# canonicalize a IP4 CIDR block
sub CIDR-IP4-canonicalize ($address) {
  constant @mask = 24, 16, 8, 0;

  # dotted-decimal / subnet size
  my ($dotted, $size) = |$address.split('/'), 32;

  # get IP as binary address
  my $binary = sum $dotted.comb(/\d+/) Z+< @mask;

  # mask off subnet
  $binary +&= (2 ** $size - 1) +< (32 - $size);

  # Return dotted-decimal notation
  (@mask.map($binary +> * +& 0xFF).join('.'), $size)
}

my @tests = <
  87.70.141.1/22
  36.18.154.103/12
  62.62.197.11/29
  67.137.119.181/4
  161.214.74.21/24
  184.232.176.184/18
  100.68.0.18/18
  10.4.30.77/30
  10.207.219.251/32
  10.207.219.251
  110.200.21/4
  10.11.12.13/8
  10.../8
>;

printf "CIDR: %18s  Routing prefix: %s/%s\n", $_, |.&CIDR-IP4-canonicalize
  for @*ARGS || @tests;

```

Output:

```
CIDR:     87.70.141.1/22  Routing prefix: 87.70.140.0/22
CIDR:   36.18.154.103/12  Routing prefix: 36.16.0.0/12
CIDR:    62.62.197.11/29  Routing prefix: 62.62.197.8/29
CIDR:   67.137.119.181/4  Routing prefix: 64.0.0.0/4
CIDR:   161.214.74.21/24  Routing prefix: 161.214.74.0/24
CIDR: 184.232.176.184/18  Routing prefix: 184.232.128.0/18
CIDR:     100.68.0.18/18  Routing prefix: 100.68.0.0/18
CIDR:      10.4.30.77/30  Routing prefix: 10.4.30.76/30
CIDR:  10.207.219.251/32  Routing prefix: 10.207.219.251/32
CIDR:     10.207.219.251  Routing prefix: 10.207.219.251/32
CIDR:       110.200.21/4  Routing prefix: 96.0.0.0/4
CIDR:      10.11.12.13/8  Routing prefix: 10.0.0.0/8
CIDR:            10.../8  Routing prefix: 10.0.0.0/8
```


[User]
Task

Draw a Cantor set.

See details at this Wikipedia webpage:   Cantor set

[Assistant]
(formerly Perl 6)

**Translation of**: Kotlin

```
sub cantor ( Int $height ) {
    my $width = 3 ** ($height - 1);

    my @lines = ( "\c[FULL BLOCK]" x $width ) xx $height;

    my sub _trim_middle_third ( $len, $start, $index ) {
        my $seg = $len div 3
            or return;

        for ( $index ..^ $height ) X ( 0 ..^ $seg ) -> ( $i, $j ) {
            @lines[$i].substr-rw( $start + $seg + $j, 1 ) = ' ';
        }

        _trim_middle_third( $seg, $start + $_, $index + 1 ) for 0, $seg * 2;
    }

    _trim_middle_third( $width, 0, 1 );
    return @lines;
}

.say for cantor(5);

```

Output:

```
█████████████████████████████████████████████████████████████████████████████████
███████████████████████████                           ███████████████████████████
█████████         █████████                           █████████         █████████
███   ███         ███   ███                           ███   ███         ███   ███
█ █   █ █         █ █   █ █                           █ █   █ █         █ █   █ █
```


[User]
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.

There are many techniques that people use to shuffle cards for card games. Some are more effective than others.

Task

Implement the (seemingly) more common techniques of the riffle shuffle and overhand shuffle for   *n*   iterations.

Implementing playing cards is not necessary if it would be easier to implement these shuffling methods for generic collections.

Where possible, compare this to a standard/built-in shuffling procedure.

One iteration of the riffle shuffle is defined as:

1. Split the deck into two piles
2. Merge the two piles by taking one card from the top of either pile in proportion to the number of cards remaining in the pile. To start with the probability for both piles will be 26/52 (50-50), then 25/51-26/51 etc etc as the riffle progresses.
3. The merged deck is now the new "shuffled" deck

One iteration of the overhand shuffle is defined as:

1. Take a group of consecutive cards from the top of the deck. For our purposes up to 20% of the deck seems like a good amount.
2. Place that group on top of a second pile
3. Repeat these steps until there are no cards remaining in the original deck
4. The second pile is now the new "shuffled" deck

Bonus

Implement other methods described in the Wikipedia
article:   card shuffling.

Allow for "human errors" of imperfect cutting and interleaving.

Related tasks:

* Playing cards
* Deal cards\_for\_FreeCell
* War Card\_Game
* Poker hand\_analyser
* Go Fish

[Assistant]
(formerly Perl 6)

```
sub overhand ( @cards ) {
    my @splits = roll 10, ^( @cards.elems div 5 )+1;
    @cards.rotor( @splits  ,:partial ).reverse.flat
}

sub riffle ( @pile is copy ) {
    my @pile2 = @pile.splice: @pile.elems div 2 ;

    roundrobin(
        @pile.rotor(  (1 .. 3).roll(7), :partial ),
        @pile2.rotor( (1 .. 3).roll(9), :partial ),
    ).flat
}

my @cards = ^20;
@cards.=&overhand for ^10;
say @cards;

my @cards2 = ^20;
@cards2.=&riffle for ^10;
say @cards2;

say (^20).pick(*);

```


[User]
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.

The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.

The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010.

Task

Find Carmichael numbers of the form:

:   :   :   :   *Prime*1 × *Prime*2 × *Prime*3

where    (*Prime*1 < *Prime*2 < *Prime*3)    for all    *Prime*1    up to   **61**.

(See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.)

Pseudocode

For a given   **Prime1**

```
for 1 < h3 < Prime1
    for 0 < d < h3+Prime1
         if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
         then
               Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
               next d if Prime2 is not prime
               Prime3 = 1 + (Prime1*Prime2/h3)
               next d if Prime3 is not prime
               next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
               Prime1 * Prime2 * Prime3 is a Carmichael Number

```

related task

Chernick's Carmichael numbers

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

An almost direct translation of the pseudocode. We take the liberty of going up to 67 to show we aren't limited to 32-bit integers. (Raku uses arbitrary precision in any case.)

```
for (2..67).grep: *.is-prime -> \Prime1 {
    for 1 ^..^ Prime1 -> \h3 {
        my \g = h3 + Prime1;
        for 0 ^..^ h3 + Prime1 -> \d {
            if (h3 + Prime1) * (Prime1 - 1) %% d and -Prime1**2 % h3 == d % h3  {
                my \Prime2 = floor 1 + (Prime1 - 1) * g / d;
                next unless Prime2.is-prime;
                my \Prime3 = floor 1 + Prime1 * Prime2 / h3;
                next unless Prime3.is-prime;
                next unless (Prime2 * Prime3) % (Prime1 - 1) == 1;
                say "{Prime1} × {Prime2} × {Prime3} == {Prime1 * Prime2 * Prime3}";
            }
        }
    }
}

```

Output:

```
3 × 11 × 17 == 561
5 × 29 × 73 == 10585
5 × 17 × 29 == 2465
5 × 13 × 17 == 1105
7 × 19 × 67 == 8911
7 × 31 × 73 == 15841
7 × 13 × 31 == 2821
7 × 23 × 41 == 6601
7 × 73 × 103 == 52633
7 × 13 × 19 == 1729
13 × 61 × 397 == 314821
13 × 37 × 241 == 115921
13 × 97 × 421 == 530881
13 × 37 × 97 == 46657
13 × 37 × 61 == 29341
17 × 41 × 233 == 162401
17 × 353 × 1201 == 7207201
19 × 43 × 409 == 334153
19 × 199 × 271 == 1024651
23 × 199 × 353 == 1615681
29 × 113 × 1093 == 3581761
29 × 197 × 953 == 5444489
31 × 991 × 15361 == 471905281
31 × 61 × 631 == 1193221
31 × 151 × 1171 == 5481451
31 × 61 × 271 == 512461
31 × 61 × 211 == 399001
31 × 271 × 601 == 5049001
31 × 181 × 331 == 1857241
37 × 109 × 2017 == 8134561
37 × 73 × 541 == 1461241
37 × 613 × 1621 == 36765901
37 × 73 × 181 == 488881
37 × 73 × 109 == 294409
41 × 1721 × 35281 == 2489462641
41 × 881 × 12041 == 434932961
41 × 101 × 461 == 1909001
41 × 241 × 761 == 7519441
41 × 241 × 521 == 5148001
41 × 73 × 137 == 410041
41 × 61 × 101 == 252601
43 × 631 × 13567 == 368113411
43 × 271 × 5827 == 67902031
43 × 127 × 2731 == 14913991
43 × 127 × 1093 == 5968873
43 × 211 × 757 == 6868261
43 × 631 × 1597 == 43331401
43 × 127 × 211 == 1152271
43 × 211 × 337 == 3057601
43 × 433 × 643 == 11972017
43 × 547 × 673 == 15829633
43 × 3361 × 3907 == 564651361
47 × 3359 × 6073 == 958762729
47 × 1151 × 1933 == 104569501
47 × 3727 × 5153 == 902645857
53 × 157 × 2081 == 17316001
53 × 79 × 599 == 2508013
53 × 157 × 521 == 4335241
59 × 1451 × 2089 == 178837201
61 × 421 × 12841 == 329769721
61 × 181 × 5521 == 60957361
61 × 1301 × 19841 == 1574601601
61 × 277 × 2113 == 35703361
61 × 181 × 1381 == 15247621
61 × 541 × 3001 == 99036001
61 × 661 × 2521 == 101649241
61 × 271 × 571 == 9439201
61 × 241 × 421 == 6189121
61 × 3361 × 4021 == 824389441
67 × 2311 × 51613 == 7991602081
67 × 331 × 7393 == 163954561
67 × 331 × 463 == 10267951
```


[User]
Background

The **Carmichael function**, or **Carmichael lambda function**, is a function in number theory. The Carmichael lambda  *λ*(*n*) of a positive integer **n** is the smallest positive integer **m** such that

:   a

    m
    ≡
    1

    (
    mod

    n
    )
    {\displaystyle {\displaystyle a^{m}\equiv 1{\pmod {n}}}}

holds for every integer coprime to **n**.

The Carmichael lambda function can be iterated, that is, called repeatedly on its result. If this iteration is
performed **k** times, this is considered the **k**-iterated Carmichael lambda function. Thus,  *λ*(*λ*(*n*))
would be the 2-iterated lambda function. With repeated, sufficiently large but finite **k**-iterations, the iterated Carmichael function will eventually compute as 1 for all positive integers **n**.

Task

* Write a function to obtain the Carmichael lambda of a positive integer. If the function is supplied by a core library of the language, this also may be used.

* Write a function to count the number of iterations **k** of the **k**-iterated lambda function needed to get to a value of 1. Show the value of  *λ*(*n*) and the number of **k**-iterations for integers from 1 to 25.

* Find the lowest integer for which the value of iterated k is i, for i from 1 to 15.

Stretch task (an extension of the third task above)

* Find, additionally, for **i** from 16 to 25, the lowest integer **n** for which the number of iterations **k** of the Carmichael lambda function from **n** to get to 1 is **i**.

See also

:   * Wikipedia entry for Carmichael function
    * OEIS lambda(lambda(n)) function sequence

[Assistant]
**Translation of**: Wren

```
# 20240228 Raku programming solution

use Prime::Factor;

sub phi(Int $p, Int $r) { return $p**($r - 1) * ($p - 1) }

sub CarmichaelLambda(Int $n) {

   state %cache = 1 => 1, 2 => 1, 4 => 2;

   sub CarmichaelHelper(Int $p, Int $r) {
      my Int $n = $p ** $r;
      return %cache{$n} if %cache{$n}:exists;
      return %cache{$n} = $p > 2 ?? phi($p, $r) !! phi($p, $r - 1)
   }

   if $n < 1 { die "'n' must be a positive integer." }
   return %cache{$n} if %cache{$n}:exists;
   if ( my %pps = prime-factors($n).Bag ).elems == 1 {
      my ($p, $r) = %pps.kv>>.Int;
      return %cache{$n} = $p > 2 ?? phi($p, $r) !! phi($p, $r - 1)
   }
   return [lcm] %pps.kv.map: -> $k, $v { CarmichaelHelper($k.Int, $v) }
}

sub iteratedToOne($i is copy) {
   my $k = 0;
   while $i > 1 { $i = CarmichaelLambda($i) andthen $k++ }
   return $k
}

say " n   λ   k";
say "----------";
for 1..25 -> $n {
   printf "%2d  %2d  %2d\n", $n, CarmichaelLambda($n), iteratedToOne($n)
}

say "\nIterations to 1       i     lambda(i)";
say "=====================================";
say "   0                  1            1";

my ($maxI, $maxN) = 5e6, 10; # for N=15, takes around 47 minutes with an i5-10500T
my @found = True, |( False xx $maxN );
for 1 .. $maxI -> $i {
   unless @found[ my $n = iteratedToOne($i) ] {
      printf "%4d %18d %12d\n", $n, $i, CarmichaelLambda($i);
      @found[$n] = True andthen ( last if $n == $maxN )
   }
}

```

Output:

Same as Wren example .. and it is probably 30X times slower 😅


[User]
Task

Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.

Demonstrate that your function/method correctly returns:

:   :   {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}

and, in contrast:

:   :   {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}

Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.

:   :   {1, 2} × {} = {}
    :   {} × {1, 2} = {}

For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.

Use your n-ary Cartesian product function to show the following products:

:   :   {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
    :   {1, 2, 3} × {30} × {500, 100}
    :   {1, 2, 3} × {} × {500, 100}

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.06

The cross meta operator X will return the cartesian product of two lists. To apply the cross meta-operator to a variable number of lists, use the reduce cross meta operator [X].

```
# cartesian product of two lists using the X cross meta-operator
say (1, 2) X (3, 4);
say (3, 4) X (1, 2);
say (1, 2) X ( );
say ( )    X ( 1, 2 );

# cartesian product of variable number of lists using
# the [X] reduce cross meta-operator
say [X] (1776, 1789), (7, 12), (4, 14, 23), (0, 1);
say [X] (1, 2, 3), (30), (500, 100);
say [X] (1, 2, 3), (),   (500, 100);

```

Output:

```
((1 3) (1 4) (2 3) (2 4))
((3 1) (3 2) (4 1) (4 2))
()
()
((1776 7 4 0) (1776 7 4 1) (1776 7 14 0) (1776 7 14 1) (1776 7 23 0) (1776 7 23 1) (1776 12 4 0) (1776 12 4 1) (1776 12 14 0) (1776 12 14 1) (1776 12 23 0) (1776 12 23 1) (1789 7 4 0) (1789 7 4 1) (1789 7 14 0) (1789 7 14 1) (1789 7 23 0) (1789 7 23 1) (1789 12 4 0) (1789 12 4 1) (1789 12 14 0) (1789 12 14 1) (1789 12 23 0) (1789 12 23 1))
((1 30 500) (1 30 100) (2 30 500) (2 30 100) (3 30 500) (3 30 100))
()
```


[User]
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:

```
The three dogs are named Benjamin, Samba and Bernie.

```

For a language that is lettercase insensitive, we get the following output:

```
There is just one dog named Bernie.

```

Related task

* Unicode variable names

[Assistant]
(formerly Perl 6)

```
my $dog = 'Benjamin';
my $Dog = 'Samba';
my $DOG = 'Bernie';
say "The three dogs are named $dog, $Dog, and $DOG."

```

The only place that Raku pays any attention to the case of identifiers is that, for certain error messages, it will guess that an identifier starting lowercase is probably a function name, while one starting uppercase is probably a type or constant name. But this case distinction is merely a convention in Raku, not mandatory:

```
constant dog = 'Benjamin';
sub Dog() { 'Samba' }
my &DOG = { 'Bernie' }
say "The three dogs are named {dog}, {Dog}, and {DOG}."

```


[User]
Task   (in three parts)

Part 1

Write a procedure (say

c
o
9
(
x
)
{\displaystyle {\displaystyle {\mathit {co9}}(x)}}
) which implements Casting Out Nines as described by returning the checksum for

x
{\displaystyle {\displaystyle x}}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.

Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.

With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.

Part 2

Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:

:   Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
:   note that

    318682
    {\displaystyle {\displaystyle 318682}}
     has the same checksum as (

    101558
    +
    217124
    {\displaystyle {\displaystyle 101558+217124}}
    );
:   note that

    101558217124
    {\displaystyle {\displaystyle 101558217124}}
     has the same checksum as (

    101558
    +
    217124
    {\displaystyle {\displaystyle 101558+217124}}
    ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
:   note that this implies that for Kaprekar numbers the checksum of

    k
    {\displaystyle {\displaystyle k}}
     equals the checksum of

    k

    2
    {\displaystyle {\displaystyle k^{2}}}
    .

Demonstrate that your procedure can be used to generate or filter a range of numbers with the property

c
o
9
(
k
)
=

c
o
9
(

k

2
)
{\displaystyle {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}}
 and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

Part 3

Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:

:   c
    o
    9
    (
    x
    )
    {\displaystyle {\displaystyle {\mathit {co9}}(x)}}
     is the residual of

    x
    {\displaystyle {\displaystyle x}}
     mod

    9
    {\displaystyle {\displaystyle 9}}
    ;
:   the procedure can be extended to bases other than 9.

Demonstrate your algorithm by generating or filtering a range of numbers with the property

k
%
(

B
a
s
e
−
1
)
==
(

k

2
)
%
(

B
a
s
e
−
1
)
{\displaystyle {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}}
 and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

related tasks

* First perfect square in base N with N unique digits
* Kaprekar numbers

[Assistant]
(formerly Perl 6)

**Translation of**: Python

**Works with**: Rakudo version 2015.12

```
sub cast-out(\BASE = 10, \MIN = 1, \MAX = BASE**2 - 1) {
  my \B9 = BASE - 1;
  my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9);
  my $x = MIN div B9;
  gather loop {
    for @ran -> \n {
      my \k = B9 * $x + n;
      take k if k >= MIN;
    }
    $x++;
  } ...^ * > MAX;
}

say cast-out;
say cast-out 16;
say cast-out 17;

```

Output:

```
(1 9 10 18 19 27 28 36 37 45 46 54 55 63 64 72 73 81 82 90 91 99)
(1 6 10 15 16 21 25 30 31 36 40 45 46 51 55 60 61 66 70 75 76 81 85 90 91 96 100 105 106 111 115 120 121 126 130 135 136 141 145 150 151 156 160 165 166 171 175 180 181 186 190 195 196 201 205 210 211 216 220 225 226 231 235 240 241 246 250 255)
(1 16 17 32 33 48 49 64 65 80 81 96 97 112 113 128 129 144 145 160 161 176 177 192 193 208 209 224 225 240 241 256 257 272 273 288)
```


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

Catalan numbers are a sequence of numbers which can be defined directly:

:   C

    n
    =

    1

    n
    +
    1

    (

    2
    n
    n

    )
    =

    (
    2
    n
    )
    !

    (
    n
    +
    1
    )
    !

    n
    !

     for
    n
    ≥
    0.
    {\displaystyle {\displaystyle C\_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}}

Or recursively:

:   C

    0
    =
    1

    and

    C

    n
    +
    1
    =

    ∑

    i
    =
    0

    n

    C

    i

    C

    n
    −
    i

    for
    n
    ≥
    0
    ;
    {\displaystyle {\displaystyle C\_{0}=1\quad {\mbox{and}}\quad C\_{n+1}=\sum \_{i=0}^{n}C\_{i}\,C\_{n-i}\quad {\text{for }}n\geq 0;}}

Or alternatively (also recursive):

:   C

    0
    =
    1

    and

    C

    n
    =

    2
    (
    2
    n
    −
    1
    )

    n
    +
    1

    C

    n
    −
    1
    ,
    {\displaystyle {\displaystyle C\_{0}=1\quad {\mbox{and}}\quad C\_{n}={\frac {2(2n-1)}{n+1}}C\_{n-1},}}

Task

Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.

Memoization   is not required, but may be worth the effort when using the second method above.

Related tasks

* Catalan numbers/Pascal's triangle
* Evaluate binomial coefficients

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

The recursive formulas are easily written into a constant array, either:

```
constant Catalan = 1, { [+] @_ Z* @_.reverse } ... *;
```

or

```
constant Catalan = 1, |[\*] (2, 6 ... *) Z/ 2 .. *;

# In both cases, the sixteen first values can be seen with:
.say for Catalan[^16];
```

Output:

```
1
1
2
5
14
42
132
429
1430
4862
16796
58786
208012
742900
2674440
```


[User]
Task

Print out the first   **15**   Catalan numbers by extracting them from Pascal's triangle.

See

* Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.
* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.

Related Tasks

Pascal's triangle

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;

constant @catalan = gather for 2, 4 ... * -> $ix {
    my @row := @pascal[$ix];
    my $mid = +@row div 2;
    take [-] @row[$mid, $mid+1]
}

.say for @catalan[^20];

```

Output:

```
1
2
5
14
42
132
429
1430
4862
16796
58786
208012
742900
2674440
9694845
35357670
129644790
477638700
1767263190
6564120420
```


[User]
*Reduce* is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.

Task

Show how *reduce* (or *foldl* or *foldr* etc), work (or would be implemented) in your language.

See also

* Wikipedia article:   Fold
* Wikipedia article:   Catamorphism

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

Any associative infix operator, either built-in or user-defined, may be turned into a reduce operator by putting it into square brackets (known as "the reduce metaoperator") and using it as a list operator. The operations will work left-to-right or right-to-left automatically depending on the natural associativity of the base operator.

```
my @list = 1..10;
say [+] @list;
say [*] @list;
say [~] @list;
say min @list;
say max @list;
say [lcm] @list;

```

Output:

```
55
3628800
12345678910
1
10
2520
```

In addition to the reduce metaoperator, a general higher-order function, reduce, can apply any appropriate function. Reproducing the above in this form, using the function names of those operators, we have:

```
my @list = 1..10;
say reduce &infix:<+>, @list;
say reduce &infix:<*>, @list;
say reduce &infix:<~>, @list;
say reduce &infix:<min>, @list;
say reduce &infix:<max>, @list;
say reduce &infix:<lcm>, @list;

```


[User] Write a function which returns the centre and radius of a circle passing through three point in a plane. Demonstrate the function using the points (22.83,2.07) (14.39,30.24) and (33.65,17.31)

[Assistant]
Don't bother defining all the intermediate variables.

```
sub circle( (\𝒳ᵢ, \𝒴ᵢ), (\𝒳ⱼ, \𝒴ⱼ), (\𝒳ₖ, \𝒴ₖ) ) {
   my \𝒞ₓ = ((𝒳ᵢ² + 𝒴ᵢ²) × (𝒴ₖ - 𝒴ⱼ) + (𝒳ⱼ² + 𝒴ⱼ²) × (𝒴ᵢ - 𝒴ₖ) + (𝒳ₖ² + 𝒴ₖ²) × (𝒴ⱼ - 𝒴ᵢ)) /
             (𝒳ᵢ × (𝒴ₖ - 𝒴ⱼ) + 𝒳ⱼ × (𝒴ᵢ - 𝒴ₖ) + 𝒳ₖ × (𝒴ⱼ - 𝒴ᵢ)) / 2 ;
   my \𝒞ᵧ = ((𝒳ᵢ² + 𝒴ᵢ²) × (𝒳ₖ - 𝒳ⱼ) + (𝒳ⱼ² + 𝒴ⱼ²) × (𝒳ᵢ - 𝒳ₖ) + (𝒳ₖ² + 𝒴ₖ²) × (𝒳ⱼ - 𝒳ᵢ)) /
             (𝒴ᵢ × (𝒳ₖ - 𝒳ⱼ) + 𝒴ⱼ × (𝒳ᵢ - 𝒳ₖ) + 𝒴ₖ × (𝒳ⱼ - 𝒳ᵢ)) / 2 ;
   center => (𝒞ₓ,𝒞ᵧ), radius => ((𝒞ₓ - 𝒳ᵢ)² + (𝒞ᵧ - 𝒴ᵢ)²).sqrt
}

say circle (22.83,2.07), (14.39,30.24), (33.65,17.31);

```

Output:

```
(center => (18.97851566 16.2654108) radius => 14.70862397833418)
```

You may Attempt This Online!


[User]
In analytic geometry, the *centroid* of a set of points is a point in the same domain as the set. The centroid point is chosen to show a property which can be calculated for that set.

Consider the centroid defined as the arithmetic mean of a set of points of arbitrary dimension.

Task

Create a function in your chosen programming language to calculate such a centroid using an arbitrary number of points of arbitrary dimension.

Test your function with the following groups of points

```
one-dimensional: (1), (2), (3)

```

```
two-dimensional: (8, 2), (0, 0)

```

```
three-dimensional: the set (5, 5, 0), (10, 10, 0) and the set (1, 3.1, 6.5), (-2, -5, 3.4), (-7, -4, 9), (2, 0, 3)

```

```
five-dimensional: (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 1, 0, 0), (0, 1, 0, 0, 0)

```

Stretch task

```
   Show a 3D plot image of the second 3-dimensional set and its centroid.

```

See Also

[Wikipedia page]

[Wolfram Mathworld on Centroid]

[Assistant]
```
sub centroid { ( [»+«] @^LoL ) »/» +@^LoL }

say .&centroid for
    ( (1,), (2,), (3,) ),
    ( (8, 2), (0, 0) ),
    ( (5, 5, 0), (10, 10, 0) ),
    ( (1, 3.1, 6.5), (-2, -5, 3.4), (-7, -4, 9), (2, 0, 3) ),
    ( (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 1, 0, 0), (0, 1, 0, 0, 0) ),
;

```

Output:

```
(2)
(4 1)
(7.5 7.5 0)
(-1.5 -1.475 5.475)
(0 0.25 0.25 0.25 0.25)
```


[User]
Task

Use the dictionary   unixdict.txt

Change letters   **e**   to   **i**   in words.

If the changed word is in the dictionary,   show it here on this page.

The length of any word shown should have a length   **>  5****.**

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
```
my %ei = 'unixdict.txt'.IO.words.grep({ .chars > 5 and /<[ie]>/ }).map: { $_ => .subst('e', 'i', :g) };
put %ei.grep( *.key.contains: 'e' ).grep({ %ei{.value}:exists }).sort.batch(4)».gist».fmt('%-22s').join: "\n";

```

Output:

```
analyses => analysis   atlantes => atlantis   bellow => billow       breton => briton
clench => clinch       convect => convict     crises => crisis       diagnoses => diagnosis
enfant => infant       enquiry => inquiry     frances => francis     galatea => galatia
harden => hardin       heckman => hickman     inequity => iniquity   inflect => inflict
jacobean => jacobian   marten => martin       module => moduli       pegging => pigging
psychoses => psychosis rabbet => rabbit       sterling => stirling   synopses => synopsis
vector => victor       welles => willis
```


[User]
Task

Using the dictionary   unixdict.txt,   change one letter in a word,   and if the changed word occurs in the dictionary,

then display the original word   and   the changed word here (on this page).

The length of any word shown should have a length   **>  11****.**

Note

* A copy of the specific unixdict.txt linked to should be used for consistency of results.
* Words **>  11** are required, ie of 12 characters or more.

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

Reference

* Levenshtein distance

[Assistant]
Sorensen-Dice is very fast to calculate similarities but isn't great for detecting small changes. Levenshtein is great for detecting small changes but isn't very fast.

Get the best of both worlds by doing an initial filter with Sorensen, then get exact results with Levenshtein.

```
use Text::Levenshtein;
use Text::Sorensen :sorensen;

my @words = grep {.chars > 11}, 'unixdict.txt'.IO.words;

my %bi-grams = @words.map: { $_ => .&bi-gram };

my %skip = @words.map: { $_ => 0 };

say (++$).fmt('%2d'), |$_ for @words.hyper.map: -> $this {
    next if %skip{$this};
    my ($word, @sorensens) = sorensen($this, %bi-grams);
    next unless @sorensens.=grep: { 1 > .[0] > .8 };
    @sorensens = @sorensens»[1].grep: {$this.chars == .chars};
    my @levenshtein = distance($this, @sorensens).grep: * == 1, :k;
    next unless +@levenshtein;
    %skip{$_}++ for @sorensens[@levenshtein];
    ": {$this.fmt('%14s')}  <->  ", @sorensens[@levenshtein].join: ', ';
}

```

Output:

```
 1:   aristotelean  <->  aristotelian
 2: claustrophobia  <->  claustrophobic
 3:   committeeman  <->  committeemen
 4: committeewoman  <->  committeewomen
 5:  complimentary  <->  complementary
 6:   confirmation  <->  conformation
 7:  congresswoman  <->  congresswomen
 8:   councilwoman  <->  councilwomen
 9:   draftsperson  <->  craftsperson
10:   eavesdropped  <->  eavesdropper
11:   frontiersman  <->  frontiersmen
12: handicraftsman  <->  handicraftsmen
13:   incommutable  <->  incomputable
14:   installation  <->  instillation
15:   kaleidescope  <->  kaleidoscope
16:   neuroanatomy  <->  neuroanotomy
17:   newspaperman  <->  newspapermen
18:   nonagenarian  <->  nonogenarian
19:   onomatopoeia  <->  onomatopoeic
20:   philanthrope  <->  philanthropy
21:   proscription  <->  prescription
22:  schizophrenia  <->  schizophrenic
23:  shakespearean  <->  shakespearian
24:   spectroscope  <->  spectroscopy
25:  underclassman  <->  underclassmen
26:  upperclassman  <->  upperclassmen
```


[User]
Description

The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.

The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.

Task

Code the algorithm in your language and test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.03

```
my @left;
my @right;

sub reset {
    @left  = <HXUCZVAMDSLKPEFJRIGTWOBNYQ>.comb;
    @right = <PTLNBQDEOYSFAVZKGJRIHWXUMC>.comb;
}

sub encode ($letter) {
    my $index = @right.first: $letter.uc, :k;
    my $enc   = @left[$index];
    $index.&permute;
    $enc
}

sub decode ($letter) {
    my $index = @left.first: $letter.uc, :k;
    my $dec   = @right[$index];
    $index.&permute;
    $dec
}

sub permute ($index) {
    @left.=rotate: $index;
    @left[1..13].=rotate;
    @right.=rotate: $index + 1;
    @right[2..13].=rotate;
}

reset;
say 'WELLDONEISBETTERTHANWELLSAID'.comb».&encode.join;
reset;
say 'OAHQHCNYNXTSZJRRHJBYHQKSOUJY'.comb».&decode.join;

```

Output:

```
OAHQHCNYNXTSZJRRHJBYHQKSOUJY
WELLDONEISBETTERTHANWELLSAID
```


[User]
The Chaos Game is a method of generating the attractor of an iterated function system (IFS).

One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.

Task

Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random.

After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.

See also

* The Game of Chaos

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.10

```
use Image::PNG::Portable;

my ($w, $h) = (640, 640);

my $png = Image::PNG::Portable.new: :width($w), :height($h);

my @vertex = [0, 0], [$w, 0], [$w/2, $h];

my @xy = [0,0], [0,0], [0,0], [0,0];

# :degree must be equal to or less than @xy elements.
(^1e5).race(:4degree).map: {
    my $p = ++$ % +@xy;
    @xy[$p] = do given @vertex.pick -> @v { ((@xy[$p] »+« @v) »/» 2)».Int };
    $png.set: |@xy[$p], 0, 255, 0;
}

$png.write: 'Chaos-game-perl6.png';

```


[User]
Task

Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses).

Example

The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode).

Conversely, given a code, print out the corresponding character.

[Assistant]
(formerly Perl 6)
Both Perl 5 and Raku have good Unicode support, though Raku attempts to make working with Unicode effortless. Note that even multi-byte emoji and characters outside the BMP are considered single characters. Also note: all of these routines are built into the base compiler. No need to load external libraries. See Wikipedia: Unicode character properties for explanation of Unicode property.

```
for 'AΑА𪚥🇺🇸👨👩👧👦'.comb {
    .put for
    [ 'Character',
      'Character name',
      'Unicode property',
      'Unicode script',
      'Unicode block',
      'Added in Unicode version',
      'Ordinal(s)',
      'Hex ordinal(s)',
      'UTF-8',
      'UTF-16LE',
      'UTF-16BE',
      'Round trip by name',
      'Round trip by ordinal'
    ]».fmt('%25s:')
    Z
    [ $_,
      .uninames.join(', '),
      .uniprops.join(', '),
      .uniprops('Script').join(', '),
      .uniprops('Block').join(', '),
      .uniprops('Age').join(', '),
      .ords,
      .ords.fmt('0x%X'),
      .encode('utf8'   )».fmt('%02X'),
      .encode('utf16le')».fmt('%02X').join.comb(4),
      .encode('utf16be')».fmt('%02X').join.comb(4),
      .uninames».uniparse.join,
      .ords.chrs
    ];
    say '';
}
```

Output:

```
                Character: A
           Character name: LATIN CAPITAL LETTER A
         Unicode property: Lu
           Unicode script: Latin
            Unicode block: Basic Latin
 Added in Unicode version: 1.1
               Ordinal(s): 65
           Hex ordinal(s): 0x41
                    UTF-8: 41
                 UTF-16LE: 4100
                 UTF-16BE: 0041
       Round trip by name: A
    Round trip by ordinal: A

                Character: Α
           Character name: GREEK CAPITAL LETTER ALPHA
         Unicode property: Lu
           Unicode script: Greek
            Unicode block: Greek and Coptic
 Added in Unicode version: 1.1
               Ordinal(s): 913
           Hex ordinal(s): 0x391
                    UTF-8: CE 91
                 UTF-16LE: 9103
                 UTF-16BE: 0391
       Round trip by name: Α
    Round trip by ordinal: Α

                Character: А
           Character name: CYRILLIC CAPITAL LETTER A
         Unicode property: Lu
           Unicode script: Cyrillic
            Unicode block: Cyrillic
 Added in Unicode version: 1.1
               Ordinal(s): 1040
           Hex ordinal(s): 0x410
                    UTF-8: D0 90
                 UTF-16LE: 1004
                 UTF-16BE: 0410
       Round trip by name: А
    Round trip by ordinal: А

                Character: 𪚥
           Character name: CJK UNIFIED IDEOGRAPH-2A6A5
         Unicode property: Lo
           Unicode script: Han
            Unicode block: CJK Unified Ideographs Extension B
 Added in Unicode version: 3.1
               Ordinal(s): 173733
           Hex ordinal(s): 0x2A6A5
                    UTF-8: F0 AA 9A A5
                 UTF-16LE: 69D8 A5DE
                 UTF-16BE: D869 DEA5
       Round trip by name: 𪚥
    Round trip by ordinal: 𪚥

                Character: 🇺🇸
           Character name: REGIONAL INDICATOR SYMBOL LETTER U, REGIONAL INDICATOR SYMBOL LETTER S
         Unicode property: So, So
           Unicode script: Common, Common
            Unicode block: Enclosed Alphanumeric Supplement, Enclosed Alphanumeric Supplement
 Added in Unicode version: 6.0, 6.0
               Ordinal(s): 127482 127480
           Hex ordinal(s): 0x1F1FA 0x1F1F8
                    UTF-8: F0 9F 87 BA F0 9F 87 B8
                 UTF-16LE: 3CD8 FADD 3CD8 F8DD
                 UTF-16BE: D83C DDFA D83C DDF8
       Round trip by name: 🇺🇸
    Round trip by ordinal: 🇺🇸

                Character: 👨👩👧👦
           Character name: MAN, ZERO WIDTH JOINER, WOMAN, ZERO WIDTH JOINER, GIRL, ZERO WIDTH JOINER, BOY
         Unicode property: So, Cf, So, Cf, So, Cf, So
           Unicode script: Common, Inherited, Common, Inherited, Common, Inherited, Common
            Unicode block: Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs, General Punctuation, Miscellaneous Symbols and Pictographs
 Added in Unicode version: 6.0, 1.1, 6.0, 1.1, 6.0, 1.1, 6.0
               Ordinal(s): 128104 8205 128105 8205 128103 8205 128102
           Hex ordinal(s): 0x1F468 0x200D 0x1F469 0x200D 0x1F467 0x200D 0x1F466
                    UTF-8: F0 9F 91 A8 E2 80 8D F0 9F 91 A9 E2 80 8D F0 9F 91 A7 E2 80 8D F0 9F 91 A6
                 UTF-16LE: 3DD8 68DC 0D20 3DD8 69DC 0D20 3DD8 67DC 0D20 3DD8 66DC
                 UTF-16BE: D83D DC68 200D D83D DC69 200D D83D DC67 200D D83D DC66
       Round trip by name: 👨👩👧👦
    Round trip by ordinal: 👨👩👧👦
```


[User]
Task

Write a server for a minimal text based chat.

People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.

[Assistant]
(formerly Perl 6)

**Translation of**: Python

(or at least started out that way)

**Works with**: Rakudo version 2016.07

```
react {
    my %connections;

    whenever IO::Socket::Async.listen('localhost', 4004) -> $conn {
        my $name;

        $conn.print: "Please enter your name: ";

        whenever $conn.Supply.lines -> $message {
            if !$name {
                if %connections{$message} {
                    $conn.print: "Name already taken, choose another one: ";
                }
                else {
                    $name = $message;
                    %connections{$name} = $conn;
                    broadcast "+++ %s arrived +++", $name;
                }
            }
            else {
                broadcast "%s> %s", $name, $message;
            }
            LAST {
                broadcast "--- %s left ---", $name;
                %connections{$name}:delete;
                $conn.close ;
            }
            QUIT {
                 default {
                     say "oh no, $_";
                }
            }
        }
    }

    sub broadcast ($format, $from, *@message) {
        my $text = sprintf $format, $from, |@message;
        say $text;
        for %connections.kv -> $name, $conn {
            $conn.print: "$text\n" if $name ne $from;
        }
    }
}

```

Notes:

* It operates asynchronously (using IO::Socket::Async), so a slow connection to one client won't affect other clients.
* It accepts messages encoded in UTF-8.
* It tokenizes the message streams at newline boundaries (using the Supply.lines method), which I think makes the most sense for a chat application.


[User]
Chebyshev coefficients are the basis of polynomial approximations of functions.

Task

Write a program to generate Chebyshev coefficients.

Calculate coefficients:   cosine function,   **10**   coefficients,   interval   **0   1**

[Assistant]
(formerly Perl 6)

**Translation of**: C

```
sub chebft ( Code $func, Real \a, Real \b, Int \n ) {

    my \bma = ½ × (b - a);
    my \bpa = ½ × (b + a);

    my @pi-n = ( ^n »+» ½ ) »×» (π/n);
    my @f    = ( @pi-n».cos »×» bma »+» bpa )».&$func;
    my @sums = (^n).map: { [+] @f »×« ( @pi-n »×» $_ )».cos };

    @sums »×» (2/n)
}

say chebft(&cos, 0, 1, 10)».fmt: '%+13.7e';

```

Output:

```
+1.6471695e+00
-2.3229937e-01
-5.3715115e-02
+2.4582353e-03
+2.8211906e-04
-7.7222292e-06
-5.8985565e-07
+1.1521427e-08
+6.5962992e-10
-1.0021994e-11
```


[User]
Self-explanatory: given a polygon (as an array/vector/list of its vertices) and a rectangle (in x, y, width, height format), check if they intersect.

Related tasks

* Determine if two triangles overlap
* Check if two polygons overlap

[Assistant]
**Translation of**: Go

```
# 20230810 Raku programming solution

class Vector2 { has ( $.x, $.y );
   method dot ( \other ) { self.x * other.x + self.y * other.y }
};

class Rectangle { has ( $.x, $.y, $.w, $.h ) }

class Projection { has ( $.min, $.max ) };

sub getAxes(\poly) {
   return poly.append(poly[0]).rotor(2=>-1).map: -> (\vertex1,\vertex2) {
      my \vector1 = Vector2.new: x => vertex1[0], y => vertex1[1];
      my \vector2 = Vector2.new: x => vertex2[0], y => vertex2[1];
      my \edge    = Vector2.new: x => vector1.x - vector2.x,
                                 y => vector1.y - vector2.y;
      $_ = Vector2.new: x => -edge.y, y => edge.x
   }
}

sub projectOntoAxis(\poly, \axis) {
   my \vertex0 = poly[0];
   my \vector0 = Vector2.new: x => vertex0[0], y => vertex0[1];
   my $max     = my $min = axis.dot: vector0;
   for poly -> \vertex {
      my \vector = Vector2.new: x => vertex[0], y => vertex[1];
      given axis.dot: vector { when $_ < $min { $min = $_ }
                               when $_ > $max { $max = $_ } }
   }
   return Projection.new: min => $min, max => $max
}

sub projectionsOverlap(\proj1, \proj2) {
   return ! ( proj1.max < proj2.min or proj2.max < proj1.min )
}

sub rectToPolygon( \r ) {
    return [(r.x, r.y), (r.x, r.y+r.h), (r.x+r.w, r.y+r.h), (r.x+r.w, r.y)]
}

sub polygonOverlapsRect(\poly1, \rect) {
   my \poly2 = rectToPolygon rect;
   my (\axes1,\axes2) := (poly1,poly2).map: { getAxes $_ };
   for (axes1, axes2) -> \axes {
     for axes -> \axis {
         my (\proj1,\proj2) := (poly1,poly2).map: { projectOntoAxis $_, axis }
         return False unless projectionsOverlap(proj1, proj2)
      }
   }
   return True
}

my \poly = [ <0 0>, <0 2>, <1 4>, <2 2>, <2 0> ];
my \rect1 = Rectangle.new: :4x, :0y, :2h, :2w;
my \rect2 = Rectangle.new: :1x, :0y, :8h, :2w;
say "poly  = ", poly;
say "rect1 = ", rectToPolygon(rect1);
say "rect2 = ", rectToPolygon(rect2);
say();
say "poly and rect1 overlap? ", polygonOverlapsRect(poly, rect1);
say "poly and rect2 overlap? ", polygonOverlapsRect(poly, rect2);

```

You may Attempt This Online!


[User]
Self-explanatory: given two polygons (as a list of their vertices), check whether they overlap.

Related tasks

* Determine if two triangles overlap
* Check if a polygon overlaps with a rectangle

[Assistant]
**Translation of**: Go

```
# 20230810 Raku programming solution

class Vector2 { has ( $.x, $.y );
   method dot ( \other ) { self.x * other.x + self.y * other.y }
};

class Projection { has ( $.min, $.max ) };

sub getAxes ( \poly ) {
   return poly.append(poly[0]).rotor(2=>-1).map: -> (\vertex1,\vertex2) {
      my \vector1 = Vector2.new: x => vertex1[0], y => vertex1[1];
      my \vector2 = Vector2.new: x => vertex2[0], y => vertex2[1];
      my \edge    = Vector2.new: x => vector1.x - vector2.x,
                                 y => vector1.y - vector2.y;
      $_ = Vector2.new: x => -edge.y, y => edge.x
   }
}

sub projectOntoAxis ( \poly, \axis ) {
   my \vertex0 = poly[0];
   my \vector0 = Vector2.new: x => vertex0[0], y => vertex0[1];
   my $max     = my $min = axis.dot: vector0;
   for poly -> \vertex {
      my \vector = Vector2.new: x => vertex[0], y => vertex[1];
      given axis.dot: vector { when $_ < $min { $min = $_ }
                               when $_ > $max { $max = $_ } }
   }
   return Projection.new: min => $min, max => $max
}

sub projectionsOverlap ( \proj1, \proj2 ) {
   return ! ( proj1.max < proj2.min or proj2.max < proj1.min )
}

sub polygonsOverlap( \poly1, \poly2 ) {
   my (\axes1,\axes2) := (poly1,poly2).map: { getAxes $_ };
   for (axes1, axes2) -> \axes {
     for axes -> \axis {
         my (\proj1,\proj2) := (poly1,poly2).map: { projectOntoAxis $_, axis }
         return False unless projectionsOverlap(proj1, proj2)
      }
   }
   return True
}

my \poly1 = [ <0 0>, <0 2>, <1 4>, <2 2>, <2 0> ];
my \poly2 = [ <4 0>, <4 2>, <5 4>, <6 2>, <6 0> ];
my \poly3 = [ <1 0>, <1 2>, <5 4>, <9 2>, <9 0> ];

say "poly1 = ", poly1;
say "poly2 = ", poly2;
say "poly3 = ", poly3;
say();
say "poly1 and poly2 overlap? ", polygonsOverlap(poly1, poly2);
say "poly1 and poly3 overlap? ", polygonsOverlap(poly1, poly3);
say "poly2 and poly3 overlap? ", polygonsOverlap(poly2, poly3);

```

You may Attempt This Online!


[User]
Task

Demonstrate how to check whether the input device is a terminal or not.

Related task

* Check output device is a terminal

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";

```

```
$ raku istty.raku
Input comes from tty.
$ true | raku istty.raku
Input doesn't come from tty.

```


[User]
Machin-like formulas   are useful for efficiently computing numerical approximations for

π
{\displaystyle {\displaystyle \pi }}

Task

Verify the following Machin-like formulas are correct by calculating the value of **tan**   (*right hand side)* for each equation using exact arithmetic and showing they equal **1**:

:   π
    4
    =
    arctan

    1
    2
    +
    arctan

    1
    3
    {\displaystyle {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}}}
:   π
    4
    =
    2
    arctan

    1
    3
    +
    arctan

    1
    7
    {\displaystyle {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}}}
:   π
    4
    =
    4
    arctan

    1
    5
    −
    arctan

    1
    239
    {\displaystyle {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}}}
:   π
    4
    =
    5
    arctan

    1
    7
    +
    2
    arctan

    3
    79
    {\displaystyle {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}}}
:   π
    4
    =
    5
    arctan

    29
    278
    +
    7
    arctan

    3
    79
    {\displaystyle {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}}}
:   π
    4
    =
    arctan

    1
    2
    +
    arctan

    1
    5
    +
    arctan

    1
    8
    {\displaystyle {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}}}
:   π
    4
    =
    4
    arctan

    1
    5
    −
    arctan

    1
    70
    +
    arctan

    1
    99
    {\displaystyle {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}}}
:   π
    4
    =
    5
    arctan

    1
    7
    +
    4
    arctan

    1
    53
    +
    2
    arctan

    1
    4443
    {\displaystyle {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}}}
:   π
    4
    =
    6
    arctan

    1
    8
    +
    2
    arctan

    1
    57
    +
    arctan

    1
    239
    {\displaystyle {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}}}
:   π
    4
    =
    8
    arctan

    1
    10
    −
    arctan

    1
    239
    −
    4
    arctan

    1
    515
    {\displaystyle {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}}}
:   π
    4
    =
    12
    arctan

    1
    18
    +
    8
    arctan

    1
    57
    −
    5
    arctan

    1
    239
    {\displaystyle {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}}}
:   π
    4
    =
    16
    arctan

    1
    21
    +
    3
    arctan

    1
    239
    +
    4
    arctan

    3
    1042
    {\displaystyle {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}}}
:   π
    4
    =
    22
    arctan

    1
    28
    +
    2
    arctan

    1
    443
    −
    5
    arctan

    1
    1393
    −
    10
    arctan

    1
    11018
    {\displaystyle {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}}}
:   π
    4
    =
    22
    arctan

    1
    38
    +
    17
    arctan

    7
    601
    +
    10
    arctan

    7
    8149
    {\displaystyle {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}}}
:   π
    4
    =
    44
    arctan

    1
    57
    +
    7
    arctan

    1
    239
    −
    12
    arctan

    1
    682
    +
    24
    arctan

    1
    12943
    {\displaystyle {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}}}
:   π
    4
    =
    88
    arctan

    1
    172
    +
    51
    arctan

    1
    239
    +
    32
    arctan

    1
    682
    +
    44
    arctan

    1
    5357
    +
    68
    arctan

    1
    12943
    {\displaystyle {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}}}

and confirm that the following formula is *incorrect* by showing   **tan**   (*right hand side)*   is *not*   **1**:

:   π
    4
    =
    88
    arctan

    1
    172
    +
    51
    arctan

    1
    239
    +
    32
    arctan

    1
    682
    +
    44
    arctan

    1
    5357
    +
    68
    arctan

    1
    12944
    {\displaystyle {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}}}

These identities are useful in calculating the values:

:   tan

    (
    a
    +
    b
    )
    =

    tan

    (
    a
    )
    +
    tan

    (
    b
    )

    1
    −
    tan

    (
    a
    )
    tan

    (
    b
    )
    {\displaystyle {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}}}

:   tan

    (

    arctan

    a
    b
    )
    =

    a
    b
    {\displaystyle {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}}}

:   tan

    (
    −
    a
    )
    =
    −
    tan

    (
    a
    )
    {\displaystyle {\displaystyle \tan(-a)=-\tan(a)}}

You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.

Note: to formally prove the formula correct, it would have to be shown that *−
3
π
4
{\displaystyle {\displaystyle {-3\pi \over 4}}}
 < right hand side <

5
π
4
{\displaystyle {\displaystyle {5\pi \over 4}}}* due to *tan

(
)
{\displaystyle {\displaystyle \tan()}}* periodicity.

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2018.03

The coercion to FatRat provides for exact computation for all input.

**Translation of**: Perl

```
sub taneval ($coef, $f) {
  return 0 if $coef == 0;
  return $f if $coef == 1;
  return -taneval(-$coef, $f) if $coef < 0;

  my $a = taneval($coef+>1, $f);
  my $b = taneval($coef - $coef+>1, $f);
  ($a+$b)/(1-$a*$b);
}

sub tans (@xs) {
  return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1;

  my $a = tans(@xs[0 .. (-1+@xs+>1)]);
  my $b = tans(@xs[(-1+@xs+>1)+1 .. -1+@xs]);
  ($a+$b)/(1-$a*$b);
}

sub verify (@eqn) {
  printf "%5s (%s)\n", (tans(@eqn) == 1) ?? "OK" !! "Error",
    (map { "[{.[0]} {.[1].nude.join('/')}]" }, @eqn).join(' ');
}

verify($_) for
   ([[1,1/2], [1,1/3]],
    [[2,1/3], [1,1/7]],
    [[4,1/5], [-1,1/239]],
    [[5,1/7], [2,3/79]],
    [[5,29/278], [7,3/79]],
    [[1,1/2], [1,1/5], [1,1/8]],
    [[4,1/5], [-1,1/70], [1,1/99]],
    [[5,1/7], [4,1/53], [2,1/4443]],
    [[6,1/8], [2,1/57], [1,1/239]],
    [[8,1/10], [-1,1/239], [-4,1/515]],
    [[12,1/18], [8,1/57], [-5,1/239]],
    [[16,1/21], [3,1/239], [4,3/1042]],
    [[22,1/28], [2,1/443], [-5,1/1393], [-10,1/11018]],
    [[22,1/38], [17,7/601], [10,7/8149]],
    [[44,1/57], [7,1/239], [-12,1/682], [24,1/12943]],
    [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/12943]],
    [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/21944]]
    );

```

Output:

```
   OK ([1 1/2] [1 1/3])
   OK ([2 1/3] [1 1/7])
   OK ([4 1/5] [-1 1/239])
   OK ([5 1/7] [2 3/79])
   OK ([5 29/278] [7 3/79])
   OK ([1 1/2] [1 1/5] [1 1/8])
   OK ([4 1/5] [-1 1/70] [1 1/99])
   OK ([5 1/7] [4 1/53] [2 1/4443])
   OK ([6 1/8] [2 1/57] [1 1/239])
   OK ([8 1/10] [-1 1/239] [-4 1/515])
   OK ([12 1/18] [8 1/57] [-5 1/239])
   OK ([16 1/21] [3 1/239] [4 3/1042])
   OK ([22 1/28] [2 1/443] [-5 1/1393] [-10 1/11018])
   OK ([22 1/38] [17 7/601] [10 7/8149])
   OK ([44 1/57] [7 1/239] [-12 1/682] [24 1/12943])
   OK ([88 1/172] [51 1/239] [32 1/682] [44 1/5357] [68 1/12943])
Error ([88 1/172] [51 1/239] [32 1/682] [44 1/5357] [68 1/21944])
```


[User]
Task

Demonstrate how to check whether the output device is a terminal or not.

Related task

* Check input device is a terminal

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

The .t method on a filehandle tells you whether it's going to the terminal. Here we use the note function to emit our result to standard error rather than standard out.

```
$ raku -e 'note $*OUT.t'
True
$ raku -e 'note $*OUT.t' >/dev/null
False
```


[User]
Task

Verify that a file called     **input.txt**     and   a directory called     **docs**     exist.

This should be done twice:

:   :   :   * once for the current working directory,   and
            * once for a file and a directory in the filesystem root.

Optional criteria (May 2015):   verify it works with:

:   :   :   * zero-length files
            * an unusual filename:     **`Abdu'l-Bahá.txt**

[Assistant]
(formerly Perl 6)

```
my $path = "/etc/passwd";
say $path.IO.e ?? "Exists" !! "Does not exist";

given $path.IO {
    when :d { say "$path is a directory"; }
    when :f { say "$path is a regular file"; }
    when :e { say "$path is neither a directory nor a file, but it does exist"; }
    default { say "$path does not exist" }
}

```

`when` internally uses the smart match operator `~~`, so `when :e` really does `$given ~~ :e` instead of the method call `$given.e`; both test whether the file exists.

```
run ('touch', "♥ Unicode.txt");

say "♥ Unicode.txt".IO.e;      # "True"
say "♥ Unicode.txt".IO ~~ :e;  # same

```


[User]
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the *checkpoint* at which tasks synchronize themselves before going their paths apart.

**The task**

Implement checkpoint synchronization in your language.

Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (*EA* and *EB* correspondingly), then waits for the AND-combination of the events (*EA*&*EB*) and resets its event. Consider the following scenario: A signals *EA* first and gets blocked waiting for *EA*&*EB*. Then B signals *EB* and loses the processor. Then A is released (both events are signaled) and resets *EA*. Now if B returns and enters waiting for *EA*&*EB*, it gets lost.

When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind.

If you can, implement workers joining and leaving.

[Assistant]
(formerly Perl 6)

```
my $TotalWorkers = 3;
my $BatchToRun = 3;
my @TimeTaken = (5..15); # in seconds

my $batch_progress = 0;
my @batch_lock = map { Semaphore.new(1) } , ^$TotalWorkers;
my $lock = Lock.new;

sub assembly_line ($ID) {
   my $wait;
   for ^$BatchToRun -> $j {
      $wait = @TimeTaken.roll;
      say "Worker ",$ID," at batch $j will work for ",$wait," seconds ..";
      sleep($wait);
      $lock.protect: {
         my $k = ++$batch_progress;
         print "Worker ",$ID," is done and update batch $j complete counter ";
         say "to $k of $TotalWorkers";
         if ($batch_progress == $TotalWorkers) {
            say ">>>>> batch $j completed.";
            $batch_progress = 0; # reset for next batch
            for @batch_lock { .release }; # and ready for next batch
         };
       };

       @batch_lock[$ID].acquire; # for next batch
   }
}

for ^$TotalWorkers -> $i {
   Thread.start(
      sub {
         @batch_lock[$i].acquire;
         assembly_line($i);
      }
   );
}

```

Output:

```
Worker 1 at batch 0 will work for 6 seconds ..
Worker 2 at batch 0 will work for 32 seconds ..
Worker 0 at batch 0 will work for 13 seconds ..
Worker 1 is done and update batch 0 complete counter to 1 of 3
Worker 0 is done and update batch 0 complete counter to 2 of 3
Worker 2 is done and update batch 0 complete counter to 3 of 3
>>>>> batch 0 completed.
Worker 2 at batch 1 will work for 27 seconds ..
Worker 0 at batch 1 will work for 18 seconds ..
Worker 1 at batch 1 will work for 13 seconds ..
Worker 1 is done and update batch 1 complete counter to 1 of 3
Worker 0 is done and update batch 1 complete counter to 2 of 3
Worker 2 is done and update batch 1 complete counter to 3 of 3
>>>>> batch 1 completed.
Worker 2 at batch 2 will work for 5 seconds ..
Worker 0 at batch 2 will work for 28 seconds ..
Worker 1 at batch 2 will work for 33 seconds ..
Worker 2 is done and update batch 2 complete counter to 1 of 3
Worker 0 is done and update batch 2 complete counter to 2 of 3
Worker 1 is done and update batch 2 complete counter to 3 of 3
>>>>> batch 2 completed.

```


[User]
**Context:** In December 2013 a patch was proposed to the coreutils list to add a --color option to the commands md5sum and shaXsum to display the checksums in color to make it easier to visually identify similarities in a list of printed checksums. The patch was not accepted for inclusion and instead it was suggested to create a command line utility which can be used to pipe the output of the md5sum and shaXsum commands similar to the utility colordiff.

**Task:** The task is to create this command line utility that we can use to pipe the output of the md5sum and shaXsum commands and that colors the checksum part of the output. Take each group of 3 or 6 hexadecimal characters and interpret it as if it was a color code and print it with the closest console color. Print with colors if the output is the terminal or print the input unchanged if the output of the utility is a pipe.

**Example:**

```
$ md5sum coreutils-* | checksumcolor
ab20d840e13adfebf2b6936a2dab071b  coreutils-8.29.tar.gz
b259b2936bb46009be3f5cc06a12c32d  coreutils-8.30.tar.gz
03cf26420de566c306d340df52f6ccd7  coreutils-8.31.tar.gz

```

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2019.03

To determine the colors, rather than breaking the md5sum into groups of 3 characters, (which leaves two lonely characters at the end), I elected to replicate the first 5 characters onto the end, then for each character, used it and the 5 characters following as a true-color index. I also added an option to output as HTML code for ease of pasting in here.

```
unit sub MAIN ($mode = 'ANSI');

if $*OUT.t or $mode eq 'HTML' { # if OUT is a terminal or if in HTML $module

    say '<div style="background-color:black; font-size:125%; font-family: Monaco, monospace;">'
      if $mode eq 'HTML';

    while my $line = get() {
        my $cs  = $line.words[0];
        my $css = $cs ~ $cs.substr(0,5);
        given $mode {
            when 'ANSI' {
                print "\e[48;5;232m";
                .print for $css.comb.rotor(6 => -5)».map({ ($^a, $^b).join })\
                .map( { sprintf "\e[38;2;%d;%d;%dm", |$_».parse-base(16) } ) Z~ $cs.comb;
                say "\e[0m  {$line.words[1..*]}";
            }
            when 'HTML' {
                print "$_\</span>" for $css.comb.rotor(6 => -5)\
                .map( { "<span style=\"color:#{.join};\">" } ) Z~ $cs.comb;
                say " <span style=\"color:#ffffff\"> {$line.words[1..*]}</span>";
                say '<br>';
            }
            default { say $line; }
        }
    }

    say '</div>' if $mode eq 'HTML';
} else { # just pass the unaltered line through
    .say while $_ = get();
}

```

Can't really show the ANSI output directly so show the HTML output. Essentially identical.

Output:

```
md5sum *.p6 | raku checksum-color.p6 HTML > checksum-color.html
```

yields:

f09a3fc8551d8a703d64d8e918ece236  checksum-color (another copy).p6

f09a3fc8551d8a703d64d8e918ece236  checksum-color (copy).p6

f09a3fc8551d8a703d64d8e918ece236  checksum-color.p6

bbd8a92c326c8a35e80d2d71ab8902cd  something-completely-different.p6


[User]
Given a molecule's chemical formula, calculate the   molar mass.

Introduction

* A molecule consists of atoms.   E.g. water, H2O, has two hydrogen atoms and one oxygen atom
* The mass of   H2O   is   1.008 \* 2 + 15.999 = 18.015
* An atom name consists of one upper-case letter followed by zero, one or two lower-case letters.
  + H       (hydrogen)
  + He     (helium)
  + Uue   (ununennium)
* The number of atoms is stated behind the atom or atom group
* An atom group is specified using parenthesis.   E.g. butyric acid, (CH3)2CHCOOH, has two CH3 groups
* A group may contain other groups, e.g.   COOH(C(CH3)2)3CH3

Background

* The mass is dimensionless,   it is relative to   1/12   of Carbon-12
* Carbon-12   has exactly   6 protons,   6 electrons,   and   6 neutrons
* One mole of   H2O   has the mass 18.015 grams
* One mole is defined as exactly   6.02214076×1023   particles

The above number is known as the   Avogadro constant,   which is
named by the International Bureau of Weights and Measures (IBPM);

the initials are taken from   *Bureau International des Poids et Mesures*,   the official name of the bureau.

An older name for   *Avogadro constant*   is   *Avogadro number*.

Atom masses

A mapping between some recognized element names and atomic mass is:

```
  H,     1.008
  He,    4.002602
  Li,    6.94
  Be,    9.0121831
  B,    10.81
  C,    12.011
  N,    14.007
  O,    15.999
  F,    18.998403163
  Ne,   20.1797
  Na,   22.98976928
  Mg,   24.305
  Al,   26.9815385
  Si,   28.085
  P,    30.973761998
  S,    32.06
  Cl,   35.45
  K,    39.0983
  Ar,   39.948
  Ca,   40.078
  Sc,   44.955908
  Ti,   47.867
  V,    50.9415
  Cr,   51.9961
  Mn,   54.938044
  Fe,   55.845
  Ni,   58.6934
  Co,   58.933194
  Cu,   63.546
  Zn,   65.38
  Ga,   69.723
  Ge,   72.63
  As,   74.921595
  Se,   78.971
  Br,   79.904
  Kr,   83.798
  Rb,   85.4678
  Sr,   87.62
  Y,    88.90584
  Zr,   91.224
  Nb,   92.90637
  Mo,   95.95
  Ru,   101.07
  Rh,   102.9055
  Pd,   106.42
  Ag,   107.8682
  Cd,   112.414
  In,   114.818
  Sn,   118.71
  Sb,   121.76
  I,    126.90447
  Te,   127.6
  Xe,   131.293
  Cs,   132.90545196
  Ba,   137.327
  La,   138.90547
  Ce,   140.116
  Pr,   140.90766
  Nd,   144.242
  Pm,   145
  Sm,   150.36
  Eu,   151.964
  Gd,   157.25
  Tb,   158.92535
  Dy,   162.5
  Ho,   164.93033
  Er,   167.259
  Tm,   168.93422
  Yb,   173.054
  Lu,   174.9668
  Hf,   178.49
  Ta,   180.94788
  W,    183.84
  Re,   186.207
  Os,   190.23
  Ir,   192.217
  Pt,   195.084
  Au,   196.966569
  Hg,   200.592
  Tl,   204.38
  Pb,   207.2
  Bi,   208.9804
  Po,   209
  At,   210
  Rn,   222
  Fr,   223
  Ra,   226
  Ac,   227
  Pa,   231.03588
  Th,   232.0377
  Np,   237
  U,    238.02891
  Am,   243
  Pu,   244
  Cm,   247
  Bk,   247
  Cf,   251
  Es,   252
  Fm,   257
  Ubn,  299
  Uue,  315
```

Examples

```
assert   1.008 == molar_mass('H')                  # hydrogen
assert   2.016 == molar_mass('H2')                 # hydrogen gas
assert  18.015 == molar_mass('H2O')                # water
assert  34.014 == molar_mass('H2O2')               # hydrogen peroxide
assert  34.014 == molar_mass('(HO)2')              # hydrogen peroxide
assert 142.036 == molar_mass('Na2SO4')             # sodium sulfate
assert  84.162 == molar_mass('C6H12')              # cyclohexane
assert 186.295 == molar_mass('COOH(C(CH3)2)3CH3')  # butyric or butanoic acid
assert 176.124 == molar_mass('C6H4O2(OH)4')        # vitamin C
assert 386.664 == molar_mass('C27H46O')            # cholesterol
assert 315     == molar_mass('Uue')                # ununennium

```

Reference
:   * Wikipedia article:   Molecular mass

[Assistant]
(formerly Perl 6)

```
my %ATOMIC_MASS =
    H  =>   1.008       , Fe =>  55.845    , Te => 127.60       , Ir => 192.217    ,
    He =>   4.002602    , Co =>  58.933194 , I  => 126.90447    , Pt => 195.084    ,
    Li =>   6.94        , Ni =>  58.6934   , Xe => 131.293      , Au => 196.966569 ,
    Be =>   9.0121831   , Cu =>  63.546    , Cs => 132.90545196 , Hg => 200.592    ,
    B  =>  10.81        , Zn =>  65.38     , Ba => 137.327      , Tl => 204.38     ,
    C  =>  12.011       , Ga =>  69.723    , La => 138.90547    , Pb => 207.2      ,
    N  =>  14.007       , Ge =>  72.630    , Ce => 140.116      , Bi => 208.98040  ,
    O  =>  15.999       , As =>  74.921595 , Pr => 140.90766    , Po => 209        ,
    F  =>  18.998403163 , Se =>  78.971    , Nd => 144.242      , At => 210        ,
    Ne =>  20.1797      , Br =>  79.904    , Pm => 145          , Rn => 222        ,
    Na =>  22.98976928  , Kr =>  83.798    , Sm => 150.36       , Fr => 223        ,
    Mg =>  24.305       , Rb =>  85.4678   , Eu => 151.964      , Ra => 226        ,
    Al =>  26.9815385   , Sr =>  87.62     , Gd => 157.25       , Ac => 227        ,
    Si =>  28.085       , Y  =>  88.90584  , Tb => 158.92535    , Th => 232.0377   ,
    P  =>  30.973761998 , Zr =>  91.224    , Dy => 162.500      , Pa => 231.03588  ,
    S  =>  32.06        , Nb =>  92.90637  , Ho => 164.93033    , U  => 238.02891  ,
    Cl =>  35.45        , Mo =>  95.95     , Er => 167.259      , Np => 237        ,
    Ar =>  39.948       , Ru => 101.07     , Tm => 168.93422    , Pu => 244        ,
    K  =>  39.0983      , Rh => 102.90550  , Yb => 173.054      , Am => 243        ,
    Ca =>  40.078       , Pd => 106.42     , Lu => 174.9668     , Cm => 247        ,
    Sc =>  44.955908    , Ag => 107.8682   , Hf => 178.49       , Bk => 247        ,
    Ti =>  47.867       , Cd => 112.414    , Ta => 180.94788    , Cf => 251        ,
    V  =>  50.9415      , In => 114.818    , W  => 183.84       , Es => 252        ,
    Cr =>  51.9961      , Sn => 118.710    , Re => 186.207      , Fm => 257        ,
    Mn =>  54.938044    , Sb => 121.760    , Os => 190.23       ,
;
grammar Chemical_formula {
    my @ATOMIC_SYMBOLS = %ATOMIC_MASS.keys.sort;

    rule  TOP      { ^ (<lparen>|<rparen>|<element>)+ $ }
    token quantity { \d+ }
    token lparen   { '(' }
    token rparen   { ')'                    <quantity>? }
    token element  { $<e>=[@ATOMIC_SYMBOLS] <quantity>? }
}
class Chemical_formula_actions {
    has @stack = 0;
    method TOP     ($/) { $/.make: @stack }
    method lparen  ($/) { push @stack, 0  }
    method rparen  ($/) { my $m = @stack.pop;
                          @stack[*-1] += ($<quantity> // 1) * $m }
    method element ($/) { @stack[*-1] += ($<quantity> // 1) * %ATOMIC_MASS{~$<e>} }
}
sub molar_mass ( Str $formula --> Real ) {
    Chemical_formula.parse( $formula, :actions(Chemical_formula_actions.new) )
        orelse die "Chemical formula not recognized: '$formula'";
    return $/.made.[0];
}
say .&molar_mass.fmt('%7.3f '), $_ for <H H2 H2O Na2SO4 C6H12 COOH(C(CH3)2)3CH3>;

```

Output:

```
  1.008 H
  2.016 H2
 18.015 H2O
142.036 Na2SO4
 84.162 C6H12
186.295 COOH(C(CH3)2)3CH3
```


[User]
In 1939, Jack Chernick proved that, for **n
≥
3
{\displaystyle {\displaystyle n\geq 3}}** and **m
≥
1
{\displaystyle {\displaystyle m\geq 1}}**:

```

            U
            (
            n
            ,
            m
            )
            =
            (
            6
            m
            +
            1
            )
            (
            12
            m
            +
            1
            )

              ∏

                k
                =
                1

                n
                −
                2

            (

              2

                k

            9
            m
            +
            1
            )

    {\displaystyle {\displaystyle U(n,m)=(6m+1)(12m+1)\prod _{k=1}^{n-2}(2^{k}\,9m+1)}}

```

is a Carmichael number if all the factors are primes and, for **n
>
4
{\displaystyle {\displaystyle n>4}}**, **m
{\displaystyle {\displaystyle m}}** is a multiple of **2

(
n
−
4
)
{\displaystyle {\displaystyle 2^{(n-4)}}}**.

Example

```

            U
            (
            3
            ,
            m
            )
            =
            (
            6
            m
            +
            1
            )
            (
            12
            m
            +
            1
            )
            (
            18
            m
            +
            1
            )

    {\displaystyle {\displaystyle U(3,m)=(6m+1)(12m+1)(18m+1)}}

            U
            (
            4
            ,
            m
            )
            =
            U
            (
            3
            ,
            m
            )
            (

              2

                2

            9
            m
            +
            1
            )

    {\displaystyle {\displaystyle U(4,m)=U(3,m)(2^{2}9m+1)}}

            U
            (
            5
            ,
            m
            )
            =
            U
            (
            4
            ,
            m
            )
            (

              2

                3

            9
            m
            +
            1
            )

    {\displaystyle {\displaystyle U(5,m)=U(4,m)(2^{3}9m+1)}}

            ⋯

    {\displaystyle {\displaystyle \cdots }}

            U
            (
            n
            ,
            m
            )
            =
            U
            (
            n
            −
            1
            ,
            m
            )
            (

              2

                (
                n
                −
                2
                )

            9
            m
            +
            1
            )

    {\displaystyle {\displaystyle U(n,m)=U(n-1,m)(2^{(n-2)}9m+1)}}

```

* The smallest Chernick's Carmichael number with **3** prime factors, is: U(3, 1) = 1729.
* The smallest Chernick's Carmichael number with **4** prime factors, is: U(4, 1) = 63973.
* The smallest Chernick's Carmichael number with **5** prime factors, is: U(5, 380) = 26641259752490421121.

For **n = 5**, the smallest number **m** that satisfy Chernick's conditions, is **m = 380**, therefore **U(5, 380)** is the smallest Chernick's Carmichael number with **5** prime factors.

**U(5, 380)** is a Chernick's Carmichael number because **m = 380** is a multiple of **2^(n-4)**, where **n = 5**, and the factors { (6\*380 + 1), (12\*380 + 1), (18\*380 + 1), (36\*380 + 1), (72\*380 + 1) } are all prime numbers.

Task

For **n ≥ 3**, let **a(n)** be the smallest Chernick's Carmichael number with **n** prime factors.

* Compute **a(n)** for **n = 3..9**.
* Optional: find **a(10)**.

**Note**: it's perfectly acceptable to show the terms in factorized form:

```
 a(3) = 7 * 13 * 19
 a(4) = 7 * 13 * 19 * 37
 a(5) = 2281 * 4561 * 6841 * 13681 * 27361
 ...

```

See also

* Jack Chernick, On Fermat's simple theorem (PDF), equation (8)

* OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors

Related tasks

* Carmichael 3 strong pseudoprimes

[Assistant]
(formerly Perl 6)

Use the ntheory library from Perl for primality testing since it is much, *much* faster than Raku's built-in .is-prime method.

**Translation of**: Perl

**Library:** ntheory

```
use Inline::Perl5;
use ntheory:from<Perl5> <:all>;

sub chernick-factors ($n, $m) {
    6×$m + 1, 12×$m + 1, |((1 .. $n-2).map: { (1 +< $_) × 9×$m + 1 } )
}

sub chernick-carmichael-number ($n) {

    my $multiplier = 1 +< (($n-4) max 0);
    my $iterator   = $n < 5 ?? (1 .. *) !! (1 .. *).map: * × 5;

    $multiplier × $iterator.first: -> $m {
        [&&] chernick-factors($n, $m × $multiplier).map: { is_prime($_) }
    }

}

for 3 .. 9 -> $n {
    my $m = chernick-carmichael-number($n);
    my @f = chernick-factors($n, $m);
    say "U($n, $m): {[×] @f} = {@f.join(' ⨉ ')}";
}

```

Output:

```
U(3, 1): 1729 = 7 ⨉ 13 ⨉ 19
U(4, 1): 63973 = 7 ⨉ 13 ⨉ 19 ⨉ 37
U(5, 380): 26641259752490421121 = 2281 ⨉ 4561 ⨉ 6841 ⨉ 13681 ⨉ 27361
U(6, 380): 1457836374916028334162241 = 2281 ⨉ 4561 ⨉ 6841 ⨉ 13681 ⨉ 27361 ⨉ 54721
U(7, 780320): 24541683183872873851606952966798288052977151461406721 = 4681921 ⨉ 9363841 ⨉ 14045761 ⨉ 28091521 ⨉ 56183041 ⨉ 112366081 ⨉ 224732161
U(8, 950560): 53487697914261966820654105730041031613370337776541835775672321 = 5703361 ⨉ 11406721 ⨉ 17110081 ⨉ 34220161 ⨉ 68440321 ⨉ 136880641 ⨉ 273761281 ⨉ 547522561
U(9, 950560): 58571442634534443082821160508299574798027946748324125518533225605795841 = 5703361 ⨉ 11406721 ⨉ 17110081 ⨉ 34220161 ⨉ 68440321 ⨉ 136880641 ⨉ 273761281 ⨉ 547522561 ⨉ 1095045121
```


[User]
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.

Cheryl gave them a list of ten possible dates:

```
     May 15,     May 16,     May 19
     June 17,    June 18
     July 14,    July 16
     August 14,  August 15,  August 17

```

Cheryl then tells Albert the   *month*   of birth,   and Bernard the   *day*   (of the month)   of birth.

```
 1)  Albert:   I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
 2)  Bernard:  At first I don't know when Cheryl's birthday is, but I know now.
 3)  Albert:   Then I also know when Cheryl's birthday is.

```

Task

Write a computer program to deduce, by successive elimination, Cheryl's birthday.

Related task

* Sum and Product Puzzle

References

* Wikipedia article of the same name.
* Tuple Relational Calculus

[Assistant]
(formerly Perl 6)

```
my @dates =
    { :15day, :5month },
    { :16day, :5month },
    { :19day, :5month },
    { :17day, :6month },
    { :18day, :6month },
    { :14day, :7month },
    { :16day, :7month },
    { :14day, :8month },
    { :15day, :8month },
    { :17day, :8month }
;

# Month can't have a unique day
my @filtered = @dates.grep(*.<month> != one(@dates.grep(*.<day> == one(@dates».<day>))».<month>));

# Day must be unique and unambiguous in remaining months
my $birthday = @filtered.grep(*.<day> == one(@filtered».<day>)).classify({.<month>})\
    .first(*.value.elems == 1).value[0];

# convenience array
my @months = <'' January February March April May June July August September October November December>;

say "Cheryl's birthday is { @months[$birthday<month>] } {$birthday<day>}.";

```

Output:

```
Cheryl's birthday is July 16.
```


[User]
Suppose

n

1
{\displaystyle {\displaystyle n\_{1}}}
,

n

2
{\displaystyle {\displaystyle n\_{2}}}
,

…
{\displaystyle {\displaystyle \ldots }}
,

n

k
{\displaystyle {\displaystyle n\_{k}}}
   are positive integers that are pairwise co-prime.

Then, for any given sequence of integers

a

1
{\displaystyle {\displaystyle a\_{1}}}
,

a

2
{\displaystyle {\displaystyle a\_{2}}}
,

…
{\displaystyle {\displaystyle \dots }}
,

a

k
{\displaystyle {\displaystyle a\_{k}}}
,   there exists an integer

x
{\displaystyle {\displaystyle x}}
   solving the following system of simultaneous congruences:

:   :   :   x

            ≡

            a

            1

            (
            mod

            n

            1
            )

            x

            ≡

            a

            2

            (
            mod

            n

            2
            )

            ⋮

            x

            ≡

            a

            k

            (
            mod

            n

            k
            )
            {\displaystyle {\displaystyle {\begin{aligned}x&\equiv a\_{1}{\pmod {n\_{1}}}\\x&\equiv a\_{2}{\pmod {n\_{2}}}\\&{}\ \ \vdots \\x&\equiv a\_{k}{\pmod {n\_{k}}}\end{aligned}}}}

Furthermore, all solutions

x
{\displaystyle {\displaystyle x}}
   of this system are congruent modulo the product,

N
=

n

1

n

2
…

n

k
{\displaystyle {\displaystyle N=n\_{1}n\_{2}\ldots n\_{k}}}
.

Task

Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem.

If the system of equations cannot be solved, your program must somehow indicate this.

(It may throw an exception or return a special false value.)

Since there are infinitely many solutions, the program should return the unique solution

s
{\displaystyle {\displaystyle s}}
   where

0
≤
s
≤

n

1

n

2
…

n

k
{\displaystyle {\displaystyle 0\leq s\leq n\_{1}n\_{2}\ldots n\_{k}}}
.

*Show the functionality of this program* by printing the result such that the

n
{\displaystyle {\displaystyle n}}
's   are

[
3
,
5
,
7
]
{\displaystyle {\displaystyle [3,5,7]}}
   and the

a
{\displaystyle {\displaystyle a}}
's   are

[
2
,
3
,
2
]
{\displaystyle {\displaystyle [2,3,2]}}
.

**Algorithm**:   The following algorithm only applies if the

n

i
{\displaystyle {\displaystyle n\_{i}}}
's   are pairwise co-prime.

Suppose, as above, that a solution is required for the system of congruences:

:   :   :   x
            ≡

            a

            i

            (
            mod

            n

            i
            )

            f
            o
            r

            i
            =
            1
            ,
            …
            ,
            k
            {\displaystyle {\displaystyle x\equiv a\_{i}{\pmod {n\_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k}}

Again, to begin, the product

N
=

n

1

n

2
…

n

k
{\displaystyle {\displaystyle N=n\_{1}n\_{2}\ldots n\_{k}}}
   is defined.

Then a solution

x
{\displaystyle {\displaystyle x}}
   can be found as follows:

For each

i
{\displaystyle {\displaystyle i}}
,   the integers

n

i
{\displaystyle {\displaystyle n\_{i}}}
   and

N

/

n

i
{\displaystyle {\displaystyle N/n\_{i}}}
   are co-prime.

Using the   Extended Euclidean algorithm,   we can find integers

r

i
{\displaystyle {\displaystyle r\_{i}}}
   and

s

i
{\displaystyle {\displaystyle s\_{i}}}
   such that

r

i

n

i
+

s

i
N

/

n

i
=
1
{\displaystyle {\displaystyle r\_{i}n\_{i}+s\_{i}N/n\_{i}=1}}
.

Then, one solution to the system of simultaneous congruences is:

:   :   :   x
            =

            ∑

            i
            =
            1

            k

            a

            i

            s

            i
            N

            /

            n

            i
            {\displaystyle {\displaystyle x=\sum \_{i=1}^{k}a\_{i}s\_{i}N/n\_{i}}}

and the minimal solution,

:   :   :   x

            (
            mod

            N
            )
            {\displaystyle {\displaystyle x{\pmod {N}}}}
            .

[Assistant]
(formerly Perl 6)

**Translation of**: C

**Works with**: Rakudo version 2015.12

```
# returns x where (a * x) % b == 1
sub mul-inv($a is copy, $b is copy) {
    return 1 if $b == 1;
    my ($b0, @x) = $b, 0, 1;
    ($a, $b, @x) = (
	$b,
	$a % $b,
	@x[1] - ($a div $b)*@x[0],
	@x[0]
    ) while $a > 1;
    @x[1] += $b0 if @x[1] < 0;
    return @x[1];
}

sub chinese-remainder(*@n) {
    my \N = [*] @n;
    -> *@a {
	N R% [+] map {
	    my \p = N div @n[$_];
	    @a[$_] * mul-inv(p, @n[$_]) * p
	}, ^@n
    }
}

say chinese-remainder(3, 5, 7)(2, 3, 2);

```

Output:

```
23
```


[User]
Determine the Chinese zodiac sign and related associations for a given year.

In the Chinese calendar, years are identified using two lists of labels, one of length 10 – the "celestial" (or "heavenly") "stems" – and one of length 12 – the "terrestrial" (or "earthly") "branches". The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.

Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. However, since both lists are of even length, only like-parity pairs occur (A1, A3, A5, but not A2, A4, A6), so only half of the 120 possible pairs are included in the sequence. The result is a repeating 60-year pattern within which each name pair occurs only once.

Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Wednesday, January 29, 2025 CE (in the common Gregorian calendar) begins the lunisolar Year of the Snake.

The stems do not have a one-to-one mapping like that of the branches to animals; however, the five *pairs* of consecutive stems are each associated with one of the traditional *wǔxíng* elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to *yin*, the other to *yang*.

Thus, the Chinese year beginning in 2025 CE is also the yin year of Wood. Since 12 is an even number, the association between animals and yin/yang aspect doesn't change; consecutive Years of the Snake will cycle through the five elements, but will always be yin.

Task
:   Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.

You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).

Requisite information

* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
* Each element gets two consecutive years; a yang followed by a yin.
* The first year (Wood Rat, yang) of the current 60-year cycle began in 1984 CE.

The lunisolar year beginning in 2025 CE - which, as already noted, is the year of the Wood Snake (yin) - is the 42nd of the current cycle.

Information for optional task

* The ten celestial stems are **甲** *jiă*, **乙** *yĭ*, **丙** *bĭng*, **丁** *dīng*, **戊** *wù*, **己** *jĭ*, **庚** *gēng*, **辛** *xīn*, **壬** *rén*, and **癸** *gŭi*. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
* The twelve terrestrial branches are **子** *zĭ*, **丑** *chŏu*, **寅** *yín*, **卯** *măo*, **辰** *chén*, **巳** *sì*, **午** *wŭ*, **未** *wèi*, **申** *shēn*, **酉** *yŏu*, **戌** *xū*, **亥** *hài*. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".

Therefore 1984 was **甲子** (*jiă-zĭ*, or jia3-zi3), while 2025 is **乙巳** (*yĭ-sì* or yi3-si4).

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2017.01

**Translation of**: Ruby

```
sub Chinese-zodiac ( Int $year ) {
    my @heaven  = <甲 jiă 乙 yĭ 丙 bĭng 丁 dīng 戊 wù 己 jĭ 庚 gēng 辛 xīn 壬 rén 癸 gŭi>.pairup;
    my @earth   = <子 zĭ 丑 chŏu 寅 yín 卯 măo 辰 chén 巳 sì 午 wŭ 未 wèi 申 shēn 酉 yŏu 戌 xū 亥 hài>.pairup;
    my @animal  = <Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig>;
    my @element = <Wood Fire Earth Metal Water>;
    my @aspect  = <yang yin>;

    my $cycle_year = ($year - 4) % 60;
    my $i2         = $cycle_year % 2;
    my $i10        = $cycle_year % 10;
    my $i12        = $cycle_year % 12;

    %(
        'Han'     => @heaven[$i10].key ~ @earth[$i12].key,
        'pinyin'  => @heaven[$i10].value ~ @earth[$i12].value,
        'heaven'  => @heaven[$i10],
        'earth'   => @earth[$i12],
        'element' => @element[$i10 div 2],
        'animal'  => @animal[$i12],
        'aspect'  => @aspect[$i2],
        'cycle'   => $cycle_year + 1
    )
}

# TESTING
printf "%d: %s (%s, %s %s; %s - year %d in the cycle)\n",
    $_, .&Chinese-zodiac<Han pinyin element animal aspect cycle>
    for 1935, 1938, 1968, 1972, 1976, 1984, Date.today.year;

```

Output:

```
1935: 乙亥 (yĭhài, Wood Pig; yin - year 12 in the cycle)
1938: 戊寅 (wùyín, Earth Tiger; yang - year 15 in the cycle)
1968: 戊申 (wùshēn, Earth Monkey; yang - year 45 in the cycle)
1972: 壬子 (rénzĭ, Water Rat; yang - year 49 in the cycle)
1976: 丙辰 (bĭngchén, Fire Dragon; yang - year 53 in the cycle)
1984: 甲子 (jiăzĭ, Wood Rat; yang - year 1 in the cycle)
2017: 丁酉 (dīngyŏu, Fire Rooster; yin - year 34 in the cycle)
```


[User]
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:

:   A
    =
    L

    L

    T
    {\displaystyle {\displaystyle A=LL^{T}}}

L
{\displaystyle {\displaystyle L}}
 is called the *Cholesky factor* of

A
{\displaystyle {\displaystyle A}}
, and can be interpreted as a generalized square root of

A
{\displaystyle {\displaystyle A}}
, as described in Cholesky decomposition.

In a 3x3 example, we have to solve the following system of equations:

:   A

    =

    (

    a

    11

    a

    21

    a

    31

    a

    21

    a

    22

    a

    32

    a

    31

    a

    32

    a

    33
    )

    =

    (

    l

    11

    0

    0

    l

    21

    l

    22

    0

    l

    31

    l

    32

    l

    33
    )

    (

    l

    11

    l

    21

    l

    31

    0

    l

    22

    l

    32

    0

    0

    l

    33
    )
    ≡
    L

    L

    T

    =

    (

    l

    11

    2

    l

    21

    l

    11

    l

    31

    l

    11

    l

    21

    l

    11

    l

    21

    2
    +

    l

    22

    2

    l

    31

    l

    21
    +

    l

    32

    l

    22

    l

    31

    l

    11

    l

    31

    l

    21
    +

    l

    32

    l

    22

    l

    31

    2
    +

    l

    32

    2
    +

    l

    33

    2
    )
    {\displaystyle {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a\_{11}&a\_{21}&a\_{31}\\a\_{21}&a\_{22}&a\_{32}\\a\_{31}&a\_{32}&a\_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l\_{11}&0&0\\l\_{21}&l\_{22}&0\\l\_{31}&l\_{32}&l\_{33}\\\end{pmatrix}}{\begin{pmatrix}l\_{11}&l\_{21}&l\_{31}\\0&l\_{22}&l\_{32}\\0&0&l\_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l\_{11}^{2}&l\_{21}l\_{11}&l\_{31}l\_{11}\\l\_{21}l\_{11}&l\_{21}^{2}+l\_{22}^{2}&l\_{31}l\_{21}+l\_{32}l\_{22}\\l\_{31}l\_{11}&l\_{31}l\_{21}+l\_{32}l\_{22}&l\_{31}^{2}+l\_{32}^{2}+l\_{33}^{2}\end{pmatrix}}\end{aligned}}}}

We can see that for the diagonal elements (

l

k
k
{\displaystyle {\displaystyle l\_{kk}}}
) of

L
{\displaystyle {\displaystyle L}}
 there is a calculation pattern:

:   l

    11
    =

    a

    11
    {\displaystyle {\displaystyle l\_{11}={\sqrt {a\_{11}}}}}
:   l

    22
    =

    a

    22
    −

    l

    21

    2
    {\displaystyle {\displaystyle l\_{22}={\sqrt {a\_{22}-l\_{21}^{2}}}}}
:   l

    33
    =

    a

    33
    −
    (

    l

    31

    2
    +

    l

    32

    2
    )
    {\displaystyle {\displaystyle l\_{33}={\sqrt {a\_{33}-(l\_{31}^{2}+l\_{32}^{2})}}}}

or in general:

:   l

    k
    k
    =

    a

    k
    k
    −

    ∑

    j
    =
    1

    k
    −
    1

    l

    k
    j

    2
    {\displaystyle {\displaystyle l\_{kk}={\sqrt {a\_{kk}-\sum \_{j=1}^{k-1}l\_{kj}^{2}}}}}

For the elements below the diagonal (

l

i
k
{\displaystyle {\displaystyle l\_{ik}}}
, where

i
>
k
{\displaystyle {\displaystyle i>k}}
) there is also a calculation pattern:

:   l

    21
    =

    1

    l

    11

    a

    21
    {\displaystyle {\displaystyle l\_{21}={\frac {1}{l\_{11}}}a\_{21}}}
:   l

    31
    =

    1

    l

    11

    a

    31
    {\displaystyle {\displaystyle l\_{31}={\frac {1}{l\_{11}}}a\_{31}}}
:   l

    32
    =

    1

    l

    22
    (

    a

    32
    −

    l

    31

    l

    21
    )
    {\displaystyle {\displaystyle l\_{32}={\frac {1}{l\_{22}}}(a\_{32}-l\_{31}l\_{21})}}

which can also be expressed in a general formula:

:   l

    i
    k
    =

    1

    l

    k
    k

    (

    a

    i
    k
    −

    ∑

    j
    =
    1

    k
    −
    1

    l

    i
    j

    l

    k
    j
    )
    {\displaystyle {\displaystyle l\_{ik}={\frac {1}{l\_{kk}}}\left(a\_{ik}-\sum \_{j=1}^{k-1}l\_{ij}l\_{kj}\right)}}

**Task description**

The task is to implement a routine which will return a lower Cholesky factor

L
{\displaystyle {\displaystyle L}}
 for every given symmetric, positive definite nxn matrix

A
{\displaystyle {\displaystyle A}}
. You should then test it on the following two examples and include your output.

Example 1:

```
25  15  -5                 5   0   0
15  18   0         -->     3   3   0
-5   0  11                -1   1   3

```

Example 2:

```
18  22   54   42           4.24264    0.00000    0.00000    0.00000
22  70   86   62   -->     5.18545    6.56591    0.00000    0.00000
54  86  174  134          12.72792    3.04604    1.64974    0.00000
42  62  134  106           9.89949    1.62455    1.84971    1.39262

```

Note

1. The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size.
2. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.

[Assistant]
(formerly Perl 6)

```
sub cholesky(@A) {
    my @L = @A »×» 0;
    for ^@A -> \i {
        for 0..i -> \j {
            @L[i;j] = (i == j ?? &sqrt !! 1/@L[j;j] × * )\      # select function
                      (@A[i;j] - [+] (@L[i;*] Z× @L[j;*])[^j])  # provide value
        }
    }
    @L
}

.fmt('%3d').say for cholesky [
    [25],
    [15, 18],
    [-5,  0, 11],
];

say '';

.fmt('%6.3f').say for cholesky [
    [18, 22,  54,  42],
    [22, 70,  86,  62],
    [54, 86, 174, 134],
    [42, 62, 134, 106],
];

```

Output:

```
  5
  3   3
 -1   1   3

 4.243  0.000  0.000  0.000
 5.185  6.566  0.000  0.000
12.728  3.046  1.650  0.000
 9.899  1.625  1.850  1.393
```