[User]
Chowla numbers are also known as:

:   :   * Chowla's function
        * chowla numbers
        * the chowla function
        * the chowla number
        * the chowla sequence

The chowla number of   **n**   is   (as defined by Chowla's function):

:   :   * the sum of the divisors of   **n**     excluding unity and   **n**
        * where   **n**   is a positive integer

The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995),

a London born Indian American mathematician specializing in *number theory*.

German mathematician Carl Friedrich Gauss (1777─1855) said:

```
   "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics".

```

Definitions

Chowla numbers can also be expressed as:

```

   chowla(n) = sum of divisors of  n  excluding unity and  n
   chowla(n) = sum(       divisors(n))   - 1  -  n
   chowla(n) = sum( properDivisors(n))   - 1
   chowla(n) = sum(aliquotDivisors(n))   - 1
   chowla(n) = aliquot(n)                - 1
   chowla(n) = sigma(n)                  - 1  -  n
   chowla(n) = sigmaProperDivisiors(n)   - 1

   chowla(a*b) =  a + b,    if  a  and  b  are distinct primes
   if  chowla(n) =  0,       and n > 1,  then   n   is prime
   if  chowla(n) =  n - 1,  and n > 1,  then   n   is a perfect number

```

Task
:   :   * create a   **chowla**   function that returns the   **chowla number**   for a positive integer   **n**
        * Find and display   (1 per line)   for the 1st   **37**   integers:

        :   :   * the integer   (the index)
                * the chowla number for that integer

        * For finding primes, use the   **chowla**   function to find values of zero
        * Find and display the   *count*   of the primes up to              **100**
        * Find and display the   *count*   of the primes up to           **1,000**
        * Find and display the   *count*   of the primes up to         **10,000**
        * Find and display the   *count*   of the primes up to       **100,000**
        * Find and display the   *count*   of the primes up to    **1,000,000**
        * Find and display the   *count*   of the primes up to  **10,000,000**
        * For finding perfect numbers, use the   **chowla**   function to find values of   **n - 1**
        * Find and display all   perfect numbers   up to   **35,000,000**
        * use commas within appropriate numbers
        * show all output here

Related tasks
:   * totient function
    * perfect numbers
    * Proper divisors
    * Sieve of Eratosthenes

See also
:   * the OEIS entry for   A48050 Chowla's function.

[Assistant]
(formerly Perl 6)
Much like in the Totient function task, we are using a thing poorly suited to finding prime numbers, to find large quantities of prime numbers.

:   :   :   (From the task's author):   the object is not in the   *finding*   of prime numbers,   but in   *verifying*   that the Chowla function operates correctly   (and **can be** used for such a purpose, whatever the efficacy).   These types of comments belong in the *discussion* page.   Whether or not this function is poorly suited for finding prime numbers (or anything else) is not part of this task's purpose or objective.

(For a more reasonable test, reduce the orders-of-magnitude range in the "Primes count" line from 2..7 to 2..5)

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

sub schnitzel (\Radda, \radDA = 0) {
    Radda.is-prime ?? !Radda !! ?radDA ?? Radda
    !! sum flat (2 .. Radda.sqrt.floor).map: -> \RAdda {
        my \RADDA = Radda div RAdda;
        next if RADDA * RAdda !== Radda;
        RAdda !== RADDA ?? (RAdda, RADDA) !! RADDA
    }
}

my \chowder = cache (1..Inf).hyper(:8degree).grep( !*.&schnitzel: 'panini' );

my \mung-daal = lazy gather for chowder -> \panini {
    my \gazpacho = 2**panini - 1;
    take gazpacho * 2**(panini - 1) unless schnitzel gazpacho, panini;
}

printf "chowla(%2d) = %2d\n", $_, .&schnitzel for 1..37;

say '';

printf "Count of primes up to %10s: %s\n", comma(10**$_),
  comma chowder.first( * > 10**$_, :k) for 2..7;

say "\nPerfect numbers less than 35,000,000";

.&comma.say for mung-daal[^5];

```

Output:

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

Count of primes up to        100: 25
Count of primes up to      1,000: 168
Count of primes up to     10,000: 1,229
Count of primes up to    100,000: 9,592
Count of primes up to  1,000,000: 78,498
Count of primes up to 10,000,000: 664,579

Perfect numbers less than 35,000,000
6
28
496
8,128
33,550,336

```


[User]
Task

In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.

* **Church zero** always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
* **Church one** applies its first argument f just once to its second argument x, yielding **f(x)**
* **Church two** applies its first argument f twice to its second argument x, yielding **f(f(x))**
* and each successive Church numeral applies its first argument one additional time to its second argument, **f(f(f(x)))**, **f(f(f(f(x))))** ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.

Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.

In your language define:

* Church Zero,
* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
* functions for Addition, Multiplication and Exponentiation over Church numerals,
* a function to convert integers to corresponding Church numerals,
* and a function to convert Church numerals to corresponding integers.

You should:

* Derive Church numerals three and four in terms of Church zero and a Church successor function.
* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
* convert each result back to an integer, and return it or print it to the console.

[Assistant]
(formerly Perl 6)

### Traditional subs and sigils

**Translation of**: Python

```
constant $zero  = sub (Code $f) {
                  sub (     $x) { $x }}

constant $succ  = sub (Code $n) {
                  sub (Code $f) {
                  sub (     $x) { $f($n($f)($x)) }}}

constant $add   = sub (Code $n) {
                  sub (Code $m) {
                  sub (Code $f) {
                  sub (     $x) { $m($f)($n($f)($x)) }}}}

constant $mult  = sub (Code $n) {
                  sub (Code $m) {
                  sub (Code $f) {
                  sub (     $x) { $m($n($f))($x) }}}}

constant $power = sub (Code $b) {
                  sub (Code $e) { $e($b) }}

sub to_int (Code $f) {
    sub countup (Int $i) { $i + 1 }
    return $f(&countup).(0)
}

sub from_int (Int $x) {
    multi sub countdown (     0) { $zero }
    multi sub countdown (Int $i) { $succ( countdown($i - 1) ) }
    return countdown($x);
}

constant $three = $succ($succ($succ($zero)));
constant $four  = from_int(4);

say map &to_int,
    $add(   $three )( $four  ),
    $mult(  $three )( $four  ),
    $power( $four  )( $three ),
    $power( $three )( $four  ),
;

```

### Arrow subs without sigils

**Translation of**: Julia

```
my \zero  = -> \f {                 -> \x { x               }}
my \succ  = -> \n {         -> \f { -> \x { f.(n.(f)(x))    }}}
my \add   = -> \n { -> \m { -> \f { -> \x { m.(f)(n.(f)(x)) }}}}
my \mult  = -> \n { -> \m { -> \f { -> \x { m.(n.(f))(x)    }}}}
my \power = -> \b {                 -> \e { e.(b)           }}

my \to_int   = -> \f { f.( -> \i { i + 1 } ).(0) }
my \from_int = -> \i { i == 0 ?? zero !! succ.( &?BLOCK(i - 1) ) }

my \three = succ.(succ.(succ.(zero)));
my \four  = from_int.(4);

say map -> \f { to_int.(f) },
    add.(   three )( four  ),
    mult.(  three )( four  ),
    power.( four  )( three ),
    power.( three )( four  ),
;

```

Output:

```
(7 12 64 81)
```


[User]
**Cipolla's algorithm**

Solve **x² ≡ n (mod p)**

In computational number theory, Cipolla's algorithm is a technique for solving an equation of the form **x² ≡ n (mod p)**, where p is an odd prime and x ,n ∊ Fp = {0, 1, ... p-1}.

To apply the algorithm we need the Legendre symbol, and arithmetic in Fp².

Legendre symbol

* The Legendre symbol ( a | p) denotes the value of a ^ ((p-1)/2) (mod p)
* (a | p) ≡ 1 if a is a square (mod p)
* (a | p) ≡ -1 if a is not a square (mod p)
* (a | p) ≡ 0 is a ≡ 0

Arithmetic in Fp²

Let ω a symbol such as ω² is a member of Fp and not a square, x and y members of Fp. The set Fp² is defined as {x + ω y }. The subset { x + 0 ω} of Fp² is Fp. Fp² is somewhat equivalent to the field of complex number, with ω analoguous to i, and i² = -1 . Remembering that all operations are modulo p, addition, multiplication and exponentiation in Fp² are defined as :

* (x1 + ω y1) + (x2 + ω y2) := (x1 + x2 + ω (y1 + y2))
* (x1 + ω y1) \* (x2 + ω y2) := (x1\*x2 + y1\*y2\*ω²) + ω (x1\*y2 + x2\*y1)
  + (0 + ω) \* (0 + ω) := (ω² + 0 ω) ≡ ω² in Fp
* (x1 + ω y1) ^ n := (x + ω y) \* (x + ω y) \* ... ( n times) (1)

**Algorithm pseudo-code**

* Input : p an odd prime, and n ≠ 0 in Fp
* Step 0. Check that n is indeed a square  : (n | p) must be ≡ 1
* Step 1. Find, by trial and error, an a > 0 such as (a² - n) is **not** a square : (a²-n | p) must be ≡ -1.
* Step 2. Let ω² = a² - n. Compute, in Fp2 : (a + ω) ^ ((p + 1)/2) (mod p)

To compute this step, use a pair of numbers, initially [a,1], and use repeated "multiplication" which is defined such that [c,d] times [e,f] is (mod p) [ c\*c + ω²\*f\*f, d\*e + c\*f ].

* Step 3. Check that the result is ≡ x + 0 \* ω in Fp2, that is x in Fp.
* Step 4. Output the two positive solutions, x and p - x (mod p).
* Step 5. Check that x \* x ≡ n (mod p)

**Example** from Wikipedia

```
n := 10 , p := 13
Legendre(10,13) → 1         // 10 is indeed a square
a := 2                      // try
ω² := a*a - 10             // ≡ 7 ≡ -6
Legendre (ω² , 13) → -1    // ok - not square
(2 + ω) ^ 7 → 6 + 0 ω      // by modular exponentiation (1)
                            // 6 and (13 - 6) = 7 are solutions
(6 * 6) % 13 → 10           // = n . Checked.

```

**Task**

Implement the above.

Find solutions (if any) for

* n = 10 p = 13
* n = 56 p = 101
* n = 8218 p = 10007
* n = 8219 p = 10007
* n = 331575 p = 1000003

**Extra credit**

* n 665165880 p 1000000007
* n 881398088036 p 1000000000039
* n = 34035243914635549601583369544560650254325084643201 p = 10^50 + 151

See also:

* Modular exponentiation
* Tonelli-Shanks algorithm

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.10

**Translation of**: Sidef

```
#  Legendre operator (𝑛│𝑝)
sub infix:<│> (Int \𝑛, Int \𝑝 where 𝑝.is-prime && (𝑝 != 2)) {
    given 𝑛.expmod( (𝑝-1) div 2, 𝑝 ) {
        when 0  {  0 }
        when 1  {  1 }
        default { -1 }
    }
}

# a coordinate in a Field of p elements
class Fp {
    has Int $.x;
    has Int $.y;
}

sub cipolla ( Int \𝑛, Int \𝑝 ) {
    note "Invalid parameters ({𝑛}, {𝑝})"
      and return Nil if (𝑛│𝑝) != 1;
    my $ω2;
    my $a = 0;
    loop {
        last if ($ω2 = ($a² - 𝑛) % 𝑝)│𝑝 < 0;
        $a++;
    }

    # define a local multiply operator for Field coordinates
    multi sub infix:<*> ( Fp $a, Fp $b ){
        Fp.new: :x(($a.x * $b.x + $a.y * $b.y * $ω2) % 𝑝),
                :y(($a.x * $b.y + $b.x * $a.y)       % 𝑝)
    }

    my $r = Fp.new: :x(1),  :y(0);
    my $s = Fp.new: :x($a), :y(1);

    for (𝑝+1) +> 1, * +> 1 ... 1 {
        $r *= $s if $_ % 2;
        $s *= $s;
    }
    return Nil if $r.y;
    $r.x;
}

my @tests = (
    (10, 13),
    (56, 101),
    (8218, 10007),
    (8219, 10007),
    (331575, 1000003),
    (665165880, 1000000007),
    (881398088036, 1000000000039),
    (34035243914635549601583369544560650254325084643201,
      100000000000000000000000000000000000000000000000151)
);

for @tests -> ($n, $p) {
   my $r = cipolla($n, $p);
   say $r ?? "Roots of $n are ($r, {$p-$r}) mod $p"
          !! "No solution for ($n, $p)"
}

```

Output:

```
Roots of 10 are (6, 7) mod 13
Roots of 56 are (37, 64) mod 101
Roots of 8218 are (9872, 135) mod 10007
Invalid parameters (8219, 10007)
No solution for (8219, 10007)
Roots of 331575 are (855842, 144161) mod 1000003
Roots of 665165880 are (475131702, 524868305) mod 1000000007
Roots of 881398088036 are (791399408049, 208600591990) mod 1000000000039
Roots of 34035243914635549601583369544560650254325084643201 are (82563118828090362261378993957450213573687113690751, 17436881171909637738621006042549786426312886309400) mod 100000000000000000000000000000000000000000000000151

```


[User]
2 circles with a given radius through 2 points in 2D space.

2 circles with a given radius through 2 points in 2D space.

Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.

Exceptions

1. r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
2. If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
3. If the points form a diameter then return two identical circles *or* return a single circle, according to which is the most natural mechanism for the implementation language.
4. If the points are too far apart then no circles can be drawn.

Task detail

* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, *or some indication of special cases where two, possibly equal, circles cannot be returned*.
* Show here the output for the following inputs:

```
      p1                p2           r
0.1234, 0.9876    0.8765, 0.2345    2.0
0.0000, 2.0000    0.0000, 0.0000    1.0
0.1234, 0.9876    0.1234, 0.9876    2.0
0.1234, 0.9876    0.8765, 0.2345    0.5
0.1234, 0.9876    0.1234, 0.9876    0.0

```

Related task

* Total circles area.

See also

* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.08.1

```
multi sub circles (@A, @B where ([and] @A Z== @B), 0.0) { 'Degenerate point' }
multi sub circles (@A, @B where ([and] @A Z== @B), $)   { 'Infinitely many share a point' }
multi sub circles (@A, @B, $radius) {
    my @middle = (@A Z+ @B) X/ 2;
    my @diff = @A Z- @B;
    my $q = sqrt [+] @diff X** 2;
    return 'Too far apart' if $q > $radius * 2;

    my @orth = -@diff[0], @diff[1] X* sqrt($radius ** 2 - ($q / 2) ** 2) / $q;
    return (@middle Z+ @orth), (@middle Z- @orth);
}

my @input =
    ([0.1234, 0.9876],  [0.8765, 0.2345],   2.0),
    ([0.0000, 2.0000],  [0.0000, 0.0000],   1.0),
    ([0.1234, 0.9876],  [0.1234, 0.9876],   2.0),
    ([0.1234, 0.9876],  [0.8765, 0.2345],   0.5),
    ([0.1234, 0.9876],  [0.1234, 0.9876],   0.0),
    ;

for @input {
    say .list.raku, ': ', circles(|$_).join(' and ');
}

```

Output:

```
([0.1234, 0.9876], [0.8765, 0.2345], 2.0): 1.86311180165819 1.97421180165819 and -0.863211801658189 -0.752111801658189
([0.0, 2.0], [0.0, 0.0], 1.0): 0 1 and 0 1
([0.1234, 0.9876], [0.1234, 0.9876], 2.0): Infinitely many share a point
([0.1234, 0.9876], [0.8765, 0.2345], 0.5): Too far apart
([0.1234, 0.9876], [0.1234, 0.9876], 0.0): Degenerate point
```

Another possibility is to use the Complex plane,
for it often makes calculations easier with plane geometry:

```
multi sub circles ($a, $b where $a == $b, 0.0) { 'Degenerate point' }
multi sub circles ($a, $b where $a == $b, $)   { 'Infinitely many share a point' }
multi sub circles ($a, $b, $r) {
    my $h = ($b - $a) / 2;
    my $l = sqrt($r**2 - $h.abs**2);
    return 'Too far apart' if $l.isNaN;
    return map { $a + $h + $l * $_ * $h / $h.abs }, i, -i;
}

my @input =
    (0.1234 + 0.9876i,  0.8765 + 0.2345i,   2.0),
    (0.0000 + 2.0000i,  0.0000 + 0.0000i,   1.0),
    (0.1234 + 0.9876i,  0.1234 + 0.9876i,   2.0),
    (0.1234 + 0.9876i,  0.8765 + 0.2345i,   0.5),
    (0.1234 + 0.9876i,  0.1234 + 0.9876i,   0.0),
    ;

for @input {
    say .join(', '), ': ', circles(|$_).join(' and ');
}

```

Output:

```
0.1234+0.9876i, 0.8765+0.2345i, 2: 1.86311180165819+1.97421180165819i and -0.863211801658189-0.752111801658189i
0+2i, 0+0i, 1: 0+1i and 0+1i
0.1234+0.9876i, 0.1234+0.9876i, 2: Infinitely many share a point
0.1234+0.9876i, 0.8765+0.2345i, 0.5: Too far apart
0.1234+0.9876i, 0.1234+0.9876i, 0: Degenerate point
```


[User]
Definitions

A **circular prime** is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.

For example:
**1193** is a circular prime, since **1931**, **9311** and **3119** are all also prime.

Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So **13** is a circular prime, but **31** is not.

A **repunit** (denoted by R) is a number whose base 10 representation contains only the digit **1**.

For example:
R(2) = 11 and R(5) = 11111 are repunits.

Task

* Find the first 19 circular primes.

* If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes.

* (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can.

See also

* Wikipedia article - Circular primes.
* Wikipedia article - Repunit.
* OEIS sequence A016114 - Circular primes.

[Assistant]
Most of the repunit testing is relatively speedy using the ntheory library. The really slow ones are R(25031), at ~42 seconds and R(49081) at 922(!!) seconds.

**Library:** ntheory

```
sub isCircular(\n) {
   return False unless n.is-prime;
   my @circular = n.comb;
   return False if @circular.min < @circular[0];
   for 1 ..^ @circular -> $i {
      return False unless .is-prime and $_ >= n given @circular.rotate($i).join;
   }
   True
}

say "The first 19 circular primes are:";
say ((2..*).hyper.grep: { isCircular $_ })[^19];

say "\nThe next 4 circular primes, in repunit format, are:";
loop ( my $i = 7, my $count = 0; $count < 4; $i++ ) {
   ++$count, say "R($i)" if (1 x $i).is-prime
}

use ntheory:from<Perl5> qw[is_prime];

say "\nRepunit testing:";

(5003, 9887, 15073, 25031, 35317, 49081).map: {
    my $now = now;
    say "R($_): Prime? ", ?is_prime("{1 x $_}"), "  {(now - $now).fmt: '%.2f'}"
}

```

Output:

```
The first 19 circular primes are:
(2 3 5 7 11 13 17 37 79 113 197 199 337 1193 3779 11939 19937 193939 199933)

The next 4 circular primes, in repunit format, are:
R(19)
R(23)
R(317)
R(1031)

Repunit testing:
R(5003): Prime? False  0.00
R(9887): Prime? False  0.01
R(15073): Prime? False  0.02
R(25031): Prime? False  41.40
R(35317): Prime? False  0.32
R(49081): Prime? True  921.73
```


[User]
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from **0** to **9999**.

How they work

All Cistercian numerals begin with a vertical line segment, which by itself represents the number **0**. Then, glyphs representing the digits **1** through **9** are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:

:   * The **upper-right** quadrant represents the **ones** place.
    * The **upper-left** quadrant represents the **tens** place.
    * The **lower-right** quadrant represents the **hundreds** place.
    * The **lower-left** quadrant represents the **thousands** place.

Please consult the following image for examples of Cistercian numerals showing each glyph: [1]

Task

:   * Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).

:   * Use the routine to show the following Cistercian numerals:

:   :   * 0
        * 1
        * 20
        * 300
        * 4000
        * 5555
        * 6789
        * And a number of your choice!

Notes

Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output.

See also

:   * **Numberphile - The Forgotten Number System**
    * **dcode.fr - Online Cistercian numeral converter**

[Assistant]
Handles 0 through 9999 only. No error trapping. If you feed it an unsupported number it will truncate to maximum 4 digits.

```
my @line-segments = (0, 0, 0, 100),
    (0,  0, 35,  0), (0, 35, 35, 35), (0,  0, 35, 35), (0, 35, 35,  0), ( 35,  0, 35, 35),
    (0,  0,-35,  0), (0, 35,-35, 35), (0,  0,-35, 35), (0, 35,-35,  0), (-35,  0,-35, 35),
    (0,100, 35,100), (0, 65, 35, 65), (0,100, 35, 65), (0, 65, 35,100), ( 35, 65, 35,100),
    (0,100,-35,100), (0, 65,-35, 65), (0,100,-35, 65), (0, 65,-35,100), (-35, 65,-35,100);

my @components = map {@line-segments[$_]}, |((0, 5, 10, 15).map: -> $m {
    |((0,), (1,), (2,), (3,), (4,), (1,4), (5,), (1,5), (2,5), (1,2,5)).map: {$_ »+» $m}
});

my $out = 'Cistercian-raku.svg'.IO.open(:w);

$out.say: # insert header
q|<svg  width="875" height="470" style="stroke:black;" version="1.1" xmlns="http://www.w3.org/2000/svg">
 <rect width="100%" height="100%" style="fill:white;"/>|;

my $hs = 50; # horizontal spacing
my $vs = 25; # vertical spacing

for flat ^10, 20, 300, 4000, 5555, 6789, 9394, (^10000).pick(14) -> $cistercian {

    $out.say: |@components[0].map: { # draw zero / base vertical bar
        qq|<line x1="{.[0] + $hs}" y1="{.[1] + $vs}" x2="{.[2] + $hs}" y2="{.[3] + $vs}"/>|
    };

    my @orders-of-magnitude = $cistercian.polymod(10 xx *);

    for @orders-of-magnitude.kv -> $order, $value {
        next unless $value; # skip zeros, already drew zero bar
        last if $order > 3; # truncate too large integers

        # draw the component line segments
        $out.say: join "\n", @components[$order * 10 + $value].map: {
            qq|<line x1="{.[0] + $hs}" y1="{.[1] + $vs}" x2="{.[2] + $hs}" y2="{.[3] + $vs}"/>|
        }
    }

    # insert the decimal number below
    $out.say: qq|<text x="{$hs - 5}" y="{$vs + 120}">{$cistercian}</text>|;

    if ++$ %% 10 { # next row
        $hs = -35;
        $vs += 150;
    }

    $hs += 85; # increment horizontal spacing

}
$out.say: q|</svg>|; # insert footer

```

Output:


[User]
In object-oriented programming **class** is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.

The first type T from the class T sometimes is called the **root type** of the class.

A class of types itself, as a type, has the values and operations of its own.
The operations of are usually called **methods** of the root type.
Both operations and values are called polymorphic.

A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument.

The action of choice the type-specific implementation of a polymorphic operation is called **dispatch**. Correspondingly, polymorphic operations are often called **dispatching** or **virtual**.
Operations with multiple arguments and/or the results of the class are called **multi-methods**.
A further generalization of is the operation with arguments and/or results from different classes.

* single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation *x*.*f*() is used instead of mathematical *f*(*x*).
* multiple-dispatch languages allow many arguments and/or results to control the dispatch.

A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type.
This type is sometimes called **the most specific type** of a [polymorphic] value.
The type tag of the value is used in order to resolve the dispatch.
The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class.

In many OO languages
the type of the class of T and T itself are considered equivalent.
In some languages they are distinct (like in Ada).
When class T and T are equivalent, there is no way to distinguish
polymorphic and specific values.

Task

Create a basic class with a method, a constructor, an instance variable and how to instantiate it.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

```
class Camel { has Int $.humps = 1; }

my Camel $a .= new;
say $a.humps;  # Automatically generated accessor method.

my Camel $b .= new: humps => 2;
say $b.humps;
```

A more complex example:

```
class Butterfly {
    has Int $!age;   # With the ! twigil, no public accessor method is generated
    has Str $.name;
    has Str $.color;
    has Bool $.wings;

    submethod BUILD(:$!name = 'Camelia', :$!age = 2, :$!color = 'pink') {
        # BUILD is called by bless. Its primary use is to to control
        # object initialization.
        $!wings = $!age > 1;
    }

    method flap() {
        say ($.wings
          ?? 'Watch out for that hurricane!'
          !! 'No wings to flap.');
    }
}

my Butterfly $a .= new: age => 5;
say "Name: {$a.name}, Color: {$a.color}";
$a.flap;

my Butterfly $b .= new(name => 'Osgood', age => 4);
say "Name: {$b.name}, Color: {$b.color}";
$b.flap;
```


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

Task

Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   *planar*   case.

The straightforward solution is a   O(n2)   algorithm   (which we can call *brute-force algorithm*);   the pseudo-code (using indexes) could be simply:

```
bruteForceClosestPair of P(1), P(2), ... P(N)
if N < 2 then
  return ∞
else
  minDistance ← |P(1) - P(2)|
  minPoints ← { P(1), P(2) }
  foreach i ∈ [1, N-1]
    foreach j ∈ [i+1, N]
      if |P(i) - P(j)| < minDistance then
        minDistance ← |P(i) - P(j)|
        minPoints ← { P(i), P(j) }
      endif
    endfor
  endfor
  return minDistance, minPoints
 endif

```

A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(*n* log *n*);   a pseudo-code could be:

```
closestPair of (xP, yP)
               where xP is P(1) .. P(N) sorted by x coordinate, and
                     yP is P(1) .. P(N) sorted by y coordinate (ascending order)
if N ≤ 3 then
  return closest points of xP using brute-force algorithm
else
  xL ← points of xP from 1 to ⌈N/2⌉
  xR ← points of xP from ⌈N/2⌉+1 to N
  xm ← xP(⌈N/2⌉)x
  yL ← { p ∈ yP : px ≤ xm }
  yR ← { p ∈ yP : px > xm }
  (dL, pairL) ← closestPair of (xL, yL)
  (dR, pairR) ← closestPair of (xR, yR)
  (dmin, pairMin) ← (dR, pairR)
  if dL < dR then
    (dmin, pairMin) ← (dL, pairL)
  endif
  yS ← { p ∈ yP : |xm - px| < dmin }
  nS ← number of points in yS
  (closest, closestPair) ← (dmin, pairMin)
  for i from 1 to nS - 1
    k ← i + 1
    while k ≤ nS and yS(k)y - yS(i)y < dmin
      if |yS(k) - yS(i)| < closest then
        (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
      endif
      k ← k + 1
    endwhile
  endfor
  return closest, closestPair
endif

```

References and further readings

* Closest pair of points problem
* Closest Pair (McGill)
* Closest Pair (UCSB)
* Closest pair (WUStL)
* Closest pair (IUPUI)

[Assistant]
(formerly Perl 6)

**Translation of**: Perl 5

Using concurrency, the 'simple' routine beats the (supposedly) more efficient one for all but the smallest sets of input.

```
sub MAIN ($N = 5000) {
    my @points = (^$N).map: { [rand × 20 - 10, rand × 20 - 10] }

    my @candidates = @points.sort(*.[0]).rotor( 10 => -2, :partial).race.map: { closest-pair-simple(@$_) }
    say 'simple ' ~ (@candidates.sort: *.[2]).head(1).gist;
    @candidates    = @points.sort(*.[0]).rotor( 10 => -2, :partial).race.map: { closest-pair(@$_)        }
    say 'real '   ~ (@candidates.sort: *.[2]).head(1).gist;
}

sub dist-squared(@a, @b) { (@a[0] - @b[0])² + (@a[1] - @b[1])² }

sub closest-pair-simple(@points is copy) {
    return ∞ if @points < 2;
    my ($a, $b, $d) = |@points[0,1], dist-squared(|@points[0,1]);
    while @points {
        my \p = pop @points;
        for @points -> \l {
            ($a, $b, $d) = p, l, $_ if $_ < $d given dist-squared(p, l);
        }
    }
    $a, $b, $d.sqrt
}

sub closest-pair(@r) {
    closest-pair-real (@r.sort: *.[0]), (@r.sort: *.[1])
}

sub closest-pair-real(@rx, @ry) {
    return closest-pair-simple(@rx) if @rx ≤ 3;

    my \N  = @rx;
    my \midx = ceiling(N/2) - 1;
    my @PL := @rx[     0 ..  midx];
    my @PR := @rx[midx+1 ..^ N   ];
    my \xm  = @rx[midx;0];
    (.[0] ≤ xm ?? my @yR !! my @yL).push: @$_ for @ry;
    my (\al, \bl, \dL) = closest-pair-real(@PL, @yR);
    my (\ar, \br, \dR) = closest-pair-real(@PR, @yL);
    my ($w1, $w2, $closest) = dR < dL ?? (ar, br, dR) !! (al, bl, dL);
    my @yS = @ry.grep: { (xm - .[0]).abs < $closest }

    for 0 ..^ @yS -> \i {
        for i+1 ..^ @yS -> \k {
            next unless @yS[k;1] - @yS[i;1] < $closest;
            ($w1, $w2, $closest) = |@yS[k, i], $_ if $_ < $closest given dist-squared(|@yS[k, i]).sqrt;
        }
    }
    $w1, $w2, $closest
}

```

Output:

```
simple (([-1.1560800527301716 -9.214015073077793] [-1.1570263876019649 -9.213340680530798] 0.0011620477602117762))
  real (([-1.1570263876019649 -9.213340680530798] [-1.1560800527301716 -9.214015073077793] 0.0011620477602117762))
```


[User]
Task

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index    ***i***     (you may choose to start     ***i***     from either    **0**    or    **1**),    when run, should return the square of the index,   that is,     ***i***  2.

Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.

Goal

Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.

In imperative languages, one would generally use a loop with a mutable counter variable.

For each function to maintain the correct number, it has to capture the *value* of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

See also: Multiple distinct objects

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2015.12

All blocks are anonymous closures in Raku, and parameters are lexicals, so it's easy to generate a list of them. We'll use a gather/take generator loop, and call the closures in random order, just to keep things interesting.

```
my @c = gather for ^10 -> $i {
    take { $i * $i }
}

.().say for @c.pick(*);  # call them in random order
```

Output:

```
36
64
25
1
16
0
4
9
81
49
```

Or equivalently, using a more functional notation:

```
say .() for pick *, map -> $i { -> {$i * $i} }, ^10
```


[User]
First, show the shortest possible program that will emit the nine-character string “Code Golf”, without the quotation marks and without anything after the final “f”. Then show the shortest possible program that does the same thing but without itself containing any string or character literals, and without requiring any input or any environment variables or command-line arguments, though the name of the running program can be used.

Extra credit: how big is the executable required to perform the first task? Skip details about any prior compilation steps that might be involved.

[Assistant]
Not very interesting, as it's pretty much just standard, non-obscure Raku. The output string is so short, there isn't any easy way to golf it shorter than just printing it directly. 17 bytes.

```
print <Code Golf>

```

Output:

```
Code Golf
```

Assuming we can't use the string literal in the source, the shortest I've come up with is:

```
print chrs 37,9,2,3,70,33,9,10,0 X+^102 # 39 chars, 39 bytes

```

Try it online!

```
print chrs -3,㊶,㉚,㉛,-㊳,1,㊶,㊳,㉜X+㉎ # 33 Chars, 49 bytes

```

Try it online!

```
print <Dpef!Hpmg>.ords».pred.chrs # 33 Chars, 34 bytes. Somewhat cheaty as it _does_ contain a string literal, but not the same literal as the output

```

Same output for each. Of course, to actually run any of that code you need the Raku compiler at 18.0Kb, the nqp vm interpreter at 17.9 Kb and the moar virtual machine at 17.9Kb. (Or the Java virtual machine, which is remarkably difficult to come up with a size for...)


[User]
Some advanced applications, such as memory resident applications, daemons and memory demanding applications unload unrequired parts of the application during use (such as initialization code that will no longer be used again once the application is operational) to free up memory and resources. Demonstrate or explain how to unload an unused section of code from memory.

Note that it is sufficient to flag the memory area as being available for reuse by the memory management system, without the need to demonstrate the zeroing of the bytes and performing a memory shuffle, unless such actions are required to free up the code segment.

Languages that do not have the facility to free up their code segment (such as scripting languages) can be omitted.

[Assistant]
(formerly Perl 6)
In general, there is no specific mechanism to do a timely destruction of an object, be it code, data, variables, whatever. Raku does automatic garbage collection on objects that are no longer being used. Unlike Perl, from which Raku is loosely derived, it doesn't use reference counting to track when memory may be garbage collected as that tends to be very difficult to get correct and performant in multi-threaded applications. Rather it performs a "reachability analysis" to determine when objects can be evicted from memory and safely removed.

Raku objects can provide a "DESTROY" method, but you cannot be sure when (if ever) it will be called. Raku tends to not be very memory frugal. If there is lots of memory to be had, it will cheerfully use lots of it. It gets more aggressive about conserving if memory is tight, but usually will trade memory for performance. If and when garbage collection *has* run, the freed memory is then available to to the general OS pool for any process to claim.

There are some specific details that will allow some finer control of garbage collection in special circumstances, but the average Raku programmer will not need to know about or deal with them.


[User]
Task

Collect and sort square numbers in ascending order from three lists.

list[1] = [3,4,34,25,9,12,36,56,36]

list[2] = [2,8,81,169,34,55,76,49,7]

list[3] = [75,121,75,144,35,16,46,35]

[Assistant]
```
my $s = cache sort ( my $l = ( cache flat

[3,4,34,25,9,12,36,56,36],
[2,8,81,169,34,55,76,49,7],
[75,121,75,144,35,16,46,35]

)).grep: * ∈ cache {$++²}…*>$l.max;

put 'Added - Sorted';
put ' ' ~ $s.sum ~ '  ' ~ $s.gist;

```

```
Added - Sorted
 690  (4 9 16 25 36 36 49 81 121 144 169)

```


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

Collections are abstractions to represent sets of values.

In statically-typed languages, the values are typically of a common data type.

Task

Create a collection, and add a few values to it.

See also

* Array
* Associative array: Creation, Iteration
* Collections
* Compound data type
* Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
* Linked list
* Queue: Definition, Usage
* Set
* Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
* Stack

[Assistant]
(formerly Perl 6)

Raku has both mutable and immutable containers of various sorts. Here are some of the most common ones:

### Mutable

```
# Array
my @array = 1,2,3;
@array.push: 4,5,6;

# Hash
my %hash = 'a' => 1, 'b' => 2;
%hash<c d> = 3,4;
%hash.push: 'e' => 5, 'f' => 6;

# SetHash
my $s = SetHash.new: <a b c>;
$s ∪= <d e f>;

# BagHash
my $b = BagHash.new: <b a k l a v a>;
$b ⊎= <a b c>;
```

### Immutable

```
# List
my @list := 1,2,3;
my @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists

# Set
my $set = set <a b c>;
my $newset = $set ∪ <d e f>;

# Bag
my $bag = bag <b a k l a v a>;
my $newbag = $bag ⊎ <b e e f>;
```

### Pair list (cons list)

```
my $tail = d => e => f => Nil;
my $new = a => b => c => $tail;
```

### P6opaque object (immutable in structure)

```
class Something { has $.foo; has $.bar };
my $obj = Something.new: foo => 1, bar => 2;
my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin
```


[User]
## The CIE ΔE2000 color difference formula

The **ΔE2000 color difference formula** is a widely used metric for comparing two colors in the CIE 1976 color space. It enhances the earlier CIE76 algorithm by integrating additional perceptual factors, resulting in more accurate **color matching**.

### Task

Given the first six values, obtain the results in column seven, accurate to 10 decimal places.

| L1 | a1 | b1 | L2 | a2 | b2 | ΔE2000 |
| --- | --- | --- | --- | --- | --- | --- |
| 73.0 | 49.0 | 39.4 | 73.0 | 49.0 | 39.4 | 0.0 |
| 30.0 | -41.0 | -119.1 | 30.0 | -41.0 | -119.0 | 0.0134319631 |
| 79.0 | -117.0 | -100.4 | 79.5 | -117.0 | -100.0 | 0.3572501235 |
| 15.0 | -55.0 | 6.7 | 14.0 | -55.0 | 7.0 | 0.6731711696 |
| 83.0 | 98.0 | -59.5 | 85.2 | 98.0 | -59.5 | 1.4597018301 |
| 59.0 | -11.0 | -95.0 | 56.3 | -11.0 | -95.0 | 2.4566352112 |
| 74.0 | -1.0 | 68.6 | 81.0 | -1.0 | 69.0 | 4.9755487499 |
| 46.4 | 125.0 | 6.0 | 40.0 | 125.0 | 6.0 | 5.8974138376 |
| 18.0 | -5.0 | 68.0 | 20.0 | 5.0 | 82.0 | 6.8542258013 |
| 35.5 | -99.0 | 109.0 | 25.0 | -99.0 | 109.0 | 8.1462591143 |
| 59.0 | 77.0 | 41.5 | 63.3 | 77.0 | 12.4 | 13.1325726695 |
| 40.0 | -92.0 | 7.7 | 58.0 | -92.0 | -8.0 | 19.1411733022 |
| 49.0 | -9.0 | -74.5 | 51.1 | 31.0 | 16.0 | 48.1082375109 |
| 88.0 | -124.0 | 56.0 | 97.0 | 62.0 | -28.0 | 63.9449872676 |
| 98.0 | 75.7 | 11.0 | 3.0 | -62.0 | 11.0 | 126.5088270078 |

* **L1 and L2** nominally ranges from 0 (white) to 100 (black)
* **a1 and a2** are unbounded and commonly clamped to the range of -128 (green) to 127 (red)
* **b1 and b2** are unbounded and commonly clamped to the range of -128 (blue) to 127 (yellow)

[Assistant]
**Translation of**: Go

```
# 20250609 Raku programming solution

sub hypot(\x, \y) { sqrt(x² + y²) }

# The classic CIE ΔE2000 implementation, which operates on two L*a*b* colors, and returns their difference.
sub ciede_2000(\L1, \A1, \B1, \L2, \A2, \B2) {

   # Kl, Kc, Kh are parametric factors to be adjusted according to
   # different viewing parameters such as textures, backgrounds...
   my (\Kl, \Kc, \Kh) = 1.0 xx 3;

   my $n = ((hypot(A1, B1) + hypot(A2, B2)) * 0.5)⁷;
   $n = 1.0 + 0.5 * (1.0 - sqrt($n / ($n + 6103515625.0)));

   # hypot calculates the Euclidean distance while avoiding overflow/underflow.
   my (\C1, \C2) = ( [A1 * $n, B1], [A2 * $n, B2] ).map: { hypot |$_ };

   # atan2 is preferred over atan because it accurately computes the angle of
   # a point (x, y) in all quadrants, handling the signs of both coordinates.
   my \H1 = $ = atan2(B1, A1 * $n);
   my \H2 = $ = atan2(B2, A2 * $n);

   if H1 < 0.0 { H1 += 2.0 * π }
   if H2 < 0.0 { H2 += 2.0 * π }

   $n = abs(H2 - H1);

   # Cross-implementation consistent rounding.
   $n = π if π - 1e-14 < $n && $n < π + 1e-14;

   # When the hue angles lie in different quadrants, the straightforward
   # average can produce a mean that incorrectly suggests a hue angle in
   # the wrong quadrant, the next lines handle this issue.
   my \Hm = $ = (H1 + H2) * 0.5;
   my \Hd = $ = (H2 - H1) * 0.5;

   if π < $n {
      0.0 < Hd ?? ( Hd -= π ) !! Hd += π;
      Hm += π;
   }

   my \p = 36.0 * Hm - 55.0 * π;
   $n = ((C1 + C2) * 0.5)⁷;

   # The hue rotation correction term is designed to account for the
   # non-linear behavior of hue differences in the blue region.
   my \Rt = -2.0 * sqrt( $n/($n+6103515625.0)) * sin(π/3.0*exp(p²/(-25.0*π²)) );
   $n = ((L1 + L2) * 0.5 - 50.0)²;

   # Lightness.
   my \l = (L2 - L1) / (Kl * (1.0 + 0.015 * $n / sqrt(20.0 + $n)));

   # These coefficients adjust the impact of different harmonic
   # components on the hue difference calculation.
   my \t = 1.0 + 0.24*sin(2.0*Hm + π*0.5) + 0.32*sin(3.0*Hm + 8.0*π/15.0) -
           0.17*sin(Hm + π/3.0) - 0.20*sin(4.0 * Hm + 3.0*π/20.0);
   $n = C1 + C2;

   # Hue.
   my \h = 2.0 * sqrt(C1 * C2) * sin(Hd) / (Kh * (1.0 + 0.0075 * $n * t));

   # Chroma.
   my \c = (C2 - C1) / (Kc * (1.0 + 0.0225 * $n));

   # Returning the square root ensures that the result represents
   # the "true" geometric distance in the color space.
   return sqrt(l² + h² + c² + c * h * Rt)
}

say "   L1     a1     b1     L2     a2     b2        ΔE2000";
say "------------------------------------------------------------";

for [
   [73.0, 49.0, 39.4, 73.0, 49.0, 39.4],
   [30.0, -41.0, -119.1, 30.0, -41.0, -119.0],
   [79.0, -117.0, -100.4, 79.5, -117.0, -100.0],
   [15.0, -55.0, 6.7, 14.0, -55.0, 7.0],
   [83.0, 98.0, -59.5, 85.2, 98.0, -59.5],
   [59.0, -11.0, -95.0, 56.3, -11.0, -95.0],
   [74.0, -1.0, 68.6, 81.0, -1.0, 69.0],
   [46.4, 125.0, 6.0, 40.0, 125.0, 6.0],
   [18.0, -5.0, 68.0, 20.0, 5.0, 82.0],
   [35.5, -99.0, 109.0, 25.0, -99.0, 109.0],
   [59.0, 77.0, 41.5, 63.3, 77.0, 12.4],
   [40.0, -92.0, 7.7, 58.0, -92.0, -8.0],
   [49.0, -9.0, -74.5, 51.1, 31.0, 16.0],
   [88.0, -124.0, 56.0, 97.0, 62.0, -28.0],
   [98.0, 75.7, 11.0, 3.0, -62.0, 11.0],
] { printf "%6.1f " x 6 ~ "%14.10f\n", $_[^6], ciede_2000 |$_[^6] }

```

You may Attempt This Online!


[User]
Task

Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor.

The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.

[Assistant]
(formerly Perl 6)

This example works with MacOS, customize with the appropriate screencapture utility for other OSes.

```
use GD::Raw;

my $file = '/tmp/one-pixel-screen-capture.png';

qqx/screencapture -R 123,456,1,1 $file/;

my $fh    = fopen($file, "rb") or die;
my $image = gdImageCreateFromPng($fh);
my $pixel = gdImageGetPixel($image, 0, 0);
my ($red,$green,$blue) =
    gdImageRed(  $image, $pixel),
    gdImageGreen($image, $pixel),
    gdImageBlue( $image, $pixel);

say "RGB: $red, $green, $blue";

fclose($fh);
unlink $file;

```

Output:

```
RGB: 20, 2, 124
```

Alternately, a version that should work in any X11 environment. Needs X11::xdo and MagickWand installed.

```
signal(SIGINT).tap: { sleep .1; cleanup(); print "\n" xx 50, "\e[H\e[J"; exit(0) }

multi MAIN () {
    use X11::libxdo;
    my $xdo = Xdo.new;
    my ($lx, $ly) = 0, 0;
    loop {
        sleep .1;
        my ($x, $y, $) = $xdo.get-mouse-location;
        next if $lx == $x and $ly == $y;
        ($lx, $ly) = $x, $y;
        display $x, $y, |get-pixel($x, $y);
    }
}

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

multi MAIN (
    Int $x,    #= Integer x coordinate to pick
    Int $y,    #= Integer y coordinate to pick
    $q = False #= Boolean "quiet" mode, set truthy for decimal values, set to h for hex values
  ) {
    my ($red, $green, $blue) = get-pixel($x, $y);

    if $q {
        $q.lc eq 'h' ??
          ( printf "%02X:%02X:%02X\n", $red, $green, $blue ) !!
          ( printf "%03d:%03d:%03d\n", $red, $green, $blue );
    } else {
        display($x, $y, $red, $green, $blue);
        cleanup();
    }
    exit(0);
}

sub get-pixel ($x, $y) {
    my $xcolor =
      qqx/import -window root -crop 1x1+{$x-1 max 0}+{$y-2 max 0} -depth 8 txt:-/
      .comb(/<?after '#'><xdigit> ** 6/);

    |$xcolor.comb(2)».parse-base(16);
}

sub display ($x, $y, $r, $g, $b) {
    print "\e[?25l\e[48;2;0;0;0m\e[38;2;255;255;255m\e[H\e[J";
    printf "  x: %4d y: $y\n", $x;
    printf "  RGB: %03d:%03d:%03d \n  HEX: %02X:%02X:%02X\n",
            $r, $g, $b, $r, $g, $b;
    print "\e[38;2;{$r};{$g};{$b}m ",
           ('█' x 18 xx 6).join("\n "), "\n\n";
}

sub cleanup { print "\e[0m\e[?25h" }

```


[User]
full color

Example: Gimp 16 color

Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There are some well know algorithms [1], each with its own advantages and drawbacks.

**Task**: Take an RGB color image and reduce its colors to some smaller number (< 256). For this task, use the frog as input and reduce colors to 16, and output the resulting colors. The chosen colors should be adaptive to the input image, meaning you should *not* use a fixed palette such as Web colors or Windows system palette. Dithering is not required.

Note: the funny color bar on top of the frog image is intentional.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.10

```
use MagickWand;
use MagickWand::Enums;

my $frog = MagickWand.new;
$frog.read("./Quantum_frog.png");
$frog.quantize(16, RGBColorspace, 0, True, False);
$frog.write('./Quantum-frog-16-perl6.png');

```

See: Quantum-frog-16-perl6.png (offsite .png image)


[User]
Task

Write a function to draw a HSV color wheel completely with code.

This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and this can easily be used to determine a color value based on a position within a circle.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2016.08

File:Color-wheel-perl6.png

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

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

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

my $center = $w/2 + $h/2*i;

color-wheel($out);

$out.write: 'Color-wheel-perl6.png';

sub color-wheel ( $png ) {
    ^$w .race.map: -> $x {
        for ^$h -> $y {
            my $vector    = $center - $x - $y*i;
            my $magnitude = $vector.abs * 2 / $w;
            my $direction = ( π + atan2( |$vector.reals ) ) / τ;
            $png.set: $x, $y, |hsv2rgb( $direction, $magnitude, $magnitude < 1 );
        }
    }
}

sub hsv2rgb ( $h, $s, $v ){
    my $c = $v * $s;
    my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
    my $m = $v - $c;
    (do given $h {
        when   0..^1/6 { $c, $x, 0 }
        when 1/6..^1/3 { $x, $c, 0 }
        when 1/3..^1/2 { 0, $c, $x }
        when 1/2..^2/3 { 0, $x, $c }
        when 2/3..^5/6 { $x, 0, $c }
        when 5/6..1    { $c, 0, $x }
    } ).map: ((*+$m) * 255).Int
}

```


[User]
A **colorful number** is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.

E.G.

24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840

Every product is unique.

2346 is **not** a colorful number. 2, 3, 4, **6**, (2×3)**6**, (3×4)12, (4×6)24, (2×3×4)48, (3×4×6)72, (2×3×4×6)144

The product **6** is repeated.

Single digit numbers **are** considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.

Task

* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
* Use that routine to find all of the colorful numbers less than 100.
* Use that routine to find the largest possible colorful number.

Stretch

* Find and display the count of colorful numbers in each order of magnitude.
* Find and show the total count of **all** colorful numbers.

*Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.*

[Assistant]
```
sub is-colorful (Int $n) {
    return True if 0 <= $n <= 9;
    return False if $n.contains(0) || $n.contains(1) || $n < 0;
    my @digits = $n.comb;
    my %sums = @digits.Bag;
    return False if %sums.values.max > 1;
    for 2..@digits -> $group {
        @digits.rotor($group => 1 - $group).map: { %sums{ [×] $_ }++ }
        return False if %sums.values.max > 1;
    }
    True
}

put "Colorful numbers less than 100:\n" ~ (^100).hyper.grep( &is-colorful).batch(10)».fmt("%2d").join: "\n";

my ($start, $total) = 23456789, 10;

print "\nLargest magnitude colorful number: ";
.put and last if .Int.&is-colorful for $start.flip … $start;

put "\nCount of colorful numbers for each order of magnitude:\n" ~
    "1 digit colorful number count: $total - 100%";

for 2..8 {
   put "$_ digit colorful number count: ",
   my $c = +(flat $start.comb.combinations($_).map: {.permutations».join».Int}).hyper.grep( &is-colorful ),
   " - {($c / (exp($_,10) - exp($_-1,10) ) * 100).round(.001)}%";
   $total += $c;
}

say "\nTotal colorful numbers: $total";

```

Output:

```
Colorful numbers less than 100:
 0  1  2  3  4  5  6  7  8  9
23 24 25 26 27 28 29 32 34 35
36 37 38 39 42 43 45 46 47 48
49 52 53 54 56 57 58 59 62 63
64 65 67 68 69 72 73 74 75 76
78 79 82 83 84 85 86 87 89 92
93 94 95 96 97 98

Largest magnitude colorful number: 98746253

Count of colorful numbers for each order of magnitude:
1 digit colorful number count: 10 - 100%
2 digit colorful number count: 56 - 62.222%
3 digit colorful number count: 328 - 36.444%
4 digit colorful number count: 1540 - 17.111%
5 digit colorful number count: 5514 - 6.127%
6 digit colorful number count: 13956 - 1.551%
7 digit colorful number count: 21596 - 0.24%
8 digit colorful number count: 14256 - 0.016%

Total colorful numbers: 57256
```


[User]
Task

Display a series of vertical color bars across the width of the display.

The color bars should either use:

:   :   :   * the system palette,   or
            * the sequence of colors:

            :   :   :   * black
                        * red
                        * green
                        * blue
                        * magenta
                        * cyan
                        * yellow
                        * white

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2018.10

```
my ($x,$y) = 1280, 720;

my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) },
      0,   0,   0,
    255,   0,   0,
      0, 255,   0,
      0,   0, 255,
    255,   0, 255,
      0, 255, 255,
    255, 255,   0,
    255, 255, 255;

my $img = open "colorbars.ppm", :w orelse die "Can't create colorbars.ppm: $_";

$img.print: qq:to/EOH/;
    P6
    # colorbars.ppm
    $x $y
    255
    EOH

for ^$y {
    for ^@colors -> $h {
        $img.write: @colors[$h];
    }
}

$img.close;

```


[User]
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display.

The pinstripes should either follow the system palette sequence,   or a sequence that includes:

black,   red,   green,   blue,   magenta,   cyan,   yellow,   and   white:

:   :   * after filling the top quarter, switch to a wider 2 pixel wide vertical pinstripe pattern,
        * halfway down the display, switch to 3 pixel wide vertical pinstripe,
        * finally to a 4 pixels wide vertical pinstripe for the last quarter of the display.

See also

* display black and white
* print colour

[Assistant]
(formerly Perl 6)

```
my ($x,$y) = 1280, 720;

my @colors = map -> $r, $g, $b { [$r, $g, $b] },
     0,   0,   0,
   255,   0,   0,
     0, 255,   0,
     0,   0, 255,
   255,   0, 255,
     0, 255, 255,
   255, 255,   0,
   255, 255, 255;

my $img = open "pinstripes.ppm", :w orelse die "Can't create pinstripes.ppm: $_";

$img.print: qq:to/EOH/;
    P3
    # pinstripes.ppm
    $x $y
    255
    EOH

my $vzones = $y div 4;
for 1..4 -> $width {
    my $stripes = ceiling $x / $width / +@colors;
    my $row = [flat ((@colors Xxx $width) xx $stripes).map: *.values].splice(0,$x);
    $img.put: $row for ^$vzones;
}

$img.close;

```


[User]
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence woud be black, red, green, blue, magenta, cyan, yellow, white.

After the first inch of printing, we switch to a wider 2 pixel wide vertical pinstripe pattern. and to 3 point wide vertical for the next inch, and then 4 point wide, etc. This trend continues for the entire length of the page (or for 12 inches of run length in the case of a printer using continuous roll stationery). After printing the test pattern the page is ejected (or the test pattern is rolled clear of the printer enclosure, in the case of continuous roll printers).

Note that it is an acceptable solution to use the smallest marks that the language provides, rather than working at native printer resolution, where this is not achievable from within the language.

Optionally, on systems where the printer resolution cannot be determined, it is permissible to prompt the user for printer resolution, and to calculate point size based on user input, enabling fractional point sizes to be used.

[Assistant]
(formerly Perl 6)

**Works with**: Rakudo version 2020.01

Note that Raku does not attempt to be a printer driver. This example allows users to specify the dpi and paper size, then generates an image and passes it to the default printer. Defaults to 300 dpi and US letter paper.

```
unit sub MAIN ($dpi = 300, $size = 'letter');

my $filename = './Color-pinstripe-printer-perl6.png';

my %paper = (
    'letter' => { :width(8.5),    :height(11.0) }
    'A4'     => { :width(8.2677), :height(11.6929)}
);

my ($w, $h) = %paper{$size}<width height> »*» $dpi;

# ROYGBIVK
my @color = (1,0,0),(1,.598,0),(1,1,0),(0,1,0),(0,0,1),(.294,0,.51),(.58,0,.827),(0,0,0);

my $gap = floor $w % ($dpi * +@color) / 2;

my $rows = (1, * * 2 … * > $dpi).elems;

my $height = $dpi;

use Cairo;

my @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) };

given Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image {
    given Cairo::Context.new($image) {
        my Cairo::Pattern::Solid $bg .= create(1,1,1);
        .rectangle(0, 0, $w, $h);
        .pattern($bg);
        .fill;
        $bg.destroy;

        my $y = $gap;
        for ^$rows -> $row {
            my $x = $gap;
            my $width = $dpi / (2 ** $row);
            for @colors -> $this {
                my $v = 0;
                while $v++ < (2 ** ($row - 1)) {
                    given Cairo::Context.new($image) -> $block {
                        $block.rectangle($x, $y, $width, $height);
                        $block.pattern($this);
                        $block.fill;
                        $block.destroy;
                    }
                    $x += $width;
                    $x += $width if $row;
                }
            }
        $y += $height;
        }
    }
    $image.write_png($filename);
}

# Uncomment next line if you actually want to print it
#run('lp', $filename)

```

See Color-pinstripe-printer-perl6.png (offsite png image)


[User]
Task

Given non-negative integers    **m**    and    **n**,   generate all size    **m**    combinations   of the integers from    **0**   (zero)   to    **n-1**    in sorted order   (each combination is sorted and the entire table is sorted).

Example

**3**   comb    **5**      is:

```
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4

```

If it is more "natural" in your language to start counting from    **1**   (unity) instead of    **0**   (zero),

the combinations can be of the integers from    **1**   to    **n**.

See also

:   :   :   :   The number of samples of size k from n objects.

                With   combinations and permutations   generation tasks.

                |  | Order Unimportant | Order Important |
                | --- | --- | --- |
                | Without replacement | (  n k  )  =  n  C  k =    n ( n − 1 ) … ( n − k + 1 )  k ( k − 1 ) … 1 {\displaystyle {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} \_{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}} | n  P  k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}} |
                | Task: Combinations | Task: Permutations |
                | With replacement | (   n + k − 1 k  )  =  n + k − 1  C  k =    ( n + k − 1 ) !  ( n − 1 ) ! k ! {\displaystyle {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} \_{k}={(n+k-1)! \over (n-1)!k!}}} | n  k {\displaystyle {\displaystyle n^{k}}} |
                | Task: Combinations with repetitions | Task: Permutations with repetitions |

[Assistant]
(formerly Perl 6)

**Works with**: rakudo version 2015.12

There actually is a builtin:

```
.say for combinations(5,3);
```

Output:

```
(0 1 2)
(0 1 3)
(0 1 4)
(0 2 3)
(0 2 4)
(0 3 4)
(1 2 3)
(1 2 4)
(1 3 4)
(2 3 4)
```

Here is an iterative routine with the same output:

```
sub combinations(Int $n, Int $k) {
    return ([],) unless $k;
    return if $k > $n || $n <= 0;
    my @c = ^$k;
    gather loop {
      take [@c];
      next if @c[$k-1]++ < $n-1;
      my $i = $k-2;
      $i-- while $i >= 0 && @c[$i] >= $n-($k-$i);
      last if $i < 0;
      @c[$i]++;
      while ++$i < $k { @c[$i] = @c[$i-1] + 1; }
    }
}
.say for combinations(5,3);
```


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

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

Task

Implement the combination    (nCk)    and permutation    (nPk)    operators in the target language:

:   :   :   * n

              C

              k
              =

              (

              n
              k

              )
              =

              n
              (
              n
              −
              1
              )
              …
              (
              n
              −
              k
              +
              1
              )

              k
              (
              k
              −
              1
              )
              …
              1
              {\displaystyle {\displaystyle ^{n}\operatorname {C} \_{k}={\binom {n}{k}}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}}

:   :   :   * n

              P

              k
              =
              n
              ⋅
              (
              n
              −
              1
              )
              ⋅
              (
              n
              −
              2
              )
              ⋯
              (
              n
              −
              k
              +
              1
              )
              {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}}

See the Wikipedia articles for a more detailed description.

**To test**, generate and print examples of:

* A sample of permutations from 1 to 12 and Combinations from 10 to 60 using exact Integer arithmetic.
* A sample of permutations from 5 to 15000 and Combinations from 100 to 1000 using approximate Floating point arithmetic.
   This 'floating point' code could be implemented using an approximation, e.g., by calling the Gamma function.

Related task

* Evaluate binomial coefficients

:   :   :   :   The number of samples of size k from n objects.

                With   combinations and permutations   generation tasks.

                |  | Order Unimportant | Order Important |
                | --- | --- | --- |
                | Without replacement | (  n k  )  =  n  C  k =    n ( n − 1 ) … ( n − k + 1 )  k ( k − 1 ) … 1 {\displaystyle {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} \_{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}} | n  P  k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}} |
                | Task: Combinations | Task: Permutations |
                | With replacement | (   n + k − 1 k  )  =  n + k − 1  C  k =    ( n + k − 1 ) !  ( n − 1 ) ! k ! {\displaystyle {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} \_{k}={(n+k-1)! \over (n-1)!k!}}} | n  k {\displaystyle {\displaystyle n^{k}}} |
                | Task: Combinations with repetitions | Task: Permutations with repetitions |

[Assistant]
(formerly Perl 6)
Raku can't compute arbitrary large floating point values, thus we will use logarithms, as is often needed when dealing with combinations. We'll also use a Stirling method to approximate

ln

(
n
!
)
{\displaystyle {\displaystyle \ln(n!)}}
:

ln

n
!
≈

1
2
ln

(
2
π
n
)
+
n
ln

(

n
e
+

1

12
e
n
)
{\displaystyle {\displaystyle \ln n!\approx {\frac {1}{2}}\ln(2\pi n)+n\ln \left({\frac {n}{e}}+{\frac {1}{12en}}\right)}}

Notice that Raku can process arbitrary long integers, though. So it's not clear whether using floating points is useful in this case.

```
multi P($n, $k) { [*] $n - $k + 1 .. $n }
multi C($n, $k) { P($n, $k) / [*] 1 .. $k }

sub lstirling(\n) {
    n < 10 ?? lstirling(n+1) - log(n+1) !!
    .5*log(2*pi*n)+ n*log(n/e+1/(12*e*n))
}

role Logarithm {
    method gist {
	my $e = (self/10.log).Int;
	sprintf "%.8fE%+d", exp(self - $e*10.log), $e;
    }
}
multi P($n, $k, :$float!) {
    (lstirling($n) - lstirling($n -$k))
    but Logarithm
}
multi C($n, $k, :$float!) {
    (lstirling($n) - lstirling($n -$k) - lstirling($k))
    but Logarithm
}

say "Exact results:";
for 1..12 -> $n {
    my $p = $n div 3;
    say "P($n, $p) = ", P($n, $p);
}

for 10, 20 ... 60 -> $n {
    my $p = $n div 3;
    say "C($n, $p) = ", C($n, $p);
}

say '';
say "Floating point approximations:";
for 5, 50, 500, 1000, 5000, 15000 -> $n {
    my $p = $n div 3;
    say "P($n, $p) = ", P($n, $p, :float);
}

for 100, 200 ... 1000 -> $n {
    my $p = $n div 3;
    say "C($n, $p) = ", C($n, $p, :float);
}

```

Output:

```
Exact results:
P(1, 0) = 1
P(2, 0) = 1
P(3, 1) = 3
P(4, 1) = 4
P(5, 1) = 5
P(6, 2) = 30
P(7, 2) = 42
P(8, 2) = 56
P(9, 3) = 504
P(10, 3) = 720
P(11, 3) = 990
P(12, 4) = 11880
C(10, 3) = 120
C(20, 6) = 38760
C(30, 10) = 30045015
C(40, 13) = 12033222880
C(50, 16) = 4923689695575
C(60, 20) = 4191844505805495

Floating point approximations:
P(5, 1) = 5.00000000E+0
P(50, 16) = 1.03017326E+26
P(500, 166) = 3.53487492E+434
P(1000, 333) = 5.96932629E+971
P(5000, 1666) = 6.85674576E+6025
P(15000, 5000) = 9.64985399E+20469
C(100, 33) = 2.94692433E+26
C(200, 66) = 7.26975256E+53
C(300, 100) = 4.15825147E+81
C(400, 133) = 1.25794868E+109
C(500, 166) = 3.92602839E+136
C(600, 200) = 2.50601778E+164
C(700, 233) = 8.10320356E+191
C(800, 266) = 2.64562336E+219
C(900, 300) = 1.74335637E+247
C(1000, 333) = 5.77613455E+274
```


[User]
The set of combinations with repetitions is computed from a set,

S
{\displaystyle {\displaystyle S}}
 (of cardinality

n
{\displaystyle {\displaystyle n}}
), and a size of resulting selection,

k
{\displaystyle {\displaystyle k}}
, by reporting the sets of cardinality

k
{\displaystyle {\displaystyle k}}
 where each member of those sets is chosen from

S
{\displaystyle {\displaystyle S}}
.
In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter.
For example:

:   Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e.,

    S
    {\displaystyle {\displaystyle S}}
     is

    {

    i
    c
    e
    d
    ,

    j
    a
    m
    ,

    p
    l
    a
    i
    n
    }
    {\displaystyle {\displaystyle \{\mathrm {iced} ,\mathrm {jam} ,\mathrm {plain} \}}}
    ,

    |
    S

    |
    =
    3
    {\displaystyle {\displaystyle |S|=3}}
    , and

    k
    =
    2
    {\displaystyle {\displaystyle k=2}}
    .)

:   A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}.

Note that both the order of items within a pair, and the order of the pairs given in the answer is not significant; the pairs represent multisets.

Also note that *doughnut* can also be spelled *donut*.

Task

* Write a function/program/routine/.. to generate all the combinations with repetitions of

  n
  {\displaystyle {\displaystyle n}}
   types of things taken

  k
  {\displaystyle {\displaystyle k}}
   at a time and use it to *show* an answer to the doughnut example above.
* For extra credit, use the function to compute and show *just the number of ways* of choosing three doughnuts from a choice of ten types of doughnut. Do not show the individual choices for this part.

References

* k-combination with repetitions

See also

:   :   :   :   The number of samples of size k from n objects.

                With   combinations and permutations   generation tasks.

                |  | Order Unimportant | Order Important |
                | --- | --- | --- |
                | Without replacement | (  n k  )  =  n  C  k =    n ( n − 1 ) … ( n − k + 1 )  k ( k − 1 ) … 1 {\displaystyle {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} \_{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}} | n  P  k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}} |
                | Task: Combinations | Task: Permutations |
                | With replacement | (   n + k − 1 k  )  =  n + k − 1  C  k =    ( n + k − 1 ) !  ( n − 1 ) ! k ! {\displaystyle {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} \_{k}={(n+k-1)! \over (n-1)!k!}}} | n  k {\displaystyle {\displaystyle n^{k}}} |
                | Task: Combinations with repetitions | Task: Permutations with repetitions |

[Assistant]
(formerly Perl 6)

One could simply generate all permutations, and then remove "duplicates":

**Works with**: Rakudo version 2016.07

```
my @S = <iced jam plain>;
my $k = 2;

.put for [X](@S xx $k).unique(as => *.sort.cache, with => &[eqv])

```

Output:

```
iced iced
iced jam
iced plain
jam jam
jam plain
plain plain

```

Alternatively, a recursive solution:

**Translation of**: Haskell

```
proto combs_with_rep (UInt, @) {*}

multi combs_with_rep (0,  @)  { () }
multi combs_with_rep (1,  @a)  { map { $_, }, @a }
multi combs_with_rep ($,  []) { () }
multi combs_with_rep ($n, [$head, *@tail]) {
    |combs_with_rep($n - 1, ($head, |@tail)).map({ $head, |@_ }),
    |combs_with_rep($n, @tail);
}

.say for combs_with_rep( 2, [< iced jam plain >] );

# Extra credit:
sub postfix:<!> { [*] 1..$^n }
sub combs_with_rep_count ($k, $n) { ($n + $k - 1)! / $k! / ($n - 1)! }

say combs_with_rep_count( 3, 10 );

```

Output:

```
(iced iced)
(iced jam)
(iced plain)
(jam jam)
(jam plain)
(plain plain)
220
```


[User]
Iterated digits squaring introduces RC the Project Euler Task #92. Combinations with repetitions introduce RC to the concept of generating all the combinations with repetitions of n types of things taken k at a time.

The purpose of this task is to combine these tasks as follows:

:   The collections of k items will be taken from [0,1,4,9,16,25,36,49,64,81] and must be obtained using code from Combinations with repetitions. The collection of k zeroes is excluded.
:   For each collection of k items determine if it translates to 1 using the rules from Iterated digits squaring
:   For each collection which translates to 1 determine the number of different ways, c say, in which the k items can be uniquely ordered.
:   Keep a running total of all the values of c obtained
:   Answer the Project Euler Task #92 question (k=7).
:   Answer the equivalent question for k=8,11,14.
:   Optionally answer the question for k=17. These numbers will be larger than the basic integer type for many languages, if it is not easy to use larger numbers it is not necessary for this task.

[Assistant]
(formerly Perl 6)

**Translation of**: Kotlin

```
use v6;

sub endsWithOne($n --> Bool) {
   my $digit;
   my $sum = 0;
   my $nn = $n;
   loop {
      while ($nn > 0) {
         $digit = $nn % 10;
         $sum += $digit²;
         $nn = $nn div 10;
      }
      ($sum == 1) and return True;
      ($sum == 89) and return False;
      $nn = $sum;
      $sum = 0;
   }
}

my @ks = (7, 8, 11, 14, 17);

for @ks -> $k {
   my @sums is default(0) = 1,0;
   my $s;
   for (1 .. $k) -> $n {
      for ($n*81 ... 1) -> $i {
         for (1 .. 9) -> $j {
            $s = $j²;
            if ($s > $i) { last };
            @sums[$i] += @sums[$i-$s];
         }
      }
   }
   my $count1 = 0;
   for (1 .. $k*81) -> $i { if (endsWithOne($i)) {$count1 += @sums[$i]} }
   my $limit = 10**$k - 1;
   say "For k = $k in the range 1 to $limit";
   say "$count1 numbers produce 1 and ",$limit-$count1," numbers produce 89";
}

```

Output:

```
For k = 7 in the range 1 to 9999999
1418853 numbers produce 1 and 8581146 numbers produce 89
For k = 8 in the range 1 to 99999999
14255666 numbers produce 1 and 85744333 numbers produce 89
For k = 11 in the range 1 to 99999999999
15091199356 numbers produce 1 and 84908800643 numbers produce 89
For k = 14 in the range 1 to 99999999999999
13770853279684 numbers produce 1 and 86229146720315 numbers produce 89
For k = 17 in the range 1 to 99999999999999999
12024696404768024 numbers produce 1 and 87975303595231975 numbers produce 89
```


[User]
Comma quibbling is a task originally set by Eric Lippert in his blog.

Task

Write a function to generate a string output which is the concatenation of input words from a list/sequence where:

1. An input of no words produces the output string of just the two brace characters "{}".
2. An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
3. An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
4. An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".

Test your function with the following series of inputs showing your output here on this page:

* [] # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]

Note: Assume words are non-empty strings of uppercase characters for this task.

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)

```
sub comma-quibbling(@A) {
    <{ }>.join: @A < 2 ?? @A !! "@A[0..*-2].join(', ') and @A[*-1]";
}

say comma-quibbling($_) for
    [], [<ABC>], [<ABC DEF>], [<ABC DEF G H>];

```

Output:

```
{}
{ABC}
{ABC and DEF}
{ABC, DEF, G and H}
```


[User]
Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see Scripted main.

See also Program name.

For parsing command line arguments intelligently, see Parsing command-line arguments.

Example command line:

```
myprogram -c "alpha beta" -h "gamma"

```

[Assistant]
(formerly Perl 6)
Perl 5's `@ARGV` is available as `@*ARGS`. Alternatively, if you define a subroutine named `MAIN`, Perl will automatically process `@*ARGS` according to Unix conventions and `MAIN`'s signature (or signatures, if your `MAIN` is a multi sub) and then call `MAIN` with appropriate arguments; for more detailed information see: https://docs.raku.org/language/create-cli

```
# with arguments supplied
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5
8

# missing argument:
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3
Usage:
-e '...' x y
```

If the program is stored in a file, the file name is printed instead of `-e '...'`.


[User]
*Commatizing*   numbers (as used here, is a handy expedient made-up word) is the act of adding commas to a number (or string), or to the numeric part of a larger string.

Task

Write a function that takes a string as an argument with optional arguments or parameters (the format of parameters/options is left to the programmer) that in general, adds commas (or some
other characters, including blanks or tabs) to the first numeric part of a string (if it's suitable for commatizing as per the rules below), and returns that newly commatized string.

Some of the commatizing rules (specified below) are arbitrary, but they'll be a part of this task requirements, if only to make the results consistent amongst national preferences and other disciplines.

The number may be part of a larger (non-numeric) string such as:

:   :   :   :   * «US$1744 millions»       ──or──
                * ±25000 motes.

The string may possibly *not* have a number suitable for commatizing, so it should be untouched and *no error generated*.

If any argument (option) is invalid, nothing is changed and no error *need be* generated (quiet execution, no fail execution).   Error message generation is optional.

The exponent part of a number is never commatized.   The following string isn't suitable for commatizing:   9.7e+12000

Leading zeroes are never commatized.   The string   0000000005714.882   after commatization is:   0000000005,714.882

Any   *period*   (**.**)   in a number is assumed to be a   *decimal point*.

The original string is never changed   *except*   by the addition of commas   [or whatever character(s) is/are used for insertion], if at all.

To wit, the following should be preserved:

:   :   * leading signs (**+**, **-**)       ── even superfluous signs
        * leading/trailing/embedded blanks, tabs, and other whitespace
        * the case (upper/lower) of the exponent indicator, e.g.:   4.8903d-002

Any exponent character(s) should be supported:

:   :   :   :   :   :   * 1247e12
                        * 57256.1D-4
                        * 4444^60
                        * 7500**∙**10\*\*35
                        * 8500x10\*\*35
                        * 9500↑35
                        * +55000↑3
                        * 1000\*\*100
                        * 2048²
                        * 409632
                        * 10000pow(pi)

Numbers may be terminated with any non-digit character, including subscripts and/or superscript:   41421356243   or   7320509076(base 24).

The character(s) to be used for the comma can be specified, and may contain blanks, tabs, and other whitespace characters, as well as multiple characters.   The default is the comma (**,**) character.

The   *period length*   can be specified   (sometimes referred to as "thousands" or "thousands separators").   The   *period length*   can be defined as the length (or number) of the decimal digits between commas.   The default period length is   3.

:   :   :   E.G.:   in this example, the   *period length*   is five:   56789,12340,14148

The location of where to start the scanning for the target field (the numeric part) should be able to be specified.   The default is   1.

The character strings below may be placed in a file (and read) or stored as simple strings within the program.

Strings to be used as a minimum

The value of   pi   (expressed in base 10)   should be separated with blanks every   **5**   places past the decimal point,

the Zimbabwe dollar amount should use a decimal point for the "comma" separator:

:   * pi=3.14159265358979323846264338327950288419716939937510582097494459231
    * The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
    * "-in Aus$+1411.8millions"
    * ===US$0017440 millions=== (in 2000 dollars)
    * 123.e8000 is pretty big.
    * The land area of the earth is 57268900(29% of the surface) square miles.
    * Ain't no numbers in this here words, nohow, no way, Jose.
    * James was never known as 0000000007
    * Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
    * ␢␢␢$-140000±100 millions.
    * 6/9/1946 was a good year for some.

where the penultimate string has three leading blanks   (real blanks are to be used).

Also see

* The Wiki entry:   (sir) Arthur Eddington's number of protons in the universe.

[Assistant]
(formerly Perl 6)

```
for ('pi=3.14159265358979323846264338327950288419716939937510582097494459231', {:6at, :5by, :ins(' ')}),
    ('The author has two Z$100000000000000 Zimbabwe notes (100 trillion).', {:ins<.>}),
    '-in Aus$+1411.8millions',
    '===US$0017440 millions=== (in 2000 dollars)',
    '123.e8000 is pretty big.',
    'The land area of the earth is  57268900(29% of the surface)  square miles.',
    'Ain\'t no numbers in this here words, nohow, no way, Jose.',
    'James was never known as  0000000007',
    'Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.',
    '   $-140000±100  millions.',
    '6/9/1946 was a good year for some.'
    {
        say "Before: ", .[0];
        say " After: ", .[1] ?? .[0].&commatize( |.[1] ) !! .&commatize;
    }

sub commatize($s, :$at = 0, :$ins = ',', :$by = 3) {
    $s.subst: :continue($at), :1st, / <[1..9]> <[0..9]>* /,
        *.flip.comb(/<{ ".**1..$by" }>/).join($ins).flip;
}

```

Output:

```
Before: pi=3.14159265358979323846264338327950288419716939937510582097494459231
 After: pi=3.14159 26535 89793 23846 26433 83279 50288 41971 69399 37510 58209 74944 59231
Before: The author has two Z$100000000000000 Zimbabwe notes (100 trillion).
 After: The author has two Z$100.000.000.000.000 Zimbabwe notes (100 trillion).
Before: -in Aus$+1411.8millions
 After: -in Aus$+1,411.8millions
Before: ===US$0017440 millions=== (in 2000 dollars)
 After: ===US$0017,440 millions=== (in 2000 dollars)
Before: 123.e8000 is pretty big.
 After: 123.e8000 is pretty big.
Before: The land area of the earth is  57268900(29% of the surface)  square miles.
 After: The land area of the earth is  57,268,900(29% of the surface)  square miles.
Before: Ain't no numbers in this here words, nohow, no way, Jose.
 After: Ain't no numbers in this here words, nohow, no way, Jose.
Before: James was never known as  0000000007
 After: James was never known as  0000000007
Before: Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.
 After: Arthur Eddington wrote: I believe there are 15,747,724,136,275,002,577,605,653,961,181,555,468,044,717,914,527,116,709,366,231,425,076,185,631,031,296 protons in the universe.
Before:    $-140000±100  millions.
 After:    $-140,000±100  millions.
Before: 6/9/1946 was a good year for some.
 After: 6/9/1946 was a good year for some.
```


[User]
Task

Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.

Related tasks

* Documentation
* Here\_document

See also

* Wikipedia
* xkcd (Humor: hand gesture denoting `//` for "commenting out" people.)

[Assistant]
(formerly Perl 6)

**Single-line comments**

A single-line comment starts with # and extends to the end of the line.

```
# the answer to everything
my $x = 42;
```

**Multi-line comments**

A multi-line comment starts with #` and followed by the commented text enclosed by bracketing characters (e.g., (), [], {}, 「」, etc.).

```
#`(
    Comments beginning with a backtick and one or more opening bracketing characters are embedded comments.
    They can span more than one line…
)

my $y = #`{ …or only part of a line. } 3;
```

Multi-line comments can also be embedded into code.

```
for #`(each element in) my @array {
    say #`(or print element) $_ #`(with a newline);
}
```

Using more than one bracketing character lets you include an unmatched close bracket, as shown below.

```
#`{{
  This close curly brace } won't terminate the comment early.
}}
```

**Pod comments**

```
=begin comment

Pod is the successor to Perl 5's POD. This is the simplest way to use it for multi-line comments.
For more about Pod, see Pod: https://docs.perl6.org/language/pod

=end comment
```

Pod also provides declarator blocks which are special comments that attach to some source code and can be extracted as documentation. They are either #| or #= and must be immediately followed by either a space or an opening curly brace. In short, blocks starting with #| are attached to the code after them, and blocks starting with #= are attached to the code before them.

```
#| Compute the distance between two points in the plane.
sub distance(
    Rat \x1, #= First point's abscissa,
    Rat \y1, #= First point's ordinate,
    Rat \x2, #= Second point's abscissa,
    Rat \y2, #= Second point's ordinate,
){
    return sqrt((x2 - x1)**2 + (y2 - y1)**2)
}
```


[User]
Given an integer array **nums**, find the common list elements.

Example

**nums** = [2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9]

**output** = [3,6,9]

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]
```
put [∩] [2,5,1,3,8,9,4,6], [3,5,6,2,9,8,4], [1,3,7,6,9,3];

```

Output:

```
6 9 3
```


[User]
Given an integer array **nums**, the goal is create common sorted list with unique elements.

Example

**nums** = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]

**output** = [1,3,4,5,7,8,9]

[Assistant]
```
put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];
put sort keys [∪] [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9], [<not everything is an integer so why not avoid special cases # ~ 23 4.2>];

```

Output:

```
1 3 4 5 7 8 9
# 1 3 4 4.2 5 7 8 9 23 an avoid cases everything integer is not so special why ~
```


[User]
Task

Given a   list   of arbitrarily many strings, show how to:

* test if they are all lexically **equal**
* test if every string is lexically **less than** the one after it *(i.e. whether the list is in strict ascending order)*

Each of those two tests should result in a single true or false value, which could be used as the condition of an    `if`    statement or similar.

If the input list has less than two elements, the tests should always return true.

There is *no* need to provide a complete program and output.

Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   `strings`,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible.

Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers.

*If you need further guidance/clarification,   see #Perl and #Python for solutions that use implicit short-circuiting loops,   and #Raku for a solution that gets away with simply using a built-in language feature.*

Other tasks related to string operations:

Metrics

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

Counting

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

Remove/replace

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

Anagrams/Derangements/shuffling

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

Find/Search/Determine

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

Formatting

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

Song lyrics/poems/Mad Libs/phrases

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

Tokenize

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

Sequences

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

[Assistant]
(formerly Perl 6)

In Raku, putting square brackets around an infix operator turns it into a listop that effectively works as if the operator had been put in between all of the elements of the argument list *(or in technical terms, it folds/reduces the list using that operator, while taking into account the operator's inherent associativity and identity value)*:

```
[eq] @strings  # All equal
[lt] @strings  # Strictly ascending

```


[User]
Task

Given two strings of different length, determine which string is longer or shorter. Print both strings and their length, one on each line. Print the longer one first.

Measure the length of your string in terms of bytes or characters, as appropriate for your language. If your language doesn't have an operator for measuring the length of a string, note it.

Extra credit

Given more than two strings:

list = ["abcd","123456789","abcdef","1234567"]

Show the strings in descending length order.

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]
So... In what way does this task differ significantly from String length? Other than being horribly under specified?

In the modern world, string "length" is pretty much a useless measurement, especially in the absence of a specified encoding; hence Raku not even having an operator: "length" for strings.

```
say 'Strings (👨👩👧👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:';
say "$_: characters:{.chars},  Unicode code points:{.codes},  UTF-8 bytes:{.encode('UTF8').bytes},  UTF-16 bytes:{.encode('UTF16').bytes}" for <👨👩👧👦 BOGUS! 🤔🇺🇸>.sort: -*.chars;

```

Output:

```
Strings (👨👩👧👦, 🤔🇺🇸, BOGUS!) sorted: "longest" first:
BOGUS!: characters:6,  Unicode code points:6,  UTF-8 bytes:6,  UTF-16 bytes:12
🤔🇺🇸: characters:2,  Unicode code points:3,  UTF-8 bytes:12,  UTF-16 bytes:12
👨👩👧👦: characters:1,  Unicode code points:7,  UTF-8 bytes:25,  UTF-16 bytes:22
```